dicemy commited on
Commit
e8c001c
·
verified ·
1 Parent(s): e82d13f

Upload 655 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/offline-compute/HiveSQL/hivesql.yaml +6 -0
  2. tasks/offline-compute/HiveSQL/hivesql_001_en/gt/expected.csv +6 -0
  3. tasks/offline-compute/HiveSQL/hivesql_001_en/gt/grade.py +715 -0
  4. tasks/offline-compute/HiveSQL/hivesql_001_en/gt/grade_spec.csv +19 -0
  5. tasks/offline-compute/HiveSQL/hivesql_001_en/gt/ground_truth.sql +28 -0
  6. tasks/offline-compute/HiveSQL/hivesql_001_en/init/init_db.py +53 -0
  7. tasks/offline-compute/HiveSQL/hivesql_001_en/init/init_db.sql +90 -0
  8. tasks/offline-compute/HiveSQL/hivesql_001_en/init/schema.sql +27 -0
  9. tasks/offline-compute/HiveSQL/hivesql_001_en/task.md +25 -0
  10. tasks/offline-compute/HiveSQL/hivesql_002/gt/expected.csv +4 -0
  11. tasks/offline-compute/HiveSQL/hivesql_002/gt/grade.py +754 -0
  12. tasks/offline-compute/HiveSQL/hivesql_002/gt/grade_spec.csv +20 -0
  13. tasks/offline-compute/HiveSQL/hivesql_002/gt/ground_truth.sql +191 -0
  14. tasks/offline-compute/HiveSQL/hivesql_002/init/init_db.py +53 -0
  15. tasks/offline-compute/HiveSQL/hivesql_002/init/init_db.sql +164 -0
  16. tasks/offline-compute/HiveSQL/hivesql_002/init/schema.sql +274 -0
  17. tasks/offline-compute/HiveSQL/hivesql_002/task.md +42 -0
  18. tasks/offline-compute/HiveSQL/hivesql_003/gt/expected.csv +3 -0
  19. tasks/offline-compute/HiveSQL/hivesql_003/gt/grade.py +753 -0
  20. tasks/offline-compute/HiveSQL/hivesql_003/gt/grade_spec.csv +20 -0
  21. tasks/offline-compute/HiveSQL/hivesql_003/gt/ground_truth.sql +166 -0
  22. tasks/offline-compute/HiveSQL/hivesql_003/init/init_db.py +53 -0
  23. tasks/offline-compute/HiveSQL/hivesql_003/init/init_db.sql +104 -0
  24. tasks/offline-compute/HiveSQL/hivesql_003/init/schema.sql +45 -0
  25. tasks/offline-compute/HiveSQL/hivesql_003/task.md +34 -0
  26. tasks/offline-compute/HiveSQL/hivesql_004/gt/expected.csv +6 -0
  27. tasks/offline-compute/HiveSQL/hivesql_004/gt/grade.py +710 -0
  28. tasks/offline-compute/HiveSQL/hivesql_004/gt/grade_spec.csv +19 -0
  29. tasks/offline-compute/HiveSQL/hivesql_004/gt/ground_truth.sql +23 -0
  30. tasks/offline-compute/HiveSQL/hivesql_004/init/init_db.py +53 -0
  31. tasks/offline-compute/HiveSQL/hivesql_004/init/init_db.sql +78 -0
  32. tasks/offline-compute/HiveSQL/hivesql_004/init/schema.sql +22 -0
  33. tasks/offline-compute/HiveSQL/hivesql_004/task.md +31 -0
  34. tasks/offline-compute/HiveSQL/hivesql_005/gt/expected.csv +3 -0
  35. tasks/offline-compute/HiveSQL/hivesql_005/gt/grade.py +700 -0
  36. tasks/offline-compute/HiveSQL/hivesql_005/gt/grade_spec.csv +19 -0
  37. tasks/offline-compute/HiveSQL/hivesql_005/gt/ground_truth.sql +34 -0
  38. tasks/offline-compute/HiveSQL/hivesql_005/init/init_db.py +53 -0
  39. tasks/offline-compute/HiveSQL/hivesql_005/init/init_db.sql +141 -0
  40. tasks/offline-compute/HiveSQL/hivesql_005/init/schema.sql +69 -0
  41. tasks/offline-compute/HiveSQL/hivesql_005/task.md +39 -0
  42. tasks/offline-compute/HiveSQL/hivesql_006_en/gt/expected.csv +4 -0
  43. tasks/offline-compute/HiveSQL/hivesql_006_en/gt/grade.py +705 -0
  44. tasks/offline-compute/HiveSQL/hivesql_006_en/gt/grade_spec.csv +19 -0
  45. tasks/offline-compute/HiveSQL/hivesql_006_en/gt/ground_truth.sql +17 -0
  46. tasks/offline-compute/HiveSQL/hivesql_006_en/init/init_db.py +53 -0
  47. tasks/offline-compute/HiveSQL/hivesql_006_en/init/init_db.sql +61 -0
  48. tasks/offline-compute/HiveSQL/hivesql_006_en/init/schema.sql +23 -0
  49. tasks/offline-compute/HiveSQL/hivesql_006_en/task.md +20 -0
  50. tasks/offline-compute/HiveSQL/hivesql_007_en/gt/expected.csv +4 -0
tasks/offline-compute/HiveSQL/hivesql.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ metastore: true
2
+ init_cmd: spark-submit --driver-memory 2g {init_script}
3
+ init_script_name: init_db.py
4
+ gateway_cmd: $SPARK_HOME/sbin/start-thriftserver.sh
5
+ gateway_stop_cmd: $SPARK_HOME/sbin/stop-thriftserver.sh
6
+ gateway_port: 10000
tasks/offline-compute/HiveSQL/hivesql_001_en/gt/expected.csv ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ business_id,business_name,cluster_set,tenant,namespaces,topic,mq_type,dw_appgroup,in_charge,description,create_time,modify_time,cluster_id,cluster_type,cluster_name,bg,category_name,is_filtered,tids,consumed_tids,unconsumed_tids,is_fully_consumed,has_unconsumed_tid,system_belong,dt
2
+ bid001,BizName1,cluster_set_a,tenant_a,ns_a,topic_mq_1,PULSAR,appgroup1,user1,desc1,2026-01-01,2026-05-01,cid001,消息队列MQ,cluster_p1,BG1,product1,,,,,,,数据总线,20260507
3
+ bid005,BizName5,cluster_set_b,tenant_c,ns_c,topic_mq_2,PULSAR,appgroup5,user5,desc5,2026-05-01,2026-05-05,cid005,消息队列MQ,cluster_p2,BG3,product5,,,,,,,流处理平台,20260507
4
+ bid002,BizName2,,,,topic_tube_1,TUBEMQ,appgroup2,user2,desc2,2026-02-01,2026-05-02,cid002,TubeMQ,cluster_t1,BG2,product2,1,"tid1,tid2",tid1,,0,1,数据总线,20260507
5
+ bid004,BizName4,,,,topic_tube_2,TUBEMQ,appgroup4,user4,desc4,2026-04-01,2026-05-04,cid004,TubeMQ,cluster_t2,BG1,product4,0,"tid3,tid4","tid3,tid4",,1,0,数据总线,20260507
6
+ bid003,BizName3,,tenant_b,ns_b,topic_inlong_1,PULSAR,appgroup3,user3,,2026-03-01,2026-05-03,,,cluster_i1,,product3,,,,,,,流处理平台,20260507
tasks/offline-compute/HiveSQL/hivesql_001_en/gt/grade.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hivesql_001 精细评分脚本
2
+
3
+ 业务场景:消息队列Topic维度表前一天分区数据原样复制到今天的分区
4
+ 难度: EASY | 特征: INSERT_OVERWRITE|PARTITION|SINGLE_TABLE
5
+
6
+ 评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
7
+ A_executability (15分): result.sql 能跑通且产出非空
8
+ B_schema (10分): 25列(5) + 列名匹配(5)
9
+ C_row_alignment (15分): 行数比例(7) + key覆盖率(8)
10
+ D_field_value_match (25分): 非key字段逐列值匹配率
11
+ D_field_completeness (15分): 关键字段非空/非空串比例
12
+ F_insert_overwrite (5分): INSERT OVERWRITE + PARTITION
13
+ F_partition_value (5分): dt 分区值 = 20260507
14
+ F_source_filter (10分): 源表分区过滤 dt=20260506
15
+
16
+ 权重: EASY -> product=0.5, process=0.5
17
+ """
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import tempfile
22
+ import json
23
+ import math
24
+
25
+
26
+ def grade(workspace_path, **kwargs):
27
+
28
+ # ========== Case 配置 ==========
29
+ OUTPUT_TABLE = "internal_platform_db.dim_mq_topic_d_copilot_cand_query_engine_001"
30
+ DIFFICULTY = "EASY"
31
+ SOURCE_TABLES = ["dim_mq_topic_d_query_engine_001", "dim_mq_topic_d_copilot_query_engine_001"]
32
+ KEY_COLUMNS = ["business_id", "cluster_id", "dt"]
33
+ EXPECTED_COL_COUNT = 25
34
+ KEY_FIELDS = ["business_id", "business_name", "cluster_id", "cluster_name", "topic", "system_belong"]
35
+ GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
36
+
37
+ DIFFICULTY_WEIGHTS = {
38
+ "EASY": (0.5, 0.5),
39
+ "MEDIUM": (0.6, 0.4),
40
+ "HARD": (0.7, 0.3),
41
+ "EXPERT": (0.8, 0.2),
42
+ }
43
+
44
+ _SPARK_SUBMIT_TIMEOUT = 300
45
+ _JSON_START = "__GRADE_JSON_START__"
46
+ _JSON_END = "__GRADE_JSON_END__"
47
+
48
+ result = {
49
+ "overall_score": 0.0,
50
+ "total_points": 0,
51
+ "grade": "",
52
+ "details": {},
53
+ "diagnostics": [],
54
+ }
55
+
56
+ # ========== 内部辅助函数 ==========
57
+
58
+ def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
59
+ if pred_val is None and gt_val is None:
60
+ return True
61
+ if pred_val is None or gt_val is None:
62
+ return False
63
+ s_pred = str(pred_val).strip()
64
+ s_gt = str(gt_val).strip()
65
+ if s_pred == s_gt:
66
+ return True
67
+ try:
68
+ pv = float(s_pred)
69
+ gv = float(s_gt)
70
+ if math.isnan(pv) and math.isnan(gv):
71
+ return True
72
+ if math.isnan(pv) or math.isnan(gv):
73
+ return False
74
+ if abs(gv) < abs_tol:
75
+ return abs(pv - gv) <= abs_tol
76
+ return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
77
+ except (ValueError, TypeError):
78
+ pass
79
+ return s_pred.lower() == s_gt.lower()
80
+
81
+ def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
82
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
83
+ f.write(script_code)
84
+ script_path = f.name
85
+ try:
86
+ r = subprocess.run(
87
+ ["spark-submit", script_path],
88
+ capture_output=True, text=True, timeout=timeout,
89
+ )
90
+ stdout = r.stdout or ""
91
+ if _JSON_START in stdout and _JSON_END in stdout:
92
+ json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
93
+ return json.loads(json_str), None
94
+ else:
95
+ if r.returncode == 0:
96
+ for line in stdout.splitlines():
97
+ if line.strip().startswith("Traceback"):
98
+ return None, f"spark-submit error: {line}"
99
+ return None, "spark-submit 无 JSON 输出"
100
+ err_msg = (r.stderr or "")[-500:]
101
+ return None, f"spark-submit failed: {err_msg}"
102
+ except subprocess.TimeoutExpired:
103
+ return None, f"spark-submit 超时 ({timeout}s)"
104
+ except Exception as e:
105
+ return None, f"spark-submit 异常: {e}"
106
+ finally:
107
+ try:
108
+ os.unlink(script_path)
109
+ except OSError:
110
+ pass
111
+
112
+ def read_table_via_spark_submit(table_name):
113
+ """Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
114
+ if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
115
+ raise ValueError(f"非法表名: {table_name}")
116
+ read_script = f'''
117
+ import json
118
+ from pyspark.sql import SparkSession
119
+ spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
120
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
121
+ try:
122
+ df = spark.sql("SELECT * FROM {table_name}")
123
+ cols = [c.lower() for c in df.columns]
124
+ rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
125
+ print("{_JSON_START}")
126
+ print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
127
+ print("{_JSON_END}")
128
+ except Exception as e:
129
+ print("{_JSON_START}")
130
+ print(json.dumps({{"error": str(e)}}))
131
+ print("{_JSON_END}")
132
+ finally:
133
+ spark.stop()
134
+ '''
135
+ data, err = _run_spark_script(read_script)
136
+ if err:
137
+ raise RuntimeError(f"read_table failed: {err}")
138
+ if "error" in data:
139
+ raise RuntimeError(f"query failed: {data['error']}")
140
+ return data["cols"], data["rows"]
141
+
142
+ # SQL executor template (self-contained, no external dependency)
143
+ _SQL_EXEC_TEMPLATE = '''
144
+ import json, re
145
+ from pyspark.sql import SparkSession
146
+ spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
147
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
148
+ try:
149
+ with open("{sql_file}", "r", encoding="utf-8") as _f:
150
+ _sql = _f.read()
151
+ _sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
152
+ _stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
153
+ while _i < len(_sql):
154
+ _ch = _sql[_i]
155
+ if _ch == "\\\\" and _i + 1 < len(_sql):
156
+ _cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
157
+ if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
158
+ while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
159
+ _cur.append("\\n"); continue
160
+ if _ch == "'" and not _in_dq: _in_sq = not _in_sq
161
+ elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
162
+ if _ch == ";" and not _in_sq and not _in_dq:
163
+ _s = "".join(_cur).strip()
164
+ if _s: _stmts.append(_s)
165
+ _cur = []
166
+ else:
167
+ _cur.append(_ch)
168
+ _i += 1
169
+ _last = "".join(_cur).strip()
170
+ if _last: _stmts.append(_last)
171
+ for _stmt in _stmts:
172
+ spark.sql(_stmt)
173
+ print("{_JSON_START}")
174
+ print(json.dumps({{"ok": True}}))
175
+ print("{_JSON_END}")
176
+ except Exception as e:
177
+ print("{_JSON_START}")
178
+ print(json.dumps({{"ok": False, "error": str(e)}}))
179
+ print("{_JSON_END}")
180
+ finally:
181
+ spark.stop()
182
+ '''
183
+
184
+ def execute_result_sql():
185
+ result_sql = os.path.join(workspace_path, "result.sql")
186
+ if not os.path.exists(result_sql):
187
+ return False, "no_result_file"
188
+ with open(result_sql, 'r', encoding='utf-8') as _rf:
189
+ _sql_text = _rf.read()
190
+ _bizdate = '20260507'
191
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
192
+ _yesterday = '20260506'
193
+ _bizdate_iso = '2026-05-07'
194
+ # 替换 数据平台WD变量(沙箱 spark-sql 不支持 ${...} 语法)
195
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate}', _bizdate, _sql_text)
196
+ # yyyymmdd-1 必须在 yyyymmdd 之前匹配,否则会被通用正则吃掉
197
+ _sql_text = re.sub(r'\${yyyymmdd-1}', _yesterday, _sql_text)
198
+ _sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
199
+ _sql_text = re.sub(r'\${bizdate-1}', _yesterday, _sql_text)
200
+ _sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
201
+ _sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
202
+ # 替换所有未被处理的 ${...} 变量(兜底,防止 agent 使用任意变量名)
203
+ _sql_text = re.sub(r'\$\{[^}]+\}', _bizdate, _sql_text)
204
+ # Mock Spark SQL 内置时间函数,使其返回测试场景日期而非真实运行日期
205
+ _sql_text = re.sub(r'\bcurrent_date\s*\(\s*\)', f"date('{_bizdate_iso}')", _sql_text, flags=re.IGNORECASE)
206
+ _sql_text = re.sub(r'\bnow\s*\(\s*\)', f"timestamp('{_bizdate_iso} 00:00:00')", _sql_text, flags=re.IGNORECASE)
207
+ _sql_text = re.sub(r'\bcurrent_timestamp\s*\(\s*\)', f"timestamp('{_bizdate_iso} 00:00:00')", _sql_text, flags=re.IGNORECASE)
208
+ with open(result_sql, 'w', encoding='utf-8') as _wf:
209
+ _wf.write(_sql_text)
210
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
211
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
212
+ data, err = _run_spark_script(script)
213
+ if err:
214
+ return False, f"execution_error: {err}"
215
+ if data and data.get("ok"):
216
+ return True, None
217
+ return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
218
+
219
+ def execute_ground_truth_sql():
220
+ gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
221
+ if not os.path.exists(gt_sql):
222
+ return False, "ground_truth.sql not found"
223
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
224
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
225
+ data, err = _run_spark_script(script)
226
+ if err:
227
+ return False, f"gt_execution_error: {err}"
228
+ if data and data.get("ok"):
229
+ return True, None
230
+ return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
231
+
232
+ def truncate_table(table_name):
233
+ script = f'''
234
+ from pyspark.sql import SparkSession
235
+ spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
236
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
237
+ spark.sql("TRUNCATE TABLE {table_name}")
238
+ spark.stop()
239
+ '''
240
+ try:
241
+ _run_spark_script(script, timeout=120)
242
+ except Exception:
243
+ pass
244
+
245
+ def restore_hive_site():
246
+ """Restore hive-site.xml to canonical state (agent may have modified it)."""
247
+ canonical_hive_site = '''<?xml version="1.0"?>
248
+ <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
249
+ <configuration>
250
+ <property>
251
+ <name>hive.metastore.uris</name>
252
+ <value>thrift://localhost:9083</value>
253
+ </property>
254
+ <property>
255
+ <name>hive.metastore.warehouse.dir</name>
256
+ <value>/tmp/hive_warehouse</value>
257
+ </property>
258
+ <property>
259
+ <name>javax.jdo.option.ConnectionURL</name>
260
+ <value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
261
+ </property>
262
+ <property>
263
+ <name>javax.jdo.option.ConnectionDriverName</name>
264
+ <value>org.apache.derby.jdbc.EmbeddedDriver</value>
265
+ </property>
266
+ <property>
267
+ <name>datanucleus.schema.autoCreateAll</name>
268
+ <value>true</value>
269
+ </property>
270
+ <property>
271
+ <name>hive.metastore.schema.verification</name>
272
+ <value>false</value>
273
+ </property>
274
+ </configuration>
275
+ '''
276
+ hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
277
+ try:
278
+ with open(hive_site_path, 'w') as f:
279
+ f.write(canonical_hive_site)
280
+ except Exception:
281
+ pass
282
+
283
+ def finalize(result):
284
+ product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
285
+ product_dims = ["A_executability"] + ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']
286
+ product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
287
+ product_ratio = product_raw / 100.0
288
+ for dim in ["H_efficiency"]:
289
+ if dim in result["details"]:
290
+ raw = result["details"][dim].get("score", 0)
291
+ result["details"][dim]["score_before_scaling"] = raw
292
+ result["details"][dim]["score"] = round(raw * product_ratio, 2)
293
+ result["details"][dim]["product_ratio"] = round(product_ratio, 4)
294
+ process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
295
+ process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
296
+ product_score = round(product_raw * product_weight, 2)
297
+ process_score = round(process_raw * process_weight, 2)
298
+ total = round(product_score + process_score, 2)
299
+ result["total_points"] = total
300
+ result["product_points"] = product_score
301
+ result["process_points"] = round(process_score, 2)
302
+ result["weights"] = {"product": product_weight, "process": process_weight}
303
+ result["overall_score"] = round(total / 100.0, 4)
304
+ if total >= 90:
305
+ result["grade"] = "优秀"
306
+ elif total >= 75:
307
+ result["grade"] = "良好"
308
+ elif total >= 60:
309
+ result["grade"] = "合格"
310
+ elif total >= 40:
311
+ result["grade"] = "偏弱"
312
+ else:
313
+ result["grade"] = "不合格"
314
+ return result
315
+
316
+ # Restore hive-site.xml (agent may have modified it)
317
+ restore_hive_site()
318
+
319
+ # ========== A. 可执行性 (15分) ==========
320
+ a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
321
+ exec_ok, exec_err = execute_result_sql()
322
+ if not exec_ok:
323
+ detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
324
+ result["details"]["A_executability"] = {"score": 0, "max": 15, "detail": detail}
325
+ result["error"] = detail
326
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
327
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
328
+ return finalize(result)
329
+
330
+ a_items["A1_exec_ok"] = 8
331
+
332
+ pred_headers, pred_rows = [], []
333
+ try:
334
+ pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
335
+ except Exception as e:
336
+ result["diagnostics"].append(f"read_pred_failed: {e}")
337
+
338
+ if not pred_rows:
339
+ result["details"]["A_executability"] = {"score": 8, "max": 15, "items": a_items}
340
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
341
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
342
+ return finalize(result)
343
+
344
+ a_items["A2_has_data"] = 7
345
+ result["details"]["A_executability"] = {"score": 15, "max": 15, "items": a_items}
346
+
347
+ # ========== Execute GT + Read GT ==========
348
+ truncate_table(GT_TABLE)
349
+ gt_ok, gt_err = execute_ground_truth_sql()
350
+ if not gt_ok:
351
+ result["error"] = f"ground_truth failed: {gt_err}"
352
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
353
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
354
+ return finalize(result)
355
+
356
+ gt_headers, gt_rows = [], []
357
+ try:
358
+ gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
359
+ except Exception as e:
360
+ result["error"] = f"read_gt_failed: {e}"
361
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
362
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
363
+ return finalize(result)
364
+
365
+ # ========== B/C/D/F 维度评分 ==========
366
+ pred_col_map = {h: i for i, h in enumerate(pred_headers)}
367
+ gt_col_map = {h: i for i, h in enumerate(gt_headers)}
368
+
369
+ # ========== B. Schema正确性 (10分) ==========
370
+ b_items = {}
371
+ # B1: 列数 (5分)
372
+ if len(pred_headers) == EXPECTED_COL_COUNT:
373
+ b_items["B1_col_count"] = 5
374
+ elif abs(len(pred_headers) - EXPECTED_COL_COUNT) <= 2:
375
+ b_items["B1_col_count"] = 3
376
+ else:
377
+ b_items["B1_col_count"] = 0
378
+
379
+ # B2: 列名匹配 (5分)
380
+ gt_col_set = set(gt_headers)
381
+ pred_col_set = set(pred_headers)
382
+ name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
383
+ if name_match_rate >= 0.95:
384
+ b_items["B2_col_names"] = 5
385
+ elif name_match_rate >= 0.8:
386
+ b_items["B2_col_names"] = 3
387
+ else:
388
+ b_items["B2_col_names"] = 0
389
+
390
+ b_score = sum(b_items.values())
391
+ result["details"]["B_schema"] = {
392
+ "score": b_score, "max": 10,
393
+ "detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
394
+ }
395
+
396
+ # ========== C. 行一致性 (15分) ==========
397
+ c_items = {}
398
+ gt_row_count = len(gt_rows)
399
+ pred_row_count = len(pred_rows)
400
+
401
+ # C1: 行数比例 (7分)
402
+ if gt_row_count > 0:
403
+ ratio = pred_row_count / gt_row_count
404
+ if 0.95 <= ratio <= 1.05:
405
+ c_items["C1_row_ratio"] = 7
406
+ elif 0.7 <= ratio <= 1.3:
407
+ c_items["C1_row_ratio"] = 4
408
+ else:
409
+ c_items["C1_row_ratio"] = 0
410
+ else:
411
+ c_items["C1_row_ratio"] = 7 if pred_row_count == 0 else 0
412
+
413
+ # C2: key覆盖率 (8分)
414
+ key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
415
+ if key_cols_avail and gt_row_count > 0:
416
+ gt_keys = set()
417
+ for row in gt_rows:
418
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
419
+ gt_keys.add(key)
420
+ pred_keys = set()
421
+ for row in pred_rows:
422
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
423
+ pred_keys.add(key)
424
+ coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
425
+ if coverage >= 0.995:
426
+ c_items["C2_key_coverage"] = 8
427
+ elif coverage >= 0.9:
428
+ c_items["C2_key_coverage"] = 6
429
+ elif coverage >= 0.7:
430
+ c_items["C2_key_coverage"] = 3
431
+ else:
432
+ c_items["C2_key_coverage"] = round(8 * coverage, 2)
433
+ else:
434
+ c_items["C2_key_coverage"] = 0
435
+
436
+ c_score = sum(v for v in c_items.values())
437
+ result["details"]["C_row_alignment"] = {"score": c_score, "max": 15, "detail": c_items}
438
+
439
+ # 构建索引
440
+ if key_cols_avail:
441
+ pred_index = {}
442
+ for row in pred_rows:
443
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
444
+ pred_index[key] = row
445
+ gt_index = {}
446
+ for row in gt_rows:
447
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
448
+ gt_index[key] = row
449
+ else:
450
+ pred_index = {}
451
+ gt_index = {}
452
+
453
+ # ========== D. 字段值匹配 (25分) ==========
454
+ value_cols = [c for c in gt_headers if c in pred_col_map and c not in KEY_COLUMNS]
455
+ if not value_cols:
456
+ value_cols = [c for c in gt_headers if c in pred_col_map]
457
+
458
+ d_val_items = {}
459
+ per_col_weight = 25.0 / max(len(value_cols), 1)
460
+ d_val_score = 0
461
+ for col in value_cols:
462
+ gt_ci = gt_col_map.get(col)
463
+ pred_ci = pred_col_map.get(col)
464
+ if gt_ci is None or pred_ci is None:
465
+ d_val_items[col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
466
+ continue
467
+ matches = 0
468
+ total = 0
469
+ for key, gt_row in gt_index.items():
470
+ pred_row = pred_index.get(key)
471
+ if pred_row is None:
472
+ total += 1
473
+ continue
474
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
475
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
476
+ if values_match(pred_val, gt_val):
477
+ matches += 1
478
+ total += 1
479
+ rate = matches / max(total, 1)
480
+ col_score = rate * per_col_weight
481
+ d_val_score += col_score
482
+ d_val_items[col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2)}
483
+
484
+ result["details"]["D_field_value_match"] = {
485
+ "score": round(d_val_score, 2), "max": 25, "detail": d_val_items,
486
+ }
487
+
488
+ # ========== D. 字段完整性 (15分) ==========
489
+ d_comp_items = {}
490
+ d_comp_score = 0
491
+ per_field_weight = 15.0 / max(len(KEY_FIELDS), 1)
492
+ for field in KEY_FIELDS:
493
+ gt_ci = gt_col_map.get(field)
494
+ pred_ci = pred_col_map.get(field)
495
+ if gt_ci is None or pred_ci is None:
496
+ d_comp_items[field] = {"score": 0, "reason": "column_missing"}
497
+ continue
498
+ # GT 中该字段非空行数
499
+ gt_nonempty = 0
500
+ pred_nonempty = 0
501
+ total = 0
502
+ for key, gt_row in gt_index.items():
503
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
504
+ if gt_val:
505
+ total += 1
506
+ pred_row = pred_index.get(key)
507
+ if pred_row is not None:
508
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
509
+ if pred_val:
510
+ pred_nonempty += 1
511
+ gt_nonempty = total
512
+ rate = pred_nonempty / max(gt_nonempty, 1)
513
+ field_score = rate * per_field_weight
514
+ d_comp_score += field_score
515
+ d_comp_items[field] = {"nonempty_rate": round(rate, 4), "score": round(field_score, 2)}
516
+
517
+ result["details"]["D_field_completeness"] = {
518
+ "score": round(d_comp_score, 2), "max": 15, "detail": d_comp_items,
519
+ }
520
+
521
+ # ========== F. INSERT OVERWRITE (5分) ==========
522
+ result_sql_path = os.path.join(workspace_path, "result.sql")
523
+ sql_text = ""
524
+ try:
525
+ with open(result_sql_path, "r", encoding="utf-8") as f:
526
+ sql_text = f.read().lower()
527
+ except Exception:
528
+ sql_text = ""
529
+
530
+ f_insert_items = {}
531
+ has_overwrite = "insert overwrite" in sql_text
532
+ has_partition = "partition" in sql_text
533
+ if has_overwrite and has_partition:
534
+ f_insert_items["insert_overwrite_partition"] = 5
535
+ elif has_overwrite:
536
+ f_insert_items["insert_overwrite_partition"] = 3
537
+ else:
538
+ f_insert_items["insert_overwrite_partition"] = 0
539
+ result["details"]["F_insert_overwrite"] = {
540
+ "score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
541
+ }
542
+
543
+ # ========== F. 分区值 (5分) ==========
544
+ f_part_items = {}
545
+ if "dt" in sql_text and "20260507" in sql_text:
546
+ f_part_items["partition_value"] = 5
547
+ else:
548
+ f_part_items["partition_value"] = 0
549
+ result["details"]["F_partition_value"] = {
550
+ "score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
551
+ }
552
+
553
+ # ========== F. 源表分区过滤 (10分) ==========
554
+ f_filter_items = {}
555
+ source_table_lower = SOURCE_TABLES[0].lower()
556
+ has_source_table = source_table_lower in sql_text
557
+ has_dt_filter = "dt" in sql_text and "20260506" in sql_text
558
+ if has_source_table and has_dt_filter:
559
+ f_filter_items["source_partition_filter"] = 10
560
+ elif has_dt_filter:
561
+ f_filter_items["source_partition_filter"] = 7
562
+ elif has_source_table:
563
+ f_filter_items["source_partition_filter"] = 3
564
+ else:
565
+ f_filter_items["source_partition_filter"] = 0
566
+ result["details"]["F_source_filter"] = {
567
+ "score": f_filter_items["source_partition_filter"], "max": 10, "detail": f_filter_items,
568
+ }
569
+
570
+ # 汇总
571
+ total = (15 + b_score + c_score + d_val_score + d_comp_score
572
+ + f_insert_items["insert_overwrite_partition"]
573
+ + f_part_items["partition_value"]
574
+ + f_filter_items["source_partition_filter"])
575
+
576
+ # ========== G~I 过程评分 ==========
577
+ TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
578
+ OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
579
+ INPUT_TABLE_SHORT = SOURCE_TABLES[0]
580
+
581
+ transcript_entries = []
582
+ has_transcript = False
583
+ try:
584
+ if os.path.exists(TRANSCRIPT_PATH):
585
+ with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f:
586
+ for line in f:
587
+ line = line.strip()
588
+ if line:
589
+ try:
590
+ transcript_entries.append(json.loads(line))
591
+ except json.JSONDecodeError:
592
+ continue
593
+ if len(transcript_entries) > 2:
594
+ has_transcript = True
595
+ except Exception:
596
+ pass
597
+
598
+ if not has_transcript:
599
+ result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}}
600
+ result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}}
601
+ result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}}
602
+ return finalize(result)
603
+
604
+ # Parse transcript into structured events
605
+ tool_uses = []
606
+ first_write_result_idx = None
607
+ last_spark_submit_success_idx = None
608
+ write_result_count = 0
609
+ logic_error_retries = 0
610
+
611
+ for idx, entry in enumerate(transcript_entries):
612
+ content = entry.get("content", [])
613
+ if isinstance(content, str):
614
+ content = [content]
615
+
616
+ for block_str in content:
617
+ if not isinstance(block_str, str):
618
+ continue
619
+ if "ToolUseBlock" in block_str:
620
+ name_match = re.search(r"name='([^']+)'", block_str)
621
+ input_match = re.search(r"input=(\{.*\})", block_str)
622
+ if name_match:
623
+ tool_name = name_match.group(1)
624
+ tool_input = input_match.group(1) if input_match else ""
625
+ tool_uses.append((idx, tool_name, tool_input))
626
+ if tool_name == "Write" and "result.sql" in tool_input:
627
+ write_result_count += 1
628
+ if first_write_result_idx is None:
629
+ first_write_result_idx = idx
630
+ if "ToolResultBlock" in block_str:
631
+ if "Traceback" in block_str or "Exception" in block_str:
632
+ env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
633
+ "db.lck", "TTransportException", "port 10000"]
634
+ is_env_error = any(e in block_str for e in env_errors)
635
+ has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
636
+ for t in tool_uses)
637
+ if not is_env_error and has_spark_submit:
638
+ logic_error_retries += 1
639
+ if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" in block_str:
640
+ if "Exit Code: 0" in block_str and "Traceback" not in block_str:
641
+ last_spark_submit_success_idx = idx
642
+
643
+ before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
644
+
645
+ # ===== G. 探索充分性 (35分) =====
646
+ g_items = {}
647
+ g1_pass = any(name == "Read" and "schema" in inp.lower()
648
+ for idx, name, inp in tool_uses if idx < before_first_write)
649
+ g_items["G1_source_schema"] = 9 if g1_pass else 0
650
+
651
+ g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
652
+ and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
653
+ for idx, name, inp in tool_uses if idx < before_first_write)
654
+ g_items["G2_source_sample"] = 9 if g2_pass else 0
655
+
656
+ g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
657
+ and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
658
+ for idx, name, inp in tool_uses if idx < before_first_write)
659
+ g_items["G3_distribution"] = 9 if g3_pass else 0
660
+
661
+ g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
662
+ and OUTPUT_TABLE_SHORT in inp
663
+ for idx, name, inp in tool_uses if idx < before_first_write)
664
+ g_items["G4_target_schema"] = 8 if g4_pass else 0
665
+
666
+ g_score = sum(g_items.values())
667
+ result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
668
+
669
+ # ===== H. 执行效率 (40分) =====
670
+ h_items = {}
671
+ if write_result_count <= 2:
672
+ h_items["H1_few_submissions"] = 20
673
+ elif write_result_count <= 4:
674
+ h_items["H1_few_submissions"] = 13
675
+ elif write_result_count <= 6:
676
+ h_items["H1_few_submissions"] = 7
677
+ else:
678
+ h_items["H1_few_submissions"] = 0
679
+
680
+ if logic_error_retries == 0:
681
+ h_items["H2_no_logic_errors"] = 13
682
+ elif logic_error_retries <= 1:
683
+ h_items["H2_no_logic_errors"] = 7
684
+ else:
685
+ h_items["H2_no_logic_errors"] = 0
686
+
687
+ h_items["H3_no_redundancy"] = 7
688
+ h_score = sum(h_items.values())
689
+ result["details"]["H_efficiency"] = {"score": min(h_score, 40), "max": 40, "items": h_items}
690
+
691
+ # ===== I. 自验证行为 (25分) =====
692
+ i_items = {}
693
+ post_submit_uses = []
694
+ if last_spark_submit_success_idx is not None:
695
+ post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
696
+ if idx > last_spark_submit_success_idx]
697
+
698
+ i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
699
+ for _, name, inp in post_submit_uses)
700
+ i_items["I1_query_output"] = 8 if i1_pass else 0
701
+
702
+ i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
703
+ and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
704
+ for _, name, inp in post_submit_uses)
705
+ i_items["I2_check_count"] = 9 if i2_pass else 0
706
+
707
+ i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
708
+ and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper())
709
+ for _, name, inp in post_submit_uses)
710
+ i_items["I3_check_values"] = 8 if i3_pass else 0
711
+
712
+ i_score = sum(i_items.values())
713
+ result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items}
714
+
715
+ return finalize(result)
tasks/offline-compute/HiveSQL/hivesql_001_en/gt/grade_spec.csv ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 维度,维度全名,子维度,满分,说明
2
+ A,A_executability,executability,15,result.sql 能跑通且产出非空
3
+ B,B_schema,schema,10,25列(5) + 列名匹配(5)
4
+ C,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)
5
+ D,D_field_value_match,field_value_match,25,非key字段逐列值匹配率
6
+ D,D_field_completeness,field_completeness,15,关键字段非空/非空串比例
7
+ F,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION
8
+ F,F_partition_value,partition_value,5,dt 分区值 = 20260507
9
+ F,F_source_filter,source_filter,10,源表分区过滤 dt=20260506
10
+
11
+ 总计,,,100,
12
+
13
+ # 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
14
+ # 难度,EASY
15
+ # 权重,"product=0.5, process=0.5"
16
+ # 范式,new
17
+ # Key列,"business_id, cluster_id, dt"
18
+ # 预期列数,25
19
+ # 输出表,internal_platform_db.dim_mq_topic_d_copilot_cand_query_engine_001
tasks/offline-compute/HiveSQL/hivesql_001_en/gt/ground_truth.sql ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INSERT overwrite TABLE internal_platform_db.dim_mq_topic_d_copilot_query_engine_001 PARTITION (dt = '20260507')
2
+ SELECT
3
+ business_id
4
+ ,business_name
5
+ ,cluster_set
6
+ ,tenant
7
+ ,namespaces
8
+ ,topic
9
+ ,mq_type
10
+ ,dw_appgroup
11
+ ,in_charge
12
+ ,description
13
+ ,create_time
14
+ ,modify_time
15
+ ,cluster_id
16
+ ,cluster_type
17
+ ,cluster_name
18
+ ,bg
19
+ ,category_name
20
+ ,is_filtered
21
+ ,tids
22
+ ,consumed_tids
23
+ ,unconsumed_tids
24
+ ,is_fully_consumed
25
+ ,has_unconsumed_tid
26
+ ,system_belong
27
+ FROM internal_platform_db.dim_mq_topic_d_query_engine_001
28
+ where dt = '20260506'
tasks/offline-compute/HiveSQL/hivesql_001_en/init/init_db.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import re
3
+ from pyspark.sql import SparkSession
4
+
5
+ spark = SparkSession.builder \
6
+ .appName('hivesql_bench_init') \
7
+ .enableHiveSupport() \
8
+ .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \
9
+ .getOrCreate()
10
+
11
+ spark.sql('CREATE DATABASE IF NOT EXISTS internal_platform_db')
12
+
13
+
14
+ def _execute_sql_file(spark, sql_path):
15
+ """Read SQL file, remove SuperSQL SET headers, split by semicolons, execute."""
16
+ with open(sql_path, 'r', encoding='utf-8') as f:
17
+ content = f.read()
18
+ content = re.sub(r'^\s*set\s+query_engine\.\S+\n?', '', content, flags=re.IGNORECASE)
19
+ stmts, cur, in_sq, in_dq, i = [], [], False, False, 0
20
+ while i < len(content):
21
+ ch = content[i]
22
+ if ch == '\\' and i + 1 < len(content):
23
+ cur.append(ch); cur.append(content[i + 1]); i += 2; continue
24
+ if ch == '-' and i + 1 < len(content) and content[i + 1] == '-' and not in_sq and not in_dq:
25
+ while i < len(content) and content[i] != '\n':
26
+ i += 1
27
+ cur.append('\n'); continue
28
+ if ch == "'" and not in_dq:
29
+ in_sq = not in_sq
30
+ elif ch == '"' and not in_sq:
31
+ in_dq = not in_dq
32
+ if ch == ';' and not in_sq and not in_dq:
33
+ s = ''.join(cur).strip()
34
+ if s:
35
+ stmts.append(s)
36
+ cur = []
37
+ else:
38
+ cur.append(ch)
39
+ i += 1
40
+ last = ''.join(cur).strip()
41
+ if last:
42
+ stmts.append(last)
43
+ for stmt in stmts:
44
+ spark.sql(stmt)
45
+
46
+
47
+ _execute_sql_file(spark, '/tmp_workspace/init_db.sql')
48
+
49
+ tables = spark.sql('SHOW TABLES IN internal_platform_db').collect()
50
+ print(f'Init complete, {len(tables)} tables created')
51
+ for t in tables:
52
+ print(f' - {t.namespace}.{t.tableName}')
53
+ spark.stop()
tasks/offline-compute/HiveSQL/hivesql_001_en/init/init_db.sql ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS internal_platform_db;
2
+
3
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dim_mq_topic_d_query_engine_001 (
4
+ business_id STRING,
5
+ business_name STRING,
6
+ cluster_set STRING,
7
+ tenant STRING,
8
+ namespaces STRING,
9
+ topic STRING,
10
+ mq_type STRING,
11
+ dw_appgroup STRING,
12
+ in_charge STRING,
13
+ description STRING,
14
+ create_time STRING,
15
+ modify_time STRING,
16
+ cluster_id STRING,
17
+ cluster_type STRING,
18
+ cluster_name STRING,
19
+ bg STRING,
20
+ category_name STRING,
21
+ is_filtered TINYINT,
22
+ tids STRING,
23
+ consumed_tids STRING,
24
+ unconsumed_tids STRING,
25
+ is_fully_consumed TINYINT,
26
+ has_unconsumed_tid TINYINT,
27
+ system_belong STRING
28
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
29
+
30
+ INSERT INTO TABLE internal_platform_db.dim_mq_topic_d_query_engine_001 PARTITION (dt='20260506') VALUES
31
+ ('bid001','BizName1','cluster_set_a','tenant_a','ns_a','topic_mq_1','PULSAR','appgroup1','user1','desc1','2026-01-01','2026-05-01','cid001','消息队列MQ','cluster_p1','BG1','product1',NULL,NULL,NULL,NULL,NULL,NULL,'数据总线'),
32
+ ('bid002','BizName2',NULL,NULL,NULL,'topic_tube_1','TUBEMQ','appgroup2','user2','desc2','2026-02-01','2026-05-02','cid002','TubeMQ','cluster_t1','BG2','product2',1,'tid1,tid2','tid1',NULL,0,1,'数据总线'),
33
+ ('bid003','BizName3',NULL,'tenant_b','ns_b','topic_inlong_1','PULSAR','appgroup3','user3',NULL,'2026-03-01','2026-05-03',NULL,NULL,'cluster_i1',NULL,'product3',NULL,NULL,NULL,NULL,NULL,NULL,'流处理平台'),
34
+ ('bid004','BizName4',NULL,NULL,NULL,'topic_tube_2','TUBEMQ','appgroup4','user4','desc4','2026-04-01','2026-05-04','cid004','TubeMQ','cluster_t2','BG1','product4',0,'tid3,tid4','tid3,tid4',NULL,1,0,'数据总线'),
35
+ ('bid005','BizName5','cluster_set_b','tenant_c','ns_c','topic_mq_2','PULSAR','appgroup5','user5','desc5','2026-05-01','2026-05-05','cid005','消息队列MQ','cluster_p2','BG3','product5',NULL,NULL,NULL,NULL,NULL,NULL,'流处理平台');
36
+
37
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dim_mq_topic_d_copilot_query_engine_001 (
38
+ business_id STRING,
39
+ business_name STRING,
40
+ cluster_set STRING,
41
+ tenant STRING,
42
+ namespaces STRING,
43
+ topic STRING,
44
+ mq_type STRING,
45
+ dw_appgroup STRING,
46
+ in_charge STRING,
47
+ description STRING,
48
+ create_time STRING,
49
+ modify_time STRING,
50
+ cluster_id STRING,
51
+ cluster_type STRING,
52
+ cluster_name STRING,
53
+ bg STRING,
54
+ category_name STRING,
55
+ is_filtered TINYINT,
56
+ tids STRING,
57
+ consumed_tids STRING,
58
+ unconsumed_tids STRING,
59
+ is_fully_consumed TINYINT,
60
+ has_unconsumed_tid TINYINT,
61
+ system_belong STRING
62
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
63
+
64
+ -- Agent 候选目标表
65
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dim_mq_topic_d_copilot_cand_query_engine_001 (
66
+ business_id STRING,
67
+ business_name STRING,
68
+ cluster_set STRING,
69
+ tenant STRING,
70
+ namespaces STRING,
71
+ topic STRING,
72
+ mq_type STRING,
73
+ dw_appgroup STRING,
74
+ in_charge STRING,
75
+ description STRING,
76
+ create_time STRING,
77
+ modify_time STRING,
78
+ cluster_id STRING,
79
+ cluster_type STRING,
80
+ cluster_name STRING,
81
+ bg STRING,
82
+ category_name STRING,
83
+ is_filtered TINYINT,
84
+ tids STRING,
85
+ consumed_tids STRING,
86
+ unconsumed_tids STRING,
87
+ is_fully_consumed TINYINT,
88
+ has_unconsumed_tid TINYINT,
89
+ system_belong STRING
90
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_001_en/init/schema.sql ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dim_mq_topic_d_copilot (
2
+ `dt` STRING COMMENT '天分区',
3
+ `business_id` STRING COMMENT 'business_id',
4
+ `business_name` STRING COMMENT 'business_name',
5
+ `cluster_set` STRING COMMENT 'cluster_set',
6
+ `tenant` STRING COMMENT 'tenant',
7
+ `namespaces` STRING COMMENT 'namespaces',
8
+ `topic` STRING COMMENT 'topic',
9
+ `mq_type` STRING COMMENT 'MQ类型(消息队列MQ/TubeMQ)',
10
+ `dw_appgroup` STRING COMMENT 'bid所属应用组',
11
+ `in_charge` STRING COMMENT 'bid负责人',
12
+ `description` STRING COMMENT 'bid描述信息',
13
+ `create_time` STRING COMMENT 'bid创建时间',
14
+ `modify_time` STRING COMMENT 'bid最后修改时间',
15
+ `cluster_id` STRING COMMENT 'bid所属集群id',
16
+ `cluster_type` STRING COMMENT 'bid所属集群类型',
17
+ `cluster_name` STRING COMMENT 'bid所属集群名',
18
+ `bg` STRING COMMENT 'bid所属的bg',
19
+ `category_name` STRING COMMENT 'bid所归属的产品',
20
+ `is_filtered` TINYINT COMMENT 'Tube-bid是否有消费组是过滤消费(1:是 0:否)',
21
+ `tids` STRING COMMENT 'Tube-bid下的所有tid',
22
+ `consumed_tids` STRING COMMENT 'Tube-bid下所有配置消费的tid',
23
+ `unconsumed_tids` STRING COMMENT 'Tube-bid下所有未配置消费的tid',
24
+ `is_fully_consumed` TINYINT COMMENT 'Tube-topic是否有消费组是全量消费(1:是 0:否)',
25
+ `has_unconsumed_tid` TINYINT COMMENT 'Tube-bid是否有没有被消费的tid',
26
+ `system_belong` STRING COMMENT 'topic所属的系统(数据总线/流处理平台)'
27
+ ) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_001_en/task.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: offline-compute_HiveSQL_hivesql_001
3
+ name: Message Queue Topic Dimension Table internal_platform_db.dim_mq_topic_d_su
4
+ category: offline-compute/HiveSQL
5
+ timeout_seconds: 600
6
+ modality: pure-text
7
+ engine: hivesql
8
+ ---
9
+ ## Prompt
10
+ **Task Objective**: Read data from the previous day's partition of the input table and copy it as-is to the output table's current day partition.
11
+
12
+ **Time Variables**: The platform provides these variables for dynamic date computation:
13
+ - `${yyyymmdd}` : current day in YYYYMMDD format
14
+ - `${yyyymmdd-1}` : previous day in YYYYMMDD format
15
+ - You may also use Spark SQL built-in functions like `current_date()` and `date_sub()`.
16
+
17
+ **Input**: `internal_platform_db.dim_mq_topic_d_query_engine_001` (a partitioned table, partitioned by `dt`).
18
+
19
+ **Processing Rules**: 1) Select all data where the `dt` partition equals the previous day (use `${yyyymmdd-1}`); 2) No joins, single-table processing; 3) All fields are retained as-is, with no transformations or filtering.
20
+
21
+ **Output Requirements**: Output all non-partition columns: `business_id`, `business_name`, `cluster_set`, `tenant`, `namespaces`, `topic`, `mq_type`, `dw_appgroup`, `in_charge`, `description`, `create_time`, `modify_time`, `cluster_id`, `cluster_type`, `cluster_name`, `bg`, `category_name`, `is_filtered`, `tids`, `consumed_tids`, `unconsumed_tids`, `is_fully_consumed`, `has_unconsumed_tid`, `system_belong`; partitioned by the `dt` field.
22
+
23
+ **Write Requirements**: Use `INSERT OVERWRITE` to write to the current day partition (use `${yyyymmdd}`) of `internal_platform_db.dim_mq_topic_d_copilot_cand_query_engine_001`.
24
+
25
+ Please write the final HiveSQL to `result.sql` and execute it.
tasks/offline-compute/HiveSQL/hivesql_002/gt/expected.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ trace_id,datawd_project_id,datawd_task_id,datawd_task_instance_id,compute_type,status_code,instance_run_time,code_run_time,resource_wait_time,code_start_time,code_end_time,instance_start_time,instance_end_time,serving_id,is_permanent,apply_for_gpu_count,pod_name,pkg_agg_time,gpu_util,gpu_count,p_date,dt
2
+ trace_001,proj_1,task_1,inst_1,ray,0,86400,75600,2400,2025-05-06 01:00:00,2025-05-06 22:00:00,2025-05-06 00:00:00,2025-05-07 00:00:00,1001,true,2,pod_alpha,,,,2025-05-06,20260507
3
+ trace_001,proj_1,task_1,inst_1,ray,0,0,,,,,,2025-05-06 00:00:00,2025-05-07 00:00:00,1001,true,2,pod_alpha,,,,2025-05-07,20260507
4
+ trace_002,proj_2,task_2,inst_2,ray,1,10800,8000,800,2025-05-07 00:13:20,2025-05-07 02:26:40,2025-05-07 00:00:00,2025-05-07 03:00:00,1002,false,2,pod_beta,,,,2025-05-07,20260507
tasks/offline-compute/HiveSQL/hivesql_002/gt/grade.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hivesql_005 精细评分脚本
2
+
3
+ 业务场景:Notebook 实例跨天 Pod 详情(多表JOIN + 时间切分)
4
+ 难度: HARD | 特征: 6表5JOIN + CTE + UNION + 跨天时间计算
5
+
6
+ 评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)
7
+ A_executability (10分): result.sql 能跑通且产出非空
8
+ B_schema (10分): 22列 + 列名匹配
9
+ C_row_alignment (10分): 行数比例 + key覆盖率
10
+ D_time_calculation (30分): instance_run_time, code_run_time 等时间指标
11
+ D_cross_day_split (15分): trace_001 应出现在两天中
12
+ D_dimension_join (10分): serving_id, pod_name 等维度列匹配
13
+ F_join_completeness (5分): 多表都被关联
14
+ F_insert_overwrite (5分): 写入模式+分区
15
+ F_partition_value (5分): 分区值正确
16
+
17
+ 权重: HARD → product=0.7, process=0.3
18
+ """
19
+ import os
20
+ import re
21
+ import subprocess
22
+ import tempfile
23
+ import json
24
+ import math
25
+
26
+
27
+ def grade(workspace_path, **kwargs):
28
+
29
+ # ========== Case 配置 ==========
30
+ OUTPUT_TABLE = "internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_query_engine_005"
31
+ DIFFICULTY = "HARD"
32
+ SOURCE_TABLES = [
33
+ "notebook_span_info_query_engine_005",
34
+ "dwd_gputj_service_instance_map_query_engine_005",
35
+ "dwd_ml_platform_instance_podname_query_engine_005",
36
+ "gputj_gpu_info_parsed_agg_1min_query_engine_005",
37
+ "notebook_engine_info_query_engine_005",
38
+ ]
39
+ KEY_COLUMNS = ["trace_id", "p_date"]
40
+ EXPECTED_TRACE_DATES = {
41
+ "trace_001": ["2025-05-06", "2025-05-07"],
42
+ "trace_002": ["2025-05-07"],
43
+ }
44
+ TIME_COLUMNS = ["instance_run_time", "code_run_time", "resource_wait_time"]
45
+ DIM_COLUMNS = ["serving_id", "is_permanent", "apply_for_gpu_count", "pod_name"]
46
+ SOURCE_TABLE_SHORT_NAMES = [
47
+ "notebook_span_info",
48
+ "dwd_gputj_service_instance_map",
49
+ "dwd_ml_platform_instance_podname",
50
+ "gputj_gpu_info_parsed_agg_1min",
51
+ "notebook_engine_info",
52
+ ]
53
+ GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
54
+
55
+ DIFFICULTY_WEIGHTS = {
56
+ "EASY": (0.5, 0.5),
57
+ "MEDIUM": (0.6, 0.4),
58
+ "HARD": (0.7, 0.3),
59
+ "EXPERT": (0.8, 0.2),
60
+ }
61
+
62
+ _SPARK_SUBMIT_TIMEOUT = 300
63
+ _JSON_START = "__GRADE_JSON_START__"
64
+ _JSON_END = "__GRADE_JSON_END__"
65
+
66
+ result = {
67
+ "overall_score": 0.0,
68
+ "total_points": 0,
69
+ "grade": "",
70
+ "details": {},
71
+ "diagnostics": [],
72
+ }
73
+
74
+ # ========== 内部辅助函数 ==========
75
+
76
+ def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
77
+ if pred_val is None and gt_val is None:
78
+ return True
79
+ if pred_val is None or gt_val is None:
80
+ return False
81
+ s_pred = str(pred_val).strip()
82
+ s_gt = str(gt_val).strip()
83
+ if s_pred == s_gt:
84
+ return True
85
+ try:
86
+ pv = float(s_pred)
87
+ gv = float(s_gt)
88
+ if math.isnan(pv) and math.isnan(gv):
89
+ return True
90
+ if math.isnan(pv) or math.isnan(gv):
91
+ return False
92
+ if abs(gv) < abs_tol:
93
+ return abs(pv - gv) <= abs_tol
94
+ return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
95
+ except (ValueError, TypeError):
96
+ pass
97
+ return s_pred.lower() == s_gt.lower()
98
+
99
+ def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
100
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
101
+ f.write(script_code)
102
+ script_path = f.name
103
+ try:
104
+ r = subprocess.run(
105
+ ["spark-submit", script_path],
106
+ capture_output=True, text=True, timeout=timeout,
107
+ )
108
+ stdout = r.stdout or ""
109
+ if _JSON_START in stdout and _JSON_END in stdout:
110
+ json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
111
+ return json.loads(json_str), None
112
+ else:
113
+ if r.returncode == 0:
114
+ for line in stdout.splitlines():
115
+ if line.strip().startswith("Traceback"):
116
+ return None, f"spark-submit error: {line}"
117
+ return None, "spark-submit 无 JSON 输出"
118
+ err_msg = (r.stderr or "")[-500:]
119
+ return None, f"spark-submit failed: {err_msg}"
120
+ except subprocess.TimeoutExpired:
121
+ return None, f"spark-submit 超时 ({timeout}s)"
122
+ except Exception as e:
123
+ return None, f"spark-submit 异常: {e}"
124
+ finally:
125
+ try:
126
+ os.unlink(script_path)
127
+ except OSError:
128
+ pass
129
+
130
+ def read_table_via_spark_submit(table_name):
131
+ """Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
132
+ if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
133
+ raise ValueError(f"非���表名: {table_name}")
134
+ read_script = f'''
135
+ import json
136
+ from pyspark.sql import SparkSession
137
+ spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
138
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
139
+ try:
140
+ df = spark.sql("SELECT * FROM {table_name}")
141
+ cols = [c.lower() for c in df.columns]
142
+ rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
143
+ print("{_JSON_START}")
144
+ print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
145
+ print("{_JSON_END}")
146
+ except Exception as e:
147
+ print("{_JSON_START}")
148
+ print(json.dumps({{"error": str(e)}}))
149
+ print("{_JSON_END}")
150
+ finally:
151
+ spark.stop()
152
+ '''
153
+ data, err = _run_spark_script(read_script)
154
+ if err:
155
+ raise RuntimeError(f"read_table failed: {err}")
156
+ if "error" in data:
157
+ raise RuntimeError(f"query failed: {data['error']}")
158
+ return data["cols"], data["rows"]
159
+
160
+ # SQL executor template (self-contained, no external dependency)
161
+ _SQL_EXEC_TEMPLATE = '''
162
+ import json, re
163
+ from pyspark.sql import SparkSession
164
+ spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
165
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
166
+ try:
167
+ with open("{sql_file}", "r", encoding="utf-8") as _f:
168
+ _sql = _f.read()
169
+ _sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
170
+ _stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
171
+ while _i < len(_sql):
172
+ _ch = _sql[_i]
173
+ if _ch == "\\\\" and _i + 1 < len(_sql):
174
+ _cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
175
+ if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
176
+ while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
177
+ _cur.append("\\n"); continue
178
+ if _ch == "'" and not _in_dq: _in_sq = not _in_sq
179
+ elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
180
+ if _ch == ";" and not _in_sq and not _in_dq:
181
+ _s = "".join(_cur).strip()
182
+ if _s: _stmts.append(_s)
183
+ _cur = []
184
+ else:
185
+ _cur.append(_ch)
186
+ _i += 1
187
+ _last = "".join(_cur).strip()
188
+ if _last: _stmts.append(_last)
189
+ for _stmt in _stmts:
190
+ spark.sql(_stmt)
191
+ print("{_JSON_START}")
192
+ print(json.dumps({{"ok": True}}))
193
+ print("{_JSON_END}")
194
+ except Exception as e:
195
+ print("{_JSON_START}")
196
+ print(json.dumps({{"ok": False, "error": str(e)}}))
197
+ print("{_JSON_END}")
198
+ finally:
199
+ spark.stop()
200
+ '''
201
+
202
+ def execute_result_sql():
203
+ result_sql = os.path.join(workspace_path, "result.sql")
204
+ if not os.path.exists(result_sql):
205
+ return False, "no_result_file"
206
+ # 替换 数据平台WD时间变量(沙箱 spark-sql 不支持 ${...} 语法)
207
+ with open(result_sql, 'r', encoding='utf-8') as _rf:
208
+ _sql_text = _rf.read()
209
+ _bizdate = '20260507'
210
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
211
+ _sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
212
+ _sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
213
+ _sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
214
+ with open(result_sql, 'w', encoding='utf-8') as _wf:
215
+ _wf.write(_sql_text)
216
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
217
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
218
+ data, err = _run_spark_script(script)
219
+ if err:
220
+ return False, f"execution_error: {err}"
221
+ if data and data.get("ok"):
222
+ return True, None
223
+ return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
224
+
225
+ def execute_ground_truth_sql():
226
+ gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
227
+ if not os.path.exists(gt_sql):
228
+ return False, "ground_truth.sql not found"
229
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
230
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
231
+ data, err = _run_spark_script(script)
232
+ if err:
233
+ return False, f"gt_execution_error: {err}"
234
+ if data and data.get("ok"):
235
+ return True, None
236
+ return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
237
+
238
+ def truncate_table(table_name):
239
+ script = f'''
240
+ from pyspark.sql import SparkSession
241
+ spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
242
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
243
+ spark.sql("TRUNCATE TABLE {table_name}")
244
+ spark.stop()
245
+ '''
246
+ try:
247
+ _run_spark_script(script, timeout=120)
248
+ except Exception:
249
+ pass
250
+
251
+ def restore_hive_site():
252
+ """Restore hive-site.xml to canonical state (agent may have modified it)."""
253
+ canonical_hive_site = '''<?xml version="1.0"?>
254
+ <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
255
+ <configuration>
256
+ <property>
257
+ <name>hive.metastore.uris</name>
258
+ <value>thrift://localhost:9083</value>
259
+ </property>
260
+ <property>
261
+ <name>hive.metastore.warehouse.dir</name>
262
+ <value>/tmp/hive_warehouse</value>
263
+ </property>
264
+ <property>
265
+ <name>javax.jdo.option.ConnectionURL</name>
266
+ <value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
267
+ </property>
268
+ <property>
269
+ <name>javax.jdo.option.ConnectionDriverName</name>
270
+ <value>org.apache.derby.jdbc.EmbeddedDriver</value>
271
+ </property>
272
+ <property>
273
+ <name>datanucleus.schema.autoCreateAll</name>
274
+ <value>true</value>
275
+ </property>
276
+ <property>
277
+ <name>hive.metastore.schema.verification</name>
278
+ <value>false</value>
279
+ </property>
280
+ </configuration>
281
+ '''
282
+ hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
283
+ try:
284
+ with open(hive_site_path, 'w') as f:
285
+ f.write(canonical_hive_site)
286
+ except Exception:
287
+ pass
288
+
289
+ def finalize(result):
290
+ product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
291
+ product_dims = ["A_executability"] + ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_dimension_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']
292
+ product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
293
+ product_ratio = product_raw / 100.0
294
+ for dim in ["H_efficiency"]:
295
+ if dim in result["details"]:
296
+ raw = result["details"][dim].get("score", 0)
297
+ result["details"][dim]["score_before_scaling"] = raw
298
+ result["details"][dim]["score"] = round(raw * product_ratio, 2)
299
+ result["details"][dim]["product_ratio"] = round(product_ratio, 4)
300
+ process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
301
+ process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
302
+ product_score = round(product_raw * product_weight, 2)
303
+ process_score = round(process_raw * process_weight, 2)
304
+ total = round(product_score + process_score, 2)
305
+ result["total_points"] = total
306
+ result["product_points"] = product_score
307
+ result["process_points"] = round(process_score, 2)
308
+ result["weights"] = {"product": product_weight, "process": process_weight}
309
+ result["overall_score"] = round(total / 100.0, 4)
310
+ if total >= 90:
311
+ result["grade"] = "优秀"
312
+ elif total >= 75:
313
+ result["grade"] = "良好"
314
+ elif total >= 60:
315
+ result["grade"] = "合格"
316
+ elif total >= 40:
317
+ result["grade"] = "偏弱"
318
+ else:
319
+ result["grade"] = "不合格"
320
+ return result
321
+
322
+ # Restore hive-site.xml (agent may have modified it)
323
+ restore_hive_site()
324
+
325
+ # ========== A. 可执行性 (10分) ==========
326
+ a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
327
+ exec_ok, exec_err = execute_result_sql()
328
+ if not exec_ok:
329
+ detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
330
+ result["details"]["A_executability"] = {"score": 0, "max": 10, "detail": detail}
331
+ result["error"] = detail
332
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_dimension_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
333
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
334
+ return finalize(result)
335
+
336
+ a_items["A1_exec_ok"] = 5
337
+
338
+ pred_headers, pred_rows = [], []
339
+ try:
340
+ pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
341
+ except Exception as e:
342
+ result["diagnostics"].append(f"read_pred_failed: {e}")
343
+
344
+ if not pred_rows:
345
+ result["details"]["A_executability"] = {"score": 5, "max": 10, "items": a_items}
346
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_dimension_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
347
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
348
+ return finalize(result)
349
+
350
+ a_items["A2_has_data"] = 5
351
+ result["details"]["A_executability"] = {"score": 10, "max": 10, "items": a_items}
352
+
353
+ # ========== Execute GT + Read GT ==========
354
+ truncate_table(GT_TABLE)
355
+ gt_ok, gt_err = execute_ground_truth_sql()
356
+ if not gt_ok:
357
+ result["error"] = f"ground_truth failed: {gt_err}"
358
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_dimension_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
359
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
360
+ return finalize(result)
361
+
362
+ gt_headers, gt_rows = [], []
363
+ try:
364
+ gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
365
+ except Exception as e:
366
+ result["error"] = f"read_gt_failed: {e}"
367
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_dimension_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
368
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
369
+ return finalize(result)
370
+
371
+ # ========== B/C/D/F 维度评分 ==========
372
+ pred_col_map = {h: i for i, h in enumerate(pred_headers)}
373
+ gt_col_map = {h: i for i, h in enumerate(gt_headers)}
374
+
375
+ # ========== B. Schema正确性 (10分) ==========
376
+ b_items = {}
377
+ expected_col_count = 22
378
+ if len(pred_headers) == expected_col_count:
379
+ b_items["B1_col_count"] = 5
380
+ elif abs(len(pred_headers) - expected_col_count) <= 2:
381
+ b_items["B1_col_count"] = 3
382
+ else:
383
+ b_items["B1_col_count"] = 0
384
+
385
+ gt_col_set = set(gt_headers)
386
+ pred_col_set = set(pred_headers)
387
+ name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
388
+ if name_match_rate >= 0.95:
389
+ b_items["B2_col_names"] = 5
390
+ elif name_match_rate >= 0.8:
391
+ b_items["B2_col_names"] = 3
392
+ else:
393
+ b_items["B2_col_names"] = 0
394
+
395
+ b_score = sum(b_items.values())
396
+ result["details"]["B_schema"] = {
397
+ "score": b_score, "max": 10,
398
+ "detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
399
+ }
400
+
401
+ # ========== C. 行一致性 (10分) ==========
402
+ c_items = {}
403
+ gt_row_count = len(gt_rows)
404
+ pred_row_count = len(pred_rows)
405
+
406
+ if gt_row_count > 0:
407
+ ratio = pred_row_count / gt_row_count
408
+ if 0.95 <= ratio <= 1.05:
409
+ c_items["C1_row_ratio"] = 5
410
+ elif 0.7 <= ratio <= 1.3:
411
+ c_items["C1_row_ratio"] = 3
412
+ else:
413
+ c_items["C1_row_ratio"] = 0
414
+ else:
415
+ c_items["C1_row_ratio"] = 5 if pred_row_count == 0 else 0
416
+
417
+ key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
418
+ if key_cols_avail and gt_row_count > 0:
419
+ gt_keys = set()
420
+ for row in gt_rows:
421
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
422
+ gt_keys.add(key)
423
+ pred_keys = set()
424
+ for row in pred_rows:
425
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
426
+ pred_keys.add(key)
427
+ coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
428
+ if coverage >= 0.995:
429
+ c_items["C2_key_coverage"] = 5
430
+ elif coverage >= 0.9:
431
+ c_items["C2_key_coverage"] = 3
432
+ elif coverage >= 0.7:
433
+ c_items["C2_key_coverage"] = 2
434
+ else:
435
+ c_items["C2_key_coverage"] = round(5 * coverage, 2)
436
+ else:
437
+ c_items["C2_key_coverage"] = 0
438
+
439
+ c_score = sum(v for v in c_items.values())
440
+ result["details"]["C_row_alignment"] = {"score": c_score, "max": 10, "detail": c_items}
441
+
442
+ # 构建 GT/pred 索引
443
+ gt_index = {}
444
+ gt_trace_idx = gt_col_map.get("trace_id")
445
+ gt_pdate_idx = gt_col_map.get("p_date")
446
+ if gt_trace_idx is not None and gt_pdate_idx is not None:
447
+ for row in gt_rows:
448
+ tid = row[gt_trace_idx].strip() if gt_trace_idx < len(row) else ""
449
+ pd = row[gt_pdate_idx].strip() if gt_pdate_idx < len(row) else ""
450
+ gt_index[(tid, pd)] = row
451
+
452
+ pred_index = {}
453
+ trace_idx = pred_col_map.get("trace_id")
454
+ pdate_idx = pred_col_map.get("p_date")
455
+ if trace_idx is not None and pdate_idx is not None:
456
+ for row in pred_rows:
457
+ if trace_idx >= len(row) or pdate_idx >= len(row):
458
+ continue
459
+ tid = row[trace_idx].strip()
460
+ pd = row[pdate_idx].strip()
461
+ pred_index[(tid, pd)] = row
462
+
463
+ # ========== D. 时间计算正确性 (30分) ==========
464
+ d_time_items = {}
465
+ per_col_weight = 30.0 / max(len(TIME_COLUMNS), 1)
466
+ for col in TIME_COLUMNS:
467
+ gt_ci = gt_col_map.get(col)
468
+ pred_ci = pred_col_map.get(col)
469
+ if gt_ci is None or pred_ci is None:
470
+ d_time_items[col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
471
+ continue
472
+
473
+ matches = 0
474
+ total = 0
475
+ for key, gt_row in gt_index.items():
476
+ pred_row = pred_index.get(key)
477
+ if pred_row is None:
478
+ total += 1
479
+ continue
480
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
481
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
482
+ if values_match(pred_val, gt_val, abs_tol=1.0, rel_tol=0.01):
483
+ matches += 1
484
+ total += 1
485
+
486
+ rate = matches / max(total, 1)
487
+ col_score = rate * per_col_weight
488
+ d_time_items[col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2)}
489
+
490
+ d_time_score = sum(v.get("score", 0) for v in d_time_items.values() if isinstance(v, dict))
491
+ result["details"]["D_time_calculation"] = {"score": round(d_time_score, 2), "max": 30, "detail": d_time_items}
492
+
493
+ # ========== D. 跨天切分正确性 (15分) ==========
494
+ d_cross_items = {}
495
+ d_cross_score = 0
496
+
497
+ if trace_idx is not None and pdate_idx is not None:
498
+ pred_trace_dates = {}
499
+ for row in pred_rows:
500
+ tid = row[trace_idx].strip() if trace_idx < len(row) else ""
501
+ pd = row[pdate_idx].strip() if pdate_idx < len(row) else ""
502
+ if tid not in pred_trace_dates:
503
+ pred_trace_dates[tid] = set()
504
+ pred_trace_dates[tid].add(pd)
505
+
506
+ # trace_001 应跨两天 (8分)
507
+ t001_dates = pred_trace_dates.get("trace_001", set())
508
+ if len(t001_dates) >= 2:
509
+ d_cross_score += 8
510
+ d_cross_items["trace_001_cross_day"] = True
511
+ elif len(t001_dates) == 1:
512
+ d_cross_score += 3
513
+ d_cross_items["trace_001_cross_day"] = f"only {t001_dates}"
514
+ else:
515
+ d_cross_items["trace_001_cross_day"] = False
516
+
517
+ # trace_002 只出现一天 (4分)
518
+ t002_dates = pred_trace_dates.get("trace_002", set())
519
+ if len(t002_dates) == 1:
520
+ d_cross_score += 4
521
+ d_cross_items["trace_002_single_day"] = True
522
+ else:
523
+ d_cross_items["trace_002_single_day"] = f"dates={t002_dates}"
524
+
525
+ # 行数正确 (3分)
526
+ if pred_row_count == gt_row_count:
527
+ d_cross_score += 3
528
+ d_cross_items["row_count_correct"] = True
529
+ elif abs(pred_row_count - gt_row_count) <= 1:
530
+ d_cross_score += 2
531
+ d_cross_items["row_count_correct"] = f"off by {abs(pred_row_count - gt_row_count)}"
532
+ else:
533
+ d_cross_items["error"] = "trace_id or p_date column missing"
534
+
535
+ result["details"]["D_cross_day_split"] = {"score": d_cross_score, "max": 15, "detail": d_cross_items}
536
+
537
+ # ========== D. 维度列关联正确性 (10分) ==========
538
+ d_dim_items = {}
539
+ for col in DIM_COLUMNS:
540
+ gt_ci = gt_col_map.get(col)
541
+ pred_ci = pred_col_map.get(col)
542
+ if gt_ci is None or pred_ci is None:
543
+ continue
544
+ matches = 0
545
+ total = 0
546
+ for key, gt_row in gt_index.items():
547
+ pred_row = pred_index.get(key)
548
+ if pred_row is None:
549
+ total += 1
550
+ continue
551
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
552
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
553
+ if values_match(pred_val, gt_val):
554
+ matches += 1
555
+ total += 1
556
+ rate = matches / max(total, 1)
557
+ d_dim_items[col] = round(rate, 4)
558
+
559
+ d_dim_score = 0
560
+ if d_dim_items:
561
+ avg_rate = sum(d_dim_items.values()) / len(d_dim_items)
562
+ d_dim_score = round(10 * avg_rate, 2)
563
+ result["details"]["D_dimension_join"] = {"score": d_dim_score, "max": 10, "detail": d_dim_items}
564
+
565
+ # ========== F. JOIN 完整性 (5分) ==========
566
+ f_join_items = {}
567
+ result_sql_path = os.path.join(workspace_path, "result.sql")
568
+ sql_text = ""
569
+ try:
570
+ with open(result_sql_path, "r", encoding="utf-8") as f:
571
+ sql_text = f.read().lower()
572
+ except Exception:
573
+ sql_text = ""
574
+
575
+ tables_found = 0
576
+ for tname in SOURCE_TABLES:
577
+ if tname.lower() in sql_text:
578
+ tables_found += 1
579
+ f_join_items[tname] = True
580
+ else:
581
+ f_join_items[tname] = False
582
+
583
+ f_join_score = round(5 * tables_found / max(len(SOURCE_TABLES), 1), 2)
584
+ result["details"]["F_join_completeness"] = {
585
+ "score": f_join_score, "max": 5, "detail": f_join_items,
586
+ }
587
+
588
+ # ========== F. INSERT OVERWRITE (5分) ==========
589
+ f_insert_items = {}
590
+ has_overwrite = "insert overwrite" in sql_text
591
+ has_partition = "partition" in sql_text
592
+ if has_overwrite and has_partition:
593
+ f_insert_items["insert_overwrite_partition"] = 5
594
+ elif has_overwrite:
595
+ f_insert_items["insert_overwrite_partition"] = 3
596
+ else:
597
+ f_insert_items["insert_overwrite_partition"] = 0
598
+ result["details"]["F_insert_overwrite"] = {
599
+ "score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
600
+ }
601
+
602
+ # ========== F. 分区值 (5分) ==========
603
+ f_part_items = {}
604
+ if ("dt" in sql_text and ("20260507" in sql_text or "2026050" in sql_text)) or "p_date" in sql_text:
605
+ f_part_items["partition_value"] = 5
606
+ else:
607
+ f_part_items["partition_value"] = 0
608
+ result["details"]["F_partition_value"] = {
609
+ "score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
610
+ }
611
+
612
+ # 汇总
613
+ total = 10 + b_score + c_score + d_time_score + d_cross_score + d_dim_score + f_join_score + f_insert_items["insert_overwrite_partition"] + f_part_items["partition_value"]
614
+
615
+ # ========== G~I 过程评分 ==========
616
+ TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
617
+ OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
618
+ INPUT_TABLE_SHORT = SOURCE_TABLES[0]
619
+
620
+ transcript_entries = []
621
+ has_transcript = False
622
+ try:
623
+ if os.path.exists(TRANSCRIPT_PATH):
624
+ with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f:
625
+ for line in f:
626
+ line = line.strip()
627
+ if line:
628
+ try:
629
+ transcript_entries.append(json.loads(line))
630
+ except json.JSONDecodeError:
631
+ continue
632
+ if len(transcript_entries) > 2:
633
+ has_transcript = True
634
+ except Exception:
635
+ pass
636
+
637
+ if not has_transcript:
638
+ result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}}
639
+ result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}}
640
+ result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}}
641
+ return finalize(result)
642
+
643
+ # Parse transcript into structured events
644
+ tool_uses = []
645
+ first_write_result_idx = None
646
+ last_spark_submit_success_idx = None
647
+ write_result_count = 0
648
+ logic_error_retries = 0
649
+
650
+ for idx, entry in enumerate(transcript_entries):
651
+ content = entry.get("content", [])
652
+ if isinstance(content, str):
653
+ content = [content]
654
+
655
+ for block_str in content:
656
+ if not isinstance(block_str, str):
657
+ continue
658
+ if "ToolUseBlock" in block_str:
659
+ name_match = re.search(r"name='([^']+)'", block_str)
660
+ input_match = re.search(r"input=(\{.*\})", block_str)
661
+ if name_match:
662
+ tool_name = name_match.group(1)
663
+ tool_input = input_match.group(1) if input_match else ""
664
+ tool_uses.append((idx, tool_name, tool_input))
665
+ if tool_name == "Write" and "result.sql" in tool_input:
666
+ write_result_count += 1
667
+ if first_write_result_idx is None:
668
+ first_write_result_idx = idx
669
+ if "ToolResultBlock" in block_str:
670
+ if "Traceback" in block_str or "Exception" in block_str:
671
+ env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
672
+ "db.lck", "TTransportException", "port 10000"]
673
+ is_env_error = any(e in block_str for e in env_errors)
674
+ has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
675
+ for t in tool_uses)
676
+ if not is_env_error and has_spark_submit:
677
+ logic_error_retries += 1
678
+ if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" in block_str:
679
+ if "Exit Code: 0" in block_str and "Traceback" not in block_str:
680
+ last_spark_submit_success_idx = idx
681
+
682
+ before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
683
+
684
+ # ===== G. 探索充分性 (35分) =====
685
+ g_items = {}
686
+ g1_pass = any(name == "Read" and "schema" in inp.lower()
687
+ for idx, name, inp in tool_uses if idx < before_first_write)
688
+ g_items["G1_source_schema"] = 9 if g1_pass else 0
689
+
690
+ g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
691
+ and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
692
+ for idx, name, inp in tool_uses if idx < before_first_write)
693
+ g_items["G2_source_sample"] = 9 if g2_pass else 0
694
+
695
+ g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
696
+ and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
697
+ for idx, name, inp in tool_uses if idx < before_first_write)
698
+ g_items["G3_distribution"] = 9 if g3_pass else 0
699
+
700
+ g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
701
+ and OUTPUT_TABLE_SHORT in inp
702
+ for idx, name, inp in tool_uses if idx < before_first_write)
703
+ g_items["G4_target_schema"] = 8 if g4_pass else 0
704
+
705
+ g_score = sum(g_items.values())
706
+ result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
707
+
708
+ # ===== H. 执行效率 (40分) =====
709
+ h_items = {}
710
+ if write_result_count <= 2:
711
+ h_items["H1_few_submissions"] = 20
712
+ elif write_result_count <= 4:
713
+ h_items["H1_few_submissions"] = 13
714
+ elif write_result_count <= 6:
715
+ h_items["H1_few_submissions"] = 7
716
+ else:
717
+ h_items["H1_few_submissions"] = 0
718
+
719
+ if logic_error_retries == 0:
720
+ h_items["H2_no_logic_errors"] = 13
721
+ elif logic_error_retries <= 1:
722
+ h_items["H2_no_logic_errors"] = 7
723
+ else:
724
+ h_items["H2_no_logic_errors"] = 0
725
+
726
+ h_items["H3_no_redundancy"] = 7
727
+ h_score = sum(h_items.values())
728
+ result["details"]["H_efficiency"] = {"score": min(h_score, 40), "max": 40, "items": h_items}
729
+
730
+ # ===== I. 自验证行为 (25分) =====
731
+ i_items = {}
732
+ post_submit_uses = []
733
+ if last_spark_submit_success_idx is not None:
734
+ post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
735
+ if idx > last_spark_submit_success_idx]
736
+
737
+ i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
738
+ for _, name, inp in post_submit_uses)
739
+ i_items["I1_query_output"] = 8 if i1_pass else 0
740
+
741
+ i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
742
+ and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
743
+ for _, name, inp in post_submit_uses)
744
+ i_items["I2_check_count"] = 9 if i2_pass else 0
745
+
746
+ i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
747
+ and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper())
748
+ for _, name, inp in post_submit_uses)
749
+ i_items["I3_check_values"] = 8 if i3_pass else 0
750
+
751
+ i_score = sum(i_items.values())
752
+ result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items}
753
+
754
+ return finalize(result)
tasks/offline-compute/HiveSQL/hivesql_002/gt/grade_spec.csv ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 维度,维度全名,子维度,满分,说明
2
+ A,A_executability,executability,10,result.sql 能跑通且产出非空
3
+ B,B_schema,schema,10,22列 + 列名匹配
4
+ C,C_row_alignment,row_consistency,10,行数比例 + key覆盖率
5
+ D,D_time_calculation,time_calculation,30,"instance_run_time, code_run_time 等时间指标"
6
+ D,D_cross_day_split,cross_day_split,15,trace_001 应出现在两天中
7
+ D,D_dimension_join,dimension_join,10,"serving_id, pod_name 等维度列匹配"
8
+ F,F_join_completeness,join_completeness,5,多表都被关联
9
+ F,F_insert_overwrite,insert_overwrite,5,写入模式+分区
10
+ F,F_partition_value,partition_value,5,分区值正确
11
+
12
+ 总计,,,100,
13
+
14
+ # 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)
15
+ # 难度,HARD
16
+ # 权重,"product=0.7, process=0.3"
17
+ # 范式,new
18
+ # Key列,"trace_id, p_date"
19
+ # 预期列数,
20
+ # 输出表,internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_query_engine_005
tasks/offline-compute/HiveSQL/hivesql_002/gt/ground_truth.sql ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INSERT overwrite TABLE internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_query_engine_005 PARTITION (dt = '20260507')
2
+ WITH
3
+ base_data_raw AS (
4
+ SELECT DISTINCT
5
+ trace_id,
6
+ span_name,
7
+ start_time,
8
+ end_time,
9
+ datawd_project_id,
10
+ datawd_task_id,
11
+ datawd_task_instance_id,
12
+ compute_type,
13
+ status_code
14
+ FROM internal_platform_db.notebook_span_info_query_engine_005
15
+ WHERE databus_imp_date >= '2026050400'
16
+ AND databus_imp_date <= '2026050700'
17
+ AND trace_id IN (
18
+ SELECT trace_id
19
+ FROM internal_platform_db.notebook_span_info_query_engine_005
20
+ WHERE databus_imp_date >= '2026050700'
21
+ AND databus_imp_date <= '2026050700'
22
+ AND compute_type = 'ray'
23
+ AND service_name = 'notebook-runner'
24
+ AND span_name = 'runner.execute'
25
+ GROUP BY trace_id
26
+ )
27
+ AND (
28
+ span_name = 'runner.execute'
29
+ OR
30
+ span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute', 'runner.killed')
31
+ )
32
+ ),
33
+ base_data_time_fixed AS (
34
+ SELECT
35
+ trace_id,
36
+ span_name,
37
+ CASE
38
+ WHEN span_name = 'runner.killed'
39
+ THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)
40
+ OVER(PARTITION BY trace_id)
41
+ ELSE start_time
42
+ END AS start_time,
43
+ CASE
44
+ WHEN span_name = 'runner.execute'
45
+ THEN MAX(CASE WHEN span_name IN ('runner.execute', 'runner.killed') THEN end_time END)
46
+ OVER(PARTITION BY trace_id)
47
+ ELSE end_time
48
+ END AS end_time,
49
+ datawd_project_id,
50
+ datawd_task_id,
51
+ datawd_task_instance_id,
52
+ compute_type,
53
+ status_code
54
+ FROM base_data_raw
55
+ ),
56
+ base_data AS (
57
+ SELECT
58
+ trace_id,
59
+ span_name,
60
+ start_time,
61
+ end_time,
62
+ datawd_project_id,
63
+ datawd_task_id,
64
+ datawd_task_instance_id,
65
+ compute_type,
66
+ status_code,
67
+ from_unixtime(CAST(start_time AS BIGINT) / 1000) as start_date,
68
+ from_unixtime(CAST(end_time AS BIGINT) / 1000) as end_date,
69
+ datediff(from_unixtime(CAST(end_time AS BIGINT) / 1000), from_unixtime(CAST(start_time AS BIGINT) / 1000)) AS diff_days
70
+ FROM base_data_time_fixed
71
+ ),
72
+ pos_series AS (
73
+ SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos
74
+ ),
75
+ daily_split_spans AS (
76
+ SELECT
77
+ trace_id,
78
+ span_name,
79
+ datawd_project_id,
80
+ datawd_task_id,
81
+ datawd_task_instance_id,
82
+ compute_type,
83
+ status_code,
84
+ start_date,
85
+ end_date,
86
+ diff_days,
87
+ date_add(b.start_date, s.pos) AS calc_date,
88
+ CASE WHEN s.pos = 0 THEN CAST(b.start_time AS BIGINT)
89
+ ELSE unix_timestamp(cast(date_add(b.start_date, s.pos) as timestamp)) * 1000
90
+ END AS start_time,
91
+ CASE WHEN s.pos = b.diff_days THEN CAST(b.end_time AS BIGINT)
92
+ ELSE (unix_timestamp(cast(date_add(b.start_date, s.pos + 1) as timestamp)) * 1000) - 1
93
+ END AS end_time,
94
+ CAST(b.start_time AS BIGINT) AS span_start_time,
95
+ CAST(b.end_time AS BIGINT) AS span_end_time
96
+ FROM base_data b
97
+ INNER JOIN pos_series s ON s.pos <= b.diff_days
98
+ ),
99
+ trace_time_metrics AS (
100
+ SELECT
101
+ trace_id,
102
+ calc_date,
103
+ MAX(datawd_project_id) AS datawd_project_id,
104
+ MAX(datawd_task_id) AS datawd_task_id,
105
+ MAX(datawd_task_instance_id) AS datawd_task_instance_id,
106
+ MAX(compute_type) AS compute_type,
107
+ MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,
108
+ ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN end_time END) -
109
+ MIN(CASE WHEN span_name = 'runner.execute' THEN start_time END)) / 1000.0) AS instance_run_time,
110
+ ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN end_time END) -
111
+ MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN start_time END)) / 1000.0) AS code_run_time,
112
+ ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN end_time END) -
113
+ MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN start_time END)) / 1000.0) AS resource_wait_time,
114
+ from_unixtime(MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN start_time END) / 1000) AS code_start_time,
115
+ from_unixtime(MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN end_time END) / 1000) AS code_end_time,
116
+ from_unixtime(MIN(CASE WHEN span_name = 'runner.execute' THEN span_start_time END) / 1000) AS instance_start_time,
117
+ from_unixtime(MAX(CASE WHEN span_name = 'runner.execute' THEN span_end_time END) / 1000) AS instance_end_time
118
+ FROM daily_split_spans
119
+ GROUP BY trace_id, calc_date
120
+ ),
121
+ gputj_dim AS (
122
+ SELECT
123
+ t1.service_id,
124
+ t2.pod_name
125
+ FROM internal_platform_db.dwd_gputj_service_instance_map_query_engine_005 t1
126
+ INNER JOIN internal_platform_db.dwd_ml_platform_instance_podname_query_engine_005 t2
127
+ ON t1.instance_uuid = t2.instance_uuid
128
+ AND t1.dt=if('2026050700'>='2025080900', '2026050700', '2025080900')
129
+ AND t2.dt=if('2026050700'>='2025060519', '2026050700', '2025060519')
130
+ GROUP BY t1.service_id, t2.pod_name
131
+ ),
132
+ gpu_metrics AS (
133
+ select
134
+ pkg_agg_time,
135
+ pod_name,
136
+ k8s_container_vgpu_gpu_util_sum / k8s_container_vgpu_gpu_util_count AS gpu_util,
137
+ k8s_container_resource_request_gpu_sum / k8s_container_resource_request_gpu_count AS gpu_count
138
+ from internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_005
139
+ where dt >= '2026050400'
140
+ AND dt <= '2026050700'
141
+ AND ( k8s_container_vgpu_gpu_util_count > 0 OR k8s_container_resource_request_gpu_count > 0 )
142
+ AND pod_name IS NOT NULL
143
+ )
144
+ SELECT
145
+ t1.trace_id,
146
+ t1.datawd_project_id,
147
+ t1.datawd_task_id,
148
+ t1.datawd_task_instance_id,
149
+ t1.compute_type,
150
+ t1.status_code,
151
+ t1.instance_run_time,
152
+ t1.code_run_time,
153
+ t1.resource_wait_time,
154
+ t1.code_start_time,
155
+ t1.code_end_time,
156
+ t1.instance_start_time,
157
+ t1.instance_end_time,
158
+ t2.serving_id,
159
+ t2.is_permanent,
160
+ t2.apply_for_gpu_count,
161
+ t3.pod_name,
162
+ t4.pkg_agg_time,
163
+ t4.gpu_util,
164
+ t4.gpu_count,
165
+ t1.calc_date AS p_date
166
+ FROM trace_time_metrics t1 LEFT JOIN (
167
+ SELECT
168
+ trace_id,
169
+ MAX(serving_id) AS serving_id,
170
+ MAX(is_permanent) AS is_permanent,
171
+ SUM(CAST(replicas AS INT) * CAST(num_gpu AS INT)) AS apply_for_gpu_count
172
+ FROM internal_platform_db.notebook_engine_info_query_engine_005
173
+ WHERE databus_imp_date >= '2026050400'
174
+ AND databus_imp_date <= '2026050700'
175
+ AND compute_type = 'ray'
176
+ AND service_name = 'notebook-runner'
177
+ GROUP BY trace_id
178
+ ) t2 ON t1.trace_id = t2.trace_id
179
+ LEFT JOIN gputj_dim t3 ON t2.serving_id = t3.service_id
180
+ LEFT JOIN gpu_metrics t4
181
+ ON t3.pod_name = t4.pod_name
182
+ AND (
183
+ CASE
184
+ WHEN t1.instance_start_time IS NOT NULL AND t1.instance_end_time IS NOT NULL
185
+ THEN t4.pkg_agg_time >= t1.instance_start_time AND t4.pkg_agg_time <= t1.instance_end_time
186
+ WHEN t1.code_start_time IS NOT NULL AND t1.code_end_time IS NOT NULL
187
+ THEN t4.pkg_agg_time >= t1.code_start_time AND t4.pkg_agg_time <= t1.code_end_time
188
+ ELSE FALSE
189
+ END
190
+ )
191
+ ;
tasks/offline-compute/HiveSQL/hivesql_002/init/init_db.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import re
3
+ from pyspark.sql import SparkSession
4
+
5
+ spark = SparkSession.builder \
6
+ .appName('hivesql_bench_init') \
7
+ .enableHiveSupport() \
8
+ .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \
9
+ .getOrCreate()
10
+
11
+ spark.sql('CREATE DATABASE IF NOT EXISTS internal_platform_db')
12
+
13
+
14
+ def _execute_sql_file(spark, sql_path):
15
+ """Read SQL file, remove SuperSQL SET headers, split by semicolons, execute."""
16
+ with open(sql_path, 'r', encoding='utf-8') as f:
17
+ content = f.read()
18
+ content = re.sub(r'^\s*set\s+query_engine\.\S+\n?', '', content, flags=re.IGNORECASE)
19
+ stmts, cur, in_sq, in_dq, i = [], [], False, False, 0
20
+ while i < len(content):
21
+ ch = content[i]
22
+ if ch == '\\' and i + 1 < len(content):
23
+ cur.append(ch); cur.append(content[i + 1]); i += 2; continue
24
+ if ch == '-' and i + 1 < len(content) and content[i + 1] == '-' and not in_sq and not in_dq:
25
+ while i < len(content) and content[i] != '\n':
26
+ i += 1
27
+ cur.append('\n'); continue
28
+ if ch == "'" and not in_dq:
29
+ in_sq = not in_sq
30
+ elif ch == '"' and not in_sq:
31
+ in_dq = not in_dq
32
+ if ch == ';' and not in_sq and not in_dq:
33
+ s = ''.join(cur).strip()
34
+ if s:
35
+ stmts.append(s)
36
+ cur = []
37
+ else:
38
+ cur.append(ch)
39
+ i += 1
40
+ last = ''.join(cur).strip()
41
+ if last:
42
+ stmts.append(last)
43
+ for stmt in stmts:
44
+ spark.sql(stmt)
45
+
46
+
47
+ _execute_sql_file(spark, '/tmp_workspace/init_db.sql')
48
+
49
+ tables = spark.sql('SHOW TABLES IN internal_platform_db').collect()
50
+ print(f'Init complete, {len(tables)} tables created')
51
+ for t in tables:
52
+ print(f' - {t.namespace}.{t.tableName}')
53
+ spark.stop()
tasks/offline-compute/HiveSQL/hivesql_002/init/init_db.sql ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS internal_platform_db;
2
+
3
+ -- Input table 1: notebook_span_info
4
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_span_info_query_engine_005 (
5
+ databus_imp_date STRING,
6
+ trace_id STRING,
7
+ span_kind STRING,
8
+ error_code STRING,
9
+ service_name STRING,
10
+ message STRING,
11
+ parent_span_id STRING,
12
+ span_name STRING,
13
+ duration BIGINT,
14
+ span_id STRING,
15
+ space_id STRING,
16
+ span_type STRING,
17
+ start_time STRING,
18
+ end_time STRING,
19
+ service_instance STRING,
20
+ status_code INT,
21
+ datawd_project_id STRING,
22
+ datawd_task_id STRING,
23
+ datawd_task_instance_id STRING,
24
+ compute_type STRING
25
+ ) STORED AS ORC;
26
+
27
+ INSERT INTO TABLE internal_platform_db.notebook_span_info_query_engine_005 VALUES
28
+ ('2026050700','trace_001','server','0','notebook-runner','','','runner.execute',60000,'s1','sp1','','1746460800000','1746547200000','inst1',0,'proj_1','task_1','inst_1','ray'),
29
+ ('2026050700','trace_001','server','0','notebook-runner','','','execute.code',50000,'s2','sp1','','1746464400000','1746540000000','inst1',0,'proj_1','task_1','inst_1','ray'),
30
+ ('2026050700','trace_001','server','0','notebook-runner','','','set.permanent.compute',5000,'s3','sp1','','1746460800000','1746463200000','inst1',0,'proj_1','task_1','inst_1','ray'),
31
+ ('2026050500','trace_001','server','0','notebook-runner','','','runner.execute',60000,'s4','sp1','','1746460800000','1746547200000','inst1',0,'proj_1','task_1','inst_1','ray'),
32
+ ('2026050500','trace_001','server','0','notebook-runner','','','execute.code',50000,'s5','sp1','','1746464400000','1746540000000','inst1',0,'proj_1','task_1','inst_1','ray'),
33
+ ('2026050700','trace_002','server','0','notebook-runner','','','runner.execute',30000,'s6','sp2','','1746547200000','1746558000000','inst2',1,'proj_2','task_2','inst_2','ray'),
34
+ ('2026050700','trace_002','server','0','notebook-runner','','','execute.code',25000,'s7','sp2','','1746548000000','1746556000000','inst2',1,'proj_2','task_2','inst_2','ray'),
35
+ ('2026050700','trace_002','server','0','notebook-runner','','','create.non.permanent.compute',3000,'s8','sp2','','1746547200000','1746548000000','inst2',1,'proj_2','task_2','inst_2','ray');
36
+
37
+ -- Input table 2: dwd_gputj_service_instance_map
38
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_gputj_service_instance_map_query_engine_005 (
39
+ dt STRING,
40
+ service_name STRING,
41
+ instance_uuid STRING,
42
+ service_id BIGINT,
43
+ version_id BIGINT,
44
+ `desc` STRING,
45
+ create_time DOUBLE,
46
+ update_time DOUBLE,
47
+ workload_name STRING
48
+ ) STORED AS ORC;
49
+
50
+ INSERT INTO TABLE internal_platform_db.dwd_gputj_service_instance_map_query_engine_005 VALUES
51
+ ('2026050700','svc_a','uuid_001',1001,1,'desc1',1.0,2.0,'wl1'),
52
+ ('2026050700','svc_b','uuid_002',1002,1,'desc2',1.0,2.0,'wl2');
53
+
54
+ -- Input table 3: dwd_ml_platform_instance_podname
55
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_ml_platform_instance_podname_query_engine_005 (
56
+ dt STRING,
57
+ instance_uuid STRING,
58
+ pod_name STRING,
59
+ pod_phase STRING,
60
+ pod_create_time BIGINT,
61
+ pod_update_time BIGINT,
62
+ namespace STRING,
63
+ trial_job_name STRING,
64
+ create_time BIGINT,
65
+ modify_time BIGINT,
66
+ fix_modify_time BIGINT
67
+ ) STORED AS ORC;
68
+
69
+ INSERT INTO TABLE internal_platform_db.dwd_ml_platform_instance_podname_query_engine_005 VALUES
70
+ ('2026050700','uuid_001','pod_alpha','Running',1746460000,1746461000,'ns1','job1',1746460000,1746461000,1746461000),
71
+ ('2026050700','uuid_002','pod_beta','Running',1746460000,1746461000,'ns2','job2',1746460000,1746461000,1746461000);
72
+
73
+ -- Input table 4: gputj_gpu_info_parsed_agg_1min (MINIMAL - only columns GT uses)
74
+ CREATE TABLE IF NOT EXISTS internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_005 (
75
+ dt STRING,
76
+ pod_name STRING,
77
+ pkg_agg_time STRING,
78
+ k8s_container_vgpu_gpu_util_sum DOUBLE,
79
+ k8s_container_vgpu_gpu_util_count BIGINT,
80
+ k8s_container_resource_request_gpu_sum DOUBLE,
81
+ k8s_container_resource_request_gpu_count BIGINT
82
+ ) STORED AS ORC;
83
+
84
+ INSERT INTO TABLE internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_005 VALUES
85
+ ('2026050700','pod_alpha','2026-05-06 02:00:00',160.0,2,4.0,2),
86
+ ('2026050600','pod_alpha','2026-05-05 20:00:00',140.0,2,2.0,2);
87
+
88
+ -- Input table 5: notebook_engine_info
89
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_engine_info_query_engine_005 (
90
+ databus_imp_date STRING,
91
+ trace_id STRING,
92
+ service_name STRING,
93
+ compute_type STRING,
94
+ datawd_project_id STRING,
95
+ datawd_task_id STRING,
96
+ datawd_task_instance_id STRING,
97
+ is_permanent STRING,
98
+ serving_id STRING,
99
+ user_name STRING,
100
+ is_model_service STRING,
101
+ compute_info STRING,
102
+ num_gpu STRING,
103
+ replicas STRING,
104
+ gpu_type STRING,
105
+ `timestamp` STRING,
106
+ ray_job_id STRING,
107
+ reason STRING,
108
+ log_url STRING,
109
+ dashboard_url STRING
110
+ ) STORED AS ORC;
111
+
112
+ INSERT INTO TABLE internal_platform_db.notebook_engine_info_query_engine_005 VALUES
113
+ ('2026050700','trace_001','notebook-runner','ray','proj_1','task_1','inst_1','true','1001','user1','false','{}','2','1','A100','1746460800','job1','','',''),
114
+ ('2026050700','trace_002','notebook-runner','ray','proj_2','task_2','inst_2','false','1002','user2','false','{}','1','2','V100','1746547200','job2','','','');
115
+
116
+ -- Target table
117
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_query_engine_005 (
118
+ trace_id STRING,
119
+ datawd_project_id STRING,
120
+ datawd_task_id STRING,
121
+ datawd_task_instance_id STRING,
122
+ compute_type STRING,
123
+ status_code INT,
124
+ instance_run_time INT,
125
+ code_run_time INT,
126
+ resource_wait_time INT,
127
+ code_start_time STRING,
128
+ code_end_time STRING,
129
+ instance_start_time STRING,
130
+ instance_end_time STRING,
131
+ serving_id STRING,
132
+ is_permanent STRING,
133
+ apply_for_gpu_count INT,
134
+ pod_name STRING,
135
+ pkg_agg_time STRING,
136
+ gpu_util DOUBLE,
137
+ gpu_count INT,
138
+ p_date STRING
139
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
140
+
141
+ -- Agent 候选目标表
142
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_query_engine_005 (
143
+ trace_id STRING,
144
+ datawd_project_id STRING,
145
+ datawd_task_id STRING,
146
+ datawd_task_instance_id STRING,
147
+ compute_type STRING,
148
+ status_code INT,
149
+ instance_run_time INT,
150
+ code_run_time INT,
151
+ resource_wait_time INT,
152
+ code_start_time STRING,
153
+ code_end_time STRING,
154
+ instance_start_time STRING,
155
+ instance_end_time STRING,
156
+ serving_id STRING,
157
+ is_permanent STRING,
158
+ apply_for_gpu_count INT,
159
+ pod_name STRING,
160
+ pkg_agg_time STRING,
161
+ gpu_util DOUBLE,
162
+ gpu_count INT,
163
+ p_date STRING
164
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_002/init/schema.sql ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_span_info_copilot (
2
+ `databus_imp_date` STRING COMMENT 'primary partition',
3
+ `trace_id` STRING COMMENT 'trace_id',
4
+ `span_kind` STRING COMMENT 'span_kind',
5
+ `error_code` STRING COMMENT 'error_code',
6
+ `service_name` STRING COMMENT 'service_name',
7
+ `message` STRING COMMENT 'message',
8
+ `parent_span_id` STRING COMMENT 'parent_span_id',
9
+ `span_name` STRING COMMENT 'span_name',
10
+ `duration` BIGINT COMMENT 'duration',
11
+ `span_id` STRING COMMENT 'span_id',
12
+ `space_id` STRING COMMENT 'space_id',
13
+ `span_type` STRING COMMENT 'span_type',
14
+ `start_time` STRING COMMENT 'start_time',
15
+ `end_time` STRING COMMENT 'end_time',
16
+ `service_instance` STRING COMMENT 'service_instance',
17
+ `status_code` INT COMMENT 'status_code',
18
+ `datawd_project_id` STRING COMMENT 'datawd_project_id',
19
+ `datawd_task_id` STRING COMMENT 'datawd_task_id',
20
+ `datawd_task_instance_id` STRING COMMENT 'datawd_task_instance_id',
21
+ `compute_type` STRING COMMENT 'compute_type'
22
+ ) STORED AS ORC;
23
+
24
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_gputj_service_instance_map_copilot (
25
+ `dt` STRING COMMENT '分区字段',
26
+ `service_name` STRING,
27
+ `instance_uuid` STRING,
28
+ `service_id` BIGINT,
29
+ `version_id` BIGINT,
30
+ `desc` STRING,
31
+ `create_time` DOUBLE,
32
+ `update_time` DOUBLE,
33
+ `workload_name` STRING
34
+ ) STORED AS ORC;
35
+
36
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_ml_platform_instance_podname_copilot (
37
+ `dt` STRING COMMENT '分区字段',
38
+ `instance_uuid` STRING,
39
+ `pod_name` STRING,
40
+ `pod_phase` STRING,
41
+ `pod_create_time` BIGINT,
42
+ `pod_update_time` BIGINT,
43
+ `namespace` STRING,
44
+ `trial_job_name` STRING,
45
+ `create_time` BIGINT COMMENT '创建时间',
46
+ `modify_time` BIGINT COMMENT '修改时间',
47
+ `fix_modify_time` BIGINT COMMENT 'GPU调度平台TJ原始的修改时间较正常少了8小时,因此这里加了回来'
48
+ ) STORED AS ORC;
49
+
50
+ CREATE TABLE IF NOT EXISTS internal_platform_db.gputj_gpu_info_parsed_agg_1min_copilot (
51
+ `dt` STRING,
52
+ `thedate` STRING,
53
+ `pod_name` STRING,
54
+ `node` STRING,
55
+ `pkg_agg_time` STRING,
56
+ `namespace` STRING,
57
+ `reason` STRING,
58
+ `instance` STRING,
59
+ `node_ip` STRING,
60
+ `source` STRING,
61
+ `pkg_time` STRING,
62
+ `mountpoint` STRING,
63
+ `node_role` STRING,
64
+ `zone` STRING,
65
+ `gpu_name` STRING,
66
+ `karmada` STRING,
67
+ `state` STRING,
68
+ `uuid` STRING,
69
+ `fstype` STRING,
70
+ `group` STRING,
71
+ `dedicated` STRING,
72
+ `resource` STRING,
73
+ `hostname` STRING,
74
+ `gpu` STRING,
75
+ `modelname` STRING,
76
+ `unit` STRING,
77
+ `exported_namespace` STRING,
78
+ `job` STRING,
79
+ `device` STRING,
80
+ `instance_type` STRING,
81
+ `status` STRING,
82
+ `k8s_dcgm_fi_dev_fb_util_max` DOUBLE,
83
+ `k8s_dcgm_fi_dev_fb_util_min` DOUBLE,
84
+ `k8s_dcgm_fi_dev_fb_util_sum` DOUBLE,
85
+ `k8s_dcgm_fi_dev_fb_util_count` BIGINT,
86
+ `k8s_pod_bs_fs_usage_bytes_usage_max` DOUBLE,
87
+ `k8s_pod_bs_fs_usage_bytes_usage_min` DOUBLE,
88
+ `k8s_pod_bs_fs_usage_bytes_usage_sum` DOUBLE,
89
+ `k8s_pod_bs_fs_usage_bytes_usage_count` BIGINT,
90
+ `k8s_pod_bs_fs_usage_bytes_max` DOUBLE,
91
+ `k8s_pod_bs_fs_usage_bytes_min` DOUBLE,
92
+ `k8s_pod_bs_fs_usage_bytes_sum` DOUBLE,
93
+ `k8s_pod_bs_fs_usage_bytes_count` BIGINT,
94
+ `k8s_container_bs_mem_working_set_bytes_max` DOUBLE,
95
+ `k8s_container_bs_mem_working_set_bytes_min` DOUBLE,
96
+ `k8s_container_bs_mem_working_set_bytes_sum` DOUBLE,
97
+ `k8s_container_bs_mem_working_set_bytes_count` BIGINT,
98
+ `k8s_container_bs_resource_request_mem_max` DOUBLE,
99
+ `k8s_container_bs_resource_request_mem_min` DOUBLE,
100
+ `k8s_container_bs_resource_request_mem_sum` DOUBLE,
101
+ `k8s_container_bs_resource_request_mem_count` BIGINT,
102
+ `k8s_container_bs_resource_request_cpu_max` DOUBLE,
103
+ `k8s_container_bs_resource_request_cpu_min` DOUBLE,
104
+ `k8s_container_bs_resource_request_cpu_sum` DOUBLE,
105
+ `k8s_container_bs_resource_request_cpu_count` BIGINT,
106
+ `k8s_pod_bs_restart_times_max` DOUBLE,
107
+ `k8s_pod_bs_restart_times_min` DOUBLE,
108
+ `k8s_pod_bs_restart_times_sum` DOUBLE,
109
+ `k8s_pod_bs_restart_times_count` BIGINT,
110
+ `k8s_container_resource_request_gpu_max` DOUBLE,
111
+ `k8s_container_resource_request_gpu_min` DOUBLE,
112
+ `k8s_container_resource_request_gpu_sum` DOUBLE,
113
+ `k8s_container_resource_request_gpu_count` BIGINT,
114
+ `k8s_container_gpu_used_max` DOUBLE,
115
+ `k8s_container_gpu_used_min` DOUBLE,
116
+ `k8s_container_gpu_used_sum` DOUBLE,
117
+ `k8s_container_gpu_used_count` BIGINT,
118
+ `k8s_container_gpu_mem_copy_util_max` DOUBLE,
119
+ `k8s_container_gpu_mem_copy_util_min` DOUBLE,
120
+ `k8s_container_gpu_mem_copy_util_sum` DOUBLE,
121
+ `k8s_container_gpu_mem_copy_util_count` BIGINT,
122
+ `dcgm_fi_prof_nvlink_tx_bytes_max` DOUBLE,
123
+ `dcgm_fi_prof_nvlink_tx_bytes_min` DOUBLE,
124
+ `dcgm_fi_prof_nvlink_tx_bytes_sum` DOUBLE,
125
+ `dcgm_fi_prof_nvlink_tx_bytes_count` BIGINT,
126
+ `dcgm_fi_prof_nvlink_rx_bytes_max` DOUBLE,
127
+ `dcgm_fi_prof_nvlink_rx_bytes_min` DOUBLE,
128
+ `dcgm_fi_prof_nvlink_rx_bytes_sum` DOUBLE,
129
+ `dcgm_fi_prof_nvlink_rx_bytes_count` BIGINT,
130
+ `dcgm_fi_prof_pcie_tx_bytes_max` DOUBLE,
131
+ `dcgm_fi_prof_pcie_tx_bytes_min` DOUBLE,
132
+ `dcgm_fi_prof_pcie_tx_bytes_sum` DOUBLE,
133
+ `dcgm_fi_prof_pcie_tx_bytes_count` BIGINT,
134
+ `dcgm_fi_prof_pcie_rx_bytes_max` DOUBLE,
135
+ `dcgm_fi_prof_pcie_rx_bytes_min` DOUBLE,
136
+ `dcgm_fi_prof_pcie_rx_bytes_sum` DOUBLE,
137
+ `dcgm_fi_prof_pcie_rx_bytes_count` BIGINT,
138
+ `k8s_namespace_pod_phase_duration_seconds_p95_1h_max` DOUBLE,
139
+ `k8s_namespace_pod_phase_duration_seconds_p95_1h_min` DOUBLE,
140
+ `k8s_namespace_pod_phase_duration_seconds_p95_1h_sum` DOUBLE,
141
+ `k8s_namespace_pod_phase_duration_seconds_p95_1h_count` BIGINT,
142
+ `k8s_namespace_pod_phase_duration_seconds_p99_1h_max` DOUBLE,
143
+ `k8s_namespace_pod_phase_duration_seconds_p99_1h_min` DOUBLE,
144
+ `k8s_namespace_pod_phase_duration_seconds_p99_1h_sum` DOUBLE,
145
+ `k8s_namespace_pod_phase_duration_seconds_p99_1h_count` BIGINT,
146
+ `k8s_container_bs_cpu_core_used_max` DOUBLE,
147
+ `k8s_container_bs_cpu_core_used_min` DOUBLE,
148
+ `k8s_container_bs_cpu_core_used_sum` DOUBLE,
149
+ `k8s_container_bs_cpu_core_used_count` BIGINT,
150
+ `k8s_container_bs_mem_no_cache_bytes_max` DOUBLE,
151
+ `k8s_container_bs_mem_no_cache_bytes_min` DOUBLE,
152
+ `k8s_container_bs_mem_no_cache_bytes_sum` DOUBLE,
153
+ `k8s_container_bs_mem_no_cache_bytes_count` BIGINT,
154
+ `k8s_container_bs_mem_usage_bytes_max` DOUBLE,
155
+ `k8s_container_bs_mem_usage_bytes_min` DOUBLE,
156
+ `k8s_container_bs_mem_usage_bytes_sum` DOUBLE,
157
+ `k8s_container_bs_mem_usage_bytes_count` BIGINT,
158
+ `k8s_container_bs_rate_cpu_core_used_request_max` DOUBLE,
159
+ `k8s_container_bs_rate_cpu_core_used_request_min` DOUBLE,
160
+ `k8s_container_bs_rate_cpu_core_used_request_sum` DOUBLE,
161
+ `k8s_container_bs_rate_cpu_core_used_request_count` BIGINT,
162
+ `k8s_container_rate_mem_working_set_request_max` DOUBLE,
163
+ `k8s_container_rate_mem_working_set_request_min` DOUBLE,
164
+ `k8s_container_rate_mem_working_set_request_sum` DOUBLE,
165
+ `k8s_container_rate_mem_working_set_request_count` BIGINT,
166
+ `k8s_container_rate_gpu_used_request_max` DOUBLE,
167
+ `k8s_container_rate_gpu_used_request_min` DOUBLE,
168
+ `k8s_container_rate_gpu_used_request_sum` DOUBLE,
169
+ `k8s_container_rate_gpu_used_request_count` BIGINT,
170
+ `k8s_workload_pod_status_ready_max` DOUBLE,
171
+ `k8s_workload_pod_status_ready_min` DOUBLE,
172
+ `k8s_workload_pod_status_ready_sum` DOUBLE,
173
+ `k8s_workload_pod_status_ready_count` BIGINT,
174
+ `k8s_workload_pod_num_max` DOUBLE,
175
+ `k8s_workload_pod_num_min` DOUBLE,
176
+ `k8s_workload_pod_num_sum` DOUBLE,
177
+ `k8s_workload_pod_num_count` BIGINT,
178
+ `k8s_pod_status_ready_max` DOUBLE,
179
+ `k8s_pod_status_ready_min` DOUBLE,
180
+ `k8s_pod_status_ready_sum` DOUBLE,
181
+ `k8s_pod_status_ready_count` BIGINT,
182
+ `k8s_workload_pod_status_ready_rate_max` DOUBLE,
183
+ `k8s_workload_pod_status_ready_rate_min` DOUBLE,
184
+ `k8s_workload_pod_status_ready_rate_sum` DOUBLE,
185
+ `k8s_workload_pod_status_ready_rate_count` BIGINT,
186
+ `k8s_star_udf_label_pod_ready_rate_max` DOUBLE,
187
+ `k8s_star_udf_label_pod_ready_rate_min` DOUBLE,
188
+ `k8s_star_udf_label_pod_ready_rate_sum` DOUBLE,
189
+ `k8s_star_udf_label_pod_ready_rate_count` BIGINT,
190
+ `k8s_container_rate_mem_request_max` DOUBLE,
191
+ `k8s_container_rate_mem_request_min` DOUBLE,
192
+ `k8s_container_rate_mem_request_sum` DOUBLE,
193
+ `k8s_container_rate_mem_request_count` BIGINT,
194
+ `k8s_container_vgpu_gpu_util_max` DOUBLE,
195
+ `k8s_container_vgpu_gpu_util_min` DOUBLE,
196
+ `k8s_container_vgpu_gpu_util_sum` DOUBLE,
197
+ `k8s_container_vgpu_gpu_util_count` BIGINT,
198
+ `k8s_dcgm_fi_dev_fb_vgpu_gpu_util_max` DOUBLE,
199
+ `k8s_dcgm_fi_dev_fb_vgpu_gpu_util_min` DOUBLE,
200
+ `k8s_dcgm_fi_dev_fb_vgpu_gpu_util_sum` DOUBLE,
201
+ `k8s_dcgm_fi_dev_fb_vgpu_gpu_util_count` BIGINT,
202
+ `k8s_dcgm_fi_prof_sm_active_max` DOUBLE,
203
+ `k8s_dcgm_fi_prof_sm_active_min` DOUBLE,
204
+ `k8s_dcgm_fi_prof_sm_active_sum` DOUBLE,
205
+ `k8s_dcgm_fi_prof_sm_active_count` BIGINT,
206
+ `k8s_pod_bs_status_abnormal_15m_max` DOUBLE,
207
+ `k8s_pod_bs_status_abnormal_15m_min` DOUBLE,
208
+ `k8s_pod_bs_status_abnormal_15m_sum` DOUBLE,
209
+ `k8s_pod_bs_status_abnormal_15m_count` BIGINT,
210
+ `k8s_pod_bs_status_abnormal_5m_max` DOUBLE,
211
+ `k8s_pod_bs_status_abnormal_5m_min` DOUBLE,
212
+ `k8s_pod_bs_status_abnormal_5m_sum` DOUBLE,
213
+ `k8s_pod_bs_status_abnormal_5m_count` BIGINT,
214
+ `k8s_pod_bs_status_abnormal_20m_max` DOUBLE,
215
+ `k8s_pod_bs_status_abnormal_20m_min` DOUBLE,
216
+ `k8s_pod_bs_status_abnormal_20m_sum` DOUBLE,
217
+ `k8s_pod_bs_status_abnormal_20m_count` BIGINT,
218
+ `k8s_pod_bs_status_abnormal_30m_max` DOUBLE,
219
+ `k8s_pod_bs_status_abnormal_30m_min` DOUBLE,
220
+ `k8s_pod_bs_status_abnormal_30m_sum` DOUBLE,
221
+ `k8s_pod_bs_status_abnormal_30m_count` BIGINT,
222
+ `k8s_pod_bs_status_abnormal_10m_max` DOUBLE,
223
+ `k8s_pod_bs_status_abnormal_10m_min` DOUBLE,
224
+ `k8s_pod_bs_status_abnormal_10m_sum` DOUBLE,
225
+ `k8s_pod_bs_status_abnormal_10m_count` BIGINT,
226
+ `dcgm_fi_dev_row_remap_failure_max` DOUBLE,
227
+ `dcgm_fi_dev_row_remap_failure_min` DOUBLE,
228
+ `dcgm_fi_dev_row_remap_failure_sum` DOUBLE,
229
+ `dcgm_fi_dev_row_remap_pending_max` DOUBLE,
230
+ `dcgm_fi_dev_row_remap_pending_min` DOUBLE,
231
+ `dcgm_fi_dev_row_remap_pending_sum` DOUBLE,
232
+ `dcgm_fi_dev_row_remap_pending_count` BIGINT,
233
+ `dcgm_fi_dev_xid_errors_max` DOUBLE,
234
+ `dcgm_fi_dev_xid_errors_min` DOUBLE,
235
+ `dcgm_fi_dev_xid_errors_sum` DOUBLE,
236
+ `dcgm_fi_dev_xid_errors_count` BIGINT,
237
+ `dcgm_fi_dev_uncorrectable_remapped_rows_max` DOUBLE,
238
+ `dcgm_fi_dev_uncorrectable_remapped_rows_min` DOUBLE,
239
+ `dcgm_fi_dev_uncorrectable_remapped_rows_sum` DOUBLE,
240
+ `dcgm_fi_dev_uncorrectable_remapped_rows_count` BIGINT,
241
+ `starrocks_timestamp` BIGINT,
242
+ `priority_class` STRING,
243
+ `k8s_container_vgpu_gpu_mem_usage_max` DOUBLE,
244
+ `k8s_container_vgpu_gpu_mem_usage_min` DOUBLE,
245
+ `k8s_container_vgpu_gpu_mem_usage_sum` DOUBLE,
246
+ `k8s_container_vgpu_gpu_mem_usage_count` BIGINT,
247
+ `k8s_container_vgpu_gpu_mem_total_max` DOUBLE,
248
+ `k8s_container_vgpu_gpu_mem_total_min` DOUBLE,
249
+ `k8s_container_vgpu_gpu_mem_total_sum` DOUBLE,
250
+ `k8s_container_vgpu_gpu_mem_total_count` BIGINT
251
+ ) STORED AS ORC;
252
+
253
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_engine_info_copilot (
254
+ `databus_imp_date` STRING COMMENT 'primary partition',
255
+ `trace_id` STRING COMMENT 'trace_id',
256
+ `service_name` STRING COMMENT 'service_name',
257
+ `compute_type` STRING COMMENT 'compute_type',
258
+ `datawd_project_id` STRING COMMENT 'datawd_project_id',
259
+ `datawd_task_id` STRING COMMENT 'datawd_task_id',
260
+ `datawd_task_instance_id` STRING COMMENT 'datawd_task_instance_id',
261
+ `is_permanent` STRING COMMENT 'is_permanent',
262
+ `serving_id` STRING COMMENT 'serving_id',
263
+ `user_name` STRING COMMENT 'user_name',
264
+ `is_model_service` STRING COMMENT 'is_model_service',
265
+ `compute_info` STRING COMMENT 'compute_info',
266
+ `num_gpu` STRING COMMENT 'num_gpu',
267
+ `replicas` STRING COMMENT 'replicas',
268
+ `gpu_type` STRING COMMENT 'gpu_type',
269
+ `timestamp` STRING COMMENT 'timestamp',
270
+ `ray_job_id` STRING,
271
+ `reason` STRING,
272
+ `log_url` STRING,
273
+ `dashboard_url` STRING
274
+ ) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_002/task.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: offline-compute_HiveSQL_hivesql_002
3
+ name: 统计数据平台WDNotebook Ray类型管道任务中运行时间跨自然天的实例明细。从`wedat
4
+ category: offline-compute/HiveSQL
5
+ timeout_seconds: 600
6
+ modality: pure-text
7
+ engine: hivesql
8
+ ---
9
+ ## Prompt
10
+ **任务目标**:统计数据平台WDNotebook Ray类型管道任务中运行时间跨自然天的实例明细,按自然天拆分并关联GPU指标。
11
+
12
+ **输入**:
13
+ - `internal_platform_db.notebook_span_info_query_engine_005`
14
+ - `internal_platform_db.dwd_gputj_service_instance_map_query_engine_005`
15
+ - `internal_platform_db.dwd_ml_platform_instance_podname_query_engine_005`
16
+ - `internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_005`
17
+ - `internal_platform_db.notebook_engine_info_query_engine_005`
18
+
19
+ **处理规则**:
20
+ 1. 时间过滤:`20260504`-`20260507`,从`notebook_span_info`筛选在`20260507`有记录且跨天的`trace_id`。
21
+ 2. 业务过滤:计算类型='ray',服务名='notebook-runner';span名称限定:'runner.execute'、'execute.code'、'execute.code.cell'、'client.execute.code'、'runner.killed'、'set.permanent.compute'、'create.non.permanent.compute';GPU表过滤无效记录。
22
+ 3. 跨天拆分:将跨天实例按自然天拆分,每条记录对应一天内的开始和结束时间。
23
+ 4. 派生字段:
24
+ - `instance_run_time`:(end_time - start_time)/1000(秒),基于'runner.execute'
25
+ - `code_run_time`:代码执行相关span总时长(秒)
26
+ - `resource_wait_time`:资源创建相关span总时长(秒)
27
+ - `apply_for_gpu_count`:SUM(replicas * num_gpu),按trace_id
28
+ - `gpu_util`:k8s_container_vgpu_gpu_util_sum / k8s_container_vgpu_gpu_util_count
29
+ - `gpu_count`:k8s_container_resource_request_gpu_sum / k8s_container_resource_request_gpu_count
30
+ 5. 表关联:
31
+ - 拆分结果按`trace_id`左关联`notebook_engine_info`获取`serving_id`
32
+ - 通过`instance_uuid`关联`dwd_gputj_service_instance_map`与`dwd_ml_platform_instance_podname`,再按`serving_id=service_id`左关联得到`pod_name`
33
+ - 按`pod_name`左关联`gputj_gpu_info_parsed_agg_1min`,条件为`pkg_agg_time`落在实例运行窗口内(优先`instance_start_time`到`instance_end_time`,否则`code_start_time`到`code_end_time`)
34
+
35
+ **输出要求**:
36
+ - 输出表:`internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_query_engine_005`
37
+ - 字段顺序:dt:STRING; trace_id:STRING; datawd_project_id:STRING; datawd_task_id:STRING; datawd_task_instance_id:STRING; compute_type:STRING; status_code:INT; instance_run_time:INT; code_run_time:INT; resource_wait_time:INT; code_start_time:STRING; code_end_time:STRING; instance_start_time:STRING; instance_end_time:STRING; serving_id:STRING; is_permanent:BOOLEAN; apply_for_gpu_count:INT; pod_name:STRING; pkg_agg_time:STRING; gpu_util:DOUBLE; gpu_count:INT; p_date:STRING
38
+ - 分区字段:`dt`
39
+
40
+ **写入要求**:写入`dt='20260507'`分区。
41
+
42
+ 请将最终 HiveSQL 写入 result.sql 并执行。
tasks/offline-compute/HiveSQL/hivesql_003/gt/expected.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ p_date,trace_id,datawd_project_id,datawd_task_id,datawd_task_instance_id,compute_type,status_code,instance_run_time,code_run_time,resource_wait_time,code_start_time,code_end_time,instance_start_time,instance_end_time,serving_id,is_permanent,apply_for_gpu_count,dt
2
+ 2025-05-07,trace_001,proj_01,task_01,inst_01,ray,2,15,13,2,2025-05-07 03:59:52,2025-05-07 04:00:05,2025-05-07 03:59:50,2025-05-07 04:00:05,srv_001,True,2,20260507
3
+ 2025-05-07,trace_002,proj_02,task_02,inst_02,ray,2,18,16,3,2025-05-07 04:01:32,2025-05-07 04:01:48,2025-05-07 04:01:30,2025-05-07 04:01:48,srv_002,False,8,20260507
tasks/offline-compute/HiveSQL/hivesql_003/gt/grade.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hivesql_007 精细评分脚本
2
+
3
+ 业务场景:Killed 实例按天拆分运行时长统计(2表 + CTE + UNION + 跨天拆分)
4
+ 难度: HARD | 特征: CTE|UNION_ALL|CROSS_DAY_SPLIT|TIME_CALCULATION|LEFT_JOIN
5
+
6
+ 评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)
7
+ A_executability (10分): result.sql 能跑通且产出非空
8
+ B_schema (10分): 18列 + 列名匹配
9
+ C_row_alignment (10分): 行数比例 + key覆盖率
10
+ D_time_calculation (30分): instance_run_time, code_run_time 等时间指标
11
+ D_cross_day_split (15分): 跨天 trace 按天拆分正确性
12
+ D_engine_join (10分): serving_id, is_permanent 等 engine 维度列匹配
13
+ F_join_completeness (5分): 2张源表都被关联
14
+ F_insert_overwrite (5分): 写入模式+分区
15
+ F_partition_value (5分): dt=20260507
16
+
17
+ 权重: HARD → product=0.7, process=0.3
18
+ """
19
+ import os
20
+ import re
21
+ import subprocess
22
+ import tempfile
23
+ import json
24
+ import math
25
+
26
+
27
+ def grade(workspace_path, **kwargs):
28
+
29
+ # ========== Case 配置 ==========
30
+ OUTPUT_TABLE = "internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_cand_query_engine_007"
31
+ DIFFICULTY = "HARD"
32
+ SOURCE_TABLES = [
33
+ "notebook_span_info_query_engine_007",
34
+ "notebook_engine_info_query_engine_007",
35
+ "dwd_notebook_killed_instance_detail_d_copilot_query_engine_007",
36
+ ]
37
+ KEY_COLUMNS = ["trace_id", "p_date"]
38
+ TIME_COLUMNS = ["instance_run_time", "code_run_time", "resource_wait_time"]
39
+ ENGINE_DIM_COLUMNS = ["serving_id", "is_permanent", "apply_for_gpu_count"]
40
+ SOURCE_TABLE_SHORT_NAMES = [
41
+ "notebook_span_info",
42
+ "notebook_engine_info",
43
+ ]
44
+ GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
45
+
46
+ DIFFICULTY_WEIGHTS = {
47
+ "EASY": (0.5, 0.5),
48
+ "MEDIUM": (0.6, 0.4),
49
+ "HARD": (0.7, 0.3),
50
+ "EXPERT": (0.8, 0.2),
51
+ }
52
+
53
+ _SPARK_SUBMIT_TIMEOUT = 300
54
+ _JSON_START = "__GRADE_JSON_START__"
55
+ _JSON_END = "__GRADE_JSON_END__"
56
+
57
+ result = {
58
+ "overall_score": 0.0,
59
+ "total_points": 0,
60
+ "grade": "",
61
+ "details": {},
62
+ "diagnostics": [],
63
+ }
64
+
65
+ # ========== 内部辅助函数 ==========
66
+
67
+ def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
68
+ if pred_val is None and gt_val is None:
69
+ return True
70
+ if pred_val is None or gt_val is None:
71
+ return False
72
+ s_pred = str(pred_val).strip()
73
+ s_gt = str(gt_val).strip()
74
+ if s_pred == s_gt:
75
+ return True
76
+ try:
77
+ pv = float(s_pred)
78
+ gv = float(s_gt)
79
+ if math.isnan(pv) and math.isnan(gv):
80
+ return True
81
+ if math.isnan(pv) or math.isnan(gv):
82
+ return False
83
+ if abs(gv) < abs_tol:
84
+ return abs(pv - gv) <= abs_tol
85
+ return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
86
+ except (ValueError, TypeError):
87
+ pass
88
+ return s_pred.lower() == s_gt.lower()
89
+
90
+ def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
91
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
92
+ f.write(script_code)
93
+ script_path = f.name
94
+ try:
95
+ r = subprocess.run(
96
+ ["spark-submit", script_path],
97
+ capture_output=True, text=True, timeout=timeout,
98
+ )
99
+ stdout = r.stdout or ""
100
+ if _JSON_START in stdout and _JSON_END in stdout:
101
+ json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
102
+ return json.loads(json_str), None
103
+ else:
104
+ if r.returncode == 0:
105
+ for line in stdout.splitlines():
106
+ if line.strip().startswith("Traceback"):
107
+ return None, f"spark-submit error: {line}"
108
+ return None, "spark-submit 无 JSON 输出"
109
+ err_msg = (r.stderr or "")[-500:]
110
+ return None, f"spark-submit failed: {err_msg}"
111
+ except subprocess.TimeoutExpired:
112
+ return None, f"spark-submit 超时 ({timeout}s)"
113
+ except Exception as e:
114
+ return None, f"spark-submit 异常: {e}"
115
+ finally:
116
+ try:
117
+ os.unlink(script_path)
118
+ except OSError:
119
+ pass
120
+
121
+ def read_table_via_spark_submit(table_name):
122
+ """Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
123
+ if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
124
+ raise ValueError(f"非法表名: {table_name}")
125
+ read_script = f'''
126
+ import json
127
+ from pyspark.sql import SparkSession
128
+ spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
129
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
130
+ try:
131
+ df = spark.sql("SELECT * FROM {table_name}")
132
+ cols = [c.lower() for c in df.columns]
133
+ rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
134
+ print("{_JSON_START}")
135
+ print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
136
+ print("{_JSON_END}")
137
+ except Exception as e:
138
+ print("{_JSON_START}")
139
+ print(json.dumps({{"error": str(e)}}))
140
+ print("{_JSON_END}")
141
+ finally:
142
+ spark.stop()
143
+ '''
144
+ data, err = _run_spark_script(read_script)
145
+ if err:
146
+ raise RuntimeError(f"read_table failed: {err}")
147
+ if "error" in data:
148
+ raise RuntimeError(f"query failed: {data['error']}")
149
+ return data["cols"], data["rows"]
150
+
151
+ # SQL executor template (self-contained, no external dependency)
152
+ _SQL_EXEC_TEMPLATE = '''
153
+ import json, re
154
+ from pyspark.sql import SparkSession
155
+ spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
156
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
157
+ try:
158
+ with open("{sql_file}", "r", encoding="utf-8") as _f:
159
+ _sql = _f.read()
160
+ _sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
161
+ _stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
162
+ while _i < len(_sql):
163
+ _ch = _sql[_i]
164
+ if _ch == "\\\\" and _i + 1 < len(_sql):
165
+ _cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
166
+ if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
167
+ while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
168
+ _cur.append("\\n"); continue
169
+ if _ch == "'" and not _in_dq: _in_sq = not _in_sq
170
+ elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
171
+ if _ch == ";" and not _in_sq and not _in_dq:
172
+ _s = "".join(_cur).strip()
173
+ if _s: _stmts.append(_s)
174
+ _cur = []
175
+ else:
176
+ _cur.append(_ch)
177
+ _i += 1
178
+ _last = "".join(_cur).strip()
179
+ if _last: _stmts.append(_last)
180
+ for _stmt in _stmts:
181
+ spark.sql(_stmt)
182
+ print("{_JSON_START}")
183
+ print(json.dumps({{"ok": True}}))
184
+ print("{_JSON_END}")
185
+ except Exception as e:
186
+ print("{_JSON_START}")
187
+ print(json.dumps({{"ok": False, "error": str(e)}}))
188
+ print("{_JSON_END}")
189
+ finally:
190
+ spark.stop()
191
+ '''
192
+
193
+ def execute_result_sql():
194
+ result_sql = os.path.join(workspace_path, "result.sql")
195
+ if not os.path.exists(result_sql):
196
+ return False, "no_result_file"
197
+ # 替换 数据平台WD时间变量(沙箱 spark-sql 不支持 ${...} 语法)
198
+ with open(result_sql, 'r', encoding='utf-8') as _rf:
199
+ _sql_text = _rf.read()
200
+ _bizdate = '20260507'
201
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
202
+ _sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
203
+ _sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
204
+ _sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
205
+ with open(result_sql, 'w', encoding='utf-8') as _wf:
206
+ _wf.write(_sql_text)
207
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
208
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
209
+ data, err = _run_spark_script(script)
210
+ if err:
211
+ return False, f"execution_error: {err}"
212
+ if data and data.get("ok"):
213
+ return True, None
214
+ return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
215
+
216
+ def execute_ground_truth_sql():
217
+ gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
218
+ if not os.path.exists(gt_sql):
219
+ return False, "ground_truth.sql not found"
220
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
221
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
222
+ data, err = _run_spark_script(script)
223
+ if err:
224
+ return False, f"gt_execution_error: {err}"
225
+ if data and data.get("ok"):
226
+ return True, None
227
+ return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
228
+
229
+ def truncate_table(table_name):
230
+ script = f'''
231
+ from pyspark.sql import SparkSession
232
+ spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
233
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
234
+ spark.sql("TRUNCATE TABLE {table_name}")
235
+ spark.stop()
236
+ '''
237
+ try:
238
+ _run_spark_script(script, timeout=120)
239
+ except Exception:
240
+ pass
241
+
242
+ def restore_hive_site():
243
+ """Restore hive-site.xml to canonical state (agent may have modified it)."""
244
+ canonical_hive_site = '''<?xml version="1.0"?>
245
+ <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
246
+ <configuration>
247
+ <property>
248
+ <name>hive.metastore.uris</name>
249
+ <value>thrift://localhost:9083</value>
250
+ </property>
251
+ <property>
252
+ <name>hive.metastore.warehouse.dir</name>
253
+ <value>/tmp/hive_warehouse</value>
254
+ </property>
255
+ <property>
256
+ <name>javax.jdo.option.ConnectionURL</name>
257
+ <value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
258
+ </property>
259
+ <property>
260
+ <name>javax.jdo.option.ConnectionDriverName</name>
261
+ <value>org.apache.derby.jdbc.EmbeddedDriver</value>
262
+ </property>
263
+ <property>
264
+ <name>datanucleus.schema.autoCreateAll</name>
265
+ <value>true</value>
266
+ </property>
267
+ <property>
268
+ <name>hive.metastore.schema.verification</name>
269
+ <value>false</value>
270
+ </property>
271
+ </configuration>
272
+ '''
273
+ hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
274
+ try:
275
+ with open(hive_site_path, 'w') as f:
276
+ f.write(canonical_hive_site)
277
+ except Exception:
278
+ pass
279
+
280
+ def finalize(result):
281
+ product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
282
+ product_dims = ["A_executability"] + ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_engine_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']
283
+ product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
284
+ product_ratio = product_raw / 100.0
285
+ for dim in ["H_efficiency"]:
286
+ if dim in result["details"]:
287
+ raw = result["details"][dim].get("score", 0)
288
+ result["details"][dim]["score_before_scaling"] = raw
289
+ result["details"][dim]["score"] = round(raw * product_ratio, 2)
290
+ result["details"][dim]["product_ratio"] = round(product_ratio, 4)
291
+ process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
292
+ process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
293
+ product_score = round(product_raw * product_weight, 2)
294
+ process_score = round(process_raw * process_weight, 2)
295
+ total = round(product_score + process_score, 2)
296
+ result["total_points"] = total
297
+ result["product_points"] = product_score
298
+ result["process_points"] = round(process_score, 2)
299
+ result["weights"] = {"product": product_weight, "process": process_weight}
300
+ result["overall_score"] = round(total / 100.0, 4)
301
+ if total >= 90:
302
+ result["grade"] = "优秀"
303
+ elif total >= 75:
304
+ result["grade"] = "良好"
305
+ elif total >= 60:
306
+ result["grade"] = "合格"
307
+ elif total >= 40:
308
+ result["grade"] = "偏弱"
309
+ else:
310
+ result["grade"] = "不合格"
311
+ return result
312
+
313
+ # Restore hive-site.xml (agent may have modified it)
314
+ restore_hive_site()
315
+
316
+ # ========== A. 可执行性 (10分) ==========
317
+ a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
318
+ exec_ok, exec_err = execute_result_sql()
319
+ if not exec_ok:
320
+ detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
321
+ result["details"]["A_executability"] = {"score": 0, "max": 10, "detail": detail}
322
+ result["error"] = detail
323
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_engine_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
324
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
325
+ return finalize(result)
326
+
327
+ a_items["A1_exec_ok"] = 5
328
+
329
+ pred_headers, pred_rows = [], []
330
+ try:
331
+ pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
332
+ except Exception as e:
333
+ result["diagnostics"].append(f"read_pred_failed: {e}")
334
+
335
+ if not pred_rows:
336
+ result["details"]["A_executability"] = {"score": 5, "max": 10, "items": a_items}
337
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_engine_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
338
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
339
+ return finalize(result)
340
+
341
+ a_items["A2_has_data"] = 5
342
+ result["details"]["A_executability"] = {"score": 10, "max": 10, "items": a_items}
343
+
344
+ # ========== Execute GT + Read GT ==========
345
+ truncate_table(GT_TABLE)
346
+ gt_ok, gt_err = execute_ground_truth_sql()
347
+ if not gt_ok:
348
+ result["error"] = f"ground_truth failed: {gt_err}"
349
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_engine_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
350
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
351
+ return finalize(result)
352
+
353
+ gt_headers, gt_rows = [], []
354
+ try:
355
+ gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
356
+ except Exception as e:
357
+ result["error"] = f"read_gt_failed: {e}"
358
+ for dim in ['B_schema', 'C_row_alignment', 'D_cross_day_split', 'D_engine_join', 'D_time_calculation', 'F_insert_overwrite', 'F_join_completeness', 'F_partition_value']:
359
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
360
+ return finalize(result)
361
+
362
+ # ========== B/C/D/F 维度评分 ==========
363
+ pred_col_map = {h: i for i, h in enumerate(pred_headers)}
364
+ gt_col_map = {h: i for i, h in enumerate(gt_headers)}
365
+
366
+ # ========== B. Schema正确性 (10分) ==========
367
+ b_items = {}
368
+ expected_col_count = 18
369
+ if len(pred_headers) == expected_col_count:
370
+ b_items["B1_col_count"] = 5
371
+ elif abs(len(pred_headers) - expected_col_count) <= 2:
372
+ b_items["B1_col_count"] = 3
373
+ else:
374
+ b_items["B1_col_count"] = 0
375
+
376
+ gt_col_set = set(gt_headers)
377
+ pred_col_set = set(pred_headers)
378
+ name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
379
+ if name_match_rate >= 0.95:
380
+ b_items["B2_col_names"] = 5
381
+ elif name_match_rate >= 0.8:
382
+ b_items["B2_col_names"] = 3
383
+ else:
384
+ b_items["B2_col_names"] = 0
385
+
386
+ b_score = sum(b_items.values())
387
+ result["details"]["B_schema"] = {
388
+ "score": b_score, "max": 10,
389
+ "detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
390
+ }
391
+
392
+ # ========== C. 行一致性 (10分) ==========
393
+ c_items = {}
394
+ gt_row_count = len(gt_rows)
395
+ pred_row_count = len(pred_rows)
396
+
397
+ if gt_row_count > 0:
398
+ ratio = pred_row_count / gt_row_count
399
+ if 0.95 <= ratio <= 1.05:
400
+ c_items["C1_row_ratio"] = 5
401
+ elif 0.7 <= ratio <= 1.3:
402
+ c_items["C1_row_ratio"] = 3
403
+ else:
404
+ c_items["C1_row_ratio"] = 0
405
+ else:
406
+ c_items["C1_row_ratio"] = 5 if pred_row_count == 0 else 0
407
+
408
+ key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
409
+ if key_cols_avail and gt_row_count > 0:
410
+ gt_keys = set()
411
+ for row in gt_rows:
412
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
413
+ gt_keys.add(key)
414
+ pred_keys = set()
415
+ for row in pred_rows:
416
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
417
+ pred_keys.add(key)
418
+ coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
419
+ if coverage >= 0.995:
420
+ c_items["C2_key_coverage"] = 5
421
+ elif coverage >= 0.9:
422
+ c_items["C2_key_coverage"] = 3
423
+ elif coverage >= 0.7:
424
+ c_items["C2_key_coverage"] = 2
425
+ else:
426
+ c_items["C2_key_coverage"] = round(5 * coverage, 2)
427
+ else:
428
+ c_items["C2_key_coverage"] = 0
429
+
430
+ c_score = sum(v for v in c_items.values())
431
+ result["details"]["C_row_alignment"] = {"score": c_score, "max": 10, "detail": c_items}
432
+
433
+ # 构建索引
434
+ pred_index = {}
435
+ if key_cols_avail:
436
+ for row in pred_rows:
437
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
438
+ pred_index[key] = row
439
+
440
+ gt_index = {}
441
+ for row in gt_rows:
442
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
443
+ gt_index[key] = row
444
+
445
+ # ========== D. 时间计算正确性 (30分) ==========
446
+ d_time_items = {}
447
+ per_col_weight = 30.0 / max(len(TIME_COLUMNS), 1)
448
+ for col in TIME_COLUMNS:
449
+ gt_ci = gt_col_map.get(col)
450
+ pred_ci = pred_col_map.get(col)
451
+ if gt_ci is None or pred_ci is None:
452
+ d_time_items[col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
453
+ continue
454
+
455
+ matches = 0
456
+ total = 0
457
+ for key, gt_row in gt_index.items():
458
+ pred_row = pred_index.get(key)
459
+ if pred_row is None:
460
+ total += 1
461
+ continue
462
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
463
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
464
+ if values_match(pred_val, gt_val, abs_tol=1.0, rel_tol=0.01):
465
+ matches += 1
466
+ total += 1
467
+
468
+ rate = matches / max(total, 1)
469
+ col_score = rate * per_col_weight
470
+ d_time_items[col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2)}
471
+
472
+ d_time_score = sum(v.get("score", 0) for v in d_time_items.values() if isinstance(v, dict))
473
+ result["details"]["D_time_calculation"] = {"score": round(d_time_score, 2), "max": 30, "detail": d_time_items}
474
+
475
+ # ========== D. 跨天切分正确性 (15分) ==========
476
+ d_cross_items = {}
477
+ d_cross_score = 0
478
+ trace_idx = pred_col_map.get("trace_id")
479
+ pdate_idx = pred_col_map.get("p_date")
480
+
481
+ if trace_idx is not None and pdate_idx is not None:
482
+ pred_trace_dates = {}
483
+ for row in pred_rows:
484
+ tid = row[trace_idx].strip() if trace_idx < len(row) else ""
485
+ pd = row[pdate_idx].strip() if pdate_idx < len(row) else ""
486
+ if tid not in pred_trace_dates:
487
+ pred_trace_dates[tid] = set()
488
+ pred_trace_dates[tid].add(pd)
489
+
490
+ # 检查是否有 trace 跨天(跨天 trace 应出现多个 p_date)
491
+ gt_trace_idx = gt_col_map.get("trace_id")
492
+ gt_pdate_idx = gt_col_map.get("p_date")
493
+ gt_trace_dates = {}
494
+ if gt_trace_idx is not None and gt_pdate_idx is not None:
495
+ for row in gt_rows:
496
+ tid = row[gt_trace_idx].strip() if gt_trace_idx < len(row) else ""
497
+ pd = row[gt_pdate_idx].strip() if gt_pdate_idx < len(row) else ""
498
+ if tid not in gt_trace_dates:
499
+ gt_trace_dates[tid] = set()
500
+ gt_trace_dates[tid].add(pd)
501
+
502
+ # 跨天 trace 拆分正确 (10分)
503
+ cross_traces = {tid: dates for tid, dates in gt_trace_dates.items() if len(dates) > 1}
504
+ if cross_traces:
505
+ correct = 0
506
+ for tid, expected_dates in cross_traces.items():
507
+ pred_dates = pred_trace_dates.get(tid, set())
508
+ if pred_dates >= expected_dates:
509
+ correct += 1
510
+ elif len(pred_dates & expected_dates) > 0:
511
+ correct += 0.5
512
+ cross_rate = correct / len(cross_traces)
513
+ d_cross_score += round(10 * cross_rate, 2)
514
+ d_cross_items["cross_day_traces"] = {"rate": round(cross_rate, 4), "count": len(cross_traces)}
515
+ else:
516
+ # 没有跨天 trace,给满分
517
+ d_cross_score += 10
518
+ d_cross_items["cross_day_traces"] = "no cross-day traces in GT"
519
+
520
+ # 行数正确 (5分)
521
+ if pred_row_count == gt_row_count:
522
+ d_cross_score += 5
523
+ d_cross_items["row_count_correct"] = True
524
+ elif abs(pred_row_count - gt_row_count) <= 1:
525
+ d_cross_score += 3
526
+ d_cross_items["row_count_correct"] = f"off by {abs(pred_row_count - gt_row_count)}"
527
+ else:
528
+ d_cross_items["row_count_correct"] = f"pred={pred_row_count}, gt={gt_row_count}"
529
+ else:
530
+ d_cross_items["error"] = "trace_id or p_date column missing"
531
+
532
+ result["details"]["D_cross_day_split"] = {"score": round(d_cross_score, 2), "max": 15, "detail": d_cross_items}
533
+
534
+ # ========== D. Engine 维度列匹配 (10分) ==========
535
+ d_engine_items = {}
536
+ for col in ENGINE_DIM_COLUMNS:
537
+ gt_ci = gt_col_map.get(col)
538
+ pred_ci = pred_col_map.get(col)
539
+ if gt_ci is None or pred_ci is None:
540
+ continue
541
+ matches = 0
542
+ total = 0
543
+ for key, gt_row in gt_index.items():
544
+ pred_row = pred_index.get(key)
545
+ if pred_row is None:
546
+ total += 1
547
+ continue
548
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
549
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
550
+ if values_match(pred_val, gt_val):
551
+ matches += 1
552
+ total += 1
553
+ rate = matches / max(total, 1)
554
+ d_engine_items[col] = round(rate, 4)
555
+
556
+ d_engine_score = 0
557
+ if d_engine_items:
558
+ avg_rate = sum(d_engine_items.values()) / len(d_engine_items)
559
+ d_engine_score = round(10 * avg_rate, 2)
560
+ result["details"]["D_engine_join"] = {"score": d_engine_score, "max": 10, "detail": d_engine_items}
561
+
562
+ # ========== F. JOIN 完整性 (5分) ==========
563
+ f_join_items = {}
564
+ result_sql_path = os.path.join(workspace_path, "result.sql")
565
+ sql_text = ""
566
+ try:
567
+ with open(result_sql_path, "r", encoding="utf-8") as f:
568
+ sql_text = f.read().lower()
569
+ except Exception:
570
+ sql_text = ""
571
+
572
+ tables_found = 0
573
+ for tname in SOURCE_TABLES:
574
+ if tname.lower() in sql_text:
575
+ tables_found += 1
576
+ f_join_items[tname] = True
577
+ else:
578
+ f_join_items[tname] = False
579
+
580
+ f_join_score = round(5 * tables_found / max(len(SOURCE_TABLES), 1), 2)
581
+ result["details"]["F_join_completeness"] = {
582
+ "score": f_join_score, "max": 5, "detail": f_join_items,
583
+ }
584
+
585
+ # ========== F. INSERT OVERWRITE (5分) ==========
586
+ f_insert_items = {}
587
+ has_overwrite = "insert overwrite" in sql_text
588
+ has_partition = "partition" in sql_text
589
+ if has_overwrite and has_partition:
590
+ f_insert_items["insert_overwrite_partition"] = 5
591
+ elif has_overwrite:
592
+ f_insert_items["insert_overwrite_partition"] = 3
593
+ else:
594
+ f_insert_items["insert_overwrite_partition"] = 0
595
+ result["details"]["F_insert_overwrite"] = {
596
+ "score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
597
+ }
598
+
599
+ # ========== F. 分区值 (5分) ==========
600
+ f_part_items = {}
601
+ if "dt" in sql_text and "20260507" in sql_text:
602
+ f_part_items["partition_value"] = 5
603
+ else:
604
+ f_part_items["partition_value"] = 0
605
+ result["details"]["F_partition_value"] = {
606
+ "score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
607
+ }
608
+
609
+ # 汇总
610
+ total = (10 + b_score + c_score + d_time_score + d_cross_score + d_engine_score
611
+ + f_join_score + f_insert_items["insert_overwrite_partition"]
612
+ + f_part_items["partition_value"])
613
+
614
+ # ========== G~I 过程评分 ==========
615
+ TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
616
+ OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
617
+ INPUT_TABLE_SHORT = SOURCE_TABLES[0]
618
+
619
+ transcript_entries = []
620
+ has_transcript = False
621
+ try:
622
+ if os.path.exists(TRANSCRIPT_PATH):
623
+ with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f:
624
+ for line in f:
625
+ line = line.strip()
626
+ if line:
627
+ try:
628
+ transcript_entries.append(json.loads(line))
629
+ except json.JSONDecodeError:
630
+ continue
631
+ if len(transcript_entries) > 2:
632
+ has_transcript = True
633
+ except Exception:
634
+ pass
635
+
636
+ if not has_transcript:
637
+ result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}}
638
+ result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}}
639
+ result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}}
640
+ return finalize(result)
641
+
642
+ # Parse transcript into structured events
643
+ tool_uses = []
644
+ first_write_result_idx = None
645
+ last_spark_submit_success_idx = None
646
+ write_result_count = 0
647
+ logic_error_retries = 0
648
+
649
+ for idx, entry in enumerate(transcript_entries):
650
+ content = entry.get("content", [])
651
+ if isinstance(content, str):
652
+ content = [content]
653
+
654
+ for block_str in content:
655
+ if not isinstance(block_str, str):
656
+ continue
657
+ if "ToolUseBlock" in block_str:
658
+ name_match = re.search(r"name='([^']+)'", block_str)
659
+ input_match = re.search(r"input=(\{.*\})", block_str)
660
+ if name_match:
661
+ tool_name = name_match.group(1)
662
+ tool_input = input_match.group(1) if input_match else ""
663
+ tool_uses.append((idx, tool_name, tool_input))
664
+ if tool_name == "Write" and "result.sql" in tool_input:
665
+ write_result_count += 1
666
+ if first_write_result_idx is None:
667
+ first_write_result_idx = idx
668
+ if "ToolResultBlock" in block_str:
669
+ if "Traceback" in block_str or "Exception" in block_str:
670
+ env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
671
+ "db.lck", "TTransportException", "port 10000"]
672
+ is_env_error = any(e in block_str for e in env_errors)
673
+ has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
674
+ for t in tool_uses)
675
+ if not is_env_error and has_spark_submit:
676
+ logic_error_retries += 1
677
+ if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" in block_str:
678
+ if "Exit Code: 0" in block_str and "Traceback" not in block_str:
679
+ last_spark_submit_success_idx = idx
680
+
681
+ before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
682
+
683
+ # ===== G. 探索充分性 (35分) =====
684
+ g_items = {}
685
+ g1_pass = any(name == "Read" and "schema" in inp.lower()
686
+ for idx, name, inp in tool_uses if idx < before_first_write)
687
+ g_items["G1_source_schema"] = 9 if g1_pass else 0
688
+
689
+ g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
690
+ and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
691
+ for idx, name, inp in tool_uses if idx < before_first_write)
692
+ g_items["G2_source_sample"] = 9 if g2_pass else 0
693
+
694
+ g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
695
+ and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
696
+ for idx, name, inp in tool_uses if idx < before_first_write)
697
+ g_items["G3_distribution"] = 9 if g3_pass else 0
698
+
699
+ g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
700
+ and OUTPUT_TABLE_SHORT in inp
701
+ for idx, name, inp in tool_uses if idx < before_first_write)
702
+ g_items["G4_target_schema"] = 8 if g4_pass else 0
703
+
704
+ g_score = sum(g_items.values())
705
+ result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
706
+
707
+ # ===== H. 执行效率 (40分) =====
708
+ h_items = {}
709
+ if write_result_count <= 2:
710
+ h_items["H1_few_submissions"] = 20
711
+ elif write_result_count <= 4:
712
+ h_items["H1_few_submissions"] = 13
713
+ elif write_result_count <= 6:
714
+ h_items["H1_few_submissions"] = 7
715
+ else:
716
+ h_items["H1_few_submissions"] = 0
717
+
718
+ if logic_error_retries == 0:
719
+ h_items["H2_no_logic_errors"] = 13
720
+ elif logic_error_retries <= 1:
721
+ h_items["H2_no_logic_errors"] = 7
722
+ else:
723
+ h_items["H2_no_logic_errors"] = 0
724
+
725
+ h_items["H3_no_redundancy"] = 7
726
+ h_score = sum(h_items.values())
727
+ result["details"]["H_efficiency"] = {"score": min(h_score, 40), "max": 40, "items": h_items}
728
+
729
+ # ===== I. 自验证行为 (25分) =====
730
+ i_items = {}
731
+ post_submit_uses = []
732
+ if last_spark_submit_success_idx is not None:
733
+ post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
734
+ if idx > last_spark_submit_success_idx]
735
+
736
+ i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
737
+ for _, name, inp in post_submit_uses)
738
+ i_items["I1_query_output"] = 8 if i1_pass else 0
739
+
740
+ i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
741
+ and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
742
+ for _, name, inp in post_submit_uses)
743
+ i_items["I2_check_count"] = 9 if i2_pass else 0
744
+
745
+ i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
746
+ and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper())
747
+ for _, name, inp in post_submit_uses)
748
+ i_items["I3_check_values"] = 8 if i3_pass else 0
749
+
750
+ i_score = sum(i_items.values())
751
+ result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items}
752
+
753
+ return finalize(result)
tasks/offline-compute/HiveSQL/hivesql_003/gt/grade_spec.csv ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 维度,维度全名,子维度,满分,说明
2
+ A,A_executability,executability,10,result.sql 能跑通且产出非空
3
+ B,B_schema,schema,10,18列 + 列名匹配
4
+ C,C_row_alignment,row_consistency,10,行数比例 + key覆盖率
5
+ D,D_time_calculation,time_calculation,30,"instance_run_time, code_run_time 等时间指标"
6
+ D,D_cross_day_split,cross_day_split,15,跨天 trace 按天拆分正确性
7
+ D,D_engine_join,engine_join,10,"serving_id, is_permanent 等 engine 维度列匹配"
8
+ F,F_join_completeness,join_completeness,5,2张源表都被关联
9
+ F,F_insert_overwrite,insert_overwrite,5,写入模式+分区
10
+ F,F_partition_value,partition_value,5,dt=20260507
11
+
12
+ 总计,,,100,
13
+
14
+ # 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)
15
+ # 难度,HARD
16
+ # 权重,"product=0.7, process=0.3"
17
+ # 范式,new
18
+ # Key列,"trace_id, p_date"
19
+ # 预期列数,
20
+ # 输出表,internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_cand_query_engine_007
tasks/offline-compute/HiveSQL/hivesql_003/gt/ground_truth.sql ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INSERT overwrite TABLE internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_query_engine_007 PARTITION (dt = '20260507')
2
+ WITH base_trace AS (
3
+ SELECT trace_id
4
+ FROM internal_platform_db.notebook_span_info_query_engine_007
5
+ WHERE databus_imp_date >= '2026050700'
6
+ AND databus_imp_date <= '2026050700'
7
+ AND compute_type = 'ray'
8
+ AND service_name = 'notebook-runner'
9
+ AND span_name IN ('runner.execute', 'runner.killed')
10
+ GROUP BY trace_id
11
+ HAVING
12
+ COUNT(CASE WHEN span_name = 'runner.killed' THEN 1 END) > 0
13
+ AND
14
+ COUNT(CASE WHEN span_name = 'runner.execute' THEN 1 END) = 0
15
+ ),
16
+ combined_spans AS (
17
+ SELECT
18
+ trace_id,
19
+ span_name,
20
+ start_time,
21
+ end_time,
22
+ datawd_project_id,
23
+ datawd_task_id,
24
+ datawd_task_instance_id,
25
+ compute_type,
26
+ status_code
27
+ FROM internal_platform_db.notebook_span_info_query_engine_007
28
+ WHERE databus_imp_date >= '2026050400'
29
+ AND databus_imp_date <= '2026050700'
30
+ AND trace_id IN (SELECT trace_id FROM base_trace)
31
+ AND span_name IN ('runner.killed', 'runner.start', 'execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute')
32
+
33
+ UNION ALL
34
+
35
+ SELECT
36
+ trace_id,
37
+ 'runner.execute' AS span_name,
38
+ MAX(CASE WHEN span_name = 'runner.start' THEN start_time END) AS start_time,
39
+ MAX(CASE WHEN span_name = 'runner.killed' THEN end_time END) AS end_time,
40
+ MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_project_id END) AS datawd_project_id,
41
+ MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_id END) AS datawd_task_id,
42
+ MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_instance_id END) AS datawd_task_instance_id,
43
+ MAX(CASE WHEN span_name = 'runner.killed' THEN compute_type END) AS compute_type,
44
+ 2 AS status_code
45
+ FROM internal_platform_db.notebook_span_info_query_engine_007
46
+ WHERE databus_imp_date >= '2026050400'
47
+ AND databus_imp_date <= '2026050700'
48
+ AND trace_id IN (SELECT trace_id FROM base_trace)
49
+ AND span_name IN ('runner.start', 'runner.killed')
50
+ GROUP BY trace_id
51
+ ),
52
+ base_data_time_fixed AS (
53
+ SELECT
54
+ trace_id,
55
+ span_name,
56
+ CASE
57
+ WHEN span_name = 'runner.killed'
58
+ THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)
59
+ OVER(PARTITION BY trace_id)
60
+ ELSE start_time
61
+ END AS start_time,
62
+ end_time,
63
+ datawd_project_id,
64
+ datawd_task_id,
65
+ datawd_task_instance_id,
66
+ compute_type,
67
+ status_code
68
+ FROM combined_spans
69
+ ),
70
+ base_data AS (
71
+ SELECT
72
+ trace_id,
73
+ span_name,
74
+ start_time,
75
+ end_time,
76
+ datawd_project_id,
77
+ datawd_task_id,
78
+ datawd_task_instance_id,
79
+ compute_type,
80
+ status_code,
81
+ from_unixtime(CAST(start_time AS BIGINT) / 1000) as start_date,
82
+ from_unixtime(CAST(end_time AS BIGINT) / 1000) as end_date,
83
+ datediff(from_unixtime(CAST(end_time AS BIGINT) / 1000), from_unixtime(CAST(start_time AS BIGINT) / 1000)) AS diff_days
84
+ FROM base_data_time_fixed
85
+ ),
86
+ pos_series AS (
87
+ SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos
88
+ ),
89
+ daily_split_spans AS (
90
+ SELECT
91
+ trace_id,
92
+ span_name,
93
+ datawd_project_id,
94
+ datawd_task_id,
95
+ datawd_task_instance_id,
96
+ compute_type,
97
+ status_code,
98
+ start_date,
99
+ end_date,
100
+ diff_days,
101
+ date_add(b.start_date, s.pos) AS calc_date,
102
+ CASE WHEN s.pos = 0 THEN CAST(b.start_time AS BIGINT)
103
+ ELSE unix_timestamp(cast(date_add(b.start_date, s.pos) as timestamp)) * 1000
104
+ END AS start_time,
105
+ CASE WHEN s.pos = b.diff_days THEN CAST(b.end_time AS BIGINT)
106
+ ELSE (unix_timestamp(cast(date_add(b.start_date, s.pos + 1) as timestamp)) * 1000) - 1
107
+ END AS end_time,
108
+ CAST(b.start_time AS BIGINT) AS span_start_time,
109
+ CAST(b.end_time AS BIGINT) AS span_end_time
110
+ FROM base_data b
111
+ INNER JOIN pos_series s ON s.pos <= b.diff_days
112
+ ),
113
+ trace_time_metrics AS (
114
+ SELECT
115
+ trace_id,
116
+ calc_date,
117
+ MAX(datawd_project_id) AS datawd_project_id,
118
+ MAX(datawd_task_id) AS datawd_task_id,
119
+ MAX(datawd_task_instance_id) AS datawd_task_instance_id,
120
+ MAX(compute_type) AS compute_type,
121
+ MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,
122
+ CAST(ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN end_time END) -
123
+ MIN(CASE WHEN span_name = 'runner.execute' THEN start_time END)) / 1000.0) AS INT) AS instance_run_time,
124
+ CAST(ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN end_time END) -
125
+ MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN start_time END)) / 1000.0) AS INT) AS code_run_time,
126
+ CAST(ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN end_time END) -
127
+ MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN start_time END)) / 1000.0) AS INT) AS resource_wait_time,
128
+ from_unixtime(MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN start_time END) / 1000) AS code_start_time,
129
+ from_unixtime(MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN end_time END) / 1000) AS code_end_time,
130
+ from_unixtime(MIN(CASE WHEN span_name = 'runner.execute' THEN span_start_time END) / 1000) AS instance_start_time,
131
+ from_unixtime(MAX(CASE WHEN span_name = 'runner.execute' THEN span_end_time END) / 1000) AS instance_end_time
132
+ FROM daily_split_spans
133
+ GROUP BY trace_id, calc_date
134
+ )
135
+ SELECT
136
+ t1.calc_date AS p_date,
137
+ t1.trace_id,
138
+ t1.datawd_project_id,
139
+ t1.datawd_task_id,
140
+ t1.datawd_task_instance_id,
141
+ t1.compute_type,
142
+ t1.status_code,
143
+ t1.instance_run_time,
144
+ t1.code_run_time,
145
+ t1.resource_wait_time,
146
+ t1.code_start_time,
147
+ t1.code_end_time,
148
+ t1.instance_start_time,
149
+ t1.instance_end_time,
150
+ t2.serving_id,
151
+ CAST(t2.is_permanent AS BOOLEAN) AS is_permanent,
152
+ CAST(t2.apply_for_gpu_count AS INT) AS apply_for_gpu_count
153
+ FROM trace_time_metrics t1 LEFT JOIN (
154
+ SELECT
155
+ trace_id,
156
+ MAX(serving_id) AS serving_id,
157
+ MAX(is_permanent) AS is_permanent,
158
+ SUM(CAST(replicas AS INT) * CAST(num_gpu AS INT)) AS apply_for_gpu_count
159
+ FROM internal_platform_db.notebook_engine_info_query_engine_007
160
+ WHERE databus_imp_date >= '2026050400'
161
+ AND databus_imp_date <= '2026050700'
162
+ AND compute_type = 'ray'
163
+ AND service_name = 'notebook-runner'
164
+ GROUP BY trace_id
165
+ ) t2 ON t1.trace_id = t2.trace_id
166
+ ;
tasks/offline-compute/HiveSQL/hivesql_003/init/init_db.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import re
3
+ from pyspark.sql import SparkSession
4
+
5
+ spark = SparkSession.builder \
6
+ .appName('hivesql_bench_init') \
7
+ .enableHiveSupport() \
8
+ .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \
9
+ .getOrCreate()
10
+
11
+ spark.sql('CREATE DATABASE IF NOT EXISTS internal_platform_db')
12
+
13
+
14
+ def _execute_sql_file(spark, sql_path):
15
+ """Read SQL file, remove SuperSQL SET headers, split by semicolons, execute."""
16
+ with open(sql_path, 'r', encoding='utf-8') as f:
17
+ content = f.read()
18
+ content = re.sub(r'^\s*set\s+query_engine\.\S+\n?', '', content, flags=re.IGNORECASE)
19
+ stmts, cur, in_sq, in_dq, i = [], [], False, False, 0
20
+ while i < len(content):
21
+ ch = content[i]
22
+ if ch == '\\' and i + 1 < len(content):
23
+ cur.append(ch); cur.append(content[i + 1]); i += 2; continue
24
+ if ch == '-' and i + 1 < len(content) and content[i + 1] == '-' and not in_sq and not in_dq:
25
+ while i < len(content) and content[i] != '\n':
26
+ i += 1
27
+ cur.append('\n'); continue
28
+ if ch == "'" and not in_dq:
29
+ in_sq = not in_sq
30
+ elif ch == '"' and not in_sq:
31
+ in_dq = not in_dq
32
+ if ch == ';' and not in_sq and not in_dq:
33
+ s = ''.join(cur).strip()
34
+ if s:
35
+ stmts.append(s)
36
+ cur = []
37
+ else:
38
+ cur.append(ch)
39
+ i += 1
40
+ last = ''.join(cur).strip()
41
+ if last:
42
+ stmts.append(last)
43
+ for stmt in stmts:
44
+ spark.sql(stmt)
45
+
46
+
47
+ _execute_sql_file(spark, '/tmp_workspace/init_db.sql')
48
+
49
+ tables = spark.sql('SHOW TABLES IN internal_platform_db').collect()
50
+ print(f'Init complete, {len(tables)} tables created')
51
+ for t in tables:
52
+ print(f' - {t.namespace}.{t.tableName}')
53
+ spark.stop()
tasks/offline-compute/HiveSQL/hivesql_003/init/init_db.sql ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS internal_platform_db;
2
+
3
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_span_info_query_engine_007 (
4
+ databus_imp_date STRING,
5
+ trace_id STRING,
6
+ span_kind STRING,
7
+ error_code STRING,
8
+ service_name STRING,
9
+ message STRING,
10
+ parent_span_id STRING,
11
+ span_name STRING,
12
+ duration BIGINT,
13
+ span_id STRING,
14
+ space_id STRING,
15
+ span_type STRING,
16
+ start_time STRING,
17
+ end_time STRING,
18
+ service_instance STRING,
19
+ status_code INT,
20
+ datawd_project_id STRING,
21
+ datawd_task_id STRING,
22
+ datawd_task_instance_id STRING,
23
+ compute_type STRING
24
+ ) STORED AS ORC;
25
+
26
+ INSERT INTO TABLE internal_platform_db.notebook_span_info_query_engine_007 VALUES
27
+ ('2026050700','trace_001','SERVER','0','notebook-runner','','','runner.killed',5000,'s1','','','1746590400000','1746590405000','inst1',2,'proj_01','task_01','inst_01','ray'),
28
+ ('2026050700','trace_001','SERVER','0','notebook-runner','','','runner.start',1000,'s2','','','1746590390000','1746590391000','inst1',0,'proj_01','task_01','inst_01','ray'),
29
+ ('2026050500','trace_001','SERVER','0','notebook-runner','','','execute.code.cell',3000,'s3','','','1746590392000','1746590395000','inst1',0,'proj_01','task_01','inst_01','ray'),
30
+ ('2026050500','trace_001','SERVER','0','notebook-runner','','','set.permanent.compute',2000,'s4','','','1746590388000','1746590390000','inst1',0,'proj_01','task_01','inst_01','ray'),
31
+ ('2026050700','trace_002','SERVER','0','notebook-runner','','','runner.killed',8000,'s5','','','1746590500000','1746590508000','inst2',2,'proj_02','task_02','inst_02','ray'),
32
+ ('2026050700','trace_002','SERVER','0','notebook-runner','','','runner.start',1000,'s6','','','1746590490000','1746590491000','inst2',0,'proj_02','task_02','inst_02','ray'),
33
+ ('2026050600','trace_002','SERVER','0','notebook-runner','','','client.execute.code',6000,'s7','','','1746590492000','1746590498000','inst2',0,'proj_02','task_02','inst_02','ray'),
34
+ ('2026050600','trace_002','SERVER','0','notebook-runner','','','create.non.permanent.compute',3000,'s8','','','1746590487000','1746590490000','inst2',0,'proj_02','task_02','inst_02','ray'),
35
+ ('2026050700','trace_003','SERVER','0','notebook-runner','','','runner.killed',4000,'s9','','','1746590600000','1746590604000','inst3',2,'proj_03','task_03','inst_03','ray'),
36
+ ('2026050700','trace_003','SERVER','0','notebook-runner','','','runner.execute',10000,'s10','','','1746590580000','1746590610000','inst3',0,'proj_03','task_03','inst_03','ray');
37
+
38
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_engine_info_query_engine_007 (
39
+ databus_imp_date STRING,
40
+ trace_id STRING,
41
+ service_name STRING,
42
+ compute_type STRING,
43
+ datawd_project_id STRING,
44
+ datawd_task_id STRING,
45
+ datawd_task_instance_id STRING,
46
+ is_permanent STRING,
47
+ serving_id STRING,
48
+ user_name STRING,
49
+ is_model_service STRING,
50
+ compute_info STRING,
51
+ num_gpu STRING,
52
+ replicas STRING,
53
+ gpu_type STRING,
54
+ `timestamp` STRING,
55
+ ray_job_id STRING,
56
+ reason STRING,
57
+ log_url STRING,
58
+ dashboard_url STRING
59
+ ) STORED AS ORC;
60
+
61
+ INSERT INTO TABLE internal_platform_db.notebook_engine_info_query_engine_007 VALUES
62
+ ('2026050700','trace_001','notebook-runner','ray','proj_01','task_01','inst_01','true','srv_001','user1','false','{}','2','1','A100','1746590400000','job1','','',''),
63
+ ('2026050700','trace_002','notebook-runner','ray','proj_02','task_02','inst_02','false','srv_002','user2','false','{}','4','2','V100','1746590500000','job2','','','');
64
+
65
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_query_engine_007 (
66
+ p_date STRING,
67
+ trace_id STRING,
68
+ datawd_project_id STRING,
69
+ datawd_task_id STRING,
70
+ datawd_task_instance_id STRING,
71
+ compute_type STRING,
72
+ status_code INT,
73
+ instance_run_time INT,
74
+ code_run_time INT,
75
+ resource_wait_time INT,
76
+ code_start_time STRING,
77
+ code_end_time STRING,
78
+ instance_start_time STRING,
79
+ instance_end_time STRING,
80
+ serving_id STRING,
81
+ is_permanent BOOLEAN,
82
+ apply_for_gpu_count INT
83
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
84
+
85
+ -- Agent 候选目标表
86
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_cand_query_engine_007 (
87
+ p_date STRING,
88
+ trace_id STRING,
89
+ datawd_project_id STRING,
90
+ datawd_task_id STRING,
91
+ datawd_task_instance_id STRING,
92
+ compute_type STRING,
93
+ status_code INT,
94
+ instance_run_time INT,
95
+ code_run_time INT,
96
+ resource_wait_time INT,
97
+ code_start_time STRING,
98
+ code_end_time STRING,
99
+ instance_start_time STRING,
100
+ instance_end_time STRING,
101
+ serving_id STRING,
102
+ is_permanent BOOLEAN,
103
+ apply_for_gpu_count INT
104
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_003/init/schema.sql ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_span_info_copilot (
2
+ `databus_imp_date` STRING COMMENT 'primary partition',
3
+ `trace_id` STRING COMMENT 'trace_id',
4
+ `span_kind` STRING COMMENT 'span_kind',
5
+ `error_code` STRING COMMENT 'error_code',
6
+ `service_name` STRING COMMENT 'service_name',
7
+ `message` STRING COMMENT 'message',
8
+ `parent_span_id` STRING COMMENT 'parent_span_id',
9
+ `span_name` STRING COMMENT 'span_name',
10
+ `duration` BIGINT COMMENT 'duration',
11
+ `span_id` STRING COMMENT 'span_id',
12
+ `space_id` STRING COMMENT 'space_id',
13
+ `span_type` STRING COMMENT 'span_type',
14
+ `start_time` STRING COMMENT 'start_time',
15
+ `end_time` STRING COMMENT 'end_time',
16
+ `service_instance` STRING COMMENT 'service_instance',
17
+ `status_code` INT COMMENT 'status_code',
18
+ `datawd_project_id` STRING COMMENT 'datawd_project_id',
19
+ `datawd_task_id` STRING COMMENT 'datawd_task_id',
20
+ `datawd_task_instance_id` STRING COMMENT 'datawd_task_instance_id',
21
+ `compute_type` STRING COMMENT 'compute_type'
22
+ ) STORED AS ORC;
23
+
24
+ CREATE TABLE IF NOT EXISTS internal_platform_db.notebook_engine_info_copilot (
25
+ `databus_imp_date` STRING COMMENT 'primary partition',
26
+ `trace_id` STRING COMMENT 'trace_id',
27
+ `service_name` STRING COMMENT 'service_name',
28
+ `compute_type` STRING COMMENT 'compute_type',
29
+ `datawd_project_id` STRING COMMENT 'datawd_project_id',
30
+ `datawd_task_id` STRING COMMENT 'datawd_task_id',
31
+ `datawd_task_instance_id` STRING COMMENT 'datawd_task_instance_id',
32
+ `is_permanent` STRING COMMENT 'is_permanent',
33
+ `serving_id` STRING COMMENT 'serving_id',
34
+ `user_name` STRING COMMENT 'user_name',
35
+ `is_model_service` STRING COMMENT 'is_model_service',
36
+ `compute_info` STRING COMMENT 'compute_info',
37
+ `num_gpu` STRING COMMENT 'num_gpu',
38
+ `replicas` STRING COMMENT 'replicas',
39
+ `gpu_type` STRING COMMENT 'gpu_type',
40
+ `timestamp` STRING COMMENT 'timestamp',
41
+ `ray_job_id` STRING,
42
+ `reason` STRING,
43
+ `log_url` STRING,
44
+ `dashboard_url` STRING
45
+ ) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_003/task.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: offline-compute_HiveSQL_hivesql_003
3
+ name: 从 `internal_platform_db.notebook_span_info_query_engine
4
+ category: offline-compute/HiveSQL
5
+ timeout_seconds: 600
6
+ modality: pure-text
7
+ engine: hivesql
8
+ ---
9
+ ## Prompt
10
+ 1) 任务目标
11
+ 识别并统计 Notebook 管道中被异常 kill 且缺失正常完成信号的 Ray 实例,按天拆分计算运行时长、代码执行时长、资源等待时长及 GPU 申请数。
12
+
13
+ 2) 输入
14
+ - `internal_platform_db.notebook_span_info_query_engine_007`
15
+ - `internal_platform_db.notebook_engine_info_query_engine_007`
16
+
17
+ 3) 处理规则
18
+ - 目标实例筛选:从 span_info 筛选 `compute_type='ray'` 且 `service_name='notebook-runner'` 的实例,选取有 `span_name='runner.killed'` 但无 `span_name='runner.execute'` 的 `trace_id`。
19
+ - 合成运行区间:对每个目标 trace_id,取 `span_name='runner.start'` 的 start_time 作为实例开始时间,取 `span_name='runner.killed'` 的 end_time 作为实例结束时间,合成 `runner.execute` 区间,`status_code` 固定为 2。
20
+ - 跨天拆分:将合成区间按自然日拆分为多条记录,每条对应一天内的部分,`calc_date` 为拆分后的日期。
21
+ - 时长计算(按 trace_id 与 calc_date):
22
+ - instance_run_time:合成区间在当天的起止时间差(毫秒转秒)。
23
+ - code_run_time:`span_name` 为 'execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed' 在当天的起止时间差(毫秒转秒)。
24
+ - resource_wait_time:`span_name` 为 'set.permanent.compute', 'create.non.permanent.compute' 在当天的起止时间差(毫秒转秒)。
25
+ - 输出 code_start_time/code_end_time/instance_start_time/instance_end_time(时间戳转字符串)。
26
+ - 关联引擎信息:左关联 engine_info(过滤 `compute_type='ray'` 且 `service_name='notebook-runner'`),关联键 `trace_id`,获取 serving_id、is_permanent,计算 `apply_for_gpu_count = SUM(replicas * num_gpu)`。
27
+
28
+ 4) 输出要求
29
+ 输出字段顺序:dt(STRING,分区)、p_date(STRING,calc_date)、trace_id(STRING)、datawd_project_id(STRING)、datawd_task_id(STRING)、datawd_task_instance_id(STRING)、compute_type(STRING)、status_code(INT)、instance_run_time(INT)、code_run_time(INT)、resource_wait_time(INT)、code_start_time(STRING)、code_end_time(STRING)、instance_start_time(STRING)、instance_end_time(STRING)、serving_id(STRING)、is_permanent(BOOLEAN)、apply_for_gpu_count(INT)。
30
+
31
+ 5) 写入要求
32
+ 目标表:`internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_cand_query_engine_007`。分区字段:dt。写入分区:`dt='20260507'`。写入模式:覆盖。
33
+
34
+ 请将最终 HiveSQL 写入 result.sql 并执行。
tasks/offline-compute/HiveSQL/hivesql_004/gt/expected.csv ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ username,application_group,application_group_owner,product_id,product_name,product_owner,obs_product_id,obs_product_name,obs_product_owner,department,plan_product_id,plan_product_name,plan_product_owner,application_group_numbers,application_group_owners,product_owners,obs_product_owners,plan_product_owners,bg,id,dt
2
+ user_e,group_delta,4,105,prod_v,205,305,obs_prod_e,405,dept_finance,505,plan_e,605,2,owner5,powner5,obs_owner5,plan_owner5,BG2,5,20260507
3
+ user_d,group_alpha,1,104,prod_w,204,304,obs_prod_d,404,dept_eng,504,plan_d,604,7,owner4,powner4,obs_owner4,plan_owner4,BG3,4,20260507
4
+ user_a,group_alpha,1,101,prod_x,201,301,obs_prod_a,401,dept_eng,501,plan_a,601,5,owner1,powner1,obs_owner1,plan_owner1,BG1,1,20260507
5
+ user_b,group_beta,2,102,prod_y,202,302,obs_prod_b,402,dept_sales,502,plan_b,602,10,owner2,powner2,obs_owner2,plan_owner2,BG2,2,20260507
6
+ user_c,group_gamma,3,103,prod_z,203,303,obs_prod_c,403,dept_hr,503,plan_c,603,3,owner3,powner3,obs_owner3,plan_owner3,BG1,3,20260507
tasks/offline-compute/HiveSQL/hivesql_004/gt/grade.py ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hivesql_011 精细评分脚本
2
+
3
+ 业务场景:应用组与产品归属关系按天做历史快照,追加 dt 分区列全量覆盖写入
4
+ 难度: EASY | 特征: INSERT_OVERWRITE|PARTITION|SINGLE_TABLE|APPEND_DT_COLUMN
5
+
6
+ 评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
7
+ A_executability (15分): result.sql 能跑通且产出非空
8
+ B_schema (10分): 21列(5) + 列名匹配(5)
9
+ C_row_alignment (15分): 行数比例(7) + key覆盖率(8)
10
+ D_field_value_match (25分): 非key字段逐列值匹配率
11
+ D_field_completeness (15分): 关键字段非空/非空串比例
12
+ F_insert_overwrite (5分): INSERT OVERWRITE + PARTITION
13
+ F_partition_value (5分): dt 分区值 = 20260507
14
+ F_dt_column (10分): dt 派生列存在于输出且值正确
15
+
16
+ 权重: EASY -> product=0.5, process=0.5
17
+ """
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import tempfile
22
+ import json
23
+ import math
24
+
25
+
26
+ def grade(workspace_path, **kwargs):
27
+
28
+ # ========== Case 配置 ==========
29
+ OUTPUT_TABLE = "internal_platform_db.app_group_product_info_history_cand_query_engine_011"
30
+ DIFFICULTY = "EASY"
31
+ SOURCE_TABLES = ["app_group_product_info_query_engine_011", "app_group_product_info_history_query_engine_011"]
32
+ KEY_COLUMNS = ["product_id", "obs_product_id", "plan_product_id", "id", "dt"]
33
+ EXPECTED_COL_COUNT = 21
34
+ KEY_FIELDS = ["username", "application_group", "product_id", "product_name", "bg", "id"]
35
+ GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
36
+
37
+ DIFFICULTY_WEIGHTS = {
38
+ "EASY": (0.5, 0.5),
39
+ "MEDIUM": (0.6, 0.4),
40
+ "HARD": (0.7, 0.3),
41
+ "EXPERT": (0.8, 0.2),
42
+ }
43
+
44
+ _SPARK_SUBMIT_TIMEOUT = 300
45
+ _JSON_START = "__GRADE_JSON_START__"
46
+ _JSON_END = "__GRADE_JSON_END__"
47
+
48
+ result = {
49
+ "overall_score": 0.0,
50
+ "total_points": 0,
51
+ "grade": "",
52
+ "details": {},
53
+ "diagnostics": [],
54
+ }
55
+
56
+ # ========== 内部辅助函数 ==========
57
+
58
+ def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
59
+ if pred_val is None and gt_val is None:
60
+ return True
61
+ if pred_val is None or gt_val is None:
62
+ return False
63
+ s_pred = str(pred_val).strip()
64
+ s_gt = str(gt_val).strip()
65
+ if s_pred == s_gt:
66
+ return True
67
+ try:
68
+ pv = float(s_pred)
69
+ gv = float(s_gt)
70
+ if math.isnan(pv) and math.isnan(gv):
71
+ return True
72
+ if math.isnan(pv) or math.isnan(gv):
73
+ return False
74
+ if abs(gv) < abs_tol:
75
+ return abs(pv - gv) <= abs_tol
76
+ return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
77
+ except (ValueError, TypeError):
78
+ pass
79
+ return s_pred.lower() == s_gt.lower()
80
+
81
+ def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
82
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
83
+ f.write(script_code)
84
+ script_path = f.name
85
+ try:
86
+ r = subprocess.run(
87
+ ["spark-submit", script_path],
88
+ capture_output=True, text=True, timeout=timeout,
89
+ )
90
+ stdout = r.stdout or ""
91
+ if _JSON_START in stdout and _JSON_END in stdout:
92
+ json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
93
+ return json.loads(json_str), None
94
+ else:
95
+ if r.returncode == 0:
96
+ for line in stdout.splitlines():
97
+ if line.strip().startswith("Traceback"):
98
+ return None, f"spark-submit error: {line}"
99
+ return None, "spark-submit 无 JSON 输出"
100
+ err_msg = (r.stderr or "")[-500:]
101
+ return None, f"spark-submit failed: {err_msg}"
102
+ except subprocess.TimeoutExpired:
103
+ return None, f"spark-submit 超时 ({timeout}s)"
104
+ except Exception as e:
105
+ return None, f"spark-submit 异常: {e}"
106
+ finally:
107
+ try:
108
+ os.unlink(script_path)
109
+ except OSError:
110
+ pass
111
+
112
+ def read_table_via_spark_submit(table_name):
113
+ """Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
114
+ if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
115
+ raise ValueError(f"非法表名: {table_name}")
116
+ read_script = f'''
117
+ import json
118
+ from pyspark.sql import SparkSession
119
+ spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
120
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
121
+ try:
122
+ df = spark.sql("SELECT * FROM {table_name}")
123
+ cols = [c.lower() for c in df.columns]
124
+ rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
125
+ print("{_JSON_START}")
126
+ print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
127
+ print("{_JSON_END}")
128
+ except Exception as e:
129
+ print("{_JSON_START}")
130
+ print(json.dumps({{"error": str(e)}}))
131
+ print("{_JSON_END}")
132
+ finally:
133
+ spark.stop()
134
+ '''
135
+ data, err = _run_spark_script(read_script)
136
+ if err:
137
+ raise RuntimeError(f"read_table failed: {err}")
138
+ if "error" in data:
139
+ raise RuntimeError(f"query failed: {data['error']}")
140
+ return data["cols"], data["rows"]
141
+
142
+ # SQL executor template (self-contained, no external dependency)
143
+ _SQL_EXEC_TEMPLATE = '''
144
+ import json, re
145
+ from pyspark.sql import SparkSession
146
+ spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
147
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
148
+ try:
149
+ with open("{sql_file}", "r", encoding="utf-8") as _f:
150
+ _sql = _f.read()
151
+ _sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
152
+ _stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
153
+ while _i < len(_sql):
154
+ _ch = _sql[_i]
155
+ if _ch == "\\\\" and _i + 1 < len(_sql):
156
+ _cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
157
+ if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
158
+ while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
159
+ _cur.append("\\n"); continue
160
+ if _ch == "'" and not _in_dq: _in_sq = not _in_sq
161
+ elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
162
+ if _ch == ";" and not _in_sq and not _in_dq:
163
+ _s = "".join(_cur).strip()
164
+ if _s: _stmts.append(_s)
165
+ _cur = []
166
+ else:
167
+ _cur.append(_ch)
168
+ _i += 1
169
+ _last = "".join(_cur).strip()
170
+ if _last: _stmts.append(_last)
171
+ for _stmt in _stmts:
172
+ spark.sql(_stmt)
173
+ print("{_JSON_START}")
174
+ print(json.dumps({{"ok": True}}))
175
+ print("{_JSON_END}")
176
+ except Exception as e:
177
+ print("{_JSON_START}")
178
+ print(json.dumps({{"ok": False, "error": str(e)}}))
179
+ print("{_JSON_END}")
180
+ finally:
181
+ spark.stop()
182
+ '''
183
+
184
+ def execute_result_sql():
185
+ result_sql = os.path.join(workspace_path, "result.sql")
186
+ if not os.path.exists(result_sql):
187
+ return False, "no_result_file"
188
+ # 替换 数据平台WD时间变量(沙箱 spark-sql 不支持 ${...} 语法)
189
+ with open(result_sql, 'r', encoding='utf-8') as _rf:
190
+ _sql_text = _rf.read()
191
+ _bizdate = '20260507'
192
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
193
+ _sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
194
+ _sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
195
+ _sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
196
+ with open(result_sql, 'w', encoding='utf-8') as _wf:
197
+ _wf.write(_sql_text)
198
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
199
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
200
+ data, err = _run_spark_script(script)
201
+ if err:
202
+ return False, f"execution_error: {err}"
203
+ if data and data.get("ok"):
204
+ return True, None
205
+ return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
206
+
207
+ def execute_ground_truth_sql():
208
+ gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
209
+ if not os.path.exists(gt_sql):
210
+ return False, "ground_truth.sql not found"
211
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
212
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
213
+ data, err = _run_spark_script(script)
214
+ if err:
215
+ return False, f"gt_execution_error: {err}"
216
+ if data and data.get("ok"):
217
+ return True, None
218
+ return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
219
+
220
+ def truncate_table(table_name):
221
+ script = f'''
222
+ from pyspark.sql import SparkSession
223
+ spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
224
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
225
+ spark.sql("TRUNCATE TABLE {table_name}")
226
+ spark.stop()
227
+ '''
228
+ try:
229
+ _run_spark_script(script, timeout=120)
230
+ except Exception:
231
+ pass
232
+
233
+ def restore_hive_site():
234
+ """Restore hive-site.xml to canonical state (agent may have modified it)."""
235
+ canonical_hive_site = '''<?xml version="1.0"?>
236
+ <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
237
+ <configuration>
238
+ <property>
239
+ <name>hive.metastore.uris</name>
240
+ <value>thrift://localhost:9083</value>
241
+ </property>
242
+ <property>
243
+ <name>hive.metastore.warehouse.dir</name>
244
+ <value>/tmp/hive_warehouse</value>
245
+ </property>
246
+ <property>
247
+ <name>javax.jdo.option.ConnectionURL</name>
248
+ <value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
249
+ </property>
250
+ <property>
251
+ <name>javax.jdo.option.ConnectionDriverName</name>
252
+ <value>org.apache.derby.jdbc.EmbeddedDriver</value>
253
+ </property>
254
+ <property>
255
+ <name>datanucleus.schema.autoCreateAll</name>
256
+ <value>true</value>
257
+ </property>
258
+ <property>
259
+ <name>hive.metastore.schema.verification</name>
260
+ <value>false</value>
261
+ </property>
262
+ </configuration>
263
+ '''
264
+ hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
265
+ try:
266
+ with open(hive_site_path, 'w') as f:
267
+ f.write(canonical_hive_site)
268
+ except Exception:
269
+ pass
270
+
271
+ def finalize(result):
272
+ product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
273
+ product_dims = ["A_executability"] + ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_dt_column', 'F_insert_overwrite', 'F_partition_value']
274
+ product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
275
+ product_ratio = product_raw / 100.0
276
+ for dim in ["H_efficiency"]:
277
+ if dim in result["details"]:
278
+ raw = result["details"][dim].get("score", 0)
279
+ result["details"][dim]["score_before_scaling"] = raw
280
+ result["details"][dim]["score"] = round(raw * product_ratio, 2)
281
+ result["details"][dim]["product_ratio"] = round(product_ratio, 4)
282
+ process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
283
+ process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
284
+ product_score = round(product_raw * product_weight, 2)
285
+ process_score = round(process_raw * process_weight, 2)
286
+ total = round(product_score + process_score, 2)
287
+ result["total_points"] = total
288
+ result["product_points"] = product_score
289
+ result["process_points"] = round(process_score, 2)
290
+ result["weights"] = {"product": product_weight, "process": process_weight}
291
+ result["overall_score"] = round(total / 100.0, 4)
292
+ if total >= 90:
293
+ result["grade"] = "优秀"
294
+ elif total >= 75:
295
+ result["grade"] = "良好"
296
+ elif total >= 60:
297
+ result["grade"] = "合格"
298
+ elif total >= 40:
299
+ result["grade"] = "偏弱"
300
+ else:
301
+ result["grade"] = "不合格"
302
+ return result
303
+
304
+ # Restore hive-site.xml (agent may have modified it)
305
+ restore_hive_site()
306
+
307
+ # ========== A. 可执行性 (15分) ==========
308
+ a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
309
+ exec_ok, exec_err = execute_result_sql()
310
+ if not exec_ok:
311
+ detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
312
+ result["details"]["A_executability"] = {"score": 0, "max": 15, "detail": detail}
313
+ result["error"] = detail
314
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_dt_column', 'F_insert_overwrite', 'F_partition_value']:
315
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
316
+ return finalize(result)
317
+
318
+ a_items["A1_exec_ok"] = 8
319
+
320
+ pred_headers, pred_rows = [], []
321
+ try:
322
+ pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
323
+ except Exception as e:
324
+ result["diagnostics"].append(f"read_pred_failed: {e}")
325
+
326
+ if not pred_rows:
327
+ result["details"]["A_executability"] = {"score": 8, "max": 15, "items": a_items}
328
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_dt_column', 'F_insert_overwrite', 'F_partition_value']:
329
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
330
+ return finalize(result)
331
+
332
+ a_items["A2_has_data"] = 7
333
+ result["details"]["A_executability"] = {"score": 15, "max": 15, "items": a_items}
334
+
335
+ # ========== Execute GT + Read GT ==========
336
+ truncate_table(GT_TABLE)
337
+ gt_ok, gt_err = execute_ground_truth_sql()
338
+ if not gt_ok:
339
+ result["error"] = f"ground_truth failed: {gt_err}"
340
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_dt_column', 'F_insert_overwrite', 'F_partition_value']:
341
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
342
+ return finalize(result)
343
+
344
+ gt_headers, gt_rows = [], []
345
+ try:
346
+ gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
347
+ except Exception as e:
348
+ result["error"] = f"read_gt_failed: {e}"
349
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_dt_column', 'F_insert_overwrite', 'F_partition_value']:
350
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
351
+ return finalize(result)
352
+
353
+ # ========== B/C/D/F 维度评分 ==========
354
+ pred_col_map = {h: i for i, h in enumerate(pred_headers)}
355
+ gt_col_map = {h: i for i, h in enumerate(gt_headers)}
356
+
357
+ # ========== B. Schema正确性 (10分) ==========
358
+ b_items = {}
359
+ # B1: ���数 (5分)
360
+ if len(pred_headers) == EXPECTED_COL_COUNT:
361
+ b_items["B1_col_count"] = 5
362
+ elif abs(len(pred_headers) - EXPECTED_COL_COUNT) <= 2:
363
+ b_items["B1_col_count"] = 3
364
+ else:
365
+ b_items["B1_col_count"] = 0
366
+
367
+ # B2: 列名匹配 (5分)
368
+ gt_col_set = set(gt_headers)
369
+ pred_col_set = set(pred_headers)
370
+ name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
371
+ if name_match_rate >= 0.95:
372
+ b_items["B2_col_names"] = 5
373
+ elif name_match_rate >= 0.8:
374
+ b_items["B2_col_names"] = 3
375
+ else:
376
+ b_items["B2_col_names"] = 0
377
+
378
+ b_score = sum(b_items.values())
379
+ result["details"]["B_schema"] = {
380
+ "score": b_score, "max": 10,
381
+ "detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
382
+ }
383
+
384
+ # ========== C. 行一致性 (15分) ==========
385
+ c_items = {}
386
+ gt_row_count = len(gt_rows)
387
+ pred_row_count = len(pred_rows)
388
+
389
+ # C1: 行数比例 (7分)
390
+ if gt_row_count > 0:
391
+ ratio = pred_row_count / gt_row_count
392
+ if 0.95 <= ratio <= 1.05:
393
+ c_items["C1_row_ratio"] = 7
394
+ elif 0.7 <= ratio <= 1.3:
395
+ c_items["C1_row_ratio"] = 4
396
+ else:
397
+ c_items["C1_row_ratio"] = 0
398
+ else:
399
+ c_items["C1_row_ratio"] = 7 if pred_row_count == 0 else 0
400
+
401
+ # C2: key覆盖率 (8分)
402
+ key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
403
+ if key_cols_avail and gt_row_count > 0:
404
+ gt_keys = set()
405
+ for row in gt_rows:
406
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
407
+ gt_keys.add(key)
408
+ pred_keys = set()
409
+ for row in pred_rows:
410
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
411
+ pred_keys.add(key)
412
+ coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
413
+ if coverage >= 0.995:
414
+ c_items["C2_key_coverage"] = 8
415
+ elif coverage >= 0.9:
416
+ c_items["C2_key_coverage"] = 6
417
+ elif coverage >= 0.7:
418
+ c_items["C2_key_coverage"] = 3
419
+ else:
420
+ c_items["C2_key_coverage"] = round(8 * coverage, 2)
421
+ else:
422
+ c_items["C2_key_coverage"] = 0
423
+
424
+ c_score = sum(v for v in c_items.values())
425
+ result["details"]["C_row_alignment"] = {"score": c_score, "max": 15, "detail": c_items}
426
+
427
+ # 构建索引
428
+ if key_cols_avail:
429
+ pred_index = {}
430
+ for row in pred_rows:
431
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
432
+ pred_index[key] = row
433
+ gt_index = {}
434
+ for row in gt_rows:
435
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
436
+ gt_index[key] = row
437
+ else:
438
+ pred_index = {}
439
+ gt_index = {}
440
+
441
+ # ========== D. 字段值匹配 (25分) ==========
442
+ value_cols = [c for c in gt_headers if c in pred_col_map and c not in KEY_COLUMNS]
443
+ if not value_cols:
444
+ value_cols = [c for c in gt_headers if c in pred_col_map]
445
+
446
+ d_val_items = {}
447
+ per_col_weight = 25.0 / max(len(value_cols), 1)
448
+ d_val_score = 0
449
+ for col in value_cols:
450
+ gt_ci = gt_col_map.get(col)
451
+ pred_ci = pred_col_map.get(col)
452
+ if gt_ci is None or pred_ci is None:
453
+ d_val_items[col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
454
+ continue
455
+ matches = 0
456
+ total = 0
457
+ for key, gt_row in gt_index.items():
458
+ pred_row = pred_index.get(key)
459
+ if pred_row is None:
460
+ total += 1
461
+ continue
462
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
463
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
464
+ if values_match(pred_val, gt_val):
465
+ matches += 1
466
+ total += 1
467
+ rate = matches / max(total, 1)
468
+ col_score = rate * per_col_weight
469
+ d_val_score += col_score
470
+ d_val_items[col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2)}
471
+
472
+ result["details"]["D_field_value_match"] = {
473
+ "score": round(d_val_score, 2), "max": 25, "detail": d_val_items,
474
+ }
475
+
476
+ # ========== D. 字段完整性 (15分) ==========
477
+ d_comp_items = {}
478
+ d_comp_score = 0
479
+ per_field_weight = 15.0 / max(len(KEY_FIELDS), 1)
480
+ for field in KEY_FIELDS:
481
+ gt_ci = gt_col_map.get(field)
482
+ pred_ci = pred_col_map.get(field)
483
+ if gt_ci is None or pred_ci is None:
484
+ d_comp_items[field] = {"score": 0, "reason": "column_missing"}
485
+ continue
486
+ gt_nonempty = 0
487
+ pred_nonempty = 0
488
+ total = 0
489
+ for key, gt_row in gt_index.items():
490
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
491
+ if gt_val:
492
+ total += 1
493
+ pred_row = pred_index.get(key)
494
+ if pred_row is not None:
495
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
496
+ if pred_val:
497
+ pred_nonempty += 1
498
+ gt_nonempty = total
499
+ rate = pred_nonempty / max(gt_nonempty, 1)
500
+ field_score = rate * per_field_weight
501
+ d_comp_score += field_score
502
+ d_comp_items[field] = {"nonempty_rate": round(rate, 4), "score": round(field_score, 2)}
503
+
504
+ result["details"]["D_field_completeness"] = {
505
+ "score": round(d_comp_score, 2), "max": 15, "detail": d_comp_items,
506
+ }
507
+
508
+ # ========== F. INSERT OVERWRITE (5分) ==========
509
+ result_sql_path = os.path.join(workspace_path, "result.sql")
510
+ sql_text = ""
511
+ try:
512
+ with open(result_sql_path, "r", encoding="utf-8") as f:
513
+ sql_text = f.read().lower()
514
+ except Exception:
515
+ sql_text = ""
516
+
517
+ f_insert_items = {}
518
+ has_overwrite = "insert overwrite" in sql_text
519
+ has_partition = "partition" in sql_text
520
+ if has_overwrite and has_partition:
521
+ f_insert_items["insert_overwrite_partition"] = 5
522
+ elif has_overwrite:
523
+ f_insert_items["insert_overwrite_partition"] = 3
524
+ else:
525
+ f_insert_items["insert_overwrite_partition"] = 0
526
+ result["details"]["F_insert_overwrite"] = {
527
+ "score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
528
+ }
529
+
530
+ # ========== F. 分区值 (5分) ==========
531
+ f_part_items = {}
532
+ if "dt" in sql_text and "20260507" in sql_text:
533
+ f_part_items["partition_value"] = 5
534
+ else:
535
+ f_part_items["partition_value"] = 0
536
+ result["details"]["F_partition_value"] = {
537
+ "score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
538
+ }
539
+
540
+ # ========== F. dt 派生列 (10分) ==========
541
+ f_dt_items = {}
542
+ dt_col_exists = "dt" in pred_col_map
543
+ dt_values_correct = False
544
+ if dt_col_exists:
545
+ dt_ci = pred_col_map["dt"]
546
+ correct_count = 0
547
+ total_count = 0
548
+ for row in pred_rows:
549
+ if dt_ci < len(row):
550
+ total_count += 1
551
+ if row[dt_ci].strip() == "20260507":
552
+ correct_count += 1
553
+ dt_values_correct = total_count > 0 and correct_count == total_count
554
+
555
+ if dt_col_exists and dt_values_correct:
556
+ f_dt_items["dt_column"] = 10
557
+ elif dt_col_exists:
558
+ f_dt_items["dt_column"] = 5
559
+ else:
560
+ f_dt_items["dt_column"] = 0
561
+ result["details"]["F_dt_column"] = {
562
+ "score": f_dt_items["dt_column"], "max": 10, "detail": f_dt_items,
563
+ }
564
+
565
+ # 汇总
566
+ total = (15 + b_score + c_score + d_val_score + d_comp_score
567
+ + f_insert_items["insert_overwrite_partition"]
568
+ + f_part_items["partition_value"]
569
+ + f_dt_items["dt_column"])
570
+
571
+ # ========== G~I 过程评分 ==========
572
+ TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
573
+ OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
574
+ INPUT_TABLE_SHORT = SOURCE_TABLES[0]
575
+
576
+ transcript_entries = []
577
+ has_transcript = False
578
+ try:
579
+ if os.path.exists(TRANSCRIPT_PATH):
580
+ with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f:
581
+ for line in f:
582
+ line = line.strip()
583
+ if line:
584
+ try:
585
+ transcript_entries.append(json.loads(line))
586
+ except json.JSONDecodeError:
587
+ continue
588
+ if len(transcript_entries) > 2:
589
+ has_transcript = True
590
+ except Exception:
591
+ pass
592
+
593
+ if not has_transcript:
594
+ result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}}
595
+ result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}}
596
+ result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}}
597
+ return finalize(result)
598
+
599
+ # Parse transcript into structured events
600
+ tool_uses = []
601
+ first_write_result_idx = None
602
+ last_spark_submit_success_idx = None
603
+ write_result_count = 0
604
+ logic_error_retries = 0
605
+
606
+ for idx, entry in enumerate(transcript_entries):
607
+ content = entry.get("content", [])
608
+ if isinstance(content, str):
609
+ content = [content]
610
+
611
+ for block_str in content:
612
+ if not isinstance(block_str, str):
613
+ continue
614
+ if "ToolUseBlock" in block_str:
615
+ name_match = re.search(r"name='([^']+)'", block_str)
616
+ input_match = re.search(r"input=(\{.*\})", block_str)
617
+ if name_match:
618
+ tool_name = name_match.group(1)
619
+ tool_input = input_match.group(1) if input_match else ""
620
+ tool_uses.append((idx, tool_name, tool_input))
621
+ if tool_name == "Write" and "result.sql" in tool_input:
622
+ write_result_count += 1
623
+ if first_write_result_idx is None:
624
+ first_write_result_idx = idx
625
+ if "ToolResultBlock" in block_str:
626
+ if "Traceback" in block_str or "Exception" in block_str:
627
+ env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
628
+ "db.lck", "TTransportException", "port 10000"]
629
+ is_env_error = any(e in block_str for e in env_errors)
630
+ has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
631
+ for t in tool_uses)
632
+ if not is_env_error and has_spark_submit:
633
+ logic_error_retries += 1
634
+ if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" in block_str:
635
+ if "Exit Code: 0" in block_str and "Traceback" not in block_str:
636
+ last_spark_submit_success_idx = idx
637
+
638
+ before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
639
+
640
+ # ===== G. 探索充分性 (35分) =====
641
+ g_items = {}
642
+ g1_pass = any(name == "Read" and "schema" in inp.lower()
643
+ for idx, name, inp in tool_uses if idx < before_first_write)
644
+ g_items["G1_source_schema"] = 9 if g1_pass else 0
645
+
646
+ g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
647
+ and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
648
+ for idx, name, inp in tool_uses if idx < before_first_write)
649
+ g_items["G2_source_sample"] = 9 if g2_pass else 0
650
+
651
+ g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
652
+ and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
653
+ for idx, name, inp in tool_uses if idx < before_first_write)
654
+ g_items["G3_distribution"] = 9 if g3_pass else 0
655
+
656
+ g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
657
+ and OUTPUT_TABLE_SHORT in inp
658
+ for idx, name, inp in tool_uses if idx < before_first_write)
659
+ g_items["G4_target_schema"] = 8 if g4_pass else 0
660
+
661
+ g_score = sum(g_items.values())
662
+ result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
663
+
664
+ # ===== H. 执行效率 (40分) =====
665
+ h_items = {}
666
+ if write_result_count <= 2:
667
+ h_items["H1_few_submissions"] = 20
668
+ elif write_result_count <= 4:
669
+ h_items["H1_few_submissions"] = 13
670
+ elif write_result_count <= 6:
671
+ h_items["H1_few_submissions"] = 7
672
+ else:
673
+ h_items["H1_few_submissions"] = 0
674
+
675
+ if logic_error_retries == 0:
676
+ h_items["H2_no_logic_errors"] = 13
677
+ elif logic_error_retries <= 1:
678
+ h_items["H2_no_logic_errors"] = 7
679
+ else:
680
+ h_items["H2_no_logic_errors"] = 0
681
+
682
+ h_items["H3_no_redundancy"] = 7
683
+ h_score = sum(h_items.values())
684
+ result["details"]["H_efficiency"] = {"score": min(h_score, 40), "max": 40, "items": h_items}
685
+
686
+ # ===== I. 自验证行为 (25分) =====
687
+ i_items = {}
688
+ post_submit_uses = []
689
+ if last_spark_submit_success_idx is not None:
690
+ post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
691
+ if idx > last_spark_submit_success_idx]
692
+
693
+ i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
694
+ for _, name, inp in post_submit_uses)
695
+ i_items["I1_query_output"] = 8 if i1_pass else 0
696
+
697
+ i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
698
+ and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
699
+ for _, name, inp in post_submit_uses)
700
+ i_items["I2_check_count"] = 9 if i2_pass else 0
701
+
702
+ i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
703
+ and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper())
704
+ for _, name, inp in post_submit_uses)
705
+ i_items["I3_check_values"] = 8 if i3_pass else 0
706
+
707
+ i_score = sum(i_items.values())
708
+ result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items}
709
+
710
+ return finalize(result)
tasks/offline-compute/HiveSQL/hivesql_004/gt/grade_spec.csv ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 维度,维度全名,子维度,满分,说明
2
+ A,A_executability,executability,15,result.sql 能跑通且产出非空
3
+ B,B_schema,schema,10,21列(5) + 列名匹配(5)
4
+ C,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)
5
+ D,D_field_value_match,field_value_match,25,非key字段逐列值匹配率
6
+ D,D_field_completeness,field_completeness,15,关键字段非空/非空串比例
7
+ F,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION
8
+ F,F_partition_value,partition_value,5,dt 分区值 = 20260507
9
+ F,F_dt_column,dt_column,10,dt 派生列存在于输出且值正确
10
+
11
+ 总计,,,100,
12
+
13
+ # 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
14
+ # 难度,EASY
15
+ # 权重,"product=0.5, process=0.5"
16
+ # 范式,new
17
+ # Key列,"product_id, obs_product_id, plan_product_id, id, dt"
18
+ # 预期列数,21
19
+ # 输出表,internal_platform_db.app_group_product_info_history_cand_query_engine_011
tasks/offline-compute/HiveSQL/hivesql_004/gt/ground_truth.sql ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ insert overwrite TABLE internal_platform_db.app_group_product_info_history_query_engine_011 PARTITION (dt = '20260507')
2
+ SELECT
3
+ username,
4
+ application_group,
5
+ application_group_owner,
6
+ product_id,
7
+ product_name,
8
+ product_owner,
9
+ obs_product_id,
10
+ obs_product_name,
11
+ obs_product_owner,
12
+ department,
13
+ plan_product_id,
14
+ plan_product_name,
15
+ plan_product_owner,
16
+ application_group_numbers,
17
+ application_group_owners,
18
+ product_owners,
19
+ obs_product_owners,
20
+ plan_product_owners,
21
+ bg,
22
+ id
23
+ FROM internal_platform_db.app_group_product_info_query_engine_011;
tasks/offline-compute/HiveSQL/hivesql_004/init/init_db.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import re
3
+ from pyspark.sql import SparkSession
4
+
5
+ spark = SparkSession.builder \
6
+ .appName('hivesql_bench_init') \
7
+ .enableHiveSupport() \
8
+ .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \
9
+ .getOrCreate()
10
+
11
+ spark.sql('CREATE DATABASE IF NOT EXISTS internal_platform_db')
12
+
13
+
14
+ def _execute_sql_file(spark, sql_path):
15
+ """Read SQL file, remove SuperSQL SET headers, split by semicolons, execute."""
16
+ with open(sql_path, 'r', encoding='utf-8') as f:
17
+ content = f.read()
18
+ content = re.sub(r'^\s*set\s+query_engine\.\S+\n?', '', content, flags=re.IGNORECASE)
19
+ stmts, cur, in_sq, in_dq, i = [], [], False, False, 0
20
+ while i < len(content):
21
+ ch = content[i]
22
+ if ch == '\\' and i + 1 < len(content):
23
+ cur.append(ch); cur.append(content[i + 1]); i += 2; continue
24
+ if ch == '-' and i + 1 < len(content) and content[i + 1] == '-' and not in_sq and not in_dq:
25
+ while i < len(content) and content[i] != '\n':
26
+ i += 1
27
+ cur.append('\n'); continue
28
+ if ch == "'" and not in_dq:
29
+ in_sq = not in_sq
30
+ elif ch == '"' and not in_sq:
31
+ in_dq = not in_dq
32
+ if ch == ';' and not in_sq and not in_dq:
33
+ s = ''.join(cur).strip()
34
+ if s:
35
+ stmts.append(s)
36
+ cur = []
37
+ else:
38
+ cur.append(ch)
39
+ i += 1
40
+ last = ''.join(cur).strip()
41
+ if last:
42
+ stmts.append(last)
43
+ for stmt in stmts:
44
+ spark.sql(stmt)
45
+
46
+
47
+ _execute_sql_file(spark, '/tmp_workspace/init_db.sql')
48
+
49
+ tables = spark.sql('SHOW TABLES IN internal_platform_db').collect()
50
+ print(f'Init complete, {len(tables)} tables created')
51
+ for t in tables:
52
+ print(f' - {t.namespace}.{t.tableName}')
53
+ spark.stop()
tasks/offline-compute/HiveSQL/hivesql_004/init/init_db.sql ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS internal_platform_db;
2
+
3
+ CREATE TABLE IF NOT EXISTS internal_platform_db.app_group_product_info_query_engine_011 (
4
+ username STRING,
5
+ application_group STRING,
6
+ application_group_owner INT,
7
+ product_id INT,
8
+ product_name STRING,
9
+ product_owner INT,
10
+ obs_product_id INT,
11
+ obs_product_name STRING,
12
+ obs_product_owner INT,
13
+ department STRING,
14
+ plan_product_id INT,
15
+ plan_product_name STRING,
16
+ plan_product_owner INT,
17
+ application_group_numbers STRING,
18
+ application_group_owners STRING,
19
+ product_owners STRING,
20
+ obs_product_owners STRING,
21
+ plan_product_owners STRING,
22
+ bg STRING,
23
+ id INT
24
+ ) STORED AS ORC;
25
+
26
+ INSERT INTO TABLE internal_platform_db.app_group_product_info_query_engine_011 VALUES
27
+ ('user_a', 'group_alpha', 1, 101, 'prod_x', 201, 301, 'obs_prod_a', 401, 'dept_eng', 501, 'plan_a', 601, '5', 'owner1', 'powner1', 'obs_owner1', 'plan_owner1', 'BG1', 1),
28
+ ('user_b', 'group_beta', 2, 102, 'prod_y', 202, 302, 'obs_prod_b', 402, 'dept_sales', 502, 'plan_b', 602, '10', 'owner2', 'powner2', 'obs_owner2', 'plan_owner2', 'BG2', 2),
29
+ ('user_c', 'group_gamma', 3, 103, 'prod_z', 203, 303, 'obs_prod_c', 403, 'dept_hr', 503, 'plan_c', 603, '3', 'owner3', 'powner3', 'obs_owner3', 'plan_owner3', 'BG1', 3),
30
+ ('user_d', 'group_alpha', 1, 104, 'prod_w', 204, 304, 'obs_prod_d', 404, 'dept_eng', 504, 'plan_d', 604, '7', 'owner4', 'powner4', 'obs_owner4', 'plan_owner4', 'BG3', 4),
31
+ ('user_e', 'group_delta', 4, 105, 'prod_v', 205, 305, 'obs_prod_e', 405, 'dept_finance', 505, 'plan_e', 605, '2', 'owner5', 'powner5', 'obs_owner5', 'plan_owner5', 'BG2', 5);
32
+
33
+ CREATE TABLE IF NOT EXISTS internal_platform_db.app_group_product_info_history_query_engine_011 (
34
+ username STRING,
35
+ application_group STRING,
36
+ application_group_owner INT,
37
+ product_id INT,
38
+ product_name STRING,
39
+ product_owner INT,
40
+ obs_product_id INT,
41
+ obs_product_name STRING,
42
+ obs_product_owner INT,
43
+ department STRING,
44
+ plan_product_id INT,
45
+ plan_product_name STRING,
46
+ plan_product_owner INT,
47
+ application_group_numbers STRING,
48
+ application_group_owners STRING,
49
+ product_owners STRING,
50
+ obs_product_owners STRING,
51
+ plan_product_owners STRING,
52
+ bg STRING,
53
+ id INT
54
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
55
+
56
+ -- Agent 候选目标表
57
+ CREATE TABLE IF NOT EXISTS internal_platform_db.app_group_product_info_history_cand_query_engine_011 (
58
+ username STRING,
59
+ application_group STRING,
60
+ application_group_owner INT,
61
+ product_id INT,
62
+ product_name STRING,
63
+ product_owner INT,
64
+ obs_product_id INT,
65
+ obs_product_name STRING,
66
+ obs_product_owner INT,
67
+ department STRING,
68
+ plan_product_id INT,
69
+ plan_product_name STRING,
70
+ plan_product_owner INT,
71
+ application_group_numbers STRING,
72
+ application_group_owners STRING,
73
+ product_owners STRING,
74
+ obs_product_owners STRING,
75
+ plan_product_owners STRING,
76
+ bg STRING,
77
+ id INT
78
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_004/init/schema.sql ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS internal_platform_db.app_group_product_info (
2
+ `username` STRING,
3
+ `application_group` STRING,
4
+ `application_group_owner` INT,
5
+ `product_id` INT,
6
+ `product_name` STRING,
7
+ `product_owner` INT,
8
+ `obs_product_id` INT,
9
+ `obs_product_name` STRING,
10
+ `obs_product_owner` INT,
11
+ `department` STRING,
12
+ `plan_product_id` INT,
13
+ `plan_product_name` STRING,
14
+ `plan_product_owner` INT,
15
+ `application_group_numbers` STRING,
16
+ `application_group_owners` STRING,
17
+ `product_owners` STRING,
18
+ `obs_product_owners` STRING,
19
+ `plan_product_owners` STRING,
20
+ `bg` STRING,
21
+ `id` INT
22
+ ) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_004/task.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: offline-compute_HiveSQL_hivesql_004
3
+ name: 将源表 internal_platform_db.app_group_product_info_sup
4
+ category: offline-compute/HiveSQL
5
+ timeout_seconds: 600
6
+ modality: pure-text
7
+ engine: hivesql
8
+ ---
9
+ ## Prompt
10
+ 任务目标:将应用组与产品归属关系按天做历史快照,按分区全量覆盖写入目标表。
11
+
12
+ 输入:internal_platform_db.app_group_product_info_query_engine_011
13
+ - 字段:username、application_group、application_group_owner、product_id、product_name、product_owner、obs_product_id、obs_product_name、obs_product_owner、department、plan_product_id、plan_product_name、plan_product_owner、application_group_numbers、application_group_owners、product_owners、obs_product_owners、plan_product_owners、bg、id
14
+
15
+ 处理规则:
16
+ 1. 无 Join,单表处理
17
+ 2. 无过滤条件,全量读取源表所有记录
18
+ 3. 无聚合操作
19
+ 4. 追加派生列 dt(STRING 类型),填充当天日期字符串(格式 YYYYMMDD,如 '20260507'),置于输出字段最前
20
+
21
+ 输出要求:
22
+ - 输出字段顺序:dt、username、application_group、application_group_owner、product_id、product_name、product_owner、obs_product_id、obs_product_name、obs_product_owner、department、plan_product_id、plan_product_name、plan_product_owner、application_group_numbers、application_group_owners、product_owners、obs_product_owners、plan_product_owners、bg、id
23
+ - 无需去重
24
+
25
+ 写入要求:
26
+ - 目标表:internal_platform_db.app_group_product_info_history_cand_query_engine_011
27
+ - 分区字段:dt(STRING)
28
+ - 写入方式:INSERT OVERWRITE 按分区写入
29
+ - 若目标表不存在,先按 Hive 标准建表(ORC 存储、按 dt 分区),再写入
30
+
31
+ 请将最终 HiveSQL 写入 result.sql 并执行。
tasks/offline-compute/HiveSQL/hivesql_005/gt/expected.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ business_id,business_name,topic,cluster_set,mq_full_topic,system_belong,app_group,bid_incharge,bid_description,bid_create_time,bid_modify_time,cluster_id,cluster_type,cluster_name,bg,category_name,total_produce_pkg_d,production_days_last_7d,total_produce_pkg_last_7d,production_days_last_30d,total_produce_pkg_last_30d,production_days_last_90d,total_produce_pkg_last_90d,is_consumed,has_consumption_days_last_7d,has_consumption_days_last_30d,has_consumption_days_last_90d,hitted_gov_items,governance_benefit_estimate,dt
2
+ bid_001,account_alpha,topic_x,cluster_a,persistent://tenant1/ns1/topic_x,数据总线,appgrp1,user_a,desc1,2025-01-01,2025-06-01,c001,dedicated,cluster_alpha,DEPT_I,product_a,5000,7,35000,30,150000,90,450000,1,7,30,90,,,20260507
3
+ bid_002,account_beta,topic_y,cluster_b,topic_y,流处理平台,appgrp2,user_b,desc2,2025-02-15,2025-05-20,c002,shared,cluster_beta,DEPT_C,product_b,1000,5,7000,20,30000,60,90000,0,3,10,30,,,20260507
tasks/offline-compute/HiveSQL/hivesql_005/gt/grade.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hivesql_013 精细评分脚本
2
+
3
+ 业务场景:汇总当天有生产量的 消息队列MQ topic 维度信息,派生 mq_full_topic 等字段,落地为 topic 治理项明细表
4
+ 难度: EASY | 特征: INSERT_OVERWRITE|PARTITION|SINGLE_TABLE|FIELD_MAPPING|DERIVED_COLUMN
5
+
6
+ 评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
7
+ A_executability (15分): result.sql 能跑通且产出非空
8
+ B_schema (10分): 30列(5) + 列名匹配(5)
9
+ C_row_alignment (15分): 行数比例(7) + key覆盖率(8)
10
+ D_field_mapping (25分): 字段别名映射正确性(app_group/bid_*等)
11
+ D_derived_mq_full_topic (15分): mq_full_topic 派生列拼接逻辑正确性
12
+ F_insert_overwrite (5分): INSERT OVERWRITE + PARTITION
13
+ F_partition_value (5分): dt 分区值 = 20260507
14
+ F_filter_condition (10分): WHERE dt='20260507' AND total_produce_pkg_last_90d>0
15
+
16
+ 权重: EASY -> product=0.5, process=0.5
17
+ """
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import tempfile
22
+ import json
23
+ import math
24
+
25
+
26
+ def grade(workspace_path, **kwargs):
27
+
28
+ # ========== Case 配置 ==========
29
+ OUTPUT_TABLE = "internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013"
30
+ DIFFICULTY = "EASY"
31
+ SOURCE_TABLES = ["dws_mq_production_feature_d_increase_query_engine_013", "ads_mq_topic_governance_item_d_query_engine_013"]
32
+ KEY_COLUMNS = ["business_id", "bid_incharge", "bid_description", "bid_create_time", "bid_modify_time", "cluster_id", "dt"]
33
+ EXPECTED_COL_COUNT = 30
34
+ FIELD_MAPPINGS = {
35
+ "dw_appgroup": "app_group",
36
+ "in_charge": "bid_incharge",
37
+ "description": "bid_description",
38
+ "create_time": "bid_create_time",
39
+ "modify_time": "bid_modify_time",
40
+ }
41
+ GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
42
+
43
+ DIFFICULTY_WEIGHTS = {
44
+ "EASY": (0.5, 0.5),
45
+ "MEDIUM": (0.6, 0.4),
46
+ "HARD": (0.7, 0.3),
47
+ "EXPERT": (0.8, 0.2),
48
+ }
49
+
50
+ _SPARK_SUBMIT_TIMEOUT = 300
51
+ _JSON_START = "__GRADE_JSON_START__"
52
+ _JSON_END = "__GRADE_JSON_END__"
53
+
54
+ result = {
55
+ "overall_score": 0.0,
56
+ "total_points": 0,
57
+ "grade": "",
58
+ "details": {},
59
+ "diagnostics": [],
60
+ }
61
+
62
+ # ========== 内部辅助函数 ==========
63
+
64
+ def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
65
+ if pred_val is None and gt_val is None:
66
+ return True
67
+ if pred_val is None or gt_val is None:
68
+ return False
69
+ s_pred = str(pred_val).strip()
70
+ s_gt = str(gt_val).strip()
71
+ if s_pred == s_gt:
72
+ return True
73
+ try:
74
+ pv = float(s_pred)
75
+ gv = float(s_gt)
76
+ if math.isnan(pv) and math.isnan(gv):
77
+ return True
78
+ if math.isnan(pv) or math.isnan(gv):
79
+ return False
80
+ if abs(gv) < abs_tol:
81
+ return abs(pv - gv) <= abs_tol
82
+ return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
83
+ except (ValueError, TypeError):
84
+ pass
85
+ return s_pred.lower() == s_gt.lower()
86
+
87
+ def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
88
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
89
+ f.write(script_code)
90
+ script_path = f.name
91
+ try:
92
+ r = subprocess.run(
93
+ ["spark-submit", script_path],
94
+ capture_output=True, text=True, timeout=timeout,
95
+ )
96
+ stdout = r.stdout or ""
97
+ if _JSON_START in stdout and _JSON_END in stdout:
98
+ json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
99
+ return json.loads(json_str), None
100
+ else:
101
+ if r.returncode == 0:
102
+ for line in stdout.splitlines():
103
+ if line.strip().startswith("Traceback"):
104
+ return None, f"spark-submit error: {line}"
105
+ return None, "spark-submit 无 JSON 输出"
106
+ err_msg = (r.stderr or "")[-500:]
107
+ return None, f"spark-submit failed: {err_msg}"
108
+ except subprocess.TimeoutExpired:
109
+ return None, f"spark-submit 超时 ({timeout}s)"
110
+ except Exception as e:
111
+ return None, f"spark-submit 异常: {e}"
112
+ finally:
113
+ try:
114
+ os.unlink(script_path)
115
+ except OSError:
116
+ pass
117
+
118
+ def read_table_via_spark_submit(table_name):
119
+ """Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
120
+ if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
121
+ raise ValueError(f"非法表名: {table_name}")
122
+ read_script = f'''
123
+ import json
124
+ from pyspark.sql import SparkSession
125
+ spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
126
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
127
+ try:
128
+ df = spark.sql("SELECT * FROM {table_name}")
129
+ cols = [c.lower() for c in df.columns]
130
+ rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
131
+ print("{_JSON_START}")
132
+ print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
133
+ print("{_JSON_END}")
134
+ except Exception as e:
135
+ print("{_JSON_START}")
136
+ print(json.dumps({{"error": str(e)}}))
137
+ print("{_JSON_END}")
138
+ finally:
139
+ spark.stop()
140
+ '''
141
+ data, err = _run_spark_script(read_script)
142
+ if err:
143
+ raise RuntimeError(f"read_table failed: {err}")
144
+ if "error" in data:
145
+ raise RuntimeError(f"query failed: {data['error']}")
146
+ return data["cols"], data["rows"]
147
+
148
+ # SQL executor template (self-contained, no external dependency)
149
+ _SQL_EXEC_TEMPLATE = '''
150
+ import json, re
151
+ from pyspark.sql import SparkSession
152
+ spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
153
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
154
+ try:
155
+ with open("{sql_file}", "r", encoding="utf-8") as _f:
156
+ _sql = _f.read()
157
+ _sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
158
+ _stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
159
+ while _i < len(_sql):
160
+ _ch = _sql[_i]
161
+ if _ch == "\\\\" and _i + 1 < len(_sql):
162
+ _cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
163
+ if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
164
+ while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
165
+ _cur.append("\\n"); continue
166
+ if _ch == "'" and not _in_dq: _in_sq = not _in_sq
167
+ elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
168
+ if _ch == ";" and not _in_sq and not _in_dq:
169
+ _s = "".join(_cur).strip()
170
+ if _s: _stmts.append(_s)
171
+ _cur = []
172
+ else:
173
+ _cur.append(_ch)
174
+ _i += 1
175
+ _last = "".join(_cur).strip()
176
+ if _last: _stmts.append(_last)
177
+ for _stmt in _stmts:
178
+ spark.sql(_stmt)
179
+ print("{_JSON_START}")
180
+ print(json.dumps({{"ok": True}}))
181
+ print("{_JSON_END}")
182
+ except Exception as e:
183
+ print("{_JSON_START}")
184
+ print(json.dumps({{"ok": False, "error": str(e)}}))
185
+ print("{_JSON_END}")
186
+ finally:
187
+ spark.stop()
188
+ '''
189
+
190
+ def execute_result_sql():
191
+ result_sql = os.path.join(workspace_path, "result.sql")
192
+ if not os.path.exists(result_sql):
193
+ return False, "no_result_file"
194
+ # 替换 数据平台WD时间变量(沙箱 spark-sql 不支持 ${...} 语法)
195
+ with open(result_sql, 'r', encoding='utf-8') as _rf:
196
+ _sql_text = _rf.read()
197
+ _bizdate = '20260507'
198
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
199
+ _sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
200
+ _sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
201
+ _sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
202
+ with open(result_sql, 'w', encoding='utf-8') as _wf:
203
+ _wf.write(_sql_text)
204
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
205
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
206
+ data, err = _run_spark_script(script)
207
+ if err:
208
+ return False, f"execution_error: {err}"
209
+ if data and data.get("ok"):
210
+ return True, None
211
+ return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
212
+
213
+ def execute_ground_truth_sql():
214
+ gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
215
+ if not os.path.exists(gt_sql):
216
+ return False, "ground_truth.sql not found"
217
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
218
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
219
+ data, err = _run_spark_script(script)
220
+ if err:
221
+ return False, f"gt_execution_error: {err}"
222
+ if data and data.get("ok"):
223
+ return True, None
224
+ return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
225
+
226
+ def truncate_table(table_name):
227
+ script = f'''
228
+ from pyspark.sql import SparkSession
229
+ spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
230
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
231
+ spark.sql("TRUNCATE TABLE {table_name}")
232
+ spark.stop()
233
+ '''
234
+ try:
235
+ _run_spark_script(script, timeout=120)
236
+ except Exception:
237
+ pass
238
+
239
+ def restore_hive_site():
240
+ """Restore hive-site.xml to canonical state (agent may have modified it)."""
241
+ canonical_hive_site = '''<?xml version="1.0"?>
242
+ <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
243
+ <configuration>
244
+ <property>
245
+ <name>hive.metastore.uris</name>
246
+ <value>thrift://localhost:9083</value>
247
+ </property>
248
+ <property>
249
+ <name>hive.metastore.warehouse.dir</name>
250
+ <value>/tmp/hive_warehouse</value>
251
+ </property>
252
+ <property>
253
+ <name>javax.jdo.option.ConnectionURL</name>
254
+ <value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
255
+ </property>
256
+ <property>
257
+ <name>javax.jdo.option.ConnectionDriverName</name>
258
+ <value>org.apache.derby.jdbc.EmbeddedDriver</value>
259
+ </property>
260
+ <property>
261
+ <name>datanucleus.schema.autoCreateAll</name>
262
+ <value>true</value>
263
+ </property>
264
+ <property>
265
+ <name>hive.metastore.schema.verification</name>
266
+ <value>false</value>
267
+ </property>
268
+ </configuration>
269
+ '''
270
+ hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
271
+ try:
272
+ with open(hive_site_path, 'w') as f:
273
+ f.write(canonical_hive_site)
274
+ except Exception:
275
+ pass
276
+
277
+ def finalize(result):
278
+ product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
279
+ 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']
280
+ product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
281
+ product_ratio = product_raw / 100.0
282
+ for dim in ["H_efficiency"]:
283
+ if dim in result["details"]:
284
+ raw = result["details"][dim].get("score", 0)
285
+ result["details"][dim]["score_before_scaling"] = raw
286
+ result["details"][dim]["score"] = round(raw * product_ratio, 2)
287
+ result["details"][dim]["product_ratio"] = round(product_ratio, 4)
288
+ process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
289
+ process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
290
+ product_score = round(product_raw * product_weight, 2)
291
+ process_score = round(process_raw * process_weight, 2)
292
+ total = round(product_score + process_score, 2)
293
+ result["total_points"] = total
294
+ result["product_points"] = product_score
295
+ result["process_points"] = round(process_score, 2)
296
+ result["weights"] = {"product": product_weight, "process": process_weight}
297
+ result["overall_score"] = round(total / 100.0, 4)
298
+ if total >= 90:
299
+ result["grade"] = "优秀"
300
+ elif total >= 75:
301
+ result["grade"] = "良好"
302
+ elif total >= 60:
303
+ result["grade"] = "合格"
304
+ elif total >= 40:
305
+ result["grade"] = "偏弱"
306
+ else:
307
+ result["grade"] = "不合格"
308
+ return result
309
+
310
+ # Restore hive-site.xml (agent may have modified it)
311
+ restore_hive_site()
312
+
313
+ # ========== A. 可执行性 (15分) ==========
314
+ a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
315
+ exec_ok, exec_err = execute_result_sql()
316
+ if not exec_ok:
317
+ detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
318
+ result["details"]["A_executability"] = {"score": 0, "max": 15, "detail": detail}
319
+ result["error"] = detail
320
+ 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']:
321
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
322
+ return finalize(result)
323
+
324
+ a_items["A1_exec_ok"] = 8
325
+
326
+ pred_headers, pred_rows = [], []
327
+ try:
328
+ pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
329
+ except Exception as e:
330
+ result["diagnostics"].append(f"read_pred_failed: {e}")
331
+
332
+ if not pred_rows:
333
+ result["details"]["A_executability"] = {"score": 8, "max": 15, "items": a_items}
334
+ 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']:
335
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
336
+ return finalize(result)
337
+
338
+ a_items["A2_has_data"] = 7
339
+ result["details"]["A_executability"] = {"score": 15, "max": 15, "items": a_items}
340
+
341
+ # ========== Execute GT + Read GT ==========
342
+ truncate_table(GT_TABLE)
343
+ gt_ok, gt_err = execute_ground_truth_sql()
344
+ if not gt_ok:
345
+ result["error"] = f"ground_truth failed: {gt_err}"
346
+ 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']:
347
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
348
+ return finalize(result)
349
+
350
+ gt_headers, gt_rows = [], []
351
+ try:
352
+ gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
353
+ except Exception as e:
354
+ result["error"] = f"read_gt_failed: {e}"
355
+ 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']:
356
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
357
+ return finalize(result)
358
+
359
+ # ========== B/C/D/F 维度评分 ==========
360
+ pred_col_map = {h: i for i, h in enumerate(pred_headers)}
361
+ gt_col_map = {h: i for i, h in enumerate(gt_headers)}
362
+
363
+ # ========== B. Schema正确性 (10分) ==========
364
+ b_items = {}
365
+ # B1: 列数 (5分)
366
+ if len(pred_headers) == EXPECTED_COL_COUNT:
367
+ b_items["B1_col_count"] = 5
368
+ elif abs(len(pred_headers) - EXPECTED_COL_COUNT) <= 2:
369
+ b_items["B1_col_count"] = 3
370
+ else:
371
+ b_items["B1_col_count"] = 0
372
+
373
+ # B2: 列名匹配 (5分)
374
+ gt_col_set = set(gt_headers)
375
+ pred_col_set = set(pred_headers)
376
+ name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
377
+ if name_match_rate >= 0.95:
378
+ b_items["B2_col_names"] = 5
379
+ elif name_match_rate >= 0.8:
380
+ b_items["B2_col_names"] = 3
381
+ else:
382
+ b_items["B2_col_names"] = 0
383
+
384
+ b_score = sum(b_items.values())
385
+ result["details"]["B_schema"] = {
386
+ "score": b_score, "max": 10,
387
+ "detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
388
+ }
389
+
390
+ # ========== C. 行一致性 (15分) ==========
391
+ c_items = {}
392
+ gt_row_count = len(gt_rows)
393
+ pred_row_count = len(pred_rows)
394
+
395
+ # C1: 行数比例 (7分)
396
+ if gt_row_count > 0:
397
+ ratio = pred_row_count / gt_row_count
398
+ if 0.95 <= ratio <= 1.05:
399
+ c_items["C1_row_ratio"] = 7
400
+ elif 0.7 <= ratio <= 1.3:
401
+ c_items["C1_row_ratio"] = 4
402
+ else:
403
+ c_items["C1_row_ratio"] = 0
404
+ else:
405
+ c_items["C1_row_ratio"] = 7 if pred_row_count == 0 else 0
406
+
407
+ # C2: key覆盖率 (8分)
408
+ key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
409
+ if key_cols_avail and gt_row_count > 0:
410
+ gt_keys = set()
411
+ for row in gt_rows:
412
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
413
+ gt_keys.add(key)
414
+ pred_keys = set()
415
+ for row in pred_rows:
416
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
417
+ pred_keys.add(key)
418
+ coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
419
+ if coverage >= 0.995:
420
+ c_items["C2_key_coverage"] = 8
421
+ elif coverage >= 0.9:
422
+ c_items["C2_key_coverage"] = 6
423
+ elif coverage >= 0.7:
424
+ c_items["C2_key_coverage"] = 3
425
+ else:
426
+ c_items["C2_key_coverage"] = round(8 * coverage, 2)
427
+ else:
428
+ c_items["C2_key_coverage"] = 0
429
+
430
+ c_score = sum(v for v in c_items.values())
431
+ result["details"]["C_row_alignment"] = {"score": c_score, "max": 15, "detail": c_items}
432
+
433
+ # 构建索引
434
+ if key_cols_avail:
435
+ pred_index = {}
436
+ for row in pred_rows:
437
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
438
+ pred_index[key] = row
439
+ gt_index = {}
440
+ for row in gt_rows:
441
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
442
+ gt_index[key] = row
443
+ else:
444
+ pred_index = {}
445
+ gt_index = {}
446
+
447
+ # ========== D. 字段映射正确性 (25分) ==========
448
+ d_map_items = {}
449
+ per_mapping_weight = 25.0 / max(len(FIELD_MAPPINGS), 1)
450
+ d_map_score = 0
451
+ for src_col, dst_col in FIELD_MAPPINGS.items():
452
+ # GT 中该列用 dst_col 名
453
+ gt_ci = gt_col_map.get(dst_col)
454
+ pred_ci = pred_col_map.get(dst_col)
455
+ if gt_ci is None or pred_ci is None:
456
+ d_map_items[dst_col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
457
+ continue
458
+ matches = 0
459
+ total = 0
460
+ for key, gt_row in gt_index.items():
461
+ pred_row = pred_index.get(key)
462
+ if pred_row is None:
463
+ total += 1
464
+ continue
465
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
466
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
467
+ if values_match(pred_val, gt_val):
468
+ matches += 1
469
+ total += 1
470
+ rate = matches / max(total, 1)
471
+ col_score = rate * per_mapping_weight
472
+ d_map_score += col_score
473
+ d_map_items[dst_col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2), "mapped_from": src_col}
474
+
475
+ result["details"]["D_field_mapping"] = {
476
+ "score": round(d_map_score, 2), "max": 25, "detail": d_map_items,
477
+ }
478
+
479
+ # ========== D. mq_full_topic 派生列 (15分) ==========
480
+ d_mq_items = {}
481
+ d_mq_score = 0
482
+ mq_ci = pred_col_map.get("mq_full_topic")
483
+ gt_mq_ci = gt_col_map.get("mq_full_topic")
484
+ if mq_ci is None or gt_mq_ci is None:
485
+ d_mq_items["mq_full_topic"] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
486
+ else:
487
+ matches = 0
488
+ total = 0
489
+ for key, gt_row in gt_index.items():
490
+ pred_row = pred_index.get(key)
491
+ if pred_row is None:
492
+ total += 1
493
+ continue
494
+ gt_val = gt_row[gt_mq_ci].strip() if gt_mq_ci < len(gt_row) else ""
495
+ pred_val = pred_row[mq_ci].strip() if mq_ci < len(pred_row) else ""
496
+ if values_match(pred_val, gt_val):
497
+ matches += 1
498
+ total += 1
499
+ rate = matches / max(total, 1)
500
+ d_mq_score = rate * 15
501
+ d_mq_items["mq_full_topic"] = {"pass_rate": round(rate, 4), "score": round(d_mq_score, 2)}
502
+
503
+ result["details"]["D_derived_mq_full_topic"] = {
504
+ "score": round(d_mq_score, 2), "max": 15, "detail": d_mq_items,
505
+ }
506
+
507
+ # ========== F. INSERT OVERWRITE (5分) ==========
508
+ result_sql_path = os.path.join(workspace_path, "result.sql")
509
+ sql_text = ""
510
+ try:
511
+ with open(result_sql_path, "r", encoding="utf-8") as f:
512
+ sql_text = f.read().lower()
513
+ except Exception:
514
+ sql_text = ""
515
+
516
+ f_insert_items = {}
517
+ has_overwrite = "insert overwrite" in sql_text
518
+ has_partition = "partition" in sql_text
519
+ if has_overwrite and has_partition:
520
+ f_insert_items["insert_overwrite_partition"] = 5
521
+ elif has_overwrite:
522
+ f_insert_items["insert_overwrite_partition"] = 3
523
+ else:
524
+ f_insert_items["insert_overwrite_partition"] = 0
525
+ result["details"]["F_insert_overwrite"] = {
526
+ "score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
527
+ }
528
+
529
+ # ========== F. 分区值 (5分) ==========
530
+ f_part_items = {}
531
+ if "dt" in sql_text and "20260507" in sql_text:
532
+ f_part_items["partition_value"] = 5
533
+ else:
534
+ f_part_items["partition_value"] = 0
535
+ result["details"]["F_partition_value"] = {
536
+ "score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
537
+ }
538
+
539
+ # ========== F. 过滤条件 (10分) ==========
540
+ f_filter_items = {}
541
+ has_dt_filter = "dt" in sql_text and "20260507" in sql_text
542
+ has_pkg_filter = "total_produce_pkg_last_90d" in sql_text and (">0" in sql_text.replace(" ", "") or "> 0" in sql_text)
543
+ if has_dt_filter and has_pkg_filter:
544
+ f_filter_items["filter_condition"] = 10
545
+ elif has_dt_filter:
546
+ f_filter_items["filter_condition"] = 5
547
+ elif has_pkg_filter:
548
+ f_filter_items["filter_condition"] = 3
549
+ else:
550
+ f_filter_items["filter_condition"] = 0
551
+ result["details"]["F_filter_condition"] = {
552
+ "score": f_filter_items["filter_condition"], "max": 10, "detail": f_filter_items,
553
+ }
554
+
555
+ # 汇总
556
+ total = (15 + b_score + c_score + d_map_score + d_mq_score
557
+ + f_insert_items["insert_overwrite_partition"]
558
+ + f_part_items["partition_value"]
559
+ + f_filter_items["filter_condition"])
560
+
561
+ # ========== G~I 过程评分 ==========
562
+ TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
563
+ OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
564
+ INPUT_TABLE_SHORT = SOURCE_TABLES[0]
565
+
566
+ transcript_entries = []
567
+ has_transcript = False
568
+ try:
569
+ if os.path.exists(TRANSCRIPT_PATH):
570
+ with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f:
571
+ for line in f:
572
+ line = line.strip()
573
+ if line:
574
+ try:
575
+ transcript_entries.append(json.loads(line))
576
+ except json.JSONDecodeError:
577
+ continue
578
+ if len(transcript_entries) > 2:
579
+ has_transcript = True
580
+ except Exception:
581
+ pass
582
+
583
+ if not has_transcript:
584
+ result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}}
585
+ result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}}
586
+ result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}}
587
+ return finalize(result)
588
+
589
+ # Parse transcript into structured events
590
+ tool_uses = []
591
+ first_write_result_idx = None
592
+ last_spark_submit_success_idx = None
593
+ write_result_count = 0
594
+ logic_error_retries = 0
595
+
596
+ for idx, entry in enumerate(transcript_entries):
597
+ content = entry.get("content", [])
598
+ if isinstance(content, str):
599
+ content = [content]
600
+
601
+ for block_str in content:
602
+ if not isinstance(block_str, str):
603
+ continue
604
+ if "ToolUseBlock" in block_str:
605
+ name_match = re.search(r"name='([^']+)'", block_str)
606
+ input_match = re.search(r"input=(\{.*\})", block_str)
607
+ if name_match:
608
+ tool_name = name_match.group(1)
609
+ tool_input = input_match.group(1) if input_match else ""
610
+ tool_uses.append((idx, tool_name, tool_input))
611
+ if tool_name == "Write" and "result.sql" in tool_input:
612
+ write_result_count += 1
613
+ if first_write_result_idx is None:
614
+ first_write_result_idx = idx
615
+ if "ToolResultBlock" in block_str:
616
+ if "Traceback" in block_str or "Exception" in block_str:
617
+ env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
618
+ "db.lck", "TTransportException", "port 10000"]
619
+ is_env_error = any(e in block_str for e in env_errors)
620
+ has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
621
+ for t in tool_uses)
622
+ if not is_env_error and has_spark_submit:
623
+ logic_error_retries += 1
624
+ if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" in block_str:
625
+ if "Exit Code: 0" in block_str and "Traceback" not in block_str:
626
+ last_spark_submit_success_idx = idx
627
+
628
+ before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
629
+
630
+ # ===== G. 探索充分性 (35分) =====
631
+ g_items = {}
632
+ g1_pass = any(name == "Read" and "schema" in inp.lower()
633
+ for idx, name, inp in tool_uses if idx < before_first_write)
634
+ g_items["G1_source_schema"] = 9 if g1_pass else 0
635
+
636
+ g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
637
+ and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
638
+ for idx, name, inp in tool_uses if idx < before_first_write)
639
+ g_items["G2_source_sample"] = 9 if g2_pass else 0
640
+
641
+ g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
642
+ and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
643
+ for idx, name, inp in tool_uses if idx < before_first_write)
644
+ g_items["G3_distribution"] = 9 if g3_pass else 0
645
+
646
+ g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
647
+ and OUTPUT_TABLE_SHORT in inp
648
+ for idx, name, inp in tool_uses if idx < before_first_write)
649
+ g_items["G4_target_schema"] = 8 if g4_pass else 0
650
+
651
+ g_score = sum(g_items.values())
652
+ result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
653
+
654
+ # ===== H. 执行效率 (40分) =====
655
+ h_items = {}
656
+ if write_result_count <= 2:
657
+ h_items["H1_few_submissions"] = 20
658
+ elif write_result_count <= 4:
659
+ h_items["H1_few_submissions"] = 13
660
+ elif write_result_count <= 6:
661
+ h_items["H1_few_submissions"] = 7
662
+ else:
663
+ h_items["H1_few_submissions"] = 0
664
+
665
+ if logic_error_retries == 0:
666
+ h_items["H2_no_logic_errors"] = 13
667
+ elif logic_error_retries <= 1:
668
+ h_items["H2_no_logic_errors"] = 7
669
+ else:
670
+ h_items["H2_no_logic_errors"] = 0
671
+
672
+ h_items["H3_no_redundancy"] = 7
673
+ h_score = sum(h_items.values())
674
+ result["details"]["H_efficiency"] = {"score": min(h_score, 40), "max": 40, "items": h_items}
675
+
676
+ # ===== I. 自验证行为 (25分) =====
677
+ i_items = {}
678
+ post_submit_uses = []
679
+ if last_spark_submit_success_idx is not None:
680
+ post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
681
+ if idx > last_spark_submit_success_idx]
682
+
683
+ i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
684
+ for _, name, inp in post_submit_uses)
685
+ i_items["I1_query_output"] = 8 if i1_pass else 0
686
+
687
+ i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
688
+ and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
689
+ for _, name, inp in post_submit_uses)
690
+ i_items["I2_check_count"] = 9 if i2_pass else 0
691
+
692
+ i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
693
+ and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper())
694
+ for _, name, inp in post_submit_uses)
695
+ i_items["I3_check_values"] = 8 if i3_pass else 0
696
+
697
+ i_score = sum(i_items.values())
698
+ result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items}
699
+
700
+ return finalize(result)
tasks/offline-compute/HiveSQL/hivesql_005/gt/grade_spec.csv ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 维度,维度全名,子维度,满分,说明
2
+ A,A_executability,executability,15,result.sql 能跑通且产出非空
3
+ B,B_schema,schema,10,30列(5) + 列名匹配(5)
4
+ C,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)
5
+ D,D_field_mapping,field_mapping,25,字段别名映射正确性(app_group/bid_*等)
6
+ D,D_derived_mq_full_topic,derived_mq_full_topic,15,mq_full_topic 派生列拼接逻辑正确性
7
+ F,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION
8
+ F,F_partition_value,partition_value,5,dt 分区值 = 20260507
9
+ F,F_filter_condition,filter_condition,10,WHERE dt='20260507' AND total_produce_pkg_last_90d>0
10
+
11
+ 总计,,,100,
12
+
13
+ # 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
14
+ # 难度,EASY
15
+ # 权重,"product=0.5, process=0.5"
16
+ # 范式,new
17
+ # Key列,"business_id, bid_incharge, bid_description, bid_create_time, bid_modify_time, cluster_id, dt"
18
+ # 预期列数,30
19
+ # 输出表,internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013
tasks/offline-compute/HiveSQL/hivesql_005/gt/ground_truth.sql ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INSERT OVERWRITE TABLE internal_platform_db.ads_mq_topic_governance_item_d_query_engine_013 PARTITION (dt = '20260507')
2
+ SELECT
3
+ business_id,
4
+ business_name,
5
+ topic,
6
+ cluster_set,
7
+ IF ( tenant IS NOT NULL AND namespaces IS NOT NULL, CONCAT( 'persistent://', tenant, '/', namespaces, '/', topic ), topic ) AS mq_full_topic,
8
+ system_belong,
9
+ dw_appgroup AS app_group,
10
+ in_charge AS bid_incharge,
11
+ description AS bid_description,
12
+ create_time AS bid_create_time,
13
+ modify_time AS bid_modify_time,
14
+ cluster_id,
15
+ cluster_type,
16
+ cluster_name,
17
+ bg,
18
+ category_name,
19
+ total_produce_pkg_d,
20
+ production_days_last_7d,
21
+ total_produce_pkg_last_7d,
22
+ production_days_last_30d,
23
+ total_produce_pkg_last_30d,
24
+ production_days_last_90d,
25
+ total_produce_pkg_last_90d,
26
+ is_consumed,
27
+ has_consumption_days_last_7d,
28
+ has_consumption_days_last_30d,
29
+ has_consumption_days_last_90d,
30
+ NULL AS hitted_gov_items,
31
+ NULL AS governance_benefit_estimate
32
+ FROM internal_platform_db.dws_mq_production_feature_d_increase_query_engine_013
33
+ WHERE dt = '20260507'
34
+ AND total_produce_pkg_last_90d > 0
tasks/offline-compute/HiveSQL/hivesql_005/init/init_db.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import re
3
+ from pyspark.sql import SparkSession
4
+
5
+ spark = SparkSession.builder \
6
+ .appName('hivesql_bench_init') \
7
+ .enableHiveSupport() \
8
+ .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \
9
+ .getOrCreate()
10
+
11
+ spark.sql('CREATE DATABASE IF NOT EXISTS internal_platform_db')
12
+
13
+
14
+ def _execute_sql_file(spark, sql_path):
15
+ """Read SQL file, remove SuperSQL SET headers, split by semicolons, execute."""
16
+ with open(sql_path, 'r', encoding='utf-8') as f:
17
+ content = f.read()
18
+ content = re.sub(r'^\s*set\s+query_engine\.\S+\n?', '', content, flags=re.IGNORECASE)
19
+ stmts, cur, in_sq, in_dq, i = [], [], False, False, 0
20
+ while i < len(content):
21
+ ch = content[i]
22
+ if ch == '\\' and i + 1 < len(content):
23
+ cur.append(ch); cur.append(content[i + 1]); i += 2; continue
24
+ if ch == '-' and i + 1 < len(content) and content[i + 1] == '-' and not in_sq and not in_dq:
25
+ while i < len(content) and content[i] != '\n':
26
+ i += 1
27
+ cur.append('\n'); continue
28
+ if ch == "'" and not in_dq:
29
+ in_sq = not in_sq
30
+ elif ch == '"' and not in_sq:
31
+ in_dq = not in_dq
32
+ if ch == ';' and not in_sq and not in_dq:
33
+ s = ''.join(cur).strip()
34
+ if s:
35
+ stmts.append(s)
36
+ cur = []
37
+ else:
38
+ cur.append(ch)
39
+ i += 1
40
+ last = ''.join(cur).strip()
41
+ if last:
42
+ stmts.append(last)
43
+ for stmt in stmts:
44
+ spark.sql(stmt)
45
+
46
+
47
+ _execute_sql_file(spark, '/tmp_workspace/init_db.sql')
48
+
49
+ tables = spark.sql('SHOW TABLES IN internal_platform_db').collect()
50
+ print(f'Init complete, {len(tables)} tables created')
51
+ for t in tables:
52
+ print(f' - {t.namespace}.{t.tableName}')
53
+ spark.stop()
tasks/offline-compute/HiveSQL/hivesql_005/init/init_db.sql ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS internal_platform_db;
2
+
3
+ -- 输入表: dws_mq_production_feature_d_increase
4
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dws_mq_production_feature_d_increase_query_engine_013 (
5
+ dt STRING,
6
+ business_id STRING,
7
+ business_name STRING,
8
+ cluster_set STRING,
9
+ tenant STRING,
10
+ namespaces STRING,
11
+ topic STRING,
12
+ mq_type STRING,
13
+ system_belong STRING,
14
+ dw_appgroup STRING,
15
+ in_charge STRING,
16
+ description STRING,
17
+ create_time STRING,
18
+ modify_time STRING,
19
+ cluster_id STRING,
20
+ cluster_type STRING,
21
+ cluster_name STRING,
22
+ bg STRING,
23
+ category_name STRING,
24
+ is_produce TINYINT,
25
+ total_produce_pkg_d BIGINT,
26
+ is_consumed TINYINT,
27
+ is_consumed_by_reader TINYINT,
28
+ max_consume_pkg_d BIGINT,
29
+ min_consume_pkg_d BIGINT,
30
+ min_consume_pkg_without_reader_d BIGINT,
31
+ is_backlog TINYINT,
32
+ is_backlog_without_reader TINYINT,
33
+ total_backlog_pkg_d BIGINT,
34
+ total_backlog_pkg_without_reader_d BIGINT,
35
+ backlog_ratio STRING,
36
+ backlog_ratio_without_reader STRING,
37
+ is_produce_all_7d TINYINT,
38
+ production_days_last_7d TINYINT,
39
+ total_produce_pkg_last_7d BIGINT,
40
+ is_produce_all_30d TINYINT,
41
+ production_days_last_30d TINYINT,
42
+ total_produce_pkg_last_30d BIGINT,
43
+ is_produce_all_90d TINYINT,
44
+ production_days_last_90d TINYINT,
45
+ total_produce_pkg_last_90d BIGINT,
46
+ is_consumed_all_7d TINYINT,
47
+ has_consumption_days_last_7d TINYINT,
48
+ max_consume_pkg_last_7d BIGINT,
49
+ min_consume_pkg_last_7d BIGINT,
50
+ is_consumed_all_30d TINYINT,
51
+ has_consumption_days_last_30d TINYINT,
52
+ max_consume_pkg_last_30d BIGINT,
53
+ min_consume_pkg_last_30d BIGINT,
54
+ is_consumed_all_90d TINYINT,
55
+ has_consumption_days_last_90d TINYINT,
56
+ max_consume_pkg_last_90d BIGINT,
57
+ min_consume_pkg_last_90d BIGINT,
58
+ is_backlog_all_7d TINYINT,
59
+ has_backlog_days_last_7d TINYINT,
60
+ total_backlog_last_7d BIGINT,
61
+ backlog_ratio_last_7d STRING,
62
+ is_backlog_all_30d TINYINT,
63
+ has_backlog_days_last_30d TINYINT,
64
+ total_backlog_last_30d BIGINT,
65
+ backlog_ratio_last_30d STRING,
66
+ is_backlog_all_90d TINYINT,
67
+ has_backlog_days_last_90d TINYINT,
68
+ total_backlog_last_90d BIGINT,
69
+ backlog_ratio_last_90d STRING
70
+ ) STORED AS ORC;
71
+
72
+ INSERT INTO TABLE internal_platform_db.dws_mq_production_feature_d_increase_query_engine_013 VALUES
73
+ ('20260507','bid_001','account_alpha','cluster_a','tenant1','ns1','topic_x','消息队列MQ','数据总线','appgrp1','user_a','desc1','2025-01-01','2025-06-01','c001','dedicated','cluster_alpha','DEPT_I','product_a',1,5000,1,0,4000,3000,3000,0,0,0,0,'0','0',1,7,35000,1,30,150000,1,90,450000,1,7,28000,20000,1,30,120000,80000,1,90,360000,240000,0,0,0,'0',0,0,0,'0',0,0,0,'0'),
74
+ ('20260507','bid_002','account_beta','cluster_b',NULL,NULL,'topic_y','消息队列MQ','流处理平台','appgrp2','user_b','desc2','2025-02-15','2025-05-20','c002','shared','cluster_beta','DEPT_C','product_b',1,1000,0,0,0,0,0,0,0,0,0,'0','0',1,5,7000,1,20,30000,1,60,90000,0,3,0,0,0,10,0,0,0,30,0,0,0,0,0,'0',0,0,0,'0',0,0,0,'0'),
75
+ ('20260507','bid_003','account_gamma','cluster_c','tenant3','ns3','topic_z','TubeMQ','数据总线','appgrp3','user_c','desc3','2024-12-01','2025-04-10','c003','dedicated','cluster_gamma','DEPT_P','product_c',0,0,0,0,0,0,0,0,0,0,0,'0','0',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'0',0,0,0,'0',0,0,0,'0');
76
+
77
+ -- 目标表: ads_mq_topic_governance_item_d
78
+ CREATE TABLE IF NOT EXISTS internal_platform_db.ads_mq_topic_governance_item_d_query_engine_013 (
79
+ business_id STRING,
80
+ business_name STRING,
81
+ topic STRING,
82
+ cluster_set STRING,
83
+ mq_full_topic STRING,
84
+ system_belong STRING,
85
+ app_group STRING,
86
+ bid_incharge STRING,
87
+ bid_description STRING,
88
+ bid_create_time STRING,
89
+ bid_modify_time STRING,
90
+ cluster_id STRING,
91
+ cluster_type STRING,
92
+ cluster_name STRING,
93
+ bg STRING,
94
+ category_name STRING,
95
+ total_produce_pkg_d BIGINT,
96
+ production_days_last_7d TINYINT,
97
+ total_produce_pkg_last_7d BIGINT,
98
+ production_days_last_30d TINYINT,
99
+ total_produce_pkg_last_30d BIGINT,
100
+ production_days_last_90d TINYINT,
101
+ total_produce_pkg_last_90d BIGINT,
102
+ is_consumed TINYINT,
103
+ has_consumption_days_last_7d TINYINT,
104
+ has_consumption_days_last_30d TINYINT,
105
+ has_consumption_days_last_90d TINYINT,
106
+ hitted_gov_items STRING,
107
+ governance_benefit_estimate DOUBLE
108
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
109
+
110
+ -- Agent 候选目标表
111
+ CREATE TABLE IF NOT EXISTS internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013 (
112
+ business_id STRING,
113
+ business_name STRING,
114
+ topic STRING,
115
+ cluster_set STRING,
116
+ mq_full_topic STRING,
117
+ system_belong STRING,
118
+ app_group STRING,
119
+ bid_incharge STRING,
120
+ bid_description STRING,
121
+ bid_create_time STRING,
122
+ bid_modify_time STRING,
123
+ cluster_id STRING,
124
+ cluster_type STRING,
125
+ cluster_name STRING,
126
+ bg STRING,
127
+ category_name STRING,
128
+ total_produce_pkg_d BIGINT,
129
+ production_days_last_7d TINYINT,
130
+ total_produce_pkg_last_7d BIGINT,
131
+ production_days_last_30d TINYINT,
132
+ total_produce_pkg_last_30d BIGINT,
133
+ production_days_last_90d TINYINT,
134
+ total_produce_pkg_last_90d BIGINT,
135
+ is_consumed TINYINT,
136
+ has_consumption_days_last_7d TINYINT,
137
+ has_consumption_days_last_30d TINYINT,
138
+ has_consumption_days_last_90d TINYINT,
139
+ hitted_gov_items STRING,
140
+ governance_benefit_estimate DOUBLE
141
+ ) PARTITIONED BY (dt STRING) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_005/init/schema.sql ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dws_mq_production_feature_d_increase (
2
+ `dt` STRING COMMENT '天分区',
3
+ `business_id` STRING COMMENT 'business_id',
4
+ `business_name` STRING COMMENT 'business_name',
5
+ `cluster_set` STRING COMMENT 'cluster_set',
6
+ `tenant` STRING COMMENT 'tenant',
7
+ `namespaces` STRING COMMENT 'namespaces',
8
+ `topic` STRING COMMENT 'topic',
9
+ `mq_type` STRING COMMENT 'MQ类型(消息队列MQ/TubeMQ)',
10
+ `system_belong` STRING COMMENT 'topic所属的系统(数据总线/流处理平台)',
11
+ `dw_appgroup` STRING COMMENT 'bid所属应用组',
12
+ `in_charge` STRING COMMENT 'bid负责人',
13
+ `description` STRING COMMENT 'bid描述信息',
14
+ `create_time` STRING COMMENT 'bid创建时间',
15
+ `modify_time` STRING COMMENT 'bid最后修改时间',
16
+ `cluster_id` STRING COMMENT 'bid所属集群id',
17
+ `cluster_type` STRING COMMENT 'bid所属集群类型',
18
+ `cluster_name` STRING COMMENT 'bid所属集群名',
19
+ `bg` STRING COMMENT 'bid所属的bg',
20
+ `category_name` STRING COMMENT 'bid所归属的产品',
21
+ `is_produce` TINYINT COMMENT '当天topic是否有生产',
22
+ `total_produce_pkg_d` BIGINT COMMENT '当天topic生产的消息数的总量',
23
+ `is_consumed` TINYINT COMMENT '当天topic下游是否有消费',
24
+ `is_consumed_by_reader` TINYINT COMMENT '当天topic下游是否有reader消费组在消费',
25
+ `max_consume_pkg_d` BIGINT COMMENT '当天topic的所有消费组中最大的消费量',
26
+ `min_consume_pkg_d` BIGINT COMMENT '当天topic的所有消费组中最小的消费量',
27
+
28
+ `min_consume_pkg_without_reader_d` BIGINT COMMENT '当天topic的所有消费组中最小的消费量(不计算reader消费组)',
29
+ `is_backlog` TINYINT COMMENT '当天topic下游是否有积压',
30
+ `is_backlog_without_reader` TINYINT COMMENT '当天topic下游是否有积压(不计算reader消费组)',
31
+ `total_backlog_pkg_d` BIGINT COMMENT '当天topic下游积压增量',
32
+
33
+ `total_backlog_pkg_without_reader_d` BIGINT COMMENT '当天topic下游积压增量(不计算reader消费组)',
34
+ `backlog_ratio` STRING COMMENT '当天topic下游积压生产占比(%)',
35
+ `backlog_ratio_without_reader` STRING COMMENT '当天topic下游积压生产占比(%)(不计算reader消费组)',
36
+ `is_produce_all_7d` TINYINT COMMENT '是否近7天每天都有生产(1:是 0:否)',
37
+ `production_days_last_7d` TINYINT COMMENT '近7天有生产的天数',
38
+ `total_produce_pkg_last_7d` BIGINT COMMENT '近7天topic生产的消息数总量',
39
+ `is_produce_all_30d` TINYINT COMMENT '是否近30天每天都有生产(1:是 0:否)',
40
+ `production_days_last_30d` TINYINT COMMENT '近30天有生产的天数',
41
+ `total_produce_pkg_last_30d` BIGINT COMMENT '近30天topic生产的消息数总量',
42
+ `is_produce_all_90d` TINYINT COMMENT '是否近90天每天都有生产(1:是 0:否)',
43
+ `production_days_last_90d` TINYINT COMMENT '近90天有生产的天数',
44
+ `total_produce_pkg_last_90d` BIGINT COMMENT '近90天topic生产的消息数总量',
45
+ `is_consumed_all_7d` TINYINT COMMENT '是否近7天每天都有消费(1:是 0:否)',
46
+ `has_consumption_days_last_7d` TINYINT COMMENT '近7天topic下游有消费的天数',
47
+ `max_consume_pkg_last_7d` BIGINT COMMENT '近7天topic所有消费组中最大的消费量',
48
+ `min_consume_pkg_last_7d` BIGINT COMMENT '近7天topic所有消费组中最小的消费量',
49
+ `is_consumed_all_30d` TINYINT COMMENT '是否近30天每天都有消费(1:是 0:否)',
50
+ `has_consumption_days_last_30d` TINYINT COMMENT '近30天topic下游有消费的天数',
51
+ `max_consume_pkg_last_30d` BIGINT COMMENT '近30天topic所有消费组中最大的消费量',
52
+ `min_consume_pkg_last_30d` BIGINT COMMENT '近30天topic所有消费组中最小的消费量',
53
+ `is_consumed_all_90d` TINYINT COMMENT '是否近90天每天都有消费(1:是 0:否)',
54
+ `has_consumption_days_last_90d` TINYINT COMMENT '近90天topic下游有消费的天数',
55
+ `max_consume_pkg_last_90d` BIGINT COMMENT '近90天topic所有消费组中最大的消费量',
56
+ `min_consume_pkg_last_90d` BIGINT COMMENT '近90天topic所有消费组中最小的消费量',
57
+ `is_backlog_all_7d` TINYINT COMMENT '是否近7天每天都有积压(1:是 0:否)',
58
+ `has_backlog_days_last_7d` TINYINT COMMENT '近7天topic下游有积压的天数',
59
+ `total_backlog_last_7d` BIGINT COMMENT '近7天topic的积压量',
60
+ `backlog_ratio_last_7d` STRING COMMENT '近七天topic下游积压生产占比(%)',
61
+ `is_backlog_all_30d` TINYINT COMMENT '是否近30天每天都有积压(1:是 0:否)',
62
+ `has_backlog_days_last_30d` TINYINT COMMENT '近30天topic下游有积压的天数',
63
+ `total_backlog_last_30d` BIGINT COMMENT '近30天topic的积压量',
64
+ `backlog_ratio_last_30d` STRING COMMENT '近30天topic下游积压生产占比(%)',
65
+ `is_backlog_all_90d` TINYINT COMMENT '是否近90天每天都有积压(1:是 0:否)',
66
+ `has_backlog_days_last_90d` TINYINT COMMENT '近90天topic下游有积压的天数',
67
+ `total_backlog_last_90d` BIGINT COMMENT '近90天topic的积压量',
68
+ `backlog_ratio_last_90d` STRING COMMENT '近90天topic下游积压生产占比(%)'
69
+ ) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_005/task.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: offline-compute_HiveSQL_hivesql_005
3
+ name: 从 internal_platform_db.dws_mq_production_featur
4
+ category: offline-compute/HiveSQL
5
+ timeout_seconds: 600
6
+ modality: pure-text
7
+ engine: hivesql
8
+ ---
9
+ ## Prompt
10
+ 任务目标:汇总当天有生产量的 消息队列MQ topic 维度信息及近7/30/90天生产统计,落地为 topic 治理项明细表。
11
+
12
+ 输入:
13
+ - 表:internal_platform_db.dws_mq_production_feature_d_increase_query_engine_013
14
+ - 分区字段:dt(STRING,格式 YYYYMMDD)
15
+ - 关键字段:business_id、business_name、topic、cluster_set、tenant、namespaces、system_belong、dw_appgroup、in_charge、description、create_time、modify_time、cluster_id、cluster_type、cluster_name、bg、category_name、total_produce_pkg_d、production_days_last_7d、total_produce_pkg_last_7d、production_days_last_30d、total_produce_pkg_last_30d、production_days_last_90d、total_produce_pkg_last_90d、is_consumed、has_consumption_days_last_7d、has_consumption_days_last_30d、has_consumption_days_last_90d
16
+
17
+ 处理规则:
18
+ 1. 过滤条件:dt = '20260507' AND total_produce_pkg_last_90d > 0
19
+ 2. 无 Join,单表处理
20
+ 3. 派生字段:
21
+ - mq_full_topic:若 tenant 和 namespaces 均非 NULL,则拼接为 'persistent://' + tenant + '/' + namespaces + '/' + topic;否则直接取 topic
22
+ - app_group:取自 dw_appgroup
23
+ - bid_incharge:取自 in_charge
24
+ - bid_description:取自 description
25
+ - bid_create_time:取自 create_time
26
+ - bid_modify_time:取自 modify_time
27
+ - hitted_gov_items:固定为 NULL
28
+ - governance_benefit_estimate:固定为 NULL
29
+
30
+ 输出要求:
31
+ - 输出字段顺序:dt、business_id、business_name、topic、cluster_set、mq_full_topic、system_belong、app_group、bid_incharge、bid_description、bid_create_time、bid_modify_time、cluster_id、cluster_type、cluster_name、bg、category_name、total_produce_pkg_d、production_days_last_7d、total_produce_pkg_last_7d、production_days_last_30d、total_produce_pkg_last_30d、production_days_last_90d、total_produce_pkg_last_90d、is_consumed、has_consumption_days_last_7d、has_consumption_days_last_30d、has_consumption_days_last_90d、hitted_gov_items、governance_benefit_estimate
32
+
33
+ 写入要求:
34
+ - 目标表:internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013
35
+ - 分区字段:dt(STRING,格式 YYYYMMDD)
36
+ - 写入方式:INSERT OVERWRITE 按分区写入
37
+ - 若目标表不存在,先按 Hive 标准建表(ORC存储、按 dt 分区),再写入
38
+
39
+ 请将最终 HiveSQL 写入 result.sql 并执行。
tasks/offline-compute/HiveSQL/hivesql_006_en/gt/expected.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ system_belong,category_name,dw_appgroup,city_id,cluster_set,topic,total_data_size_d,total_cost,in_charge,dt
2
+ SystemAlpha,数据仓库DWProdA,AppGroupX,101,ClusterA,topic_billing,2560000,162.0,user_zhang,20260507
3
+ SystemBeta,数据仓库DWProdB,AppGroupY,202,ClusterB,topic_log,1200000,81.0,user_li,20260507
4
+ SystemGamma,数据仓库DWProdC,AppGroupZ,303,ClusterC,topic_metrics,512000,50.0,user_wang,20260507
tasks/offline-compute/HiveSQL/hivesql_006_en/gt/grade.py ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hivesql_015 精细评分脚本
2
+
3
+ 业务场景:数据总线 topic接入成本原始数据清洗并按topic维度聚合,排除测试topic,写入明细表
4
+ 难度: EASY | 特征: INSERT_OVERWRITE|PARTITION|SINGLE_TABLE|GROUP_BY
5
+
6
+ 评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
7
+ A_executability (15分): result.sql 能跑通且产出非空
8
+ B_schema (10分): 列数(5) + 列名匹配(5)
9
+ C_row_alignment (15分): 行数比例(7) + key覆盖率(8)
10
+ D_field_value_match (25分): 非key字段逐列值匹配率
11
+ D_field_completeness (15分): 关键字段非空/非空串比例
12
+ F_insert_overwrite (5分): INSERT OVERWRITE + PARTITION
13
+ F_partition_value (5分): dt 分区值 = 20260507
14
+ F_source_filter (10分): 源表分区过滤 dt=20260507 + topic<>'test'
15
+
16
+ 权重: EASY -> product=0.5, process=0.5
17
+ """
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import tempfile
22
+ import json
23
+ import math
24
+
25
+
26
+ def grade(workspace_path, **kwargs):
27
+
28
+ # ========== Case 配置 ==========
29
+ OUTPUT_TABLE = "internal_platform_db.dwd_databus_topic_cost_detail_d_cand_query_engine_015"
30
+ DIFFICULTY = "EASY"
31
+ SOURCE_TABLES = ["ods_t_databus_access_topic_cost_date_d_query_engine_015", "dwd_databus_topic_cost_detail_d_query_engine_015"]
32
+ KEY_COLUMNS = ["city_id", "dt"]
33
+ EXPECTED_COL_COUNT = 10
34
+ KEY_FIELDS = ["system_belong", "topic", "total_data_size_d", "total_cost", "in_charge"]
35
+ GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
36
+
37
+ DIFFICULTY_WEIGHTS = {
38
+ "EASY": (0.5, 0.5),
39
+ "MEDIUM": (0.6, 0.4),
40
+ "HARD": (0.7, 0.3),
41
+ "EXPERT": (0.8, 0.2),
42
+ }
43
+
44
+ _SPARK_SUBMIT_TIMEOUT = 300
45
+ _JSON_START = "__GRADE_JSON_START__"
46
+ _JSON_END = "__GRADE_JSON_END__"
47
+
48
+ result = {
49
+ "overall_score": 0.0,
50
+ "total_points": 0,
51
+ "grade": "",
52
+ "details": {},
53
+ "diagnostics": [],
54
+ }
55
+
56
+ # ========== 内部辅助函数 ==========
57
+
58
+ def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
59
+ if pred_val is None and gt_val is None:
60
+ return True
61
+ if pred_val is None or gt_val is None:
62
+ return False
63
+ s_pred = str(pred_val).strip()
64
+ s_gt = str(gt_val).strip()
65
+ if s_pred == s_gt:
66
+ return True
67
+ try:
68
+ pv = float(s_pred)
69
+ gv = float(s_gt)
70
+ if math.isnan(pv) and math.isnan(gv):
71
+ return True
72
+ if math.isnan(pv) or math.isnan(gv):
73
+ return False
74
+ if abs(gv) < abs_tol:
75
+ return abs(pv - gv) <= abs_tol
76
+ return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
77
+ except (ValueError, TypeError):
78
+ pass
79
+ return s_pred.lower() == s_gt.lower()
80
+
81
+ def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
82
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
83
+ f.write(script_code)
84
+ script_path = f.name
85
+ try:
86
+ r = subprocess.run(
87
+ ["spark-submit", script_path],
88
+ capture_output=True, text=True, timeout=timeout,
89
+ )
90
+ stdout = r.stdout or ""
91
+ if _JSON_START in stdout and _JSON_END in stdout:
92
+ json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
93
+ return json.loads(json_str), None
94
+ else:
95
+ if r.returncode == 0:
96
+ for line in stdout.splitlines():
97
+ if line.strip().startswith("Traceback"):
98
+ return None, f"spark-submit error: {line}"
99
+ return None, "spark-submit 无 JSON 输出"
100
+ err_msg = (r.stderr or "")[-500:]
101
+ return None, f"spark-submit failed: {err_msg}"
102
+ except subprocess.TimeoutExpired:
103
+ return None, f"spark-submit 超时 ({timeout}s)"
104
+ except Exception as e:
105
+ return None, f"spark-submit 异常: {e}"
106
+ finally:
107
+ try:
108
+ os.unlink(script_path)
109
+ except OSError:
110
+ pass
111
+
112
+ def read_table_via_spark_submit(table_name):
113
+ """Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
114
+ if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
115
+ raise ValueError(f"非法表名: {table_name}")
116
+ read_script = f'''
117
+ import json
118
+ from pyspark.sql import SparkSession
119
+ spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
120
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
121
+ try:
122
+ df = spark.sql("SELECT * FROM {table_name}")
123
+ cols = [c.lower() for c in df.columns]
124
+ rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
125
+ print("{_JSON_START}")
126
+ print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
127
+ print("{_JSON_END}")
128
+ except Exception as e:
129
+ print("{_JSON_START}")
130
+ print(json.dumps({{"error": str(e)}}))
131
+ print("{_JSON_END}")
132
+ finally:
133
+ spark.stop()
134
+ '''
135
+ data, err = _run_spark_script(read_script)
136
+ if err:
137
+ raise RuntimeError(f"read_table failed: {err}")
138
+ if "error" in data:
139
+ raise RuntimeError(f"query failed: {data['error']}")
140
+ return data["cols"], data["rows"]
141
+
142
+ # SQL executor template (self-contained, no external dependency)
143
+ _SQL_EXEC_TEMPLATE = '''
144
+ import json, re
145
+ from pyspark.sql import SparkSession
146
+ spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
147
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
148
+ try:
149
+ with open("{sql_file}", "r", encoding="utf-8") as _f:
150
+ _sql = _f.read()
151
+ _sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
152
+ _stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
153
+ while _i < len(_sql):
154
+ _ch = _sql[_i]
155
+ if _ch == "\\\\" and _i + 1 < len(_sql):
156
+ _cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
157
+ if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
158
+ while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
159
+ _cur.append("\\n"); continue
160
+ if _ch == "'" and not _in_dq: _in_sq = not _in_sq
161
+ elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
162
+ if _ch == ";" and not _in_sq and not _in_dq:
163
+ _s = "".join(_cur).strip()
164
+ if _s: _stmts.append(_s)
165
+ _cur = []
166
+ else:
167
+ _cur.append(_ch)
168
+ _i += 1
169
+ _last = "".join(_cur).strip()
170
+ if _last: _stmts.append(_last)
171
+ for _stmt in _stmts:
172
+ spark.sql(_stmt)
173
+ print("{_JSON_START}")
174
+ print(json.dumps({{"ok": True}}))
175
+ print("{_JSON_END}")
176
+ except Exception as e:
177
+ print("{_JSON_START}")
178
+ print(json.dumps({{"ok": False, "error": str(e)}}))
179
+ print("{_JSON_END}")
180
+ finally:
181
+ spark.stop()
182
+ '''
183
+
184
+ def execute_result_sql():
185
+ result_sql = os.path.join(workspace_path, "result.sql")
186
+ if not os.path.exists(result_sql):
187
+ return False, "no_result_file"
188
+ # 替换 数据平台WD时间变量(沙箱 spark-sql 不支持 ${...} 语法)
189
+ with open(result_sql, 'r', encoding='utf-8') as _rf:
190
+ _sql_text = _rf.read()
191
+ _bizdate = '20260507'
192
+ _sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
193
+ _sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
194
+ _sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
195
+ _sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
196
+ with open(result_sql, 'w', encoding='utf-8') as _wf:
197
+ _wf.write(_sql_text)
198
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
199
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
200
+ data, err = _run_spark_script(script)
201
+ if err:
202
+ return False, f"execution_error: {err}"
203
+ if data and data.get("ok"):
204
+ return True, None
205
+ return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
206
+
207
+ def execute_ground_truth_sql():
208
+ gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
209
+ if not os.path.exists(gt_sql):
210
+ return False, "ground_truth.sql not found"
211
+ script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
212
+ _JSON_START=_JSON_START, _JSON_END=_JSON_END)
213
+ data, err = _run_spark_script(script)
214
+ if err:
215
+ return False, f"gt_execution_error: {err}"
216
+ if data and data.get("ok"):
217
+ return True, None
218
+ return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
219
+
220
+ def truncate_table(table_name):
221
+ script = f'''
222
+ from pyspark.sql import SparkSession
223
+ spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
224
+ .config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
225
+ spark.sql("TRUNCATE TABLE {table_name}")
226
+ spark.stop()
227
+ '''
228
+ try:
229
+ _run_spark_script(script, timeout=120)
230
+ except Exception:
231
+ pass
232
+
233
+ def restore_hive_site():
234
+ """Restore hive-site.xml to canonical state (agent may have modified it)."""
235
+ canonical_hive_site = '''<?xml version="1.0"?>
236
+ <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
237
+ <configuration>
238
+ <property>
239
+ <name>hive.metastore.uris</name>
240
+ <value>thrift://localhost:9083</value>
241
+ </property>
242
+ <property>
243
+ <name>hive.metastore.warehouse.dir</name>
244
+ <value>/tmp/hive_warehouse</value>
245
+ </property>
246
+ <property>
247
+ <name>javax.jdo.option.ConnectionURL</name>
248
+ <value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
249
+ </property>
250
+ <property>
251
+ <name>javax.jdo.option.ConnectionDriverName</name>
252
+ <value>org.apache.derby.jdbc.EmbeddedDriver</value>
253
+ </property>
254
+ <property>
255
+ <name>datanucleus.schema.autoCreateAll</name>
256
+ <value>true</value>
257
+ </property>
258
+ <property>
259
+ <name>hive.metastore.schema.verification</name>
260
+ <value>false</value>
261
+ </property>
262
+ </configuration>
263
+ '''
264
+ hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
265
+ try:
266
+ with open(hive_site_path, 'w') as f:
267
+ f.write(canonical_hive_site)
268
+ except Exception:
269
+ pass
270
+
271
+ def finalize(result):
272
+ product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
273
+ product_dims = ["A_executability"] + ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']
274
+ product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
275
+ product_ratio = product_raw / 100.0
276
+ for dim in ["H_efficiency"]:
277
+ if dim in result["details"]:
278
+ raw = result["details"][dim].get("score", 0)
279
+ result["details"][dim]["score_before_scaling"] = raw
280
+ result["details"][dim]["score"] = round(raw * product_ratio, 2)
281
+ result["details"][dim]["product_ratio"] = round(product_ratio, 4)
282
+ process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
283
+ process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
284
+ product_score = round(product_raw * product_weight, 2)
285
+ process_score = round(process_raw * process_weight, 2)
286
+ total = round(product_score + process_score, 2)
287
+ result["total_points"] = total
288
+ result["product_points"] = product_score
289
+ result["process_points"] = round(process_score, 2)
290
+ result["weights"] = {"product": product_weight, "process": process_weight}
291
+ result["overall_score"] = round(total / 100.0, 4)
292
+ if total >= 90:
293
+ result["grade"] = "优秀"
294
+ elif total >= 75:
295
+ result["grade"] = "良好"
296
+ elif total >= 60:
297
+ result["grade"] = "合格"
298
+ elif total >= 40:
299
+ result["grade"] = "偏弱"
300
+ else:
301
+ result["grade"] = "不合格"
302
+ return result
303
+
304
+ # Restore hive-site.xml (agent may have modified it)
305
+ restore_hive_site()
306
+
307
+ # ========== A. 可执行性 (15分) ==========
308
+ a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
309
+ exec_ok, exec_err = execute_result_sql()
310
+ if not exec_ok:
311
+ detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
312
+ result["details"]["A_executability"] = {"score": 0, "max": 15, "detail": detail}
313
+ result["error"] = detail
314
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
315
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
316
+ return finalize(result)
317
+
318
+ a_items["A1_exec_ok"] = 8
319
+
320
+ pred_headers, pred_rows = [], []
321
+ try:
322
+ pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
323
+ except Exception as e:
324
+ result["diagnostics"].append(f"read_pred_failed: {e}")
325
+
326
+ if not pred_rows:
327
+ result["details"]["A_executability"] = {"score": 8, "max": 15, "items": a_items}
328
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
329
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
330
+ return finalize(result)
331
+
332
+ a_items["A2_has_data"] = 7
333
+ result["details"]["A_executability"] = {"score": 15, "max": 15, "items": a_items}
334
+
335
+ # ========== Execute GT + Read GT ==========
336
+ truncate_table(GT_TABLE)
337
+ gt_ok, gt_err = execute_ground_truth_sql()
338
+ if not gt_ok:
339
+ result["error"] = f"ground_truth failed: {gt_err}"
340
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
341
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
342
+ return finalize(result)
343
+
344
+ gt_headers, gt_rows = [], []
345
+ try:
346
+ gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
347
+ except Exception as e:
348
+ result["error"] = f"read_gt_failed: {e}"
349
+ for dim in ['B_schema', 'C_row_alignment', 'D_field_completeness', 'D_field_value_match', 'F_insert_overwrite', 'F_partition_value', 'F_source_filter']:
350
+ result["details"][dim] = {"score": 0, "max": 0, "items": {}}
351
+ return finalize(result)
352
+
353
+ # ========== B/C/D/F 维度评分 ==========
354
+ pred_col_map = {h: i for i, h in enumerate(pred_headers)}
355
+ gt_col_map = {h: i for i, h in enumerate(gt_headers)}
356
+
357
+ # ========== B. Schema正确性 (10分) ==========
358
+ b_items = {}
359
+ # B1: 列数 (5分)
360
+ if len(pred_headers) == EXPECTED_COL_COUNT:
361
+ b_items["B1_col_count"] = 5
362
+ elif abs(len(pred_headers) - EXPECTED_COL_COUNT) <= 2:
363
+ b_items["B1_col_count"] = 3
364
+ else:
365
+ b_items["B1_col_count"] = 0
366
+
367
+ # B2: 列名匹配 (5分)
368
+ gt_col_set = set(gt_headers)
369
+ pred_col_set = set(pred_headers)
370
+ name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
371
+ if name_match_rate >= 0.95:
372
+ b_items["B2_col_names"] = 5
373
+ elif name_match_rate >= 0.8:
374
+ b_items["B2_col_names"] = 3
375
+ else:
376
+ b_items["B2_col_names"] = 0
377
+
378
+ b_score = sum(b_items.values())
379
+ result["details"]["B_schema"] = {
380
+ "score": b_score, "max": 10,
381
+ "detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
382
+ }
383
+
384
+ # ========== C. 行一致性 (15分) ==========
385
+ c_items = {}
386
+ gt_row_count = len(gt_rows)
387
+ pred_row_count = len(pred_rows)
388
+
389
+ # C1: 行数比例 (7分)
390
+ if gt_row_count > 0:
391
+ ratio = pred_row_count / gt_row_count
392
+ if 0.95 <= ratio <= 1.05:
393
+ c_items["C1_row_ratio"] = 7
394
+ elif 0.7 <= ratio <= 1.3:
395
+ c_items["C1_row_ratio"] = 4
396
+ else:
397
+ c_items["C1_row_ratio"] = 0
398
+ else:
399
+ c_items["C1_row_ratio"] = 7 if pred_row_count == 0 else 0
400
+
401
+ # C2: key覆盖率 (8分)
402
+ key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
403
+ if key_cols_avail and gt_row_count > 0:
404
+ gt_keys = set()
405
+ for row in gt_rows:
406
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
407
+ gt_keys.add(key)
408
+ pred_keys = set()
409
+ for row in pred_rows:
410
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
411
+ pred_keys.add(key)
412
+ coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
413
+ if coverage >= 0.995:
414
+ c_items["C2_key_coverage"] = 8
415
+ elif coverage >= 0.9:
416
+ c_items["C2_key_coverage"] = 6
417
+ elif coverage >= 0.7:
418
+ c_items["C2_key_coverage"] = 3
419
+ else:
420
+ c_items["C2_key_coverage"] = round(8 * coverage, 2)
421
+ else:
422
+ c_items["C2_key_coverage"] = 0
423
+
424
+ c_score = sum(v for v in c_items.values())
425
+ result["details"]["C_row_alignment"] = {"score": c_score, "max": 15, "detail": c_items}
426
+
427
+ # 构建索引
428
+ if key_cols_avail:
429
+ pred_index = {}
430
+ for row in pred_rows:
431
+ key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
432
+ pred_index[key] = row
433
+ gt_index = {}
434
+ for row in gt_rows:
435
+ key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
436
+ gt_index[key] = row
437
+ else:
438
+ pred_index = {}
439
+ gt_index = {}
440
+
441
+ # ========== D. 字段值匹配 (25分) ==========
442
+ value_cols = [c for c in gt_headers if c in pred_col_map and c not in KEY_COLUMNS]
443
+ if not value_cols:
444
+ value_cols = [c for c in gt_headers if c in pred_col_map]
445
+
446
+ d_val_items = {}
447
+ per_col_weight = 25.0 / max(len(value_cols), 1)
448
+ d_val_score = 0
449
+ for col in value_cols:
450
+ gt_ci = gt_col_map.get(col)
451
+ pred_ci = pred_col_map.get(col)
452
+ if gt_ci is None or pred_ci is None:
453
+ d_val_items[col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
454
+ continue
455
+ matches = 0
456
+ total = 0
457
+ for key, gt_row in gt_index.items():
458
+ pred_row = pred_index.get(key)
459
+ if pred_row is None:
460
+ total += 1
461
+ continue
462
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
463
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
464
+ if values_match(pred_val, gt_val):
465
+ matches += 1
466
+ total += 1
467
+ rate = matches / max(total, 1)
468
+ col_score = rate * per_col_weight
469
+ d_val_score += col_score
470
+ d_val_items[col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2)}
471
+
472
+ result["details"]["D_field_value_match"] = {
473
+ "score": round(d_val_score, 2), "max": 25, "detail": d_val_items,
474
+ }
475
+
476
+ # ========== D. 字段完整性 (15分) ==========
477
+ d_comp_items = {}
478
+ d_comp_score = 0
479
+ per_field_weight = 15.0 / max(len(KEY_FIELDS), 1)
480
+ for field in KEY_FIELDS:
481
+ gt_ci = gt_col_map.get(field)
482
+ pred_ci = pred_col_map.get(field)
483
+ if gt_ci is None or pred_ci is None:
484
+ d_comp_items[field] = {"score": 0, "reason": "column_missing"}
485
+ continue
486
+ gt_nonempty = 0
487
+ pred_nonempty = 0
488
+ total = 0
489
+ for key, gt_row in gt_index.items():
490
+ gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
491
+ if gt_val:
492
+ total += 1
493
+ pred_row = pred_index.get(key)
494
+ if pred_row is not None:
495
+ pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
496
+ if pred_val:
497
+ pred_nonempty += 1
498
+ gt_nonempty = total
499
+ rate = pred_nonempty / max(gt_nonempty, 1)
500
+ field_score = rate * per_field_weight
501
+ d_comp_score += field_score
502
+ d_comp_items[field] = {"nonempty_rate": round(rate, 4), "score": round(field_score, 2)}
503
+
504
+ result["details"]["D_field_completeness"] = {
505
+ "score": round(d_comp_score, 2), "max": 15, "detail": d_comp_items,
506
+ }
507
+
508
+ # ========== F. INSERT OVERWRITE (5分) ==========
509
+ result_sql_path = os.path.join(workspace_path, "result.sql")
510
+ sql_text = ""
511
+ try:
512
+ with open(result_sql_path, "r", encoding="utf-8") as f:
513
+ sql_text = f.read().lower()
514
+ except Exception:
515
+ sql_text = ""
516
+
517
+ f_insert_items = {}
518
+ has_overwrite = "insert overwrite" in sql_text
519
+ has_partition = "partition" in sql_text
520
+ if has_overwrite and has_partition:
521
+ f_insert_items["insert_overwrite_partition"] = 5
522
+ elif has_overwrite:
523
+ f_insert_items["insert_overwrite_partition"] = 3
524
+ else:
525
+ f_insert_items["insert_overwrite_partition"] = 0
526
+ result["details"]["F_insert_overwrite"] = {
527
+ "score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
528
+ }
529
+
530
+ # ========== F. 分区值 (5分) ==========
531
+ f_part_items = {}
532
+ if "dt" in sql_text and "20260507" in sql_text:
533
+ f_part_items["partition_value"] = 5
534
+ else:
535
+ f_part_items["partition_value"] = 0
536
+ result["details"]["F_partition_value"] = {
537
+ "score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
538
+ }
539
+
540
+ # ========== F. 源表分区过滤 (10分) ==========
541
+ f_filter_items = {}
542
+ source_table_lower = SOURCE_TABLES[0].lower()
543
+ has_source_table = source_table_lower in sql_text
544
+ has_dt_filter = "dt" in sql_text and "20260507" in sql_text
545
+ has_topic_filter = "test" in sql_text and "<>" in sql_text
546
+ if has_source_table and has_dt_filter and has_topic_filter:
547
+ f_filter_items["source_partition_filter"] = 10
548
+ elif has_dt_filter and has_topic_filter:
549
+ f_filter_items["source_partition_filter"] = 7
550
+ elif has_dt_filter:
551
+ f_filter_items["source_partition_filter"] = 4
552
+ elif has_source_table:
553
+ f_filter_items["source_partition_filter"] = 2
554
+ else:
555
+ f_filter_items["source_partition_filter"] = 0
556
+ result["details"]["F_source_filter"] = {
557
+ "score": f_filter_items["source_partition_filter"], "max": 10, "detail": f_filter_items,
558
+ }
559
+
560
+ # 汇总
561
+ total = (15 + b_score + c_score + d_val_score + d_comp_score
562
+ + f_insert_items["insert_overwrite_partition"]
563
+ + f_part_items["partition_value"]
564
+ + f_filter_items["source_partition_filter"])
565
+
566
+ # ========== G~I 过程评分 ==========
567
+ TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
568
+ OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
569
+ INPUT_TABLE_SHORT = SOURCE_TABLES[0]
570
+
571
+ transcript_entries = []
572
+ has_transcript = False
573
+ try:
574
+ if os.path.exists(TRANSCRIPT_PATH):
575
+ with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f:
576
+ for line in f:
577
+ line = line.strip()
578
+ if line:
579
+ try:
580
+ transcript_entries.append(json.loads(line))
581
+ except json.JSONDecodeError:
582
+ continue
583
+ if len(transcript_entries) > 2:
584
+ has_transcript = True
585
+ except Exception:
586
+ pass
587
+
588
+ if not has_transcript:
589
+ result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}}
590
+ result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}}
591
+ result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}}
592
+ return finalize(result)
593
+
594
+ # Parse transcript into structured events
595
+ tool_uses = []
596
+ first_write_result_idx = None
597
+ last_spark_submit_success_idx = None
598
+ write_result_count = 0
599
+ logic_error_retries = 0
600
+
601
+ for idx, entry in enumerate(transcript_entries):
602
+ content = entry.get("content", [])
603
+ if isinstance(content, str):
604
+ content = [content]
605
+
606
+ for block_str in content:
607
+ if not isinstance(block_str, str):
608
+ continue
609
+ if "ToolUseBlock" in block_str:
610
+ name_match = re.search(r"name='([^']+)'", block_str)
611
+ input_match = re.search(r"input=(\{.*\})", block_str)
612
+ if name_match:
613
+ tool_name = name_match.group(1)
614
+ tool_input = input_match.group(1) if input_match else ""
615
+ tool_uses.append((idx, tool_name, tool_input))
616
+ if tool_name == "Write" and "result.sql" in tool_input:
617
+ write_result_count += 1
618
+ if first_write_result_idx is None:
619
+ first_write_result_idx = idx
620
+ if "ToolResultBlock" in block_str:
621
+ if "Traceback" in block_str or "Exception" in block_str:
622
+ env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
623
+ "db.lck", "TTransportException", "port 10000"]
624
+ is_env_error = any(e in block_str for e in env_errors)
625
+ has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
626
+ for t in tool_uses)
627
+ if not is_env_error and has_spark_submit:
628
+ logic_error_retries += 1
629
+ if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" in block_str:
630
+ if "Exit Code: 0" in block_str and "Traceback" not in block_str:
631
+ last_spark_submit_success_idx = idx
632
+
633
+ before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
634
+
635
+ # ===== G. 探索充分性 (35分) =====
636
+ g_items = {}
637
+ g1_pass = any(name == "Read" and "schema" in inp.lower()
638
+ for idx, name, inp in tool_uses if idx < before_first_write)
639
+ g_items["G1_source_schema"] = 9 if g1_pass else 0
640
+
641
+ g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
642
+ and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
643
+ for idx, name, inp in tool_uses if idx < before_first_write)
644
+ g_items["G2_source_sample"] = 9 if g2_pass else 0
645
+
646
+ g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
647
+ and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
648
+ for idx, name, inp in tool_uses if idx < before_first_write)
649
+ g_items["G3_distribution"] = 9 if g3_pass else 0
650
+
651
+ g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
652
+ and OUTPUT_TABLE_SHORT in inp
653
+ for idx, name, inp in tool_uses if idx < before_first_write)
654
+ g_items["G4_target_schema"] = 8 if g4_pass else 0
655
+
656
+ g_score = sum(g_items.values())
657
+ result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
658
+
659
+ # ===== H. 执行效率 (40分) =====
660
+ h_items = {}
661
+ if write_result_count <= 2:
662
+ h_items["H1_few_submissions"] = 20
663
+ elif write_result_count <= 4:
664
+ h_items["H1_few_submissions"] = 13
665
+ elif write_result_count <= 6:
666
+ h_items["H1_few_submissions"] = 7
667
+ else:
668
+ h_items["H1_few_submissions"] = 0
669
+
670
+ if logic_error_retries == 0:
671
+ h_items["H2_no_logic_errors"] = 13
672
+ elif logic_error_retries <= 1:
673
+ h_items["H2_no_logic_errors"] = 7
674
+ else:
675
+ h_items["H2_no_logic_errors"] = 0
676
+
677
+ h_items["H3_no_redundancy"] = 7
678
+ h_score = sum(h_items.values())
679
+ result["details"]["H_efficiency"] = {"score": min(h_score, 40), "max": 40, "items": h_items}
680
+
681
+ # ===== I. 自验证行为 (25分) =====
682
+ i_items = {}
683
+ post_submit_uses = []
684
+ if last_spark_submit_success_idx is not None:
685
+ post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
686
+ if idx > last_spark_submit_success_idx]
687
+
688
+ i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
689
+ for _, name, inp in post_submit_uses)
690
+ i_items["I1_query_output"] = 8 if i1_pass else 0
691
+
692
+ i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
693
+ and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
694
+ for _, name, inp in post_submit_uses)
695
+ i_items["I2_check_count"] = 9 if i2_pass else 0
696
+
697
+ i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
698
+ and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper())
699
+ for _, name, inp in post_submit_uses)
700
+ i_items["I3_check_values"] = 8 if i3_pass else 0
701
+
702
+ i_score = sum(i_items.values())
703
+ result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items}
704
+
705
+ return finalize(result)
tasks/offline-compute/HiveSQL/hivesql_006_en/gt/grade_spec.csv ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 维度,维度全名,子维度,满分,说明
2
+ A,A_executability,executability,15,result.sql 能跑通且产出非空
3
+ B,B_schema,schema,10,列数(5) + 列名匹配(5)
4
+ C,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)
5
+ D,D_field_value_match,field_value_match,25,非key字段逐列值匹配率
6
+ D,D_field_completeness,field_completeness,15,关键字段非空/非空串比例
7
+ F,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION
8
+ F,F_partition_value,partition_value,5,dt 分区值 = 20260507
9
+ F,F_source_filter,source_filter,10,源表分区过滤 dt=20260507 + topic<>'test'
10
+
11
+ 总计,,,100,
12
+
13
+ # 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
14
+ # 难度,EASY
15
+ # 权重,"product=0.5, process=0.5"
16
+ # 范式,new
17
+ # Key列,"city_id, dt"
18
+ # 预期列数,10
19
+ # 输出表,internal_platform_db.dwd_databus_topic_cost_detail_d_cand_query_engine_015
tasks/offline-compute/HiveSQL/hivesql_006_en/gt/ground_truth.sql ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INSERT overwrite TABLE internal_platform_db.dwd_databus_topic_cost_detail_d_query_engine_015 PARTITION (dt = '20260507')
2
+ SELECT
3
+ MAX(systemname) AS system_belong,
4
+ MAX(dwproductname) AS category_name,
5
+ MAX(dwappgroup) AS dw_appgroup,
6
+ MAX(cityid) AS city_id,
7
+ MAX(iset) AS cluster_set,
8
+ topic,
9
+ MAX(data_size) AS total_data_size_d,
10
+ MAX(total_cost) AS total_cost,
11
+ MAX(in_charge) AS in_charge
12
+ FROM
13
+ internal_platform_db.ods_t_databus_access_topic_cost_date_d_query_engine_015
14
+ WHERE
15
+ dt = '20260507'
16
+ AND topic <> 'test'
17
+ GROUP BY topic
tasks/offline-compute/HiveSQL/hivesql_006_en/init/init_db.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import re
3
+ from pyspark.sql import SparkSession
4
+
5
+ spark = SparkSession.builder \
6
+ .appName('hivesql_bench_init') \
7
+ .enableHiveSupport() \
8
+ .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \
9
+ .getOrCreate()
10
+
11
+ spark.sql('CREATE DATABASE IF NOT EXISTS internal_platform_db')
12
+
13
+
14
+ def _execute_sql_file(spark, sql_path):
15
+ """Read SQL file, remove SuperSQL SET headers, split by semicolons, execute."""
16
+ with open(sql_path, 'r', encoding='utf-8') as f:
17
+ content = f.read()
18
+ content = re.sub(r'^\s*set\s+query_engine\.\S+\n?', '', content, flags=re.IGNORECASE)
19
+ stmts, cur, in_sq, in_dq, i = [], [], False, False, 0
20
+ while i < len(content):
21
+ ch = content[i]
22
+ if ch == '\\' and i + 1 < len(content):
23
+ cur.append(ch); cur.append(content[i + 1]); i += 2; continue
24
+ if ch == '-' and i + 1 < len(content) and content[i + 1] == '-' and not in_sq and not in_dq:
25
+ while i < len(content) and content[i] != '\n':
26
+ i += 1
27
+ cur.append('\n'); continue
28
+ if ch == "'" and not in_dq:
29
+ in_sq = not in_sq
30
+ elif ch == '"' and not in_sq:
31
+ in_dq = not in_dq
32
+ if ch == ';' and not in_sq and not in_dq:
33
+ s = ''.join(cur).strip()
34
+ if s:
35
+ stmts.append(s)
36
+ cur = []
37
+ else:
38
+ cur.append(ch)
39
+ i += 1
40
+ last = ''.join(cur).strip()
41
+ if last:
42
+ stmts.append(last)
43
+ for stmt in stmts:
44
+ spark.sql(stmt)
45
+
46
+
47
+ _execute_sql_file(spark, '/tmp_workspace/init_db.sql')
48
+
49
+ tables = spark.sql('SHOW TABLES IN internal_platform_db').collect()
50
+ print(f'Init complete, {len(tables)} tables created')
51
+ for t in tables:
52
+ print(f' - {t.namespace}.{t.tableName}')
53
+ spark.stop()
tasks/offline-compute/HiveSQL/hivesql_006_en/init/init_db.sql ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS internal_platform_db;
2
+
3
+ -- 输入表
4
+ CREATE TABLE IF NOT EXISTS internal_platform_db.ods_t_databus_access_topic_cost_date_d_query_engine_015 (
5
+ dt STRING COMMENT '天分区',
6
+ rep_date STRING COMMENT '日期',
7
+ systemclass STRING COMMENT '系统',
8
+ systemname STRING COMMENT '系统名',
9
+ odsproductid STRING COMMENT '产品ID',
10
+ odsproductname STRING COMMENT '产品名称',
11
+ dwproductid STRING COMMENT '数据仓库DW产品ID',
12
+ dwproductname STRING COMMENT '数据仓库DW产品名称',
13
+ dwappgroup STRING COMMENT '数据仓库DW应用组',
14
+ cityid STRING COMMENT '城市ID',
15
+ iset STRING COMMENT '集群',
16
+ topic STRING COMMENT 'topic',
17
+ data_count BIGINT COMMENT '条数',
18
+ data_pkgcnt BIGINT COMMENT '包数',
19
+ data_size BIGINT COMMENT '大小',
20
+ cost_count BIGINT COMMENT '核算数',
21
+ cost_per DOUBLE COMMENT '占比',
22
+ cost_tco DOUBLE COMMENT '设备成本',
23
+ cost_lan DOUBLE COMMENT '专线成本',
24
+ total_cost DOUBLE COMMENT '总成本',
25
+ in_charge STRING COMMENT '负责人'
26
+ ) STORED AS ORC;
27
+
28
+ INSERT INTO TABLE internal_platform_db.ods_t_databus_access_topic_cost_date_d_query_engine_015 VALUES
29
+ ('20260507','20260507','classA','SystemAlpha','P001','ProdAlpha','T001','数据仓库DWProdA','AppGroupX','101','ClusterA','topic_billing',1000,50,2048000,800,0.35,120.5,30.2,150.7,'user_zhang'),
30
+ ('20260507','20260507','classA','SystemAlpha','P001','ProdAlpha','T001','数据仓库DWProdA','AppGroupX','101','ClusterA','topic_billing',1200,60,2560000,900,0.40,130.0,32.0,162.0,'user_zhang'),
31
+ ('20260507','20260507','classB','SystemBeta','P002','ProdBeta','T002','数据仓库DWProdB','AppGroupY','202','ClusterB','topic_log',500,25,1024000,400,0.20,60.0,15.0,75.0,'user_li'),
32
+ ('20260507','20260507','classB','SystemBeta','P002','ProdBeta','T002','数据仓库DWProdB','AppGroupY','202','ClusterB','topic_log',600,30,1200000,450,0.22,65.0,16.0,81.0,'user_li'),
33
+ ('20260507','20260507','classC','SystemGamma','P003','ProdGamma','T003','数据仓库DWProdC','AppGroupZ','303','ClusterC','topic_metrics',300,15,512000,200,0.10,40.0,10.0,50.0,'user_wang'),
34
+ ('20260507','20260507','classC','SystemGamma','P003','ProdGamma','T003','数据仓库DWProdC','AppGroupZ','303','ClusterC','test',10,1,1000,5,0.01,1.0,0.5,1.5,'user_test'),
35
+ ('20260506','20260506','classA','SystemAlpha','P001','ProdAlpha','T001','数据仓库DWProdA','AppGroupX','101','ClusterA','topic_billing',900,45,1800000,700,0.30,100.0,25.0,125.0,'user_zhang');
36
+
37
+ -- 目标表
38
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_databus_topic_cost_detail_d_query_engine_015 (
39
+ system_belong STRING COMMENT '系统名',
40
+ category_name STRING COMMENT '数据仓库DW产品名称',
41
+ dw_appgroup STRING COMMENT '数据仓库DW应用组',
42
+ city_id STRING COMMENT '城市ID',
43
+ cluster_set STRING COMMENT '集群',
44
+ topic STRING COMMENT 'topic',
45
+ total_data_size_d BIGINT COMMENT '大小',
46
+ total_cost DOUBLE COMMENT '总成本',
47
+ in_charge STRING COMMENT '负责人'
48
+ ) PARTITIONED BY (dt STRING COMMENT '天分区') STORED AS ORC;
49
+
50
+ -- Agent 候选目标表
51
+ CREATE TABLE IF NOT EXISTS internal_platform_db.dwd_databus_topic_cost_detail_d_cand_query_engine_015 (
52
+ system_belong STRING COMMENT '系统名',
53
+ category_name STRING COMMENT '数据仓库DW产品名称',
54
+ dw_appgroup STRING COMMENT '数据仓库DW应用组',
55
+ city_id STRING COMMENT '城市ID',
56
+ cluster_set STRING COMMENT '集群',
57
+ topic STRING COMMENT 'topic',
58
+ total_data_size_d BIGINT COMMENT '大小',
59
+ total_cost DOUBLE COMMENT '总成本',
60
+ in_charge STRING COMMENT '负责人'
61
+ ) PARTITIONED BY (dt STRING COMMENT '天分区') STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_006_en/init/schema.sql ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS internal_platform_db.ods_t_databus_access_topic_cost_date_d (
2
+ `dt` STRING COMMENT '天分区',
3
+ `rep_date` STRING COMMENT '日期',
4
+ `systemclass` STRING COMMENT '系统',
5
+ `systemname` STRING COMMENT '系统名',
6
+ `odsproductid` STRING COMMENT '产品ID',
7
+ `odsproductname` STRING COMMENT '产品名称',
8
+ `dwproductid` STRING COMMENT '数据仓库DW产品ID',
9
+ `dwproductname` STRING COMMENT '数据仓库DW产品名称',
10
+ `dwappgroup` STRING COMMENT '数据仓库DW应用组',
11
+ `cityid` STRING COMMENT '城市ID',
12
+ `iset` STRING COMMENT '集群',
13
+ `topic` STRING COMMENT 'topic',
14
+ `data_count` BIGINT COMMENT '条数',
15
+ `data_pkgcnt` BIGINT COMMENT '包数',
16
+ `data_size` BIGINT COMMENT '大小',
17
+ `cost_count` BIGINT COMMENT '核算数',
18
+ `cost_per` DOUBLE COMMENT '占比',
19
+ `cost_tco` DOUBLE COMMENT '设备成本',
20
+ `cost_lan` DOUBLE COMMENT '专线成本',
21
+ `total_cost` DOUBLE COMMENT '总成本',
22
+ `in_charge` STRING COMMENT '负责人'
23
+ ) STORED AS ORC;
tasks/offline-compute/HiveSQL/hivesql_006_en/task.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: offline-compute_HiveSQL_hivesql_006
3
+ name: Input Table internal_platform_db.ods_t_databus_access_topic
4
+ category: offline-compute/HiveSQL
5
+ timeout_seconds: 600
6
+ modality: pure-text
7
+ engine: hivesql
8
+ ---
9
+ ## Prompt
10
+ Task Objective: Cleanse the 数据总线 topic access cost raw data and aggregate it by topic dimension, excluding test topics, then write the results to a detail table.
11
+
12
+ Input: `internal_platform_db.ods_t_databus_access_topic_cost_date_d_query_engine_015`, partitioned by field `dt` (STRING, YYYYMMDD). Key fields: `systemname`, `dwproductname`, `dwappgroup`, `cityid`, `iset`, `topic`, `data_size` (BIGINT), `total_cost` (DOUBLE), `in_charge`.
13
+
14
+ Processing Rules: No joins, single-table processing. Filter condition: `dt = '20260507' AND topic <> 'test'`. Aggregation: Group by `topic`, applying `MAX` to `systemname`, `dwproductname`, `dwappgroup`, `cityid`, `iset`, `data_size`, `total_cost`, and `in_charge`. Derived column: `dt` directly takes the partition value `'20260507'`.
15
+
16
+ Output Requirements: The output field order is `dt`, `system_belong`, `category_name`, `dw_appgroup`, `city_id`, `cluster_set`, `topic`, `total_data_size_d`, `total_cost`, `in_charge`. Field mappings: `dt=dt`, `system_belong=MAX(systemname)`, `category_name=MAX(dwproductname)`, `dw_appgroup=MAX(dwappgroup)`, `city_id=MAX(cityid)`, `cluster_set=MAX(iset)`, `topic=topic`, `total_data_size_d=MAX(data_size)`, `total_cost=MAX(total_cost)`, `in_charge=MAX(in_charge)`. Data types: `dt` STRING, `system_belong` STRING, `category_name` STRING, `dw_appgroup` STRING, `city_id` STRING, `cluster_set` STRING, `topic` STRING, `total_data_size_d` BIGINT, `total_cost` DOUBLE, `in_charge` STRING.
17
+
18
+ Write Requirements: Target table `internal_platform_db.dwd_databus_topic_cost_detail_d_cand_query_engine_015`. Table comment: "数据总线 topic access cost detail table, including access cost and dimension information, performing data cleansing on the ODS layer." Partition field `dt` (STRING, YYYYMMDD). Write method: `INSERT OVERWRITE`, overwriting the partition `dt='20260507'`. If the target table does not exist, first create the table using standard Hive ORC storage format partitioned by `dt`, then write the data.
19
+
20
+ Please write the final HiveSQL to `result.sql` and execute it.
tasks/offline-compute/HiveSQL/hivesql_007_en/gt/expected.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ trace_id,p_date,datawd_project_id,datawd_task_id,datawd_task_instance_id,compute_type,status_code,instance_run_time,code_run_time,resource_wait_time,code_start_time,code_end_time,instance_start_time,instance_end_time,serving_id,is_permanent,apply_for_gpu_count,code_gpu_count,instance_gpu_util,code_gpu_util,dt
2
+ trace_001,20260507,proj_01,task_01,inst_01,GPU,0,120,100,20,2026-05-07 10:00:00,2026-05-07 10:01:40,2026-05-07 09:59:40,2026-05-07 10:01:40,srv_01,True,2,2.0,82.5,89.0,20260507
3
+ trace_002,20260507,proj_02,task_02,inst_02,CPU,1,60,50,10,2026-05-07 11:00:00,2026-05-07 11:00:50,2026-05-07 11:00:00,2026-05-07 11:01:00,srv_02,False,0,4.0,0.0,,20260507
4
+ trace_003,20260507,proj_03,task_03,inst_03,GPU,0,300,280,20,2026-05-07 12:00:00,2026-05-07 12:04:40,2026-05-07 11:59:40,2026-05-07 12:04:40,srv_03,True,4,4.0,95.0,92.0,20260507