{"task_id": "hivesql_001_en", "id": "offline-compute_HiveSQL_hivesql_001", "name": "Message Queue Topic Dimension Table internal_platform_db.dim_mq_topic_d_su", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n**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.\n\n**Time Variables**: The platform provides these variables for dynamic date computation:\n- `${yyyymmdd}` : current day in YYYYMMDD format\n- `${yyyymmdd-1}` : previous day in YYYYMMDD format\n- You may also use Spark SQL built-in functions like `current_date()` and `date_sub()`.\n\n**Input**: `internal_platform_db.dim_mq_topic_d_query_engine_001` (a partitioned table, partitioned by `dt`).\n\n**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.\n\n**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.\n\n**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`.\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT overwrite TABLE internal_platform_db.dim_mq_topic_d_copilot_query_engine_001 PARTITION (dt = '20260507')\nSELECT\n business_id\n ,business_name\n ,cluster_set\n ,tenant\n ,namespaces\n ,topic\n ,mq_type\n ,dw_appgroup\n ,in_charge\n ,description\n ,create_time\n ,modify_time\n ,cluster_id\n ,cluster_type\n ,cluster_name\n ,bg\n ,category_name\n ,is_filtered\n ,tids\n ,consumed_tids\n ,unconsumed_tids\n ,is_fully_consumed\n ,has_unconsumed_tid\n ,system_belong\nFROM internal_platform_db.dim_mq_topic_d_query_engine_001\nwhere dt = '20260506'", "expected_csv": "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\nbid001,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\nbid005,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\nbid002,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\nbid004,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\nbid003,BizName3,,tenant_b,ns_b,topic_inlong_1,PULSAR,appgroup3,user3,,2026-03-01,2026-05-03,,,cluster_i1,,product3,,,,,,,流处理平台,20260507", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,25列(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,25,非key字段逐列值匹配率\nD,D_field_completeness,field_completeness,15,关键字段非空/非空串比例\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,dt 分区值 = 20260507\nF,F_source_filter,source_filter,10,源表分区过滤 dt=20260506\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"business_id, cluster_id, dt\"\n# 预期列数,25\n# 输出表,internal_platform_db.dim_mq_topic_d_copilot_cand_query_engine_001", "path": "tasks/offline-compute/HiveSQL/hivesql_001_en"} {"task_id": "hivesql_002", "id": "offline-compute_HiveSQL_hivesql_002", "name": "统计数据平台WDNotebook Ray类型管道任务中运行时间跨自然天的实例明细。从`wedat", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n**任务目标**:统计数据平台WDNotebook Ray类型管道任务中运行时间跨自然天的实例明细,按自然天拆分并关联GPU指标。\n\n**输入**:\n- `internal_platform_db.notebook_span_info_query_engine_005`\n- `internal_platform_db.dwd_gputj_service_instance_map_query_engine_005`\n- `internal_platform_db.dwd_ml_platform_instance_podname_query_engine_005`\n- `internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_005`\n- `internal_platform_db.notebook_engine_info_query_engine_005`\n\n**处理规则**:\n1. 时间过滤:`20260504`-`20260507`,从`notebook_span_info`筛选在`20260507`有记录且跨天的`trace_id`。\n2. 业务过滤:计算类型='ray',服务名='notebook-runner';span名称限定:'runner.execute'、'execute.code'、'execute.code.cell'、'client.execute.code'、'runner.killed'、'set.permanent.compute'、'create.non.permanent.compute';GPU表过滤无效记录。\n3. 跨天拆分:将跨天实例按自然天拆分,每条记录对应一天内的开始和结束时间。\n4. 派生字段:\n - `instance_run_time`:(end_time - start_time)/1000(秒),基于'runner.execute'\n - `code_run_time`:代码执行相关span总时长(秒)\n - `resource_wait_time`:资源创建相关span总时长(秒)\n - `apply_for_gpu_count`:SUM(replicas * num_gpu),按trace_id\n - `gpu_util`:k8s_container_vgpu_gpu_util_sum / k8s_container_vgpu_gpu_util_count\n - `gpu_count`:k8s_container_resource_request_gpu_sum / k8s_container_resource_request_gpu_count\n5. 表关联:\n - 拆分结果按`trace_id`左关联`notebook_engine_info`获取`serving_id`\n - 通过`instance_uuid`关联`dwd_gputj_service_instance_map`与`dwd_ml_platform_instance_podname`,再按`serving_id=service_id`左关联得到`pod_name`\n - 按`pod_name`左关联`gputj_gpu_info_parsed_agg_1min`,条件为`pkg_agg_time`落在实例运行窗口内(优先`instance_start_time`到`instance_end_time`,否则`code_start_time`到`code_end_time`)\n\n**输出要求**:\n- 输出表:`internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_query_engine_005`\n- 字段顺序: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\n- 分区字段:`dt`\n\n**写入要求**:写入`dt='20260507'`分区。\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT overwrite TABLE internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_query_engine_005 PARTITION (dt = '20260507')\nWITH\nbase_data_raw AS (\n SELECT DISTINCT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM internal_platform_db.notebook_span_info_query_engine_005\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (\n SELECT trace_id\n FROM internal_platform_db.notebook_span_info_query_engine_005\n WHERE databus_imp_date >= '2026050700'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n AND span_name = 'runner.execute'\n GROUP BY trace_id\n )\n AND (\n span_name = 'runner.execute'\n OR\n span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute', 'runner.killed')\n )\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'runner.killed'\n THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n CASE\n WHEN span_name = 'runner.execute'\n THEN MAX(CASE WHEN span_name IN ('runner.execute', 'runner.killed') THEN end_time END)\n OVER(PARTITION BY trace_id)\n ELSE end_time\n END AS end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM base_data_raw\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) as start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) as end_date,\n datediff(from_unixtime(CAST(end_time AS BIGINT) / 1000), from_unixtime(CAST(start_time AS BIGINT) / 1000)) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n date_add(b.start_date, s.pos) AS calc_date,\n CASE WHEN s.pos = 0 THEN CAST(b.start_time AS BIGINT)\n ELSE unix_timestamp(cast(date_add(b.start_date, s.pos) as timestamp)) * 1000\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN CAST(b.end_time AS BIGINT)\n ELSE (unix_timestamp(cast(date_add(b.start_date, s.pos + 1) as timestamp)) * 1000) - 1\n END AS end_time,\n CAST(b.start_time AS BIGINT) AS span_start_time,\n CAST(b.end_time AS BIGINT) AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN end_time END) -\n MIN(CASE WHEN span_name = 'runner.execute' THEN start_time END)) / 1000.0) AS instance_run_time,\n ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN end_time END) -\n 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,\n ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN end_time END) -\n MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN start_time END)) / 1000.0) AS resource_wait_time,\n 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,\n 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,\n from_unixtime(MIN(CASE WHEN span_name = 'runner.execute' THEN span_start_time END) / 1000) AS instance_start_time,\n from_unixtime(MAX(CASE WHEN span_name = 'runner.execute' THEN span_end_time END) / 1000) AS instance_end_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n),\ngputj_dim AS (\n SELECT\n t1.service_id,\n t2.pod_name\n FROM internal_platform_db.dwd_gputj_service_instance_map_query_engine_005 t1\n INNER JOIN internal_platform_db.dwd_ml_platform_instance_podname_query_engine_005 t2\n ON t1.instance_uuid = t2.instance_uuid\n AND t1.dt=if('2026050700'>='2025080900', '2026050700', '2025080900')\n AND t2.dt=if('2026050700'>='2025060519', '2026050700', '2025060519')\n GROUP BY t1.service_id, t2.pod_name\n),\ngpu_metrics AS (\n select\n pkg_agg_time,\n pod_name,\n k8s_container_vgpu_gpu_util_sum / k8s_container_vgpu_gpu_util_count AS gpu_util,\n k8s_container_resource_request_gpu_sum / k8s_container_resource_request_gpu_count AS gpu_count\n from internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_005\n where dt >= '2026050400'\n AND dt <= '2026050700'\n AND ( k8s_container_vgpu_gpu_util_count > 0 OR k8s_container_resource_request_gpu_count > 0 )\n AND pod_name IS NOT NULL\n)\nSELECT\n t1.trace_id,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n t1.instance_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n t1.code_start_time,\n t1.code_end_time,\n t1.instance_start_time,\n t1.instance_end_time,\n t2.serving_id,\n t2.is_permanent,\n t2.apply_for_gpu_count,\n t3.pod_name,\n t4.pkg_agg_time,\n t4.gpu_util,\n t4.gpu_count,\n t1.calc_date AS p_date\nFROM trace_time_metrics t1 LEFT JOIN (\n SELECT\n trace_id,\n MAX(serving_id) AS serving_id,\n MAX(is_permanent) AS is_permanent,\n SUM(CAST(replicas AS INT) * CAST(num_gpu AS INT)) AS apply_for_gpu_count\n FROM internal_platform_db.notebook_engine_info_query_engine_005\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\nLEFT JOIN gputj_dim t3 ON t2.serving_id = t3.service_id\nLEFT JOIN gpu_metrics t4 \n ON t3.pod_name = t4.pod_name\n AND (\n CASE\n WHEN t1.instance_start_time IS NOT NULL AND t1.instance_end_time IS NOT NULL\n THEN t4.pkg_agg_time >= t1.instance_start_time AND t4.pkg_agg_time <= t1.instance_end_time\n WHEN t1.code_start_time IS NOT NULL AND t1.code_end_time IS NOT NULL\n THEN t4.pkg_agg_time >= t1.code_start_time AND t4.pkg_agg_time <= t1.code_end_time\n ELSE FALSE\n END\n )\n;", "expected_csv": "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\ntrace_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\ntrace_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\ntrace_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", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,22列 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key覆盖率\nD,D_time_calculation,time_calculation,30,\"instance_run_time, code_run_time 等时间指标\"\nD,D_cross_day_split,cross_day_split,15,trace_001 应出现在两天中\nD,D_dimension_join,dimension_join,10,\"serving_id, pod_name 等维度列匹配\"\nF,F_join_completeness,join_completeness,5,多表都被关联\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,分区值正确\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,\"trace_id, p_date\"\n# 预期列数,\n# 输出表,internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_query_engine_005", "path": "tasks/offline-compute/HiveSQL/hivesql_002"} {"task_id": "hivesql_003", "id": "offline-compute_HiveSQL_hivesql_003", "name": "从 `internal_platform_db.notebook_span_info_query_engine", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n1) 任务目标\n识别并统计 Notebook 管道中被异常 kill 且缺失正常完成信号的 Ray 实例,按天拆分计算运行时长、代码执行时长、资源等待时长及 GPU 申请数。\n\n2) 输入\n- `internal_platform_db.notebook_span_info_query_engine_007`\n- `internal_platform_db.notebook_engine_info_query_engine_007`\n\n3) 处理规则\n- 目标实例筛选:从 span_info 筛选 `compute_type='ray'` 且 `service_name='notebook-runner'` 的实例,选取有 `span_name='runner.killed'` 但无 `span_name='runner.execute'` 的 `trace_id`。\n- 合成运行区间:对每个目标 trace_id,取 `span_name='runner.start'` 的 start_time 作为实例开始时间,取 `span_name='runner.killed'` 的 end_time 作为实例结束时间,合成 `runner.execute` 区间,`status_code` 固定为 2。\n- 跨天拆分:将合成区间按自然日拆分为多条记录,每条对应一天内的部分,`calc_date` 为拆分后的日期。\n- 时长计算(按 trace_id 与 calc_date):\n - instance_run_time:合成区间在当天的起止时间差(毫秒转秒)。\n - code_run_time:`span_name` 为 'execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed' 在当天的起止时间差(毫秒转秒)。\n - resource_wait_time:`span_name` 为 'set.permanent.compute', 'create.non.permanent.compute' 在当天的起止时间差(毫秒转秒)。\n - 输出 code_start_time/code_end_time/instance_start_time/instance_end_time(时间戳转字符串)。\n- 关联引擎信息:左关联 engine_info(过滤 `compute_type='ray'` 且 `service_name='notebook-runner'`),关联键 `trace_id`,获取 serving_id、is_permanent,计算 `apply_for_gpu_count = SUM(replicas * num_gpu)`。\n\n4) 输出要求\n输出字段顺序: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)。\n\n5) 写入要求\n目标表:`internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_cand_query_engine_007`。分区字段:dt。写入分区:`dt='20260507'`。写入模式:覆盖。\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT overwrite TABLE internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_query_engine_007 PARTITION (dt = '20260507')\nWITH base_trace AS (\n SELECT trace_id\n FROM internal_platform_db.notebook_span_info_query_engine_007\n WHERE databus_imp_date >= '2026050700'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n AND span_name IN ('runner.execute', 'runner.killed')\n GROUP BY trace_id\n HAVING\n COUNT(CASE WHEN span_name = 'runner.killed' THEN 1 END) > 0\n AND\n COUNT(CASE WHEN span_name = 'runner.execute' THEN 1 END) = 0\n),\ncombined_spans AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM internal_platform_db.notebook_span_info_query_engine_007\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('runner.killed', 'runner.start', 'execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute')\n\n UNION ALL\n\n SELECT\n trace_id,\n 'runner.execute' AS span_name,\n MAX(CASE WHEN span_name = 'runner.start' THEN start_time END) AS start_time,\n MAX(CASE WHEN span_name = 'runner.killed' THEN end_time END) AS end_time,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_project_id END) AS datawd_project_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_id END) AS datawd_task_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_instance_id END) AS datawd_task_instance_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN compute_type END) AS compute_type,\n 2 AS status_code\n FROM internal_platform_db.notebook_span_info_query_engine_007\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('runner.start', 'runner.killed')\n GROUP BY trace_id\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'runner.killed'\n THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM combined_spans\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) as start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) as end_date,\n datediff(from_unixtime(CAST(end_time AS BIGINT) / 1000), from_unixtime(CAST(start_time AS BIGINT) / 1000)) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n date_add(b.start_date, s.pos) AS calc_date,\n CASE WHEN s.pos = 0 THEN CAST(b.start_time AS BIGINT)\n ELSE unix_timestamp(cast(date_add(b.start_date, s.pos) as timestamp)) * 1000\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN CAST(b.end_time AS BIGINT)\n ELSE (unix_timestamp(cast(date_add(b.start_date, s.pos + 1) as timestamp)) * 1000) - 1\n END AS end_time,\n CAST(b.start_time AS BIGINT) AS span_start_time,\n CAST(b.end_time AS BIGINT) AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n CAST(ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN end_time END) -\n MIN(CASE WHEN span_name = 'runner.execute' THEN start_time END)) / 1000.0) AS INT) AS instance_run_time,\n CAST(ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN end_time END) -\n 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,\n CAST(ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN end_time END) -\n 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,\n 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,\n 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,\n from_unixtime(MIN(CASE WHEN span_name = 'runner.execute' THEN span_start_time END) / 1000) AS instance_start_time,\n from_unixtime(MAX(CASE WHEN span_name = 'runner.execute' THEN span_end_time END) / 1000) AS instance_end_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n)\nSELECT\n t1.calc_date AS p_date,\n t1.trace_id,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n t1.instance_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n t1.code_start_time,\n t1.code_end_time,\n t1.instance_start_time,\n t1.instance_end_time,\n t2.serving_id,\n CAST(t2.is_permanent AS BOOLEAN) AS is_permanent,\n CAST(t2.apply_for_gpu_count AS INT) AS apply_for_gpu_count\nFROM trace_time_metrics t1 LEFT JOIN (\n SELECT\n trace_id,\n MAX(serving_id) AS serving_id,\n MAX(is_permanent) AS is_permanent,\n SUM(CAST(replicas AS INT) * CAST(num_gpu AS INT)) AS apply_for_gpu_count\n FROM internal_platform_db.notebook_engine_info_query_engine_007\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\n;", "expected_csv": "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\n2025-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\n2025-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", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,18列 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key覆盖率\nD,D_time_calculation,time_calculation,30,\"instance_run_time, code_run_time 等时间指标\"\nD,D_cross_day_split,cross_day_split,15,跨天 trace 按天拆分正确性\nD,D_engine_join,engine_join,10,\"serving_id, is_permanent 等 engine 维度列匹配\"\nF,F_join_completeness,join_completeness,5,2张源表都被关联\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,dt=20260507\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,\"trace_id, p_date\"\n# 预期列数,\n# 输出表,internal_platform_db.dwd_notebook_killed_instance_detail_d_copilot_cand_query_engine_007", "path": "tasks/offline-compute/HiveSQL/hivesql_003"} {"task_id": "hivesql_004", "id": "offline-compute_HiveSQL_hivesql_004", "name": "将源表 internal_platform_db.app_group_product_info_sup", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:将应用组与产品归属关系按天做历史快照,按分区全量覆盖写入目标表。\n\n输入:internal_platform_db.app_group_product_info_query_engine_011\n- 字段: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\n\n处理规则:\n1. 无 Join,单表处理\n2. 无过滤条件,全量读取源表所有记录\n3. 无聚合操作\n4. 追加派生列 dt(STRING 类型),填充当天日期字符串(格式 YYYYMMDD,如 '20260507'),置于输出字段最前\n\n输出要求:\n- 输出字段顺序: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\n- 无需去重\n\n写入要求:\n- 目标表:internal_platform_db.app_group_product_info_history_cand_query_engine_011\n- 分区字段:dt(STRING)\n- 写入方式:INSERT OVERWRITE 按分区写入\n- 若目标表不存在,先按 Hive 标准建表(ORC 存储、按 dt 分区),再写入\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "insert overwrite TABLE internal_platform_db.app_group_product_info_history_query_engine_011 PARTITION (dt = '20260507')\nSELECT\nusername,\napplication_group,\napplication_group_owner,\nproduct_id,\nproduct_name,\nproduct_owner,\nobs_product_id,\nobs_product_name,\nobs_product_owner,\ndepartment,\nplan_product_id,\nplan_product_name,\nplan_product_owner,\napplication_group_numbers,\napplication_group_owners,\nproduct_owners,\nobs_product_owners,\nplan_product_owners,\nbg,\nid\nFROM internal_platform_db.app_group_product_info_query_engine_011;", "expected_csv": "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\nuser_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\nuser_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\nuser_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\nuser_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\nuser_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", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,21列(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,25,非key字段逐列值匹配率\nD,D_field_completeness,field_completeness,15,关键字段非空/非空串比例\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,dt 分区值 = 20260507\nF,F_dt_column,dt_column,10,dt 派生列存在于输出且值正确\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"product_id, obs_product_id, plan_product_id, id, dt\"\n# 预期列数,21\n# 输出表,internal_platform_db.app_group_product_info_history_cand_query_engine_011", "path": "tasks/offline-compute/HiveSQL/hivesql_004"} {"task_id": "hivesql_005", "id": "offline-compute_HiveSQL_hivesql_005", "name": "从 internal_platform_db.dws_mq_production_featur", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:汇总当天有生产量的 消息队列MQ topic 维度信息及近7/30/90天生产统计,落地为 topic 治理项明细表。\n\n输入:\n- 表:internal_platform_db.dws_mq_production_feature_d_increase_query_engine_013\n- 分区字段:dt(STRING,格式 YYYYMMDD)\n- 关键字段: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\n\n处理规则:\n1. 过滤条件:dt = '20260507' AND total_produce_pkg_last_90d > 0\n2. 无 Join,单表处理\n3. 派生字段:\n - mq_full_topic:若 tenant 和 namespaces 均非 NULL,则拼接为 'persistent://' + tenant + '/' + namespaces + '/' + topic;否则直接取 topic\n - app_group:取自 dw_appgroup\n - bid_incharge:取自 in_charge\n - bid_description:取自 description\n - bid_create_time:取自 create_time\n - bid_modify_time:取自 modify_time\n - hitted_gov_items:固定为 NULL\n - governance_benefit_estimate:固定为 NULL\n\n输出要求:\n- 输出字段顺序: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\n\n写入要求:\n- 目标表:internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013\n- 分区字段:dt(STRING,格式 YYYYMMDD)\n- 写入方式:INSERT OVERWRITE 按分区写入\n- 若目标表不存在,先按 Hive 标准建表(ORC存储、按 dt 分区),再写入\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.ads_mq_topic_governance_item_d_query_engine_013 PARTITION (dt = '20260507')\nSELECT\n business_id,\n business_name,\n topic,\n cluster_set,\n IF ( tenant IS NOT NULL AND namespaces IS NOT NULL, CONCAT( 'persistent://', tenant, '/', namespaces, '/', topic ), topic ) AS mq_full_topic,\n system_belong,\n dw_appgroup AS app_group,\n in_charge AS bid_incharge,\n description AS bid_description,\n create_time AS bid_create_time,\n modify_time AS bid_modify_time,\n cluster_id,\n cluster_type,\n cluster_name,\n bg,\n category_name,\n total_produce_pkg_d,\n production_days_last_7d,\n total_produce_pkg_last_7d,\n production_days_last_30d,\n total_produce_pkg_last_30d,\n production_days_last_90d,\n total_produce_pkg_last_90d,\n is_consumed,\n has_consumption_days_last_7d,\n has_consumption_days_last_30d,\n has_consumption_days_last_90d,\n NULL AS hitted_gov_items,\n NULL AS governance_benefit_estimate\nFROM internal_platform_db.dws_mq_production_feature_d_increase_query_engine_013\nWHERE dt = '20260507'\nAND total_produce_pkg_last_90d > 0", "expected_csv": "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\nbid_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\nbid_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", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,30列(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_mapping,field_mapping,25,字段别名映射正确性(app_group/bid_*等)\nD,D_derived_mq_full_topic,derived_mq_full_topic,15,mq_full_topic 派生列拼接逻辑正确性\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,dt 分区值 = 20260507\nF,F_filter_condition,filter_condition,10,WHERE dt='20260507' AND total_produce_pkg_last_90d>0\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"business_id, bid_incharge, bid_description, bid_create_time, bid_modify_time, cluster_id, dt\"\n# 预期列数,30\n# 输出表,internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013", "path": "tasks/offline-compute/HiveSQL/hivesql_005"} {"task_id": "hivesql_006_en", "id": "offline-compute_HiveSQL_hivesql_006", "name": "Input Table internal_platform_db.ods_t_databus_access_topic", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask 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.\n\nInput: `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`.\n\nProcessing 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'`.\n\nOutput 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.\n\nWrite 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.\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT overwrite TABLE internal_platform_db.dwd_databus_topic_cost_detail_d_query_engine_015 PARTITION (dt = '20260507')\nSELECT\n MAX(systemname) AS system_belong,\n MAX(dwproductname) AS category_name,\n MAX(dwappgroup) AS dw_appgroup,\n MAX(cityid) AS city_id,\n MAX(iset) AS cluster_set,\n topic,\n MAX(data_size) AS total_data_size_d,\n MAX(total_cost) AS total_cost,\n MAX(in_charge) AS in_charge\nFROM\n internal_platform_db.ods_t_databus_access_topic_cost_date_d_query_engine_015\nWHERE\n dt = '20260507'\n AND topic <> 'test'\nGROUP BY topic", "expected_csv": "system_belong,category_name,dw_appgroup,city_id,cluster_set,topic,total_data_size_d,total_cost,in_charge,dt\nSystemAlpha,数据仓库DWProdA,AppGroupX,101,ClusterA,topic_billing,2560000,162.0,user_zhang,20260507\nSystemBeta,数据仓库DWProdB,AppGroupY,202,ClusterB,topic_log,1200000,81.0,user_li,20260507\nSystemGamma,数据仓库DWProdC,AppGroupZ,303,ClusterC,topic_metrics,512000,50.0,user_wang,20260507", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,25,非key字段逐列值匹配率\nD,D_field_completeness,field_completeness,15,关键字段非空/非空串比例\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,dt 分区值 = 20260507\nF,F_source_filter,source_filter,10,源表分区过滤 dt=20260507 + topic<>'test'\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"city_id, dt\"\n# 预期列数,10\n# 输出表,internal_platform_db.dwd_databus_topic_cost_detail_d_cand_query_engine_015", "path": "tasks/offline-compute/HiveSQL/hivesql_006_en"} {"task_id": "hivesql_007_en", "id": "offline-compute_HiveSQL_hivesql_007", "name": "Aggregate Notebook instance runtime statistics by trace_id and p_date for the day: Input table w", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Aggregate Notebook instance runtime statistics grouped by `trace_id` and `p_date`.\n\nInput: `internal_platform_db.dws_notebook_instance_execute_minute_stat_d_query_engine_019`\n- Partition field: `dt` (STRING, format YYYYMMDD)\n- Key fields: `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` (numeric), `used_gpu_count` (numeric), `is_code_running` (INT), `code_used_gpu_count` (numeric)\n\nProcessing Rules:\n- Filter condition: `dt = '20260507'`\n- No joins, single-table processing\n- Aggregation: Group by `trace_id`, `p_date`\n - Most fields use `MAX`: `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`\n - `code_gpu_count`: Use `AVG`\n - `instance_gpu_util`: `AVG(used_gpu_count / code_gpu_count) * 100`\n - `code_gpu_util`: `AVG(IF(is_code_running = 1, code_used_gpu_count / code_gpu_count, NULL)) * 100`\n\nOutput Requirements:\n- Output field order: `dt` (STRING), `trace_id` (STRING), `p_date` (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), `code_gpu_count` (INT), `instance_gpu_util` (DOUBLE), `code_gpu_util` (DOUBLE)\n- Partition field: `dt` (STRING, format YYYYMMDD)\n\nWrite Requirements:\n- Target table: `internal_platform_db.dws_notebook_instance_execute_stat_d_cand_query_engine_019`\n- Write method: `INSERT OVERWRITE` partitioned by `dt`\n- If the target table does not exist, first create the table using standard Hive ORC storage, then write the data\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT overwrite TABLE internal_platform_db.dws_notebook_instance_execute_stat_d_query_engine_019 PARTITION (dt = '20260507')\nSELECT\n t1.trace_id,\n t1.p_date,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n t1.instance_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n t1.code_start_time,\n t1.code_end_time,\n t1.instance_start_time,\n t1.instance_end_time,\n t1.serving_id,\n t1.is_permanent,\n t1.apply_for_gpu_count,\n t1.code_gpu_count,\n t1.instance_gpu_util,\n t1.code_gpu_util\nFROM (\n SELECT\n trace_id,\n p_date,\n MAX(datawd_project_id) as datawd_project_id,\n MAX(datawd_task_id) as datawd_task_id,\n MAX(datawd_task_instance_id) as datawd_task_instance_id,\n MAX(compute_type) as compute_type,\n MAX(status_code) as status_code,\n MAX(instance_run_time) as instance_run_time,\n MAX(code_run_time) as code_run_time,\n MAX(resource_wait_time) as resource_wait_time,\n MAX(code_start_time) as code_start_time,\n MAX(code_end_time) as code_end_time,\n MAX(instance_start_time) as instance_start_time,\n MAX(instance_end_time) as instance_end_time,\n MAX(serving_id) as serving_id,\n MAX(is_permanent) as is_permanent,\n MAX(apply_for_gpu_count) as apply_for_gpu_count,\n AVG(code_gpu_count) as code_gpu_count,\n AVG(used_gpu_count / code_gpu_count) * 100 as instance_gpu_util,\n AVG(if(is_code_running = 1, code_used_gpu_count / code_gpu_count, null)) * 100 as code_gpu_util\n FROM internal_platform_db.dws_notebook_instance_execute_minute_stat_d_query_engine_019\n WHERE dt = '20260507'\n GROUP BY trace_id, p_date\n) t1\n;", "expected_csv": "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\ntrace_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\ntrace_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\ntrace_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", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,25,非key字段逐列值匹配率\nD,D_field_completeness,field_completeness,15,关键字段非空/非空串比例\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,dt 分区值 = 20260507\nF,F_source_filter,source_filter,10,源表分区过滤 dt=20260507\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"trace_id, datawd_project_id, datawd_task_id, datawd_task_instance_id, serving_id, dt\"\n# 预期列数,21\n# 输出表,internal_platform_db.dws_notebook_instance_execute_stat_d_cand_query_engine_019", "path": "tasks/offline-compute/HiveSQL/hivesql_007_en"} {"task_id": "hivesql_008_en", "id": "offline-compute_HiveSQL_hivesql_008", "name": "Count tasks matching the shuffle_split tuning rule. Input table: internal_platform_db", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Count tasks that match the `shuffle_split` tuning rule, producing task-level tuning rule hit results.\n\nInputs:\n- `internal_platform_db.nextgen_platform_dsl_spark_props_fht0_query_engine_021`\n- `internal_platform_db.ods_spark_props_extra_query_engine_021`\n- `internal_platform_db.deep_tuning_rule_hit_app_info_query_engine_021`\n- `internal_platform_db.nextgen_platform_dsl_us_task_detail_fdt0_query_engine_021`\n- `internal_platform_db.nextgen_platform_dsl_gputj_task_detail_fdt0_query_engine_021`\n- `internal_platform_db.app_group_product_info_history_query_engine_021`\n\nProcessing Rules: Join the Spark configuration table, task detail tables (from both the `us` and `gputj` sources), and the application group product mapping table. Based on `deep_tuning_rule_hit_app_info`, filter records that match the `shuffle_split` tuning rule, and aggregate at the task granularity to produce deduplicated results. The join conditions and aggregation logic must be consistent with the historical logic, without introducing additional filtering or business rules.\n\nOutput Requirements: The output field order must match the target table schema, retaining task-level fields related to tuning rule hits, deduplicated at the task granularity.\n\nWrite Requirements: Write to table `internal_platform_db.shuffle_split_tuning_rule_hit_task_info_cand_query_engine_021`.\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "insert overwrite table internal_platform_db.shuffle_split_tuning_rule_hit_task_info_query_engine_021 partition (databus_imp_date = '20260507')\nwith spark_props as\n(\n select\n t1.app_id\n ,max(spark_partition_min) spark_partition_min\n ,max(spark_partition_max) spark_partition_max\n ,max(round(ifnull(spark_task_shuffle_size,'')/(1024*1024))) spark_task_shuffle_size\n ,max(spark_shuffle_sort_bypassMergeThreshold) spark_shuffle_sort_bypassMergeThreshold\n ,max(spark_default_parallelism) spark_default_parallelism\n ,max(spark_sql_shuffle_partitions) spark_sql_shuffle_partitions\n ,max(mapreduce_input_fileinputformat_split_minsize) mapreduce_input_fileinputformat_split_minsize\n ,max(mapreduce_input_fileinputformat_split_maxsize) mapreduce_input_fileinputformat_split_maxsize\n ,max(mapreduce_input_fileinputformat_split_minsize_per_node) mapreduce_input_fileinputformat_split_minsize_per_node\n ,max(mapreduce_input_fileinputformat_split_minsize_per_rack) mapreduce_input_fileinputformat_split_minsize_per_rack\n from\n (\n select\n app_id\n ,max(spark_partition_max) spark_partition_max\n ,max(spark_task_shuffle_size) spark_task_shuffle_size\n ,max(spark_default_parallelism) spark_default_parallelism\n ,max(spark_sql_shuffle_partitions) spark_sql_shuffle_partitions\n from internal_platform_db.nextgen_platform_dsl_spark_props_fht0_query_engine_021\n where databus_imp_date >= '2026050700' and databus_imp_date <= '2026050723'\n group by app_id\n ) t1\n left join\n (\n select\n app_id\n ,max(spark_partition_min) spark_partition_min\n ,max(spark_shuffle_sort_bypassMergeThreshold) spark_shuffle_sort_bypassMergeThreshold\n ,max(mapreduce_input_fileinputformat_split_minsize) mapreduce_input_fileinputformat_split_minsize\n ,max(mapreduce_input_fileinputformat_split_maxsize) mapreduce_input_fileinputformat_split_maxsize\n ,max(mapreduce_input_fileinputformat_split_minsize_per_node) mapreduce_input_fileinputformat_split_minsize_per_node\n ,max(mapreduce_input_fileinputformat_split_minsize_per_rack) mapreduce_input_fileinputformat_split_minsize_per_rack\n from internal_platform_db.ods_spark_props_extra_query_engine_021\n where dt = '20260507'\n group by app_id\n ) t2\n on t1.app_id=t2.app_id\n group by t1.app_id\n),\napp_info as\n(\n select\n t1.*\n ,dw_appgroup\n ,case when (project_id is null or project_id = '') then 'us' else 'datawd' end tag\n from\n (\n select *\n from internal_platform_db.deep_tuning_rule_hit_app_info_query_engine_021\n where databus_imp_date = '20260507' and stage_type = 'shuffleInputStage'\n ) t1\n join\n (\n select\n task_id\n ,max(project_id) project_id\n ,max(dw_appgroup) dw_appgroup\n from internal_platform_db.nextgen_platform_dsl_us_task_detail_fdt0_query_engine_021\n where databus_imp_date = '20260507'\n group by task_id\n ) t2\n on t1.usp_task_id=t2.task_id\n\n union all\n\n select\n t1.*\n ,dw_appgroup\n ,'gputj' tag\n from\n (\n select *\n from internal_platform_db.deep_tuning_rule_hit_app_info_query_engine_021\n where databus_imp_date = '20260507' and stage_type = 'shuffleInputStage'\n ) t1\n join\n (\n select\n task_id\n ,max(app_group_id) dw_appgroup\n from internal_platform_db.nextgen_platform_dsl_gputj_task_detail_fdt0_query_engine_021\n where databus_imp_date >= '2026050700' and databus_imp_date <= '2026050723'\n group by task_id\n ) t2\n on t1.usp_task_id=t2.task_id\n),\ntask_info as\n(\n select\n usp_task_id\n ,t1.app_id app_id\n ,app_time_usage\n ,dw_appgroup\n ,tag\n ,product_name\n ,shuffle_split\n ,max_shuffle_stage_task_num\n ,shuffle_stage_time\n ,shuffle_stage_task_time_50th\n ,shuffle_stage_task_time_90th\n ,spark_partition_min\n ,spark_partition_max\n ,spark_task_shuffle_size\n ,spark_default_parallelism\n ,spark_sql_shuffle_partitions\n ,spark_shuffle_sort_bypassMergeThreshold\n ,spark_version\n ,start_time\n ,end_time\n ,row_number() over (partition by usp_task_id order by app_time_usage desc) as rk\n from\n (\n select\n usp_task_id\n ,a.app_id app_id\n ,dw_appgroup\n ,tag\n ,app_time_usage\n ,spark_version\n ,case when\n ( (spark_version <>'2.1.0' and (spark_default_parallelism is not null and spark_default_parallelism <>'') and cast(task_num as int)>=cast(spark_default_parallelism as int))\n or\n (spark_version<>'2.1.0'and (spark_sql_shuffle_partitions is not null and spark_sql_shuffle_partitions <>'') and cast(task_num as int)>=cast(spark_sql_shuffle_partitions as int))\n or\n (spark_version='2.1.0' and (spark_partition_max is not null and spark_partition_max <>'') and cast(task_num as int)>=cast(spark_partition_max as int))\n or\n (spark_version='2.1.0' and (spark_partition_max ='' or spark_partition_max is null))\n or\n (spark_version<>'2.1.0' and (spark_default_parallelism ='' or spark_default_parallelism is null) and (spark_sql_shuffle_partitions ='' or spark_sql_shuffle_partitions is null))\n ) then '1' else '0' end as shuffle_split\n ,task_num max_shuffle_stage_task_num\n ,stage_time shuffle_stage_time\n ,task_time_50th shuffle_stage_task_time_50th\n ,task_time_90th shuffle_stage_task_time_90th\n ,spark_partition_min\n ,spark_partition_max\n ,spark_task_shuffle_size\n ,spark_default_parallelism\n ,spark_sql_shuffle_partitions\n ,spark_shuffle_sort_bypassMergeThreshold\n ,start_time\n ,end_time\n from app_info a\n left join spark_props b\n on a.app_id = b.app_id\n ) t1\n left join\n (\n select\n application_group\n ,max(product_name) product_name\n from internal_platform_db.app_group_product_info_history_query_engine_021\n where dt = '20260507'\n group by\n application_group\n ) t2\n on t1.dw_appgroup = t2.application_group\n where shuffle_split = '1'\n)\n\nselect\n usp_task_id\n ,app_id\n ,app_time_usage\n ,tag\n ,dw_appgroup\n ,product_name\n ,shuffle_split\n ,max_shuffle_stage_task_num\n ,shuffle_stage_time\n ,shuffle_stage_task_time_50th\n ,shuffle_stage_task_time_90th\n ,spark_partition_min\n ,spark_partition_max\n ,spark_task_shuffle_size\n ,spark_default_parallelism\n ,spark_sql_shuffle_partitions\n ,spark_shuffle_sort_bypassMergeThreshold\n ,spark_version\n ,concat('https://internal-tools.example.com/optimization/appgroupfigure/config/recommended?taskId=',usp_task_id,'&applicationId=',app_id,'&startTime=',start_time,'&endTime=',end_time,'&applicationGroup=',dw_appgroup) brain_url\nfrom task_info\nwhere rk = 1", "expected_csv": "usp_task_id,app_id,app_time_usage,tag,dw_appgroup,product_name,shuffle_split,max_shuffle_stage_task_num,shuffle_stage_time,shuffle_stage_task_time_50th,shuffle_stage_task_time_90th,spark_partition_min,spark_partition_max,spark_task_shuffle_size,spark_default_parallelism,spark_sql_shuffle_partitions,spark_shuffle_sort_bypassmergethreshold,spark_version,brain_url,databus_imp_date\ntask_001,app_001,3600,datawd,appgroup_A,ProductAlpha,1,250,120,5,10,100,200,0.0,,,300,3.2.1,https://internal-tools.example.com/optimization/appgroupfigure/config/recommended?taskId=task_001&applicationId=app_001&startTime=1714000000&endTime=1714003600&applicationGroup=appgroup_A,20260507\ntask_003,app_003,1800,us,appgroup_C,ProductGamma,1,100,60,3,6,,,0.0,,,,3.2.1,https://internal-tools.example.com/optimization/appgroupfigure/config/recommended?taskId=task_003&applicationId=app_003&startTime=1714000200&endTime=1714002000&applicationGroup=appgroup_C,20260507\ntask_004,app_001,5000,datawd,appgroup_A,ProductAlpha,1,500,200,7,12,100,200,0.0,,,300,3.2.1,https://internal-tools.example.com/optimization/appgroupfigure/config/recommended?taskId=task_004&applicationId=app_001&startTime=1714010000&endTime=1714015000&applicationGroup=appgroup_A,20260507", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,20列 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key覆盖率\nD,D_shuffle_logic,shuffle_logic,20,shuffle_split 条件逻辑(CASE WHEN 版本判断)\nD,D_deduplication,deduplication,15,ROW_NUMBER 按 usp_task_id 去重\nD,D_numeric_values,numeric_values,10,时间/阈值等业务指标逐行匹配\nD,D_url_concat,url_concat,10,brain_url 字段拼接正确性\nF,F_union_completeness,union_completeness,5,us/datawd + gputj 两个 UNION 分支\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,分区值正确\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,EXPERT\n# 权重,\"product=0.8, process=0.2\"\n# 范式,new\n# Key列,usp_task_id\n# 预期列数,\n# 输出表,internal_platform_db.shuffle_split_tuning_rule_hit_task_info_cand_query_engine_021", "path": "tasks/offline-compute/HiveSQL/hivesql_008_en"} {"task_id": "hivesql_009_en", "id": "offline-compute_HiveSQL_hivesql_009", "name": "Compute GPU card-hours for task instances within 5-minute windows, joining Pod mapping and task instance configuration, outputting hourly instanc", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Compute GPU card-hours for task instances within 5-minute windows, outputting hourly instance-level GPU usage statistics.\n\nInputs:\n- `internal_platform_db.gputj_gpu_info_parsed_query_engine_022`\n- `internal_platform_db.dwd_ml_platform_instance_podname_query_engine_022`\n- `internal_platform_db.dwd_task_management_taskinstance2_query_engine_022`\n- `internal_platform_db.task_management_taskinstance2_query_engine_022`\n\nProcessing Rules: Join the Pod mapping table with the task instance configuration table, aggregate GPU card-hours by 5-minute windows, and roll up to hourly-level statistics. The specific join keys and aggregation logic must be determined based on the table structures.\n\nOutput Requirements: Output the task instance GPU usage statistics, including fields such as instance identifier, time window, and GPU card-hours. The specific field list must be determined based on the output table structure.\n\nWrite Requirements: Write the results to `internal_platform_db.task_instance_gpu_time_stats_cand_query_engine_022`.\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.task_instance_gpu_time_stats_query_engine_022\nPARTITION (dt='2026050700')\nWITH\n-- Step 1: 从GPU监控数据中提取pod运行记录,按分钟去重\npod_run_minutes AS (\n SELECT\n pod_name,\n gpu_name,\n FLOOR(CAST(pkg_time AS BIGINT) / 60) * 60 AS minute_timestamp,\n FLOOR(CAST(pkg_time AS BIGINT) / 300) * 300 AS time_5min\n FROM internal_platform_db.gputj_gpu_info_parsed_query_engine_022\n WHERE dt = '2026050700'\n AND metric IN ('k8s_container_vgpu_gpu_mem_usage', 'k8s_dcgm_fi_dev_fb_util')\n GROUP BY pod_name, gpu_name, FLOOR(CAST(pkg_time AS BIGINT) / 60) * 60, FLOOR(CAST(pkg_time AS BIGINT) / 300) * 300\n),\n\n-- Step 2: 统计每个pod在每个5分钟窗口内的运行分钟数\npod_run_time AS (\n SELECT\n pod_name,\n MAX(gpu_name) AS gpu_name,\n time_5min,\n CAST(COUNT(DISTINCT minute_timestamp) AS DOUBLE) AS run_time_m\n FROM pod_run_minutes\n GROUP BY pod_name, time_5min\n),\n\n-- Step 3: 关联pod与instance的映射关系\ninstance_run_time AS (\n SELECT\n p.time_5min,\n m.instance_uuid,\n MAX(p.gpu_name) AS gpu_name,\n CAST(SUM(p.run_time_m) AS DOUBLE) AS sum_run_time_m,\n COUNT(DISTINCT m.pod_name) AS pod_count\n FROM pod_run_time p\n INNER JOIN internal_platform_db.dwd_ml_platform_instance_podname_query_engine_022 m\n ON p.pod_name = m.pod_name\n AND m.dt = '2026050700'\n GROUP BY p.time_5min, m.instance_uuid\n),\n\n-- Step 4: 获取任务实例的GPU配置\nlatest_task_config AS (\n SELECT\n instance_uuid,\n CAST(host_gpu_num AS DOUBLE) AS host_gpu_num,\n CAST(host_num AS DOUBLE) AS host_num\n FROM (\n SELECT\n instance_uuid,\n host_gpu_num,\n host_num,\n last_modify,\n ROW_NUMBER() OVER (PARTITION BY instance_uuid ORDER BY last_modify DESC) AS rn\n FROM (\n SELECT\n instance_uuid,\n host_gpu_num,\n host_num,\n last_modify\n FROM internal_platform_db.dwd_task_management_taskinstance2_query_engine_022\n WHERE databus_imp_date = (\n SELECT MAX(databus_imp_date)\n FROM internal_platform_db.dwd_task_management_taskinstance2_query_engine_022\n )\n\n UNION ALL\n\n SELECT\n instance_uuid,\n host_gpu_num,\n host_num,\n last_modify\n FROM internal_platform_db.task_management_taskinstance2_query_engine_022\n WHERE databus_imp_date = (\n SELECT MAX(databus_imp_date)\n FROM internal_platform_db.task_management_taskinstance2_query_engine_022\n )\n ) combined\n ) ranked\n WHERE rn = 1\n)\n\n-- Step 5: 关联GPU配置并计算卡时\nSELECT\n i.instance_uuid,\n i.time_5min,\n t.host_gpu_num,\n i.sum_run_time_m,\n CASE\n WHEN t.host_gpu_num IS NOT NULL AND i.sum_run_time_m IS NOT NULL\n THEN t.host_gpu_num * i.sum_run_time_m / 60.0\n ELSE NULL\n END AS gpu_hour,\n i.gpu_name,\n i.pod_count,\n t.host_num\nFROM instance_run_time i\nLEFT JOIN latest_task_config t\n ON i.instance_uuid = t.instance_uuid", "expected_csv": "instance_uuid,time_5min,host_gpu_num,sum_run_time_m,gpu_hour,gpu_name,pod_count,host_num\ninst-uuid-aaa,1767225600,8.0,7.0,0.9333333333333333,A100,2,2.0\ninst-uuid-ccc,1767225600,2.0,1.0,0.03333333333333333,A100,1,1.0\ninst-uuid-bbb,1767225900,4.0,2.0,0.13333333333333333,V100,1,1.0\ninst-uuid-ddd,1767225900,8.0,1.0,0.13333333333333333,H100,1,4.0\ninst-uuid-ccc,1767226200,2.0,1.0,0.03333333333333333,A100,1,1.0", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,8列 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key覆盖率\nD,D_gpu_hour_calculation,gpu_hour_calculation,30,gpu_hour 核心指标计算正确性\nD,D_window_aggregation,window_aggregation,15,\"sum_run_time_m, pod_count 等窗口聚合指标\"\nD,D_gpu_config_lookup,gpu_config_lookup,10,\"host_gpu_num, host_num 等 GPU 配置列匹配\"\nF,F_join_completeness,join_completeness,5,4张源表都被关联\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,dt=2026050700\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,\"instance_uuid, time_5min\"\n# 预期列数,\n# 输出表,internal_platform_db.task_instance_gpu_time_stats_cand_query_engine_022", "path": "tasks/offline-compute/HiveSQL/hivesql_009_en"} {"task_id": "hivesql_010", "id": "offline-compute_HiveSQL_hivesql_010", "name": "从输入表中筛选状态为 killed 的 Notebook runner trace 数据,按天拆分后", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n1) 任务目标\n产出 killed 状态的 Notebook 实例 Pod 运行明细宽表。\n\n2) 输入\n- internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_024\n- internal_platform_db.notebook_span_info_query_engine_024\n- internal_platform_db.dwd_gputj_service_instance_map_query_engine_024\n- internal_platform_db.dwd_ml_platform_instance_podname_query_engine_024\n- internal_platform_db.notebook_engine_info_query_engine_024\n\n3) 处理规则\n- 过滤条件:筛选 Notebook runner trace 中状态为 killed 的记录\n- 时间处理:对 runner trace 数据按天拆分\n- 关联顺序:runner trace → 服务实例 → Pod → GPU 聚合 → engine 信息\n- 关联方式:按各表对应键字段进行左连接\n\n4) 输出要求\n- 输出表:internal_platform_db.dwd_notebook_killed_instance_pod_detail_d_cand_query_engine_024\n- 包含 runner trace、服务实例、Pod、GPU、engine 等关联后的明细字段\n- 去重规则:按主键去重(若存在)\n\n5) 写入要求\n- 写入模式:INSERT OVERWRITE\n- 分区字段:按天分区(如有)\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.dwd_notebook_killed_instance_pod_detail_d_query_engine_024 PARTITION (dt = '20260507')\nWITH base_trace AS (\n SELECT trace_id\n FROM internal_platform_db.notebook_span_info_query_engine_024\n WHERE databus_imp_date >= '2026050700'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n AND span_name IN ('runner.execute', 'runner.killed')\n GROUP BY trace_id\n HAVING\n COUNT(CASE WHEN span_name = 'runner.killed' THEN 1 END) > 0\n AND\n COUNT(CASE WHEN span_name = 'runner.execute' THEN 1 END) = 0\n),\ncombined_spans AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM internal_platform_db.notebook_span_info_query_engine_024\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('runner.killed', 'runner.start', 'execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute')\n\n UNION ALL\n\n SELECT\n trace_id,\n 'runner.execute' AS span_name,\n MAX(CASE WHEN span_name = 'runner.start' THEN start_time END) AS start_time,\n MAX(CASE WHEN span_name = 'runner.killed' THEN end_time END) AS end_time,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_project_id END) AS datawd_project_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_id END) AS datawd_task_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_instance_id END) AS datawd_task_instance_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN compute_type END) AS compute_type,\n 2 AS status_code\n FROM internal_platform_db.notebook_span_info_query_engine_024\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('runner.start', 'runner.killed')\n GROUP BY trace_id\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'runner.killed'\n THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM combined_spans\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) as start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) as end_date,\n datediff(from_unixtime(CAST(end_time AS BIGINT) / 1000), from_unixtime(CAST(start_time AS BIGINT) / 1000)) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n date_add(b.start_date, s.pos) AS calc_date,\n CASE WHEN s.pos = 0 THEN b.start_time\n ELSE CAST(unix_timestamp(CAST(date_add(b.start_date, s.pos) AS TIMESTAMP)) * 1000 AS STRING)\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN b.end_time\n ELSE CAST((unix_timestamp(CAST(date_add(b.start_date, s.pos + 1) AS TIMESTAMP)) * 1000) - 1 AS STRING)\n END AS end_time,\n b.start_time AS span_start_time,\n b.end_time AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name = 'runner.execute' THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS instance_run_time,\n ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS code_run_time,\n ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS resource_wait_time,\n from_unixtime(MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(start_time AS BIGINT) END) / 1000) AS code_start_time,\n from_unixtime(MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(end_time AS BIGINT) END) / 1000) AS code_end_time,\n from_unixtime(MIN(CASE WHEN span_name = 'runner.execute' THEN CAST(span_start_time AS BIGINT) END) / 1000) AS instance_start_time,\n from_unixtime(MAX(CASE WHEN span_name = 'runner.execute' THEN CAST(span_end_time AS BIGINT) END) / 1000) AS instance_end_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n),\ngputj_dim AS (\n SELECT\n t1.service_id,\n t2.pod_name\n FROM internal_platform_db.dwd_gputj_service_instance_map_query_engine_024 t1\n INNER JOIN internal_platform_db.dwd_ml_platform_instance_podname_query_engine_024 t2\n ON t1.instance_uuid = t2.instance_uuid\n AND t1.dt=if('2026050700'>='2025080900', '2026050700', '2025080900')\n AND t2.dt=if('2026050700'>='2025060519', '2026050700', '2025060519')\n GROUP BY t1.service_id, t2.pod_name\n),\ngpu_metrics AS (\n SELECT\n pkg_agg_time,\n pod_name,\n k8s_container_vgpu_gpu_util_sum / k8s_container_vgpu_gpu_util_count AS gpu_util,\n k8s_container_resource_request_gpu_sum / k8s_container_resource_request_gpu_count AS gpu_count\n FROM internal_platform_db.gputj_gpu_info_parsed_agg_1min_query_engine_024\n WHERE dt >= '2026050400'\n AND dt <= '2026050700'\n AND ( k8s_container_vgpu_gpu_util_count > 0 OR k8s_container_resource_request_gpu_count > 0 )\n AND pod_name IS NOT NULL\n)\nSELECT\n t1.trace_id,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n CAST(t1.instance_run_time AS INT),\n CAST(t1.code_run_time AS INT),\n CAST(t1.resource_wait_time AS INT),\n t1.code_start_time,\n t1.code_end_time,\n t1.instance_start_time,\n t1.instance_end_time,\n t2.serving_id,\n CAST(t2.is_permanent AS BOOLEAN),\n CAST(t2.apply_for_gpu_count AS INT),\n t3.pod_name,\n t4.pkg_agg_time,\n t4.gpu_util,\n CAST(t4.gpu_count AS INT),\n CAST(t1.calc_date AS STRING) AS p_date\nFROM trace_time_metrics t1 LEFT JOIN (\n SELECT\n trace_id,\n MAX(serving_id) AS serving_id,\n MAX(is_permanent) AS is_permanent,\n SUM(CAST(replicas AS DOUBLE) * CAST(num_gpu AS DOUBLE)) AS apply_for_gpu_count\n FROM internal_platform_db.notebook_engine_info_query_engine_024\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\nLEFT JOIN gputj_dim t3 ON t2.serving_id = CAST(t3.service_id AS STRING)\nLEFT JOIN gpu_metrics t4\n ON t3.pod_name = t4.pod_name\n AND (\n CASE\n WHEN t1.instance_start_time IS NOT NULL AND t1.instance_end_time IS NOT NULL\n THEN t4.pkg_agg_time >= t1.instance_start_time AND t4.pkg_agg_time <= t1.instance_end_time\n WHEN t1.code_start_time IS NOT NULL AND t1.code_end_time IS NOT NULL\n THEN t4.pkg_agg_time >= t1.code_start_time AND t4.pkg_agg_time <= t1.code_end_time\n ELSE FALSE\n END\n )\n;", "expected_csv": "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\ntrace001,proj1,task1,inst1,ray,2,10,,2,,,2025-05-06 23:59:50,2025-05-07 00:00:05,1001,True,2,pod-abc-001,,,,2025-05-06,20260507\ntrace001,proj1,task1,inst1,ray,2,5,5,,2025-05-07 00:00:00,2025-05-07 00:00:05,2025-05-06 23:59:50,2025-05-07 00:00:05,1001,True,2,pod-abc-001,,,,2025-05-07,20260507\ntrace002,proj2,task2,inst2,ray,2,13,3,2,2025-05-07 00:01:40,2025-05-07 00:01:43,2025-05-07 00:01:30,2025-05-07 00:01:43,1002,False,8,pod-xyz-002,,,,2025-05-07,20260507", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,22列 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key覆盖率\nD,D_time_calculation,time_calculation,25,\"instance_run_time, code_run_time 等时间指标\"\nD,D_cross_day_split,cross_day_split,15,跨天 trace 按天拆分正确性\nD,D_gpu_join,gpu_join,15,\"serving_id, gpu_util 等 JOIN 维度列匹配\"\nF,F_join_completeness,join_completeness,5,5张源表都被关联\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,分区值正确\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,EXPERT\n# 权重,\"product=0.8, process=0.2\"\n# 范式,new\n# Key列,\"trace_id, p_date\"\n# 预期列数,\n# 输出表,internal_platform_db.dwd_notebook_killed_instance_pod_detail_d_cand_query_engine_024", "path": "tasks/offline-compute/HiveSQL/hivesql_010"} {"task_id": "hivesql_011", "id": "offline-compute_HiveSQL_hivesql_011", "name": "从 notebook_span_info_query_engine_026 和 notebook_engin", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:从 Notebook span 信息和 engine 信息关联产出 killed 实例运行明细表。\n\n输入:\n- internal_platform_db.notebook_span_info_query_engine_026\n- internal_platform_db.notebook_engine_info_query_engine_026\n\n处理规则:\n- 两表关联查询,关联条件需基于表结构确定\n- 具体过滤条件和字段选择需基于表结构确定\n\n输出要求:\n- 输出表:internal_platform_db.dwd_notebook_killed_instance_detail_d_cand_query_engine_026\n- 输出字段需基于目标表结构确定\n\n写入要求:\n- 写入目标表\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT overwrite TABLE internal_platform_db.dwd_notebook_killed_instance_detail_d_query_engine_026 PARTITION (dt = '20260507')\nWITH base_trace AS (\n SELECT trace_id\n FROM internal_platform_db.notebook_span_info_query_engine_026\n WHERE databus_imp_date >= '2026050700'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n AND span_name IN ('runner.execute', 'runner.killed')\n GROUP BY trace_id\n HAVING\n COUNT(CASE WHEN span_name = 'runner.killed' THEN 1 END) > 0\n AND\n COUNT(CASE WHEN span_name = 'runner.execute' THEN 1 END) = 0\n),\ncombined_spans AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM internal_platform_db.notebook_span_info_query_engine_026\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('runner.killed', 'runner.start', 'execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute')\n\n UNION ALL\n\n SELECT\n trace_id,\n 'runner.execute' AS span_name,\n MAX(CASE WHEN span_name = 'runner.start' THEN start_time END) AS start_time,\n MAX(CASE WHEN span_name = 'runner.killed' THEN end_time END) AS end_time,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_project_id END) AS datawd_project_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_id END) AS datawd_task_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN datawd_task_instance_id END) AS datawd_task_instance_id,\n MAX(CASE WHEN span_name = 'runner.killed' THEN compute_type END) AS compute_type,\n 2 AS status_code\n FROM internal_platform_db.notebook_span_info_query_engine_026\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('runner.start', 'runner.killed')\n GROUP BY trace_id\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'runner.killed'\n THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM combined_spans\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) as start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) as end_date,\n datediff(from_unixtime(CAST(end_time AS BIGINT) / 1000), from_unixtime(CAST(start_time AS BIGINT) / 1000)) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n date_add(b.start_date, s.pos) AS calc_date,\n CASE WHEN s.pos = 0 THEN b.start_time\n ELSE CAST(unix_timestamp(cast(date_add(b.start_date, s.pos) as timestamp)) * 1000 AS STRING)\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN b.end_time\n ELSE CAST((unix_timestamp(cast(date_add(b.start_date, s.pos + 1) as timestamp)) * 1000) - 1 AS STRING)\n END AS end_time,\n b.start_time AS span_start_time,\n b.end_time AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name = 'runner.execute' THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS instance_run_time,\n ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS code_run_time,\n ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS resource_wait_time,\n from_unixtime(MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(start_time AS BIGINT) END) / 1000) AS code_start_time,\n from_unixtime(MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(end_time AS BIGINT) END) / 1000) AS code_end_time,\n from_unixtime(MIN(CASE WHEN span_name = 'runner.execute' THEN CAST(span_start_time AS BIGINT) END) / 1000) AS instance_start_time,\n from_unixtime(MAX(CASE WHEN span_name = 'runner.execute' THEN CAST(span_end_time AS BIGINT) END) / 1000) AS instance_end_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n)\nSELECT\n t1.calc_date AS p_date,\n t1.trace_id,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n CAST(t1.instance_run_time AS INT) AS instance_run_time,\n CAST(t1.code_run_time AS INT) AS code_run_time,\n CAST(t1.resource_wait_time AS INT) AS resource_wait_time,\n t1.code_start_time,\n t1.code_end_time,\n t1.instance_start_time,\n t1.instance_end_time,\n t2.serving_id,\n CAST(t2.is_permanent AS BOOLEAN) AS is_permanent,\n CAST(t2.apply_for_gpu_count AS INT) AS apply_for_gpu_count\nFROM trace_time_metrics t1 LEFT JOIN (\n SELECT\n trace_id,\n MAX(serving_id) AS serving_id,\n MAX(is_permanent) AS is_permanent,\n SUM(CAST(replicas AS INT) * CAST(num_gpu AS INT)) AS apply_for_gpu_count\n FROM internal_platform_db.notebook_engine_info_query_engine_026\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\n;", "expected_csv": "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\n2025-05-07,T001,P100,TASK001,INST001,ray,2,105,55,50,2025-05-07 09:59:10,2025-05-07 10:00:05,2025-05-07 09:58:20,2025-05-07 10:00:05,SRV001,True,2,20260507", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,18列 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key覆盖率\nD,D_time_calculation,time_calculation,30,\"instance_run_time, code_run_time 等时间指标\"\nD,D_cross_day_split,cross_day_split,15,跨天 trace 按天拆分正确性\nD,D_engine_join,engine_join,10,\"serving_id, is_permanent 等 engine 维度列匹配\"\nF,F_join_completeness,join_completeness,5,2张源表都被关联\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,dt=20260507\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,\"trace_id, p_date\"\n# 预期列数,\n# 输出表,internal_platform_db.dwd_notebook_killed_instance_detail_d_cand_query_engine_026", "path": "tasks/offline-compute/HiveSQL/hivesql_011"} {"task_id": "hivesql_012_en", "id": "offline-compute_HiveSQL_hivesql_012", "name": "From input table internal_platform_db.t_ed_socialbook_qq_high_v2_ta", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective\nFilter out specified `tag_id` values from the tag incremental table and write the results to the target table.\n\nInput\n- `internal_platform_db.t_ed_socialbook_qq_high_v2_tag_guid_incr_query_engine_100`\n\nProcessing Rules\n1. Filter condition: `ds = 20260608` AND `tag_id NOT IN (10212021124, 10606061135, 10606061136, 10808011103)`\n2. No joins, single-table processing\n3. Field order: `guid`, `tag_id`, `tag_value`, `redis_sub_key`, `val_type`, `splitter1`, `splitter2`, `limit_size`, `tag_status`\n\nOutput Requirements\n- Output table: `internal_platform_db.t_ed_socialbook_qq_high_v2_tag_guid_incr_filter_cand_query_engine_100`\n- Output fields (9 in total, fixed order): `guid`, `tag_id`, `tag_value`, `redis_sub_key`, `val_type`, `splitter1`, `splitter2`, `limit_size`, `tag_status`\n- Partition column: `ds` (BIGINT type)\n\nWrite Requirements\n- Write strategy: `INSERT OVERWRITE`\n- Partition value: `ds=20260608`\n- Write format: ORC\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "insert overwrite table internal_platform_db.t_ed_socialbook_qq_high_v2_tag_guid_incr_filter_query_engine_100 partition(ds=20260608)\nselect \n guid,\n tag_id, \n tag_value,\n redis_sub_key, \n val_type, \n splitter1,\n splitter2, \n limit_size, \n tag_status\n from internal_platform_db.t_ed_socialbook_qq_high_v2_tag_guid_incr_query_engine_100\n where ds = 20260608 and tag_id not in (10212021124, 10606061135, 10606061136, 10808011103)", "expected_csv": "guid,tag_id,tag_value,redis_sub_key,val_type,splitter1,splitter2,limit_size,tag_status,ds\nguid001,10212021100,val1,sub1,type1,:,\",\",10,1,20260608\nguid005,10212021199,val5,sub5,type1,:,\",\",8,3,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,25,非key字段逐列值匹配率\nD,D_field_completeness,field_completeness,15,关键字段非空/非空串比例\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,ds 分区值 = 20260608\nF,F_source_filter,source_filter,10,源表分区过滤 ds=20260608 + tag_id NOT IN\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"guid, tag_id\"\n# 预期列数,10\n# 输出表,internal_platform_db.t_ed_socialbook_qq_high_v2_tag_guid_incr_filter_cand_query_engine_100", "path": "tasks/offline-compute/HiveSQL/hivesql_012_en"} {"task_id": "hivesql_013", "id": "offline-compute_HiveSQL_hivesql_013", "name": "从 internal_platform_db.dws_ug_app_ad_material_actio", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:统计广告素材在各维度下的行为指标汇总,并生成一条更新日期记录。\n\n输入:\n- internal_platform_db.dws_ug_app_ad_material_action_di_query_engine_101\n\n处理规则:\n- 无 Join,单表处理\n- 过滤条件:imp_date = 20260608\n- 维度字段转换(使用 CASE WHEN):\n - material_type: 1→'图片', 2→'视频'\n - source: 2→'人工素材', 3→'人机素材', 6→'AI素材'\n - video_model_type: 1→'镜头拆分模型(老模型)', 2→'剧情理解模型(新模型)'\n - create_type: 0→'无视频剪辑方式', 1→'高光剪辑', 2→'原始剪辑', 3→'拼合剪辑', 4→'二创剪辑', 5→'定点剪辑', 6→'拆条前贴', 7→'拆条剪辑', ELSE→'未知代码'+create_type\n - purpose: 1→'拉新', 2→'拉活', 3→'唤醒', 4→'收入', 5→'电商', 6→'当日拉活'\n - provider: 1→'AI侧', 2→'内部平台D侧'\n- 分组维度:上述转换后的维度字段 + channel_name\n- 聚合指标(均为 SUM):product_flag→production_cnt, audit_flag→audit_cnt, pass_flag→pass_cnt, push_madia_flag→push_cnt, imp_madia_gdt_flag→imp_cnt, click_madia_gdt_flag→clck_cnt, imp_madia_cnt→imp, click_madia_cnt→clck\n- 结果由两部分 UNION ALL 构成:第一部分为分组聚合结果,第二部分为一条 update_date=20260608 且其余字段均为 NULL 的记录\n\n输出要求:\n- 输出字段顺序:update_date, material_type_name, source_name, video_model_type_name, create_type_name, purpose_name, provider_name, production_cnt, audit_cnt, pass_cnt, push_cnt, imp_cnt, clck_cnt, imp, clck, channel_name, imp_date\n- 不去重\n\n写入要求:\n- 目标表:internal_platform_db.ads_ug_app_ad_material_action_di_cand_query_engine_101\n- 写入方式:INSERT OVERWRITE\n- 分区:imp_date=20260608\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.ads_ug_app_ad_material_action_di_query_engine_101 PARTITION (imp_date=20260608)\n SELECT\n 20260608 AS update_date\n , CASE\n WHEN material_type = 1 THEN '图片'\n WHEN material_type = 2 THEN '视频'\n END AS material_type_name\n , CASE\n WHEN `source` = 2 THEN '人工素材'\n WHEN `source` = 3 THEN '人机素材'\n WHEN `source` = 6 THEN 'AI素材'\n END AS source_name\n , CASE\n WHEN video_model_type = 1 THEN '镜头拆分模型(老模型)'\n WHEN video_model_type = 2 THEN '剧情理解模型(新模型)'\n END AS video_model_type_name\n , CASE\n WHEN create_type = 0 THEN '无视频剪辑方式'\n WHEN create_type = 1 THEN '高光剪辑'\n WHEN create_type = 2 THEN '原始剪辑'\n WHEN create_type = 3 THEN '拼合剪辑'\n WHEN create_type = 4 THEN '二创剪辑'\n WHEN create_type = 5 THEN '定点剪辑'\n WHEN create_type = 6 THEN '拆条前贴'\n WHEN create_type = 7 THEN '拆条剪辑'\n ELSE CONCAT('未知代码', create_type)\n END AS create_type_name\n , CASE\n WHEN purpose = 1 THEN '拉新'\n WHEN purpose = 2 THEN '拉活'\n WHEN purpose = 3 THEN '唤醒'\n WHEN purpose = 4 THEN '收入'\n WHEN purpose = 5 THEN '电商'\n WHEN purpose = 6 THEN '当日拉活'\n END AS purpose_name\n , CASE\n WHEN `provider` = 1 THEN 'AI侧'\n WHEN `provider` = 2 THEN '内部平台D侧'\n END AS provider_name\n , SUM(product_flag) AS production_cnt\n , SUM(audit_flag) AS audit_cnt\n , SUM(pass_flag) AS pass_cnt\n , SUM(push_madia_flag) AS push_cnt\n , SUM(imp_madia_gdt_flag) AS imp_cnt\n , SUM(click_madia_gdt_flag) AS clck_cnt\n , SUM(imp_madia_cnt) AS imp\n , SUM(click_madia_cnt) AS clck\n , channel_name\n FROM internal_platform_db.dws_ug_app_ad_material_action_di_query_engine_101\n WHERE imp_date = 20260608\n GROUP BY\n CASE\n WHEN material_type = 1 THEN '图片'\n WHEN material_type = 2 THEN '视频'\n END\n , CASE\n WHEN `source` = 2 THEN '人工素材'\n WHEN `source` = 3 THEN '人机素材'\n WHEN `source` = 6 THEN 'AI素材'\n END\n , CASE\n WHEN video_model_type = 1 THEN '镜头拆分模型(老模型)'\n WHEN video_model_type = 2 THEN '剧情理解模型(新模型)'\n END\n , CASE\n WHEN create_type = 0 THEN '无视频剪辑方式'\n WHEN create_type = 1 THEN '高光剪辑'\n WHEN create_type = 2 THEN '原始剪辑'\n WHEN create_type = 3 THEN '拼合剪辑'\n WHEN create_type = 4 THEN '二创剪辑'\n WHEN create_type = 5 THEN '定点剪辑'\n WHEN create_type = 6 THEN '拆条前贴'\n WHEN create_type = 7 THEN '拆条剪辑'\n ELSE CONCAT('未知代码', create_type)\n END\n , CASE\n WHEN purpose = 1 THEN '拉新'\n WHEN purpose = 2 THEN '拉活'\n WHEN purpose = 3 THEN '唤醒'\n WHEN purpose = 4 THEN '收入'\n WHEN purpose = 5 THEN '电商'\n WHEN purpose = 6 THEN '当日拉活'\n END\n , CASE\n WHEN `provider` = 1 THEN 'AI侧'\n WHEN `provider` = 2 THEN '内部平台D侧'\n END\n , channel_name\n\n UNION ALL\n SELECT\n 20260608 AS update_date\n , NULL AS material_type_name\n , NULL AS source_name\n , NULL AS video_model_type_name\n , NULL AS create_type_name\n , NULL AS purpose_name\n , NULL AS provider_name\n , NULL AS production_cnt\n , NULL AS audit_cnt\n , NULL AS pass_cnt\n , NULL AS push_cnt\n , NULL AS imp_cnt\n , NULL AS clck_cnt\n , NULL AS imp\n , NULL AS clck\n , NULL AS channel_name", "expected_csv": "update_date,material_type_name,source_name,video_model_type_name,create_type_name,purpose_name,provider_name,production_cnt,audit_cnt,pass_cnt,push_cnt,imp_cnt,clck_cnt,imp,clck,channel_name,imp_date\n20260608,图片,人机素材,镜头拆分模型(老模型),原始剪辑,收入,AI侧,1,1,1,1,1,0,60,8,广告平台G,20260608\n20260608,视频,人机素材,剧情理解模型(新模型),高光剪辑,拉活,内部平台D侧,1,1,1,0,1,0,80,5,广告联盟Y,20260608\n20260608,视频,人工素材,剧情理解模型(新模型),定点剪辑,电商,内部平台D侧,1,0,1,1,1,1,200,30,广告联盟Y,20260608\n20260608,图片,人工素材,镜头拆分模型(老模型),无视频剪辑方式,拉新,AI侧,1,1,1,1,1,1,100,20,广告平台G,20260608\n20260608,视频,AI素材,剧情理解模型(新模型),拆条剪辑,当日拉活,AI侧,1,1,1,0,0,0,30,2,广告平台G,20260608\n20260608,图片,AI素材,镜头拆分模型(老模型),拼合剪辑,唤醒,AI侧,0,1,0,1,0,1,50,10,广告平台G,20260608\n20260608,,,,,,,,,,,,,,,,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数17 + 列名匹配\nC,C_row_alignment,row_consistency,15,行数比例 + key覆盖率\nD,D_case_when_labels,case_when_labels,20,7个维度标签列逐行匹配\nD,D_agg_metrics,agg_metrics,20,8个聚合列按权重匹配\nF,F_union_all_sentinel,union_all_sentinel,10,是否存在NULL哨兵行\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,imp_date=20260608\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"material_type_name, source_name, channel_name\"\n# 预期列数,\n# 输出表,internal_platform_db.ads_ug_app_ad_material_action_di_cand_query_engine_101", "path": "tasks/offline-compute/HiveSQL/hivesql_013"} {"task_id": "hivesql_014_en", "id": "offline-compute_HiveSQL_hivesql_014", "name": "Filter add-friend behavior from internal_platform_db.log_17047_query_engine_102", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective:\nPerform cluster aggregation analysis on add-friend behavior logs to identify malicious clusters, and output statistical metrics for each cluster.\n\nInput:\n- `internal_platform_db.log_17047_query_engine_102` (add-friend behavior log table)\n\nProcessing Rules:\n1. No joins, single-table processing, using UNION of two subqueries\n2. Time filter: `day_` between 20260608–20260609, `hour_` between 2026060823–2026060900, `timestamp_` between 202606082320 and 202606090020\n3. Branch 1 filter: `appname_ in ('app_hello_txt', 'app_add_contact')`, `uinregcountry_ in ('CN','HK','MO')`, `touinregcountry_='CN'`, `length(headmd5_)>0`, `commfrinum_=0`\n4. Branch 2 filter: `appname_='app_contact_verify_ok'`, `uinregcountry_ in ('CN','HK','MO')`, `touinregcountry_='CN'`, `commfrinum_=0`\n5. Grouping fields: `appname_`, `clientversion_`, `scene_`, `ticketscene_`, `headmd5_` (empty string for branch 2), `uinipcountryid_`, `uinipprovinceid_`\n6. Aggregation fields: `addfri_pv=count(*)`, `user_id_cnt=count(distinct user_id_)`, `low_quality_cnt=sum(if(uinhighquality_=0,1,0))`, `low_quality_rate=low_quality_cnt/addfri_pv`, `user_id_list=concat_ws(',',collect_set(cast(user_id_ as string)))`, `hello_content_list=concat_ws('|',collect_set(content_))`, `evil_cnt=sum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10,1,0))`, `evil_rate=evil_cnt/addfri_pv`\n7. HAVING filter: `user_id_cnt>20` AND (`low_quality_rate>0.99` OR `evil_rate>0.98`)\n\nOutput Requirements:\nField order: `appname_`, `clientversion_`, `scene_`, `ticketscene_`, `headmd5_`, `uinipcountryid_`, `uinipprovinceid_`, `addfri_pv`, `user_id_cnt`, `low_quality_cnt`, `low_quality_rate`, `user_id_list`, `hello_content_list`, `evil_cnt`, `evil_rate`\n\nWrite Requirements:\n`INSERT INTO internal_platform_db.t_acct_addfri_action_cluster_minutely_cand_query_engine_102 PARTITION(ds=202606090010)`\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT INTO TABLE internal_platform_db.t_acct_addfri_action_cluster_minutely_query_engine_102 PARTITION(ds=202606090010)\nselect\nappname_,\nclientversion_,\nscene_,\nticketscene_,\nheadmd5_,\nuinipcountryid_,\nuinipprovinceid_,\ncount(*) as addfri_pv,\ncount(distinct user_id_) as user_id_cnt,\nsum(if(uinhighquality_=0, 1, 0)) as low_quality_cnt,\nsum(if(uinhighquality_=0, 1, 0))/count(*) as low_quality_rate,\nconcat_ws(\",\", collect_set(cast(user_id_ as string))) as user_id_list,\nconcat_ws(\"|\", collect_set(content_)) as hello_content_list,\nsum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10, 1, 0)) as evil_cnt,\nsum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10, 1, 0))/count(*) as evil_rate\nfrom internal_platform_db.log_17047_query_engine_102\nwhere date_format(day_, 'yyyyMMdd')>=20260608 and date_format(day_, 'yyyyMMdd')<=20260609\nand date_format(hour_, 'yyyyMMddHH')>=2026060823 and date_format(hour_, 'yyyyMMddHH')<=2026060900\nand timestamp_>=unix_timestamp('202606082320','yyyyMMddHHmm')\nand timestamp_0\nand commfrinum_=0\ngroup by appname_, clientversion_, scene_, ticketscene_, headmd5_, uinipcountryid_, uinipprovinceid_\nhaving count(distinct user_id_)>20\nand ( sum(if(uinhighquality_=0, 1, 0))/count(*) > 0.99\nor sum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10, 1, 0))/count(*) > 0.98)\nunion\nselect\nappname_,\nclientversion_,\nscene_,\nticketscene_,\n\"\",\nuinipcountryid_,\nuinipprovinceid_,\ncount(*) as addfri_pv,\ncount(distinct user_id_) as user_id_cnt,\nsum(if(uinhighquality_=0, 1, 0)) as low_quality_cnt,\nsum(if(uinhighquality_=0, 1, 0))/count(*) as low_quality_rate,\nconcat_ws(\",\", collect_set(cast(user_id_ as string))) as user_id_list,\nconcat_ws(\"|\", collect_set(content_)) as hello_content_list,\nsum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10, 1, 0)) as evil_cnt,\nsum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10, 1, 0))/count(*) as evil_rate\nfrom internal_platform_db.log_17047_query_engine_102\nwhere date_format(day_, 'yyyyMMdd')>=20260608 and date_format(day_, 'yyyyMMdd')<=20260609\nand date_format(hour_, 'yyyyMMddHH')>=2026060823 and date_format(hour_, 'yyyyMMddHH')<=2026060900\nand timestamp_>=unix_timestamp('202606082320','yyyyMMddHHmm')\nand timestamp_20\nand ( sum(if(uinhighquality_=0, 1, 0))/count(*) > 0.99\nor sum(if(uinlastunbantime_>0 or opentime_+86400*90>timestamp_ or friendnum_<10, 1, 0))/count(*) > 0.98)", "expected_csv": "appname_,clientversion_,scene_,ticketscene_,headmd5_,uinipcountryid_,uinipprovinceid_,addfri_pv,user_id_cnt,low_quality_cnt,low_quality_rate,user_id_list,hello_content_list,evil_cnt,evil_rate,ds\napp_hello_txt,800,1,100,headmd5_abc,86,440000,21,21,21,1.0,\"1011,1010,1021,1020,1008,1019,1007,1018,1006,1017,1005,1016,1004,1015,1003,1014,1002,1013,1001,1012,1009\",hello,21,1.0,202606090010\napp_add_contact,900,2,200,headmd5_def,86,110000,21,21,21,1.0,\"2001,2012,2011,2010,2021,2020,2009,2008,2019,2007,2018,2006,2017,2005,2016,2004,2015,2003,2014,2002,2013\",hi,21,1.0,202606090010\napp_contact_verify_ok,800,3,300,,852,0,21,21,21,1.0,\"3002,3013,3001,3012,3011,3010,3021,3020,3009,3008,3019,3007,3018,3006,3017,3005,3016,3004,3015,3003,3014\",verify,21,1.0,202606090010", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数16 + 列名匹配\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_agg_metrics,agg_metrics,40,\"6个聚合指标列逐行匹配(addfri_pv,user_id_cnt,low_quality_rate,evil_rate,low_quality_cnt,evil_cnt)\"\nF,F_insert_overwrite,insert_overwrite,5,写入模式应为 INSERT INTO\nF,F_partition_value,partition_value,5,ds=202606090010\nF,F_union_branches,union_branches,10,UNION两路分支均存在(app_hello_txt/app_add_contact + app_contact_verify_ok)\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"appname_, scene_, ticketscene_, headmd5_, uinipprovinceid_\"\n# 预期列数,\n# 输出表,internal_platform_db.t_acct_addfri_action_cluster_minutely_cand_query_engine_102", "path": "tasks/offline-compute/HiveSQL/hivesql_014_en"} {"task_id": "hivesql_015_en", "id": "offline-compute_HiveSQL_hivesql_015", "name": "From internal_platform_db.t_mg_dws_user_tag_preset_241", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Incrementally insert new user records (`user_id`, `loss_day`) into the `ds=20260608` partition of the target table that have not appeared before.\n\nInputs:\n- `internal_platform_db.t_mg_dws_user_tag_preset_24128_query_engine_103` (source table, containing fields such as `ds`, `user_id`, `loss_day`)\n- `internal_platform_db.t_mg_dws_user_tag_user_id_once_24128_query_engine_103` (existing users table, containing previously written `user_id` values)\n\nProcessing Rules:\n1. Select records from the source table `internal_platform_db.t_mg_dws_user_tag_preset_24128_query_engine_103` where `ds=20260608`\n2. Use a `NOT IN` subquery to exclude `user_id` values that already exist in the existing users table `internal_platform_db.t_mg_dws_user_tag_user_id_once_24128_query_engine_103` (deduplication condition: `user_id`)\n3. Extract fields: `user_id`, `loss_day`\n\nOutput Requirements:\n- Output field order: `user_id`, `loss_day`\n- No deduplication needed (duplicates are already filtered out via `NOT IN`)\n\nWrite Requirements:\n- Target table: `internal_platform_db.t_mg_dws_user_tag_user_id_once_24128_cand_query_engine_103`\n- Write method: `INSERT INTO` (append)\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "insert into internal_platform_db.t_mg_dws_user_tag_user_id_once_24128_query_engine_103 (user_id, loss_day)\nselect user_id,loss_day\nfrom internal_platform_db.t_mg_dws_user_tag_preset_24128_query_engine_103\nwhere\nds = 20260608\nand user_id not in (select user_id from internal_platform_db.t_mg_dws_user_tag_user_id_once_24128_query_engine_103)", "expected_csv": "user_id,loss_day\nuser_a,5\nuser_b,3\nuser_e,1", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数匹配 + 列名匹配\nC,C_row_alignment,row_consistency,15,行数比例 + key覆盖率\nD,D_anti_join,anti_join,25,NOT IN 排除已存在 user_id 的正确性\nD,D_value_correctness,value_correctness,20,loss_day 等数值列逐行匹配\nF,F_insert_overwrite,insert_mode,5,INSERT INTO(非 OVERWRITE)\nF,F_partition_value,partition_filter,5,只取 ds=20260608\nF,F_partition_value,partition_value,5,分区值正确\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,user_id\n# 预期列数,\n# 输出表,internal_platform_db.t_mg_dws_user_tag_user_id_once_24128_cand_query_engine_103", "path": "tasks/offline-compute/HiveSQL/hivesql_015_en"} {"task_id": "hivesql_016", "id": "offline-compute_HiveSQL_hivesql_016", "name": "从用户活跃日志表统计每日各渠道的活跃用户数", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:统计各渠道的日活跃用户数。\n\n输入:\n- internal_platform_db.dwd_user_activity_log_hi_query_engine_104(用户活跃日志表)\n\n处理规则:\n1. 过滤条件:imp_date = 20260608\n2. 分组维度:channel\n3. 聚合指标:COUNT(DISTINCT user_id) AS dau\n4. 派生列:imp_date 固定值 20260608\n\n输出要求:\n- 字段顺序:imp_date(BIGINT,固定值20260608)、channel(STRING)、dau(BIGINT)\n- 按 channel 升序排列\n\n写入要求:\n- 输出表:internal_platform_db.dws_user_daily_active_by_channel_cand_query_engine_104\n- 写入方式:INSERT OVERWRITE\n- 分区:ds=20260608\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "insert overwrite table internal_platform_db.dws_user_daily_active_by_channel_query_engine_104 partition(ds='20260608')\nselect\n20260608 as imp_date\n, channel\n, count(distinct user_id) as dau\nfrom\ninternal_platform_db.dwd_user_activity_log_hi_query_engine_104\nwhere\nimp_date = 20260608\ngroup by\nchannel\norder by\nchannel", "expected_csv": "imp_date,channel,dau,ds\n20260608,appstore,3,20260608\n20260608,huawei,2,20260608\n20260608,oppo,1,20260608\n20260608,xiaomi,1,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数(4=3数据+1分区) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,25,非key字段逐列值匹配率\nD,D_field_completeness,field_completeness,15,关键字段非空比例\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION 写入模式\nF,F_partition_value,partition_value,5,ds=20260608\nF,F_source_filter,source_filter,10,源表分区过滤 imp_date=20260608\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,channel\n# 预期列数,4\n# 输出表,internal_platform_db.dws_user_daily_active_by_channel_cand_query_engine_104", "path": "tasks/offline-compute/HiveSQL/hivesql_016"} {"task_id": "hivesql_017", "id": "offline-compute_HiveSQL_hivesql_017", "name": "从事件表和全量用户表 Join 过滤出 20260608 当天最后登录用户的事件,按 sdk_id", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:按 SDK 类型和小时统计活跃用户数。\n\n输入:\n- internal_platform_db.dws_event_tracking_ul2l6h5c_events_di_query_engine_114(事件明细表)\n- internal_platform_db.dws_event_tracking_ul2l6h5c_all_user_df_query_engine_114(用户维度表)\n\n处理规则:\n- Join 条件:e.user_id = u.user_id\n- 过滤条件:e.imp_date = 20260608,u.imp_date = 20260608,u.last_login_date = 20260608\n- 分组维度:sdk_id、event_time_hour\n- 聚合指标:COUNT(DISTINCT e.user_id) as active_users\n- 去重与排序:按 sdk_id 和 hour 分组,无额外排序要求\n\n输出要求:\n- 字段顺序:imp_date(固定值 20260608,BIGINT)、id(ROW_NUMBER() OVER())、sdk_id(STRING)、hour(STRING,来源 event_time_hour)、active_users(BIGINT)\n\n写入要求:\n- 输出表:internal_platform_db.ads_event_tracking_ul2l6h5c_user_active_hour_di_cand_query_engine_114\n- 写入方式:INSERT INTO\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT INTO internal_platform_db.ads_event_tracking_ul2l6h5c_user_active_hour_di_query_engine_114\nSELECT\n20260608 as `imp_date`\n, ROW_NUMBER() OVER(ORDER BY e.`sdk_id`, e.`event_time_hour`) as `id`\n, e.`sdk_id` as `sdk_id`\n, e.`event_time_hour` as `hour`\n, COUNT(DISTINCT e.user_id) as `active_users`\nFROM\ninternal_platform_db.dws_event_tracking_ul2l6h5c_events_di_query_engine_114 e\nJOIN\ninternal_platform_db.dws_event_tracking_ul2l6h5c_all_user_df_query_engine_114 u\nON\nu.imp_date = 20260608\nand u.user_id = e.user_id\nand u.last_login_date = 20260608\nWHERE\ne.imp_date = 20260608\nGROUP BY\ne.`sdk_id`\n, e.`event_time_hour`", "expected_csv": "imp_date,id,sdk_id,hour,active_users\n20260608,1,sdk_android,10,2\n20260608,2,sdk_ios,11,2", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数(5) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,45,非key字段逐列值匹配率\nF,F_insert_overwrite,insert_mode,5,INSERT INTO 写入模式\nF,F_source_filter,source_coverage,5,2张源表均被引用\nF,F_join_completeness,join_condition,5,JOIN条件包含user_id\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,\"imp_date, id, sdk_id\"\n# 预期列数,5\n# 输出表,internal_platform_db.ads_event_tracking_ul2l6h5c_user_active_hour_di_cand_query_engine_114", "path": "tasks/offline-compute/HiveSQL/hivesql_017"} {"task_id": "hivesql_018_en", "id": "offline-compute_HiveSQL_hivesql_018", "name": "Compute scores for first-level comments from view records and comment logs. Group by recall_uin + channel_id + fe", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Compute the composite score for first-level comments newly added by recalled read users after their first post view, for content heat analysis.\n\nInputs:\n- `internal_platform_db.dws_social_group_content_forum_hot_feed_recall_feed_view_hi_query_engine_122` (view records, filter `imp_hour` within [2026060811, 2026060910])\n- `internal_platform_db.dwd_social_group_content_forum_hot_feed_recall_comment_log_hi_query_engine_122` (comment logs, filter `imp_hour` within [2026060811, 2026060910])\n- `internal_platform_db.dwd_all_social_group_user_slice_ds_query_engine_122` (user identity, filter `imp_date >= 20260607`)\n\nProcessing Rules:\n1. Build a view aggregation: From the view table, aggregate by `uin` + `channel_id` + `feed_id`, extracting the first/last view time, detail page view count, and duration.\n2. Filter comments: Join the comment log with the view aggregation on `channel_id` + `feed_id`, keeping only records where the comment time is >= the first view time.\n3. Enrich user identity: Left join the user table, using `member_role` as a fallback for `user_type` (use the original `user_type` when missing).\n4. Compute first-level comment metrics: Group by `recall_uin` + `channel_id` + `feed_id` + `p_comment_id` (as the first-level comment ID) + `uin`, and compute:\n - Normal user like count (`action_type='comment_like'` AND `user_type=0`)\n - Author like count (`action_type='comment_like'` AND `uin=author_uin`)\n - Channel owner like count (`action_type='comment_like'` AND `user_type in (1,2)`)\n - Normal user reply count (`action_type='comment'` AND `comment_type='comment_reply'` AND `user_type=0` AND `uin<>comment_uin`)\n - Author reply count (`action_type='comment'` AND `comment_type='comment_reply'` AND `uin=author_uin` AND `uin<>comment_uin`)\n - Channel owner reply count (`action_type='comment'` AND `comment_type='comment_reply'` AND `user_type in (1,2)` AND `uin<>comment_uin`)\n5. Aggregate by `recall_uin` + `channel_id` + `feed_id` + `comment_id` to compute deduplicated UV and totals:\n - UV (count distinct of users with the behavior) and counts for each like/reply type\n - Normal user average reply count (total replies / number of users who replied)\n6. Compute scores (tiered rules):\n - Normal user like score: tiered by count (1→2, 2–4→4, 5–10→7, 11–20→8, 21–50→10, >50→12)\n - Author like score: tiered by UV, then +2\n - Channel owner like score: tiered by count, then +1\n - Normal user reply score: when count < 4, UV*2.5 (cap 30); when >= 4, UV*2 (cap 30)\n - Author reply score: normal user reply score + 3\n - Channel owner reply score: normal user reply score + 1\n - Average reply score: mean <=1.5→0, 1.5–3→3, >3→6\n - Total comment score: sum of the above 7 score components\n\nOutput Requirements:\n- Field order: `imp_hour`, `uin` (i.e., `recall_uin`), `channel_id`, `feed_id`, `comment_id`, `comment_time`, `comment_score`, and the scores, UVs, and counts for each like/reply type (20 metric fields in total)\n- `comment_time` takes the last comment time of that comment\n- Partition field `imp_hour` is fixed as `2026060910`\n\nWrite Requirements:\n- Output table: `internal_platform_db.dws_social_group_content_forum_hot_feed_recall_comment_score_hi_cand_query_engine_122`\n- Write method: `INSERT OVERWRITE` partition `imp_hour=2026060910`\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "insert overwrite table internal_platform_db.dws_social_group_content_forum_hot_feed_recall_comment_score_hi_query_engine_122 partition (imp_hour = 2026060910)\nwith social_group_feed_view as\n(\nselect\nuin as recall_uin\n, channel_id\n, feed_id\n, min(first_view_time) as first_view_time\n, max(last_view_time) as last_view_time\n, sum(forum_detail_cnt) as forum_detail_cnt\n, sum(forum_detail_dtm_s) as forum_detail_dtm_s\nfrom\ninternal_platform_db.dws_social_group_content_forum_hot_feed_recall_feed_view_hi_query_engine_122\nwhere\nimp_hour >= 2026060811 and imp_hour <= 2026060910\ngroup by\nuin\n, channel_id\n, feed_id\n),\nnew_feed_comment_log as\n(\nselect\nt4.recall_uin\n, t1.channel_id\n, t1.feed_id\n, t1.comment_id\n, t1.p_comment_id\n, t1.uin\n, t1.comment_uin\n, t1.p_comment_uin\n, t1.author_uin\n, t1.action_type\n, t1.comment_type\n, nvl(t5.member_role, t1.user_type) as user_type\n, t1.time_stamp\n, t4.first_view_time as first_view_time\nfrom\n(\nselect\nchannel_id\n, feed_id\n, comment_id\n, p_comment_id\n, uin\n, comment_uin\n, p_comment_uin\n, author_uin\n, action_type\n, comment_type\n, nvl(user_type, 0) as user_type\n, time_stamp\nfrom\ninternal_platform_db.dwd_social_group_content_forum_hot_feed_recall_comment_log_hi_query_engine_122\nwhere\nimp_hour >= 2026060811 and imp_hour <= 2026060910\n) t1\njoin\n(\nselect\nrecall_uin\n, channel_id\n, feed_id\n, first_view_time\nfrom\nsocial_group_feed_view\n) t4\non\nt1.channel_id = t4.channel_id\nand t1.feed_id = t4.feed_id\nleft join\n(\nselect\nuin\n, channel_id\n, member_role\nfrom\ninternal_platform_db.dwd_all_social_group_user_slice_ds_query_engine_122\nwhere\nimp_date >= 20260607\n) t5\non\nt1.uin = t5.uin\nand t1.channel_id = t5.channel_id\nwhere\nt1.time_stamp >= t4.first_view_time\n)\nselect\nrecall_uin as uin\n, channel_id\n, feed_id\n, comment_id\n, comment_time\n, normal_comment_like_score + key_author_comment_like_score + key_owner_comment_like_score\n+ normal_comment_reply_score + key_author_comment_reply_score + key_owner_comment_reply_score\n+ avg_normal_comment_reply_score as comment_score\n, normal_comment_like_score\n, key_author_comment_like_score\n, key_owner_comment_like_score\n, normal_comment_reply_score\n, key_author_comment_reply_score\n, key_owner_comment_reply_score\n, avg_normal_comment_reply_score\n, normal_comment_like_uv\n, normal_comment_like_cnt\n, key_author_comment_like_uv\n, key_author_comment_like_cnt\n, key_owner_comment_like_uv\n, key_owner_comment_like_cnt\n, normal_comment_reply_uv\n, normal_comment_reply_cnt\n, avg_normal_comment_reply_cnt\n, key_author_comment_reply_uv\n, key_author_comment_reply_cnt\n, key_owner_comment_reply_uv\n, key_owner_comment_reply_cnt\nfrom\n(\nselect\nrecall_uin\n, channel_id\n, feed_id\n, comment_id\n, last_comment_time as comment_time\n, case\nwhen normal_comment_like_cnt = 1 then 2\nwhen normal_comment_like_cnt > 1 and normal_comment_like_cnt < 5 then 4\nwhen normal_comment_like_cnt >= 5 and normal_comment_like_cnt <= 10 then 7\nwhen normal_comment_like_cnt > 10 and normal_comment_like_cnt <= 20 then 8\nwhen normal_comment_like_cnt > 20 and normal_comment_like_cnt <= 50 then 10\nwhen normal_comment_like_cnt > 50 then 12\nelse 0\nend as normal_comment_like_score\n, case\nwhen key_author_comment_like_uv = 1 then 2+2\nwhen key_author_comment_like_uv > 1 and key_author_comment_like_uv < 5 then 4+2\nwhen key_author_comment_like_uv >= 5 and key_author_comment_like_uv <= 10 then 7+2\nwhen key_author_comment_like_uv > 10 and key_author_comment_like_uv <= 20 then 8+2\nwhen key_author_comment_like_uv > 20 and key_author_comment_like_uv <= 50 then 10+2\nwhen key_author_comment_like_uv > 50 then 12+2\nelse 0\nend as key_author_comment_like_score\n, case\nwhen key_owner_comment_like_cnt = 1 then 2+1\nwhen key_owner_comment_like_cnt > 1 and key_owner_comment_like_cnt < 5 then 4+1\nwhen key_owner_comment_like_cnt >= 5 and key_owner_comment_like_cnt <= 10 then 7+1\nwhen key_owner_comment_like_cnt > 10 and key_owner_comment_like_cnt <= 20 then 8+1\nwhen key_owner_comment_like_cnt > 20 and key_owner_comment_like_cnt <= 50 then 10+1\nwhen key_owner_comment_like_cnt > 50 then 12+1\nelse 0\nend as key_owner_comment_like_score\n, case\nwhen normal_comment_reply_cnt >= 1 and normal_comment_reply_cnt < 4 then\ncase when normal_comment_reply_uv * 2.5 > 30 then 30 else normal_comment_reply_uv * 2.5 end\nwhen normal_comment_reply_cnt >= 4 then\ncase when normal_comment_reply_uv * 2 > 30 then 30 else normal_comment_reply_uv * 2 end\nelse 0\nend as normal_comment_reply_score\n, case\nwhen key_author_comment_reply_cnt >= 1 and key_author_comment_reply_cnt < 4 then\ncase when key_author_comment_reply_uv * 2.5 + 3 > 30 then 30 else key_author_comment_reply_uv * 2.5 + 3 end\nwhen key_author_comment_reply_cnt >= 4 then\ncase when key_author_comment_reply_uv * 2 + 3 > 30 then 30 else key_author_comment_reply_uv * 2 + 3 end\nelse 0\nend as key_author_comment_reply_score\n, case\nwhen key_owner_comment_reply_cnt >= 1 and key_owner_comment_reply_cnt < 4 then\ncase when key_owner_comment_reply_uv * 2.5 + 1 > 30 then 30 else key_owner_comment_reply_uv * 2.5 + 1 end\nwhen key_owner_comment_reply_cnt >= 4 then\ncase when key_owner_comment_reply_uv * 2 + 1 > 30 then 30 else key_owner_comment_reply_uv * 2 + 1 end\nelse 0\nend as key_owner_comment_reply_score\n, case\nwhen avg_normal_comment_reply_cnt <= 1.5 then 0\nwhen avg_normal_comment_reply_cnt > 1.5 and avg_normal_comment_reply_cnt <= 3 then 3\nwhen avg_normal_comment_reply_cnt > 3 then 6\nelse 0\nend as avg_normal_comment_reply_score\n, normal_comment_like_uv\n, normal_comment_like_cnt\n, key_author_comment_like_uv\n, key_author_comment_like_cnt\n, key_owner_comment_like_uv\n, key_owner_comment_like_cnt\n, normal_comment_reply_uv\n, normal_comment_reply_cnt\n, avg_normal_comment_reply_cnt\n, key_author_comment_reply_uv\n, key_author_comment_reply_cnt\n, key_owner_comment_reply_uv\n, key_owner_comment_reply_cnt\nfrom\n(\nselect\nrecall_uin\n, channel_id\n, feed_id\n, comment_id\n, max(last_comment_time) as last_comment_time\n, count(distinct case when normal_comment_like_cnt > 0 then uin else null end) as normal_comment_like_uv\n, sum(normal_comment_like_cnt) as normal_comment_like_cnt\n, count(distinct case when key_author_comment_like_cnt > 0 then uin else null end) as key_author_comment_like_uv\n, sum(key_author_comment_like_cnt) as key_author_comment_like_cnt\n, count(distinct case when key_owner_comment_like_cnt > 0 then uin else null end) as key_owner_comment_like_uv\n, sum(key_owner_comment_like_cnt) as key_owner_comment_like_cnt\n, count(distinct case when normal_comment_reply_cnt > 0 then uin else null end) as normal_comment_reply_uv\n, sum(normal_comment_reply_cnt) as normal_comment_reply_cnt\n, sum(normal_comment_reply_cnt)/count(distinct case when normal_comment_reply_cnt > 0 then uin else null end) as avg_normal_comment_reply_cnt\n, count(distinct case when key_author_comment_reply_cnt > 0 then uin else null end) as key_author_comment_reply_uv\n, sum(key_author_comment_reply_cnt) as key_author_comment_reply_cnt\n, count(distinct case when key_owner_comment_reply_cnt > 0 then uin else null end) as key_owner_comment_reply_uv\n, sum(key_owner_comment_reply_cnt) as key_owner_comment_reply_cnt\nfrom\n(\nselect\nrecall_uin\n, channel_id\n, feed_id\n, p_comment_id as comment_id\n, max(time_stamp) as last_comment_time\n, uin\n, sum(case when action_type = 'comment_like' and user_type in (0) then 1 else 0 end) as normal_comment_like_cnt\n, sum(case when action_type = 'comment_like' and uin = author_uin then 1 else 0 end) as key_author_comment_like_cnt\n, sum(case when action_type = 'comment_like' and user_type in (1,2) then 1 else 0 end) as key_owner_comment_like_cnt\n, sum(case when action_type = 'comment' and comment_type = 'comment_reply' and user_type in (0) and uin <> comment_uin then 1 else 0 end) normal_comment_reply_cnt\n, sum(case when action_type = 'comment' and comment_type = 'comment_reply' and uin = author_uin and uin <> comment_uin then 1 else 0 end) key_author_comment_reply_cnt\n, sum(case when action_type = 'comment' and comment_type = 'comment_reply' and user_type in (1,2) and uin <> comment_uin then 1 else 0 end) key_owner_comment_reply_cnt\nfrom\nnew_feed_comment_log\nwhere\naction_type = 'comment_like' or (action_type = 'comment' and comment_type = 'comment_reply')\ngroup by\nrecall_uin\n, channel_id\n, feed_id\n, p_comment_id\n, uin\n) t\ngroup by\nrecall_uin\n, channel_id\n, feed_id\n, comment_id\n) tt\n) t", "expected_csv": "uin,channel_id,feed_id,comment_id,comment_time,comment_score,normal_comment_like_score,key_author_comment_like_score,key_owner_comment_like_score,normal_comment_reply_score,key_author_comment_reply_score,key_owner_comment_reply_score,avg_normal_comment_reply_score,normal_comment_like_uv,normal_comment_like_cnt,key_author_comment_like_uv,key_author_comment_like_cnt,key_owner_comment_like_uv,key_owner_comment_like_cnt,normal_comment_reply_uv,normal_comment_reply_cnt,avg_normal_comment_reply_cnt,key_author_comment_reply_uv,key_author_comment_reply_cnt,key_owner_comment_reply_uv,key_owner_comment_reply_cnt\nuser_A,ch_001,feed_01,pcmt_01,1717806000,19.0,4,4,3,2.5,5.5,0.0,0,2,2,1,1,1,1,1,1,1.0,1,1,0,0\nuser_A,ch_001,feed_01,pcmt_02,1717807000,3.5,0,0,0,0.0,0.0,3.5,0,0,0,0,0,0,0,0,0,,0,0,1,1\nuser_B,ch_002,feed_02,pcmt_03,1717812000,8.5,2,4,0,2.5,0.0,0.0,0,1,1,1,1,0,0,1,1,1.0,0,0,0,0\nuser_C,ch_001,feed_03,pcmt_04,1717801000,2.0,2,0,0,0.0,0.0,0.0,0,1,1,0,0,0,0,0,0,,0,0,0,0", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数26 + 列名匹配\nC,C_row_alignment,row_consistency,10,\"行数比例 + key(uin,channel_id,feed_id,comment_id)覆盖率\"\nD,D_comment_score_correctness,comment_score_correctness,25,comment_score + 7项分档评分列逐行匹配\nD,D_uv_cnt_correctness,uv_cnt_correctness,20,13个UV/cnt聚合列逐行匹配\nD,D_comment_time_correctness,comment_time_correctness,10,comment_time列逐行匹配\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION 写入模式\nF,F_partition_value,partition_value,3,imp_hour=2026060910\nF,F_null_handling,null_handling,4,UV/cnt列无不当NULL\nF,F_source_filter,source_coverage,3,3张源表均被引用\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,\"uin, channel_id, feed_id, comment_id\"\n# 预期列数,\n# 输出表,internal_platform_db.dws_social_group_content_forum_hot_feed_recall_comment_score_hi_cand_query_engine_122", "path": "tasks/offline-compute/HiveSQL/hivesql_018_en"} {"task_id": "hivesql_019_en", "id": "offline-compute_HiveSQL_hivesql_019", "name": "From input table internal_platform_db.t_app_urlsafe_cont_topweb", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Extract qualifying potential risk domains from the top websites collection table and write them to the target table.\n\nInput:\n- `internal_platform_db.t_app_urlsafe_cont_topwebsites_collect_df_query_engine_125` (fields: `domain`, `site`, `ds`, `src`)\n\nProcessing Rules:\n1. Filter condition: `src='transco'` AND `ds=20260608` AND `length(split(domain, '\\.')[0]) > 3`\n2. No joins, single-table processing\n3. Row limit: take the first 2000 rows\n4. Field mapping and derived columns:\n - `ds` = fixed value `20260608`\n - `type` = fixed value `'transco'`\n - `fuzzer` = fixed value `'-1'`\n - `result_domain` = fixed value `'-1'`\n - `original_domain` = the `domain` field from the input table\n\nOutput Requirements:\n- Output 5 columns, in the following order: `ds`, `type`, `fuzzer`, `result_domain`, `original_domain`\n- No deduplication or aggregation required\n\nWrite Requirements:\n- Target table: `internal_platform_db.t_dws_urlsafe_cont_potential_risk_domain_di_cand_query_engine_125`\n- Write method: upsert\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.t_dws_urlsafe_cont_potential_risk_domain_di_query_engine_125\nwith topsites as\n(\nselect domain as original_domain\nfrom internal_platform_db.t_app_urlsafe_cont_topwebsites_collect_df_query_engine_125\nwhere src='transco'\nand ds=20260608\nand length(split(domain, '\\\\.')[0])>3\nlimit 2000\n)\nselect\n20260608 as ds, 'transco' as type,'-1' as fuzzer, '-1' as result_domain, original_domain\nfrom topsites", "expected_csv": "ds,type,fuzzer,result_domain,original_domain\n20260608,transco,-1,-1,long-domain-name.org\n20260608,transco,-1,-1,test.site.net\n20260608,transco,-1,-1,abcd.domain.cn", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,col_count(5) + col_names(5)\nC,C_row_alignment,row_consistency,15,row_ratio(7) + key_coverage(8)\nD,D_domain_filter_correct,domain_filter_correct,25,original_domain 列值匹配率(核心过滤逻辑)\nD,D_fixed_value_correct,fixed_value_correct,20,ds/type/fuzzer/result_domain 固定值列匹配率\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE 写入模式\nF,F_partition_value,partition_value,5,ds 分区 = 20260608\nF,F_limit_2000,limit_2000,5,SQL 中包含 LIMIT 2000\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,original_domain\n# 预期列数,\n# 输出表,internal_platform_db.t_dws_urlsafe_cont_potential_risk_domain_di_cand_query_engine_125", "path": "tasks/offline-compute/HiveSQL/hivesql_019_en"} {"task_id": "hivesql_020", "id": "offline-compute_HiveSQL_hivesql_020", "name": "从 internal_platform_db.t_boss_v1_dict_item_hour_query_engine_130 筛选", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:对指定分区的字典项小时表进行记录数监控统计,输出监控结果到目标表分区。\n\n输入:\n- internal_platform_db.t_boss_v1_dict_item_hour_query_engine_130\n\n处理规则:\n1. 无 Join,单表处理\n2. 过滤条件:imp_hour=2026060910\n3. 分组聚合:按 dim_name='AEGIS_ALL' 和 dim_value='AEGIS_ALL' 分组\n4. 聚合计算:count(1) 得到 compute_item_51323\n5. 派生列:\n - imp_time = 2026060910\n - data_type = 'monitor'\n - data_id = '1::dept_om::t_boss_v1_dict_item_hour_query_engine_130'\n - check_rule_id = 51322\n - check_item_id = 51323\n - compute_value = compute_item_51323\n - compare_value = null\n - check_value = compute_item_51323\n\n输出要求:\n- 输出字段顺序:imp_time, data_type, data_id, check_rule_id, check_item_id, dim_name, dim_value, compute_value, compare_value, check_value\n\n写入要求:\n- 目标表:internal_platform_db.t_boss_v1_dict_item_hour_monitor_res_cand_query_engine_130\n- 写入方式:insert overwrite\n- 分区:partition (p_2026060910, p_monitor)\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.t_boss_v1_dict_item_hour_monitor_res_query_engine_130 PARTITION (p_2026060910='p_2026060910', p_monitor='p_monitor')\nSELECT imp_time, data_type, data_id, check_rule_id, check_item_id, dim_name, dim_value, compute_value, compare_value, check_value\nFROM (\n WITH temp_table_1 AS (\n SELECT 'AEGIS_ALL' AS dim_name, 'AEGIS_ALL' AS dim_value, count(1) AS compute_item_51323\n FROM internal_platform_db.t_boss_v1_dict_item_hour_query_engine_130\n WHERE imp_hour = 2026060910\n )\n SELECT\n 2026060910 AS imp_time,\n 'monitor' AS data_type,\n '1::dept_om::t_boss_v1_dict_item_hour' AS data_id,\n 51322 AS check_rule_id,\n 51323 AS check_item_id,\n dim_name,\n dim_value,\n compute_item_51323 AS compute_value,\n CAST(null AS STRING) AS compare_value,\n compute_item_51323 AS check_value\n FROM temp_table_1\n) t", "expected_csv": "imp_time,data_type,data_id,check_rule_id,check_item_id,dim_name,dim_value,compute_value,compare_value,check_value,p_2026060910,p_monitor\n2026060910,monitor,1::dept_om::t_boss_v1_dict_item_hour,51322,51323,AEGIS_ALL,AEGIS_ALL,3,,3,p_2026060910,p_monitor", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数(12=10数据+2分区) + 列名匹配(5)\nC,C_row_alignment,row_consistency,15,行数比例(7) + key覆盖率(8)\nD,D_field_value_match,field_value_match,45,非key字段逐列值匹配率\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION 写入模式\nF,F_partition_value,partition_value,5,分区值 p_2026060910 / p_monitor\nF,F_cte_usage,cte_usage,5,使用CTE\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,\"data_id, check_rule_id, check_item_id\"\n# 预期列数,12\n# 输出表,internal_platform_db.t_boss_v1_dict_item_hour_monitor_res_cand_query_engine_130", "path": "tasks/offline-compute/HiveSQL/hivesql_020"} {"task_id": "hivesql_021_en", "id": "offline-compute_HiveSQL_hivesql_021", "name": "Filter Chinese add-friend content from log table and write to hourly cluster table", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n### Task Objective\nFilter Chinese content from the add-friend log table for the specified hour, deduplicate, and write to the hourly cluster table.\n\n### Input\n- `internal_platform_db.log_17047_query_engine_131`\n\n### Processing Rules\n1. No joins, single-table processing\n2. Filter conditions:\n - `day_ = '2026-06-09 00:00:00'` AND `hour_ = '2026-06-09 14:00:00'`\n - `commfrinum_ = 0`\n - `appname_ IN ('app_hello_txt', 'app_add_contact', '')`\n - `length(content_) >= 6`\n - `scene_ IN (1, 3, 10, 13, 15)`\n - `content_` contains Chinese characters (`rlike '.*[一-龥]+.*'`)\n - Number of Chinese characters > 3 (`length(regexp_replace(content_,'[^一-龥]','')) > 3`)\n - Exclude records where `content_ = concat('我是', nickname_)` AND `nicknameupdatetime_ + 86400 * 30 < timestamp_`\n3. Deduplication: `SELECT DISTINCT content_`\n4. Limit: `LIMIT 1600000`\n\n### Output Requirements\n- Output field: `content_` (STRING)\n\n### Write Requirements\n- Target table: `internal_platform_db.data_team_member14_addcontent_cluster_hour_cand_query_engine_131`\n- Write method: `INSERT INTO`\n- Partition: `ds = '2026060914'`\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT INTO TABLE internal_platform_db.data_team_member14_addcontent_cluster_hour_query_engine_131 PARTITION(ds='2026060914')\nselect distinct content_\nfrom internal_platform_db.log_17047_query_engine_131\nwhere day_='2026-06-09 00:00:00' and hour_ = '2026-06-09 14:00:00'\nand commfrinum_=0\nand appname_ in ('app_hello_txt', 'app_add_contact', '')\nand length(content_)>=6\nand scene_ in (1, 3, 10, 13, 15)\nand length(regexp_replace(content_,'[^一-龥]',''))>3\nand content_ rlike '.*[一-龥]+.*'\nand not ( content_=concat(\"我是\", nickname_) and nicknameupdatetime_ + 86400 * 30 < timestamp_ )\nlimit 1600000", "expected_csv": "content_\n加好友一起聊天交流分享\n你好我想加你好友认识\n这是一个测试内容信息", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数2(含分区列ds) + 列名匹配\nC,C_row_alignment,row_consistency,15,行数比例(7) + key(content_)覆盖率(8)\nD,D_values,values,40,content_列值集合匹配率\nF,F_insert_overwrite,insert_overwrite,5,写入模式应为 INSERT INTO\nF,F_partition_value,partition_value,5,ds='2026060914'\nF,F_regex_filters,regex_filters,10,SQL中包含正则过滤关键模式(regexp_replace/rlike + length条件)\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,content_\n# 预期列数,\n# 输出表,internal_platform_db.data_team_member14_addcontent_cluster_hour_cand_query_engine_131", "path": "tasks/offline-compute/HiveSQL/hivesql_021_en"} {"task_id": "hivesql_022", "id": "offline-compute_HiveSQL_hivesql_022", "name": "从 internal_platform_db.log_16159_query_engine_134 表中提取审核数据,过滤 ds=202", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:将日志表中符合特定条件的审核记录解析并转码,生成包含标签名称的可读审核结果表。\n\n输入:\n- internal_platform_db.log_16159_query_engine_134(包含审核日志字段:ds, functype_, actiontype_, othercol1_, resultinfo_, auditid_, operator_, strategyid_, orderid_, providerid_, uniqueauditid_, audittime_, createtime_, receivetime_, queue_label_)\n\n处理规则:\n1. 过滤条件:ds=2026060916、functype_=2141、actiontype_=3\n2. 字段提取(使用正则):\n - 从 othercol1_ 提取:bizuin(regexp_extract(othercol1_, 'bizuin:(.*?);'))、nickname(regexp_extract(othercol1_, 'nickname:(.*?);'))\n - 从 resultinfo_ 提取:account_tag 字符串(regexp_extract(resultinfo_, 'account_tag:(.*?);')),按 '\\*sc\\*' 分割为 account_tag1、account_tag2、account_tag3;remark(regexp_extract(resultinfo_, 'remark:(.*?);'))\n3. 时间格式转换:audittime_、createtime_、receivetime_ 从 Unix 时间戳转为 yyyyMMddHH 格式\n4. Join 操作:定义硬编码标签映射表(label_name 和 label 两列,包含约 100 条映射),对 account_tag1、account_tag2、account_tag3 分别 LEFT JOIN 映射表,得到 account_tag1_string、account_tag2_string、account_tag3_string\n\n输出要求:\n- 字段顺序:ds, bizuin, nickname, account_tag1, account_tag2, account_tag3, account_tag1_string, account_tag2_string, account_tag3_string, remark, auditid_, operator_, strategyid_, orderid_, providerid_, uniqueauditid_, audittime, createtime_, receivetime_, queue_label_\n- 分区字段:ds=2026060916\n\n写入要求:INSERT OVERWRITE 到 internal_platform_db.dwmid_daily_ecommerce_shop_level_func_2141_audit_result_cand_query_engine_134 的 ds=2026060916 分区。\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "insert overwrite table internal_platform_db.dwmid_daily_ecommerce_shop_level_func_2141_audit_result_query_engine_134 partition(ds ='2026060916')\nwith audit_result as\n(\nselect 2026060916 ds,regexp_extract(othercol1_,'bizuin:(.*?);')bizuin,\nregexp_extract(othercol1_,'nickname:(.*?);')nickname,\nsplit(regexp_extract(resultinfo_,'account_tag:(.*?);'),'\\\\*sc\\\\*')[0] account_tag1,\nsplit(regexp_extract(resultinfo_,'account_tag:(.*?);'),'\\\\*sc\\\\*')[1] account_tag2,\nsplit(regexp_extract(resultinfo_,'account_tag:(.*?);'),'\\\\*sc\\\\*')[2] account_tag3,\nregexp_extract(resultinfo_,'remark:(.*?);')remark,\nauditid_,operator_,strategyid_,orderid_,providerid_,\nuniqueauditid_,\nfrom_unixtime(audittime_,'yyyyMMddHH') audittime,\nfrom_unixtime(createtime_,'yyyyMMddHH') createtime_,\nfrom_unixtime(receivetime_,'yyyyMMddHH') receivetime_,\nqueue_label_\nfrom internal_platform_db.log_16159_query_engine_134\nwhere ds = '2026060916'\nand functype_ = 2141\nand actiontype_ = 3\n),\nlabel as\n(\nselect '精品' as label_name,900 as label union\nselect '品牌店铺' as label_name,9001 as label union\nselect '专业店铺' as label_name,9002 as label union\nselect '优体验店铺' as label_name,9003 as label union\nselect '无问题' as label_name,800 as label union\nselect '商品品类杂糅' as label_name,8001 as label union\nselect '商超店铺' as label_name,8002 as label union\nselect '无问题' as label_name,8003 as label union\nselect '待优化' as label_name,700 as label union\nselect '购买场景不适用' as label_name,7001 as label union\nselect '商品不可购买' as label_name,70011 as label union\nselect '条件限制商品' as label_name,70012 as label union\nselect '店铺信息随意' as label_name,7002 as label union\nselect '头像设置随意' as label_name,70021 as label union\nselect '商品图片随意' as label_name,70022 as label union\nselect '商品标题随意' as label_name,70023 as label union\nselect '商品属性信息填写随意' as label_name,70024 as label union\nselect 'sku信息设置不规范' as label_name,70025 as label union\nselect '店铺整体随意' as label_name,70026 as label union\nselect '商品重复铺货' as label_name,7003 as label union\nselect '重复铺货(轻微)' as label_name,70031 as label union\nselect '重复铺货(严重)' as label_name,70032 as label union\nselect '图片不规范' as label_name,7004 as label union\nselect '商品主体不明' as label_name,70041 as label union\nselect '图片非真实' as label_name,70042 as label union\nselect '商品详情页质量差' as label_name,70043 as label union\nselect '商品图片重复/单一图片' as label_name,70044 as label union\nselect '标题不规范' as label_name,7005 as label union\nselect '关键词/品类词堆砌' as label_name,70051 as label union\nselect '与商品无关字符' as label_name,70052 as label union\nselect '店铺综合质量差' as label_name,7006 as label union\nselect '标题图片不规范' as label_name,70061 as label union\nselect '语言规范' as label_name,7007 as label union\nselect '汉语言' as label_name,70071 as label union\nselect '其他语言规范' as label_name,70072 as label union\nselect '不规范营销' as label_name,7008 as label union\nselect '霸王条款' as label_name,70081 as label union\nselect '个人敏感信息' as label_name,70082 as label union\nselect '引人不适(轻微)' as label_name,7009 as label union\nselect '推荐体验差' as label_name,7010 as label union\nselect '画风抽象恶搞' as label_name,701001 as label union\nselect '画风低俗' as label_name,701002 as label union\nselect '特殊需求群体' as label_name,701002 as label union\nselect '店铺名称头像不规范' as label_name,7011 as label union\nselect '泛低质' as label_name,600 as label union\nselect '引人不适(严重)' as label_name,6001 as label union\nselect '低质量图片' as label_name,6002 as label union\nselect '商品图片盗图' as label_name,60021 as label union\nselect '图片明显标记' as label_name,60022 as label union\nselect '滥用标题' as label_name,6003 as label union\nselect '品牌蹭流' as label_name,60031 as label union\nselect '标题作弊' as label_name,60032 as label union\nselect '滥用同款关键词' as label_name,60033 as label union\nselect '串类目蹭流' as label_name,60034 as label union\nselect '商品信息不一致' as label_name,6004 as label union\nselect '绕类目' as label_name,6005 as label union\nselect '导流' as label_name,6006 as label union\nselect '名称头像导流' as label_name,60061 as label union\nselect '商品导流' as label_name,60062 as label union\nselect '诱导营销' as label_name,6007 as label union\nselect '低价诱导' as label_name,60071 as label union\nselect '利益诱导' as label_name,60072 as label union\nselect '宣传标语/图片夸张博眼球' as label_name,60073 as label union\nselect '额外购买门槛' as label_name,60074 as label union\nselect '不实互动诱导行为' as label_name,60075 as label union\nselect '虚假营销' as label_name,6008 as label union\nselect '商品销量虚假宣传' as label_name,60081 as label union\nselect '价格/折扣虚假宣传' as label_name,60082 as label union\nselect '滥发/虚假使用品牌专柜词' as label_name,60083 as label union\nselect '色情低俗(轻微)' as label_name,6009 as label union\nselect '店铺名称不规范' as label_name,6010 as label union\nselect '商品低质' as label_name,6011 as label union\nselect '疑似仿冒/非原创' as label_name,60111 as label union\nselect '违规风险' as label_name,500 as label union\nselect '店铺信息违规' as label_name,5001 as label union\nselect '混淆蹭流' as label_name,50011 as label union\nselect '不当营销名称' as label_name,50012 as label union\nselect '宗教' as label_name,50013 as label union\nselect '违法违禁' as label_name,5002 as label union\nselect '违法犯罪' as label_name,50021 as label union\nselect '售假山寨' as label_name,50022 as label union\nselect '未开放服务' as label_name,50023 as label union\nselect '劣迹负面艺人' as label_name,50024 as label union\nselect '色情低俗(严重)' as label_name,5003 as label union\nselect '时政敏感' as label_name,5004 as label union\nselect '社会热点' as label_name,50041 as label union\nselect '政治敏感' as label_name,50042 as label union\nselect '恐怖组织/邪教' as label_name,5005 as label union\nselect '违规营销' as label_name,5006 as label union\nselect '违反社会风尚' as label_name,5007 as label union\nselect '不文明用语' as label_name,50071 as label union\nselect '不良价值观' as label_name,50072 as label\n)\nselect bizuin,nickname,account_tag1,account_tag2,account_tag3,\nt2.label_name account_tag1_string,t3.label_name account_tag2_string,t4.label_name account_tag3_string,\nremark,\nauditid_,operator_,strategyid_,orderid_,providerid_,\nuniqueauditid_,\naudittime,\ncreatetime_,\nreceivetime_,\nqueue_label_\nfrom\n(\nselect bizuin,nickname,account_tag1,account_tag2,account_tag3,\nremark,\nauditid_,operator_,strategyid_,orderid_,providerid_,\nuniqueauditid_,\naudittime,\ncreatetime_,\nreceivetime_,\nqueue_label_\nfrom audit_result\n)t1\nleft join\nlabel t2 on t1.account_tag1 = t2.label\nleft join\nlabel t3 on t1.account_tag2 = t3.label\nleft join\nlabel t4 on t1.account_tag3 = t4.label", "expected_csv": "bizuin,nickname,account_tag1,account_tag2,account_tag3,account_tag1_string,account_tag2_string,account_tag3_string,remark,auditid_,operator_,strategyid_,orderid_,providerid_,uniqueauditid_,audittime,createtime_,receivetime_,queue_label_,ds\nbiz002,shop_B,8001,6001,5002,商品品类杂糅,引人不适(严重),违法违禁,another_remark,5002,op_user2,102,order2,provider2,90002,2024060616,2024060616,2024060616,20,2026060916\nbiz001,shop_A,900,9001,700,精品,品牌店铺,待优化,test_remark,5001,op_user1,101,order1,provider1,90001,2024060616,2024060615,2024060615,10,2026060916\nbiz003,shop_C,60031,,,品牌蹭流,,,third_remark,5003,op_user3,103,order3,provider3,90003,2024060616,2024060616,2024060616,30,2026060916", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数20 + 列名匹配\nC,C_row_alignment,row_consistency,10,\"行数比例 + key(uniqueauditid_,strategyid_,orderid_,providerid_)覆盖率\"\nD,D_regex_extraction,regex_extraction,20,\"正则提取字段逐行匹配(bizuin,nickname,account_tag1/2/3,remark)\"\nD,D_account_tag_mapping,account_tag_mapping,25,\"标签映射字段逐行匹配(account_tag1_string,account_tag2_string,account_tag3_string)\"\nD,D_time_and_passthrough,time_and_passthrough,10,\"时间转换+直传字段逐行匹配(audittime,createtime_,receivetime_,auditid_,operator_,queue_label_)\"\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE 写入模式\nF,F_partition,partition,5,ds=2026060916 分区正确\nF,F_null_handling,null_handling,5,LEFT JOIN 无不当 NULL\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,\"uniqueauditid_, strategyid_, orderid_, providerid_\"\n# 预期列数,20\n# 输出表,internal_platform_db.dwmid_daily_ecommerce_shop_level_func_2141_audit_result_cand_query_engine_134", "path": "tasks/offline-compute/HiveSQL/hivesql_022"} {"task_id": "hivesql_023_en", "id": "offline-compute_HiveSQL_hivesql_023", "name": "Compute multi-dimensional CUBE aggregation of user open-start-path data by referer_type, referer, and path", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Compute multi-dimensional aggregation metrics from the user open-start-path detail table, outputting UV and first-time UV across three dimension combinations: application category (`referer_type`), source application (`referer`), and launch path (`path`).\n\nInputs:\n- `internal_platform_db.t_ed_mapservice_user_open_start_path_dwd_di_query_engine_135`\n- `internal_platform_db.t_ed_mapservice_user_q36_active_dwd_di_query_engine_135`\n\nProcessing Rules:\n1. Main table filter: `ds=20260608`, and `referer` must be in the specified lists of application package names/keys for three categories (FoodChainA, QuickDog, JD).\n2. Path cleansing: Process the `path` field according to rules — if it matches `qqmap://map/routeplan?type=\\w+`, retain the original value; if it contains `?`, truncate to the part before the question mark; if it is empty/null/`'NULL'`, set it to `'未知'`; otherwise, retain the original value.\n3. `referer_type` mapping: Map the `referer` value to one of three categories: `'FoodChainA'`, `'CourierCoB'` (QuickDog), or `'EcommerceC'` (JD).\n4. Join: Join with `t_ed_mapservice_user_q36_active_dwd_di_query_engine_135` (`ds=20260608`, `uin` deduplicated) on `uin`, retaining active users.\n5. Aggregation: Group by `referer_type`, `CUBE(referer, path)`, computing `count(distinct uin)` as `uv` and `count(distinct case when is_first=1 then uin end)` as `first_uv`.\n6. CUBE result processing: For dimensions where `grouping` is 1, set the value to `'total'`.\n\nOutput Requirements:\n- Field order: `referer_type`, `referer`, `path`, `uv`, `first_uv`, `ds`\n- `referer` and `path` display as `'total'` on CUBE summary rows\n- `uv` is of type BIGINT, `first_uv` is of type BIGINT\n\nWrite Requirements:\n- Output table: `internal_platform_db.t_md_mapservice_user_open_start_path_dwa_di_cand_query_engine_135`\n- Partition: `ds=20260608`\n- Write method: `INSERT OVERWRITE`\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "insert overwrite table internal_platform_db.t_md_mapservice_user_open_start_path_dwa_di_query_engine_135 partition(ds=20260608)\nwith t as (\nselect \nevent_time,platform,app_version,channel,t1.uin,event_code,event_value,city,brand,device_id_type,bg,event_timestamp,referer,path,is_first\n,case when referer in ('com.foodchain_a.android.activity','FoodChainA','com.jooyum.s2pFlutter','com.jooyum.s2p','ZPVBZ-HDXWU-NQCVT-G76JZ-NMJ2H-M4FRN','ZDSBZ-HICKQ-YBW5C-4KX5E-QOXEZ-MPBI2','XTJBZ-F546Z-I6GXC-7NWJS-35WDV-RSFP5','WPRBZ-VIY6Q-NS45V-457XZ-3XUZJ-ZEFZH','U7VBZ-6XSWI-5VLGP-UYDPQ-EYNTF-4EFEJ','TUPBZ-M7GWQ-EYL5Q-2BYZ2-5WDQV-C7B7E','TOPBZ-WGE65-MNLI5-IGBOS-X3IHQ-YBBY4','RP5BZ-K5ZKZ-2CTXC-T3VKM-UQDO3-FRFYB','QB3BZ-KMC6W-G4NRU-YON5I-ORFV2-RCBFD','OZIBZ-GKVCN-ZHSFP-SAA5H-UO3ZV-D3F5Q','OZCBZ-ZN4KT-K7RXH-VFR3V-J4TPZ-OFBGJ','OW5BZ-QNACB-2RGUS-NV54M-4TEU2-JQB24','KBJBZ-UNHKM-KQH6E-67NMF-DDCGT-LLBWQ','KAWBZ-227KP-F73D6-L4JDM-6K6H5-SYFVU','IARBZ-EDBCA-BYCK7-CW7UG-LF5JS-DWFWO','HW3BZ-RQCLT-CKBXW-VWELQ-IIMGS-YVF7J','7YLBZ-2IKWM-65U64-66SIM平台Q-Y5SG7-MBBO6','3NVBZ-LALKB-A5CUC-N3IYU-S3FV6-TAFZY','3FABZ-UUIE7-TMAXI-HXWPA-XQONZ-IWBTP','2K2BZ-NVFKJ-7T3FU-DPCNP-X3IJO-N2FE6') then 'FoodChainA' \nwhen referer in ('com.couriercob.huoyun','couriercob','topapp.couriercob.directionx','topapp.couriercob.direction') then 'CourierCoB' \nwhen referer in ('com.delivery_d.mobile.android','EcommerceC秒送骑士','达达秒送骑士','达达骑士','com.dada.knight.hm','com.ecommerce_c.mall','ZZLBZ-PDU6F-POPJ3-NAMUM-GQJXV-WNBQI','ZX5BZ-53WHV-6QAP5-UZRK5-O3D5J-2PF2J','ZTABZ-76XRW-2ZRRR-OUCJW-47TS5-MXFIG','ZKKBZ-OFMWJ-DUWFN-FIM平台Q5U-ULITH-TXFCF','ZFVBZ-3P2KU-EKWVK-BN4O2-G6BWZ-Z2FIZ','Z6SBZ-ZB7CV-ZWUPO-5XZPI-6ZB4O-M2BZY','YVCBZ-PANKF-MQ5JM-N3HHT-TGW32-WXBYJ','YUNBZ-M5SWQ-5US5V-GJF6B-LU5X7-L6BS2','YRHBZ-7J2WV-GHFPD-5SS3Z-QXOC6-XJB2D','YLLBZ-3U5KJ-442FD-FM6LV-XOOCV-W5F7V','YKPBZ-3ZHKQ-EJN56-4WVGP-2UTD7-XXFPM','YHZBZ-6KUKG-IXYQH-IH2RF-AVZAJ-4LBVG','YEABZ-MA33X-2OR4T-TLTG6-ATGCV-DKBWY','Y4DBZ-OR5KP-CQIDE-VDFLC-CRFGK-ZNBBC','Y3LBZ-OVSRX-JTR4K-ZGEAY-VHWPZ-LPBGE','XZFBZ-ZL4KS-2KUO5-6S5LD-A47AV-BBF6Z','XXIBZ-EG3KS-EGNOH-6JPV5-LZQ3F-4MBTC','XX2BZ-U6C66-E2XSO-M4VV7-F5VE3-QUB3P','XUNBZ-Y5DK7-OOOXA-P5R7W-GNVOS-KHBJD','XSABZ-MKVC3-MMJ3U-R25R2-YZHCS-BTBZV','XRPBZ-GSQKQ-G3U5J-4NSC4-MXL4Q-Q7FFJ','XNTBZ-5NSWU-O32VI-2CV24-3TPBE-PBFTV','XJXBZ-AI5LU-AYSVB-BWHEJ-CGPZ6-XZBDA','XENBZ-NEH3J-I6HFS-K3WPP-IACAO-3KBLL','X6OBZ-JA3KJ-LYKFN-F6YQZ-YSIH3-MAB4L','X5PBZ-LS4K3-3GS3H-YGWU2-HSOWZ-C6BD3','WX4BZ-LBZC2-BA3UR-CJAWJ-6PVNS-S2F24','WWSBZ-ON3WX-BNQ4O-ZLAJA-4XPSJ-THFSC','WUZBZ-ENAWJ-2ZOFB-KAUKC-GSFMF-MAFAE','WQPBZ-RB7R2-TDLUB-CP4KZ-X4ZW3-NJBWN','WQKBZ-K3QHW-XVURR-37EXR-FIJ3E-U3BCG','WONBZ-ORHCL-5USP6-MNLYR-47Z2T-HNFUG','WLSBZ-5MKCU-L5IVM-2WFBE-CNNEZ-7QFQF','WLHBZ-JX6OW-KK5RL-YY63F-64JN3-XMFWG','WK6BZ-CHL6F-Q6JJX-J5BE4-JSN6K-VWFEB','WJ6BZ-JQJK3-VUI3J-YLLBJ-Y2DWS-FEFFM','WGQBZ-3HSR4-D7OUM-XWNS4-VDQ22-XCBYH','WF2BZ-JRCWW-YNVRX-3EOZC-QWXAJ-APFIO','WDPBZ-3IUKM-6IQ64-6YCC7-OQTD2-IIF5E','WC4BZ-RLGK5-LLAI2-IM平台QZZ7-HW47V-MMFIQ','WBLBZ-MPI33-KCS3K-Y3O56-IPXWH-UPBUQ','WBBBZ-GEPW6-I7DSA-MMCFV-LSCX7-VLB77','WB6BZ-7AOWK-PREJZ-AWMIR-JEXNO-5IBB4','WAWBZ-7HI3X-KUG4N-Z2Q5A-URJ6J-RZBT7','WA6BZ-3TN6F-PTYJH-N4U2N-WLJ35-2YFBT','W7FBZ-EVU65-ELVIZ-QZ3ES-PCKO6-CBFG7','W6JBZ-SZGK4-4KKUS-XL2WH-NC425-Z5BLY','W64BZ-QLMRW-ABPRE-OJP6G-5MZJJ-SCB54','VVZBZ-QGVKT-324XO-LRJPN-C7XDT-KDBGF','VN2BZ-O6YCJ-46SF4-KV7ND-CBM56-G6BE6','VKEBZ-S2SCK-5AMJU-ANYMZ-5F55H-ZVBUA','VJSBZ-JJVKR-S7YWV-WGCJ5-LMWPE-3FFJU','VEOBZ-KMYC6-4K7SJ-E42RI-VXGWQ-K2BYM','VB5BZ-URGWI-P46GJ-5TU4Z-6HAD6-RABYZ','VAYBZ-QVN6X-2GG4C-ZSRCY-P4A3J-PSBTJ','V4GBZ-NIZCG-SYYQH-IEHM2-6U2DV-HYBTJ','UWIBZ-DPEKD-KZ44R-HRQXO-TBYIZ-UOF3Z','URNBZ-XJ7CV-KXUPB-5BBOH-YSGG7-TRFER','UNIBZ-RG53P-EXPD3-V3K3J-MWD47-ZDBMO','UIWBZ-GMHE3-RMA3D-3QWOS-OOPW5-NLFNI','UI2BZ-JGQKS-SPJOW-6V7MA-7DACS-LMBJH','UDEBZ-AC6LV-5YEPU-UQPBQ-ZUQUQ-JBF4N','UALBZ-W数据仓库DWU-J47VQ-4KX4R-3UPW3-BEFYZ','U5WBZ-FCKWF-BLOJL-JCSMG-AKUY3-4IB55','U4ZBZ-PLQLU-LZ5VM-2A3YV-ROE2K-VSBNV','TWQBZ-QNWWM-W3Y6Y-6VQIY-GIDBF-7QFNJ','TVXBZ-WGC33-BFE35-3YMNI-MDJJ7-KUB4J','TUKBZ-5PRWF-MDNJ2-JLFXE-I6C72-JLBEX','TSVBZ-2TOWD-MLB4H-H6QND-BCDFF-UNBA6','TSSBZ-OYCWU-C3RVQ-4PTW6-MJ5XF-3PFB7','TQYBZ-BY464-CPWUZ-DN7UF-CXN4F-BJFU6','TMABZ-73FCT-QHDXC-L2FXB-WDW2F-MDB36','TM6BZ-MREWX-M674T-7Y577-HUHT5-73BRI','TLGBZ-ZQ2L5-5EYIW-QXWRQ-GZY7O-GRBJ7','TL7BZ-4E7KM-Q6Y6Y-6REVK-Z54RQ-OIBZ4','TJZBZ-UAZLJ-KDOFO-XZST5-LETF3-3PF6Q','TJ3BZ-2VN3D-6LW4P-P2V2R-J3SLK-OOFSS','THCBZ-HSY3J-YFEFB-F65JZ-GUAYH-7OFV5','TDMBZ-L7BWJ-XNOF3-F3J7H-7YVYE-BLBJ7','T6TBZ-34Z6Q-DCM55-2DWW7-PZDR3-QFF7W','T35BZ-FLSW5-6HTIH-IUMMI-D2MUH-ZOBXE','SZ6BZ-5PQWQ-BWO5M-BN2MP-KTUPJ-TNF57','SYSBZ-6FEC3-OYQ3L-OU7G6-74RZ2-IZFQA','SXTBZ-BOSWV-7R4PP-UJYEB-ZSF3F-3ABGZ','SUTBZ-2TOWC-HJR2P-ALIS3-MJC37-KNFHK','SU3BZ-ZYMYJ-IZ7FU-D3SCZ-P3W6J-4JFCZ','SS6BZ-BJQLS-7UEO7-63YPZ-CKIYV-LRBNP','SN4BZ-HJBWH-L3MD3-W5XNH-O2HR7-ZJFXW','SKJBZ-2NPCW-SYPR4-RDNEB-UPHP3-VNFF4','SJNBZ-DHWKD-DZ44H-HZTPA-5TGIE-3GFMK','SHNBZ-UQCKP-M5IDN-VZH5O-VEUEE-4SBGS','SGGBZ-L7BRL-NXRPA-EZOGT-TEYJ5-6EBNL','SFABZ-HQAKR-RRUWO-WPRRX-5RDYE-RTFPH','S5JBZ-I56K3-K2O3U-O3LKZ-VZBJ3-Y7BLH','S4YBZ-JXWE2-6RSUP-CJWMQ-JOBX2-6NF3D','S3DBZ-XUOCX-RDC4K-77XXV-RP262-NNBEB','RTDBZ-QWNWB-FRUUP-J4YBH-LVS5T-T7FC4','RICBZ-VHI65-IA4IB-QSTW5-SWUJK-H4B2G','RCNBZ-2A56D-CUZ4W-PRRI4-TMCFH-N5F7H','RAXBZ-CEZL3-VDN34-3QGSC-PXJVS-UCBFQ','RA4BZ-2UN6S-JVYO5-654A2-VVX42-CZBPI','R5XBZ-VPX3U-FV4VJ-2CCEG-M4PNF-R3FZR','R36BZ-5DXK6-2M4SI-MPQYI-CF4PO-IOB6Q','QZOBZ-XSAKU-FLFVN-BKHFO-KIKC3-IBBEV','QZIBZ-GGRLR-L2EWA-WJTQN-2YPBK-X7B3O','QUWBZ-A6JCJ-WY7FR-KMHQI-35GHO-RZBDJ','QRPBZ-5YLLU-GHMVC-BPOKS-N5KAE-FDF5R','QMCBZ-PLTC3-N443X-YS6EC-IS4YZ-NYBBT','QCFBZ-XFPHU-RLBVL-B7FZG-ALZOK-GGFXC','Q73BZ-DOGWQ-V3V5G-4ADG2-DTAZ3-QOFGC','PWTBZ-3QPCQ-ZMW53-GZA6H-YO7QF-5FFML','PVBBZ-ZYVCF-CI7J3-JZBV7-VXARZ-4MFU7','PRTBZ-2HZE4-TLHUA-D3KVI-T5GJQ-WFFAX','PQDBZ-O2B3H-4ZLDA-WTTJK-Q4CMF-RJB66','PJHBZ-EHDCN-R7FFD-SYVY4-IWH3H-VMBS5','PIXBZ-ZRREQ-O6G5D-2Y4K3-IMMAH-BXFB3','OW4BZ-MAZL7-LOTXV-HVTA3-XUWZK-2KBBO','OS3BZ-GC2CN-CL7FB-STVNJ-YW3S2-7MFIH','OQVBZ-WAD6X-RMY4Z-7XZJG-Q7AMH-FPFP6','OOUBZ-KKX3W-7JSR4-R2AQG-U6R6T-RXBMI','OMZBZ-EMQK4-DCIUU-DHOQA-XLPPK-3GFTM','OLVBZ-7L2HG-YPGQE-I3NON-J3X5Z-3CFQL','OL3BZ-ZBIKX-DHL4B-7EEWX-N33F6-N5FZQ','OH4BZ-RDVKP-RNSDY-VQKUA-SPQGE-7QFCY','OCKBZ-ZAGKK-RXLJR-A3PAM-YO7QH-V6FMJ','NZFBZ-EVYLZ-WQMXM-TYJRV-ZNYYF-W5FCZ','NYSBZ-EJLLC-HDT2X-A3ZPN-ISW3V-4JBBF','NU3BZ-JAPWV-VVNP7-5CEVQ-7NXXZ-R6BKN','NSKBZ-5VYKL-PFTPA-ESBZB-LGDF6-YEFKN','NRXBZ-PNV3R-LCPWU-WL562-YA427-NXBND','NQ4BZ-U7Y6D-7OM4W-HODRT-LK5Z6-DLBT4','NPFBZ-YZNKW-OIMR2-OIK23-OZPQ7-BVFWI','NMQBZ-WKRCQ-FFX5J-BFCGT-ORQHO-MFBXD','NJXBZ-ALDWU-HXSVU-27OKA-U4RE7-RQBGU','NIDBZ-A5TWU-G22V6-B25Y3-HQ6RV-MSFBQ','NENBZ-TUCW4-LL4U5-XGLVN-6YTPJ-CFBQ7','NDPBZ-SPFWW-2J6RH-RFUV3-CYPVK-XRFQ3','NC5BZ-4S2CP-UKODO-L4557-ZGPRO-DXBIE','NBWBZ-6URYV-Z6ZPL-5ISTO-TJW23-6TFNV','NAZBZ-5BYWL-JENPH-EV6GL-75ZMQ-L6B2Q','N7HBZ-ORS6J-AYQF3-KBXS3-VFRIV-QOBYY','N6VBZ-FLTWD-MAM4Q-HZR6Q-CVNV7-OOFE4','N6HBZ-6GSCU-R4YVE-BBFYK-KVP3T-F5BZJ','MVPBZ-KU7CP-YIPDZ-VFN4W-FDFMT-NTFMR','MVLBZ-FCW6Q-RIL5G-G5WTY-EV4PT-GQB4U','MPMBZ-ML5CU-V4OVT-BDVGM-K3NMQ-JIBRP','MFHBZ-S77KZ-N5YXF-TCKSB-HCOY6-PNF7K','MDIBZ-OZ6KU-REJV2-B5G46-HUJY7-IHFXS','MBCBZ-DE3LN-55AFX-SG2IE-2RYHT-ZJFQO','M6PBZ-QPUAF-KSJJD-JFNMG-NS5F2-UDB7F','LW7BZ-TK23O-SFQWS-SP6ZB-OD2J3-MNB6T','LVQBZ-N3PRG-VOTQC-I6MIR-EAAKK-TJBLZ','LUSBZ-HVG33-CXH3W-RCONB-6UMIK-ELBFL','LKMBZ-LVVK6-KG2SJ-E34GA-CHH7H-P5BIX','LHMBZ-R6CK2-V4FUE-CCFN7-AVGDF-SCFKF','LHKBZ-2IQ6U-HYRVB-45WJ7-KYKY3-67FHU','LBKBZ-ZP53Q-IBY5T-4TL3J-SDAM2-FKBYB','L6LBZ-Y3DLC-6UO2U-AJSTD-3TNR3-NLBOU','L4QBZ-4TOKG-7OKQE-QLF7O-IYCE3-S3F44','KZ2BZ-4S4RV-2TOP6-URXZA-MQD4T-6GBOK','KUEBZ-2OWCU-DP7VP-4QHTL-PMY66-RSFJC','KOHBZ-T3Q34-IBLU5-XWIEP-POSSO-SQBZV','K6IBZ-T4DCU-X5OVA-4GHZ6-WSYWO-K6BYJ','K2MBZ-AH2CR-6GWWL-WRT2W-QWLTT-O4FWV','JXJBZ-IORWR-CVDWX-WCZHK-M762V-RTFUU','JVSBZ-2KBW3-DK33H-33SVV-LYWVT-GDFAQ','JVKBZ-TN33Z-D2KXG-TJQDB-TCJNO-UKB6B','JUVBZ-FZYLJ-EMQFS-XZNK5-AT4UT-ASBDL','JQMBZ-UQ5ES-H6TON-6QLUQ-AM5P7-LXF7Z','JQHBZ-6T4RI-AHBGM-52MTT-UEKF7-WVFMR','JOEBZ-MTVHP-JR6D3-L6DVQ-RMXL7-RLFTI','JN2BZ-WX5C4-TFLUP-XCG3I-7NF2F-VLFEY','JKDBZ-QGTKO-GWFWF-SQ2ZZ-5S2GE-S4FVN','JJVBZ-JG4LV-4AAPM-UPFVK-MEW57-WXF2D','JG7BZ-VJBKO-HG7W7-SGOCJ-2YYYH-TUBFJ','JCVBZ-PHRW3-7VI3J-YXP72-HBHX2-VGB2Z','J4LBZ-W7SKW-HCGRQ-O3WEE-RI4K6-4QBLI','IXBBZ-IFKHF-CIM平台QJF-JBHXY-VP7S3-JVFOL','IWUBZ-SRQLF-KJSJ5-JIO4T-X3AVS-LSFB6','IV4BZ-TY2CV-NDRPU-U4MCE-RVSI5-2YFAA','IUMBZ-Z63W3-ZGS3J-OTXZX-5IAJ5-EZBRB','ITRBZ-PJEC4-JUIUL-XBAWG-OZKTK-3TF54','IOVBZ-R3S6Z-TJVXH-ZJ6QF-7UIUS-TRB6D','INNBZ-UVFWR-HXAW4-WAR6D-2KMDO-ZKBR3','INKBZ-PMMET-OPLX7-LE6XQ-IUNEZ-HSF6A','I6ZBZ-6NP36-W6OSU-MNXRW-RTAPQ-DWFUX','I5HBZ-2CQC4-WERUN-K5PCX-PTGUJ-AHBJY','I5ABZ-GVKHQ-HPF5Q-BLFQP-O6FPH-3XFHN','I2XBZ-H5PW5-HDKIC-IMWLW-4JT6O-QSBCK','HXPBZ-PHZWI-U5OGG-5JDIW-3OIKJ-3FBPR','HU2BZ-XXPC6-L3NSP-M3RDC-MMFP5-QRFPW','HSUBZ-2WS3K-RCLJG-AJRLN-666OK-2CFE6','HSKBZ-5A4C3-LN43L-OAIGR-JZCJJ-LZFKP','HO7BZ-WVQH3-YPC3A-OJE4P-DEQDT-CRF3Y','HJOBZ-EBJW3-Y6R3A-3TID4-CIMD3-CFB5F','HFEBZ-FBNCJ-FVEFY-FCVG2-TOQ5Z-L6FKL','HELBZ-6V5KJ-HEDFF-KZBRN-4XDF5-JFBCK','H7FBZ-DYMC6-4ERSD-MKEGK-PS5PH-6LBHI','H42WY-75WY3-Y4VSE-VXEO5-JWA7A','GWVBZ-7PCK2-XHBUZ-CTNHR-3TY45-7DBNP','GRSBZ-6YGCW-AHYRE-RSUQP-KKIVS-JPFN3','GQEBZ-GNUKS-7APOK-67QIV-Q2K2V-VCBA3','GPLBZ-N23WW-TSBRF-ROZNE-A5PQ3-Q2BUJ','GOOBZ-SDKWU-CNIV6-4CXMK-77YI7-I7BYN','GKEBZ-YYKC4-QLPU6-XNBQ5-CUY4E-22BXW','GANBZ-OWZLU-YJKVS-G5WBV-2FEGQ-P2B67','G2HBZ-YSLCD-BQS4K-PTUBH-AWJWJ-NDFHU','FYBBZ-OHOKN-HMBFJ-S7PG6-D5BZZ-NSBKK','FYABZ-ZLM3W-UM5RX-OZT4N-K5XSV-HTBKW','FRCBZ-CXMC3-YBG3U-YEJGU-YUPWO-ZRFOY','FQHBZ-RUQEJ-NUBFI-K6QF3-5MQ2J-6DFPD','FNJBZ-PM4K5-KAKIK-QJ5O3-WLU3S-PJBGV','FKXBZ-WZ36J-NIHF5-K2PVL-DMIWQ-YZBQ4','FJ5BZ-URIWP-TA5DK-V5AY7-S2DQS-ROF6C','FIUBZ-DSU6X-KUP4H-ZXFGL-W6SN2-UWFH7','FGRBZ-2FJCU-EAMVP-2G7QH-ZZN45-V7BL7','FEBBZ-3FUH2-AGDU2-CACFJ-OILEH-SYF6N','FCTBZ-2HMHJ-BDMFO-FT3FC-IPE3O-G7FLK','FBPBZ-A7Z3X-3MU4V-Z5VGB-53KG3-WEBC5','F6ZBZ-CJK3X-MT64P-TOOKY-GAPGH-TGB5D','F3ZBZ-TQAWX-42L4W-7LKDL-7PF6E-ZGB57','EZRBZ-27CRQ-VRQ5G-43QTK-ZOFK7-MBBCQ','EYHBZ-ENXW3-DHK3N-3AETB-TDFJ2-TWFLX','EXQBZ-NRYLD-KZB46-H4KUD-X63JJ-3BFNX','EVOBZ-EGIWB-PKRUO-NO4ST-RZAV6-GBB66','EQEBZ-N2FLD-MVV4U-HTQBV-43J57-WRBWZ','EM7BZ-OT3RZ-LP3X6-77G5Z-G7ONH-W3FJI','ECZBZ-6UBCF-RTVJT-NELGC-VS7D6-53F66','ECOBZ-VPKW4-AMDUB-XHLW4-5UYCO-BQBC5','EBVBZ-V553U-SGCV4-BONLC-37RRT-SOF56','E57BZ-II4EQ-ZRJ5V-252LK-QNUZO-AGF55','DZNBZ-6ZEWZ-NZCX4-7BIV5-TWU7J-RVBAN','DWGBZ-W3QWZ-E4WXE-7OQG5-GILJJ-SOBIX','DSHBZ-2IR65-SFHIN-QDW4K-R53TO-UMFKO','DOYBZ-2463Q-GMF5Y-BNKN2-3WNJT-6DFGU','DOEBZ-AZ6KS-7NZOQ-6R5WD-GJP5S-4ZFMP','DIDBZ-YFP2U-VKXVR-2FHE6-Z7ZJZ-EJFXZ','DH5BZ-V5N6K-DE4JB-AZNG6-C7SXV-Q2BNO','D4JBZ-XRXEX-XZO4W-TWL2P-66PWS-2YBVK','D24BZ-J7GLQ-T3G5T-GEUQ4-FPVMQ-R5F62','CZBBZ-KGDRT-HQUXZ-V7MLQ-CXNOK-37BGU','CZ7BZ-MXT6F-RC6J5-NY3LQ-WFP3F-OCFDD','CWUBZ-ONSH4-YBXUD-DIUOX-EHV42-RKFLA','CURBZ-YFVH3-66B35-YHMLK-Q53IH-SBFUO','CNDBZ-H4KKD-BNF45-P7NVU-6DRL3-NLFDY','CMUBZ-Z6OWF-57PJS-JCXUX-ZQCO6-44F2Q','CL7BZ-HUD6A-HMGKH-CWO2X-V2NO3-K7BN4','CJXBZ-5ZE3U-WYGVC-4IUHB-ROX3O-QVFWO','CGJBZ-FVWCT-TF7XX-VUDAR-XQYRE-Z3FHJ','CEYBZ-JABWZ-3FCXW-76VMJ-I3GGV-DZBFR','CA3BZ-CE4C7-RTKXM-HNHNO-N6QM5-3ZB3E','C6GBZ-UC7RK-LH2JM-AOZSC-RO2CQ-YSBGS','C6ABZ-VA63U-C7XVU-BNC67-ZQ3HO-F3FWB','C3WBZ-AZHCQ-2NO5C-BFVET-LRTSV-Y3BTM','BQRBZ-CBKKQ-A745F-4KR5E-3AVFT-ZAFFV','BPABZ-7E4LJ-5GCFE-FC645-RIXFJ-6PFRG','BNZBZ-MBPR3-KDB33-YNKYF-HK6AQ-GGBLD','BIBBZ-DUWE6-MGVSF-EZ6JP-OSVFZ-4LBUX','BH5BZ-VPT6Z-MCKXT-ZF2ME-4ZCUH-NEBGY','BCGBZ-IJQKG-H6PQV-INE5X-5QRPZ-2TBOV','BAZBZ-AKVCU-CKGV6-2GUBD-IZV75-MYFS2','AVLBZ-SC6KO-ACNWT-SGVGV-7H4F3-S5B4M','AVIBZ-YEXWI-A4KGK-5HBSA-KOUDJ-3CFRX','AVABZ-EIPWP-7RTDK-L6UQ3-SHYET-V5B6V','ATABZ-JVC6G-DQ7QT-I4INI-6JKLT-YZF24','AQUBZ-XIBWU-EGIV2-GBVYZ-TA3CS-2ABDS','ALMBZ-2OTKC-TXA25-ARGEJ-6OAQZ-4IFCT','AJPBZ-GSAKU-VPUV4-4ZE5K-IF7U2-S4F6Y','AETBZ-C5E64-RHOUO-FI6E2-J6VJZ-QOBIE','AE2BZ-M2FCQ-P6T5D-4NZHY-2Q7PH-GKBAB','AAUBZ-QIMWX-E2W4R-7BY7B-RAAJF-QKBA4','A7LBZ-LFGRZ-3CSX2-72TLZ-ZJZH5-UHB6K','A3TBZ-3GMKS-VXGON-6QKJ4-44752-ZTFJ5','A25BZ-QWECZ-IMRXP-7A55H-TQEPQ-YJFR5','7X4BZ-ZG4RF-RQMJS-NBS7N-UVJ75-G5BMX','7RJBZ-O6I64-XANUL-KKPHS-UOCAJ-EPFPU','7OKBZ-QB6KZ-LJ2XP-ZPBJA-455DQ-GTFRT','7MNBZ-XENKD-LUX4P-HOX5Q-IZB35-YHBVT','7L5BZ-MNBWK-3EGJ3-AMR2R-ETLV7-OTBEQ','7JOBZ-5OF3U-QUNVL-GYLKC-WCM73-U7BSJ','7IUBZ-DTMWI-3TMGU-5Y6UJ-7G2FJ-MHB7K','7FUBZ-HSMWV-7WPPQ-U6JSM-4HNPV-DRBGV','77KBZ-2XCC3-LKI3S-3C6VV-DTUEO-ESB6B','74EBZ-T35WQ-OZP57-GJQWS-LPEPQ-GWBJP','6VZBZ-J6Q6G-DN7QV-QVA4M-TGJMS-VMB6E','6TRBZ-7KN64-Y54U3-DYZ3U-5XCE3-H6BG7','6RQBZ-54BLD-XT74B-HNJC5-UXN4S-SNB2A','6Q5BZ-VGL3J-LRCF5-FCMF3-TJK3Z-XLBU2','6O2BZ-WI26J-QJ7FT-F7EBH-YJXGS-OQBFF','6N4BZ-EHK3X-WXI44-ZAKLI-DZE2K-B6FU3','6LWBZ-ZR7WL-JNUPI-EV4L2-NY3BJ-B3FZW','6FYBZ-3ULN3-4RX3X-3XJWY-2JGQT-NMFK5','6FIBZ-AWZL6-CILSN-EAND2-WZNTO-ZPF6J','6FDBZ-LW262-LMUUO-C6BDS-LWNM5-G5FMT','6BJBZ-SXG6C-BIA23-ASIXC-VPJEE-ESBG4','67ABZ-HLPRQ-XZM53-GNCSR-GNSXF-DSBDK','64HBZ-6M53I-DQ7GJ-5L2I6-6UJQS-QSBEC','63SBZ-2F7WZ-6X4XO-ZCCHG-NBTCE-T3BPH','62VBZ-ZPHCR-E6AWD-WL3XU-KLBRH-V3BG3','5YZBZ-MJH6W-7J5RS-3VYK7-MFSC7-RBBCZ','5V4BZ-KQBC6-V44ST-MBFLW-IJXQO-JRFBP','5POBZ-JFI3J-IY6FQ-KVKDL-BW7B7-56FDX','5PBBZ-A5PC4-77TUH-KHGMD-IQULE-BZFTG','5LZBZ-5JSWX-3CQ4A-ZINRT-FUDG7-7OFSU','5KUBZ-E3YKM-VTX6L-67DTE-ZOA2O-VFBW3','5KQBZ-YGR6P-EDSDJ-VAUU5-GIV23-6UFHO','5HKBZ-SRKCD-5CQ4C-PF56K-NUHCS-QKFKN','5G2BZ-K42CP-NI4DH-V4BHN-BL6BF-BWBL3','5FNBZ-EP2WJ-AK6FK-FUR5W-RKA6Z-RLBSQ','5EZBZ-BBHRW-WEBRF-O2F5N-J7MUS-I6FH7','5EYBZ-HMMCR-DETWU-W2QZL-V3PXT-UDB2J','57SBZ-BCG6P-6KRDU-VC4RA-376DO-YTFKB','55SBZ-ZK63U-AZ5VB-BJD33-XUUZF-FKBZI','55KBZ-V4RCW-4OERQ-O2EYS-D6ZSZ-S5BMP','552BZ-RXYW4-PIIU4-XFZ3V-WQWLJ-7WBLE','4YOBZ-BW7KQ-6WW5C-BLJGI-BZDN7-QABU4','4XCBZ-4GVCK-3EWJ3-A6CCD-CF5D7-XEB3Z','4WJBZ-CUILX-DK642-7BSIM平台Q-KODTZ-BEBCH','4WIBZ-BZRCU-MQHVK-4N62Y-ART3K-2JFTF','4QUBZ-J4FWT-RE3XR-VQUOB-NXO32-GGBOK','4QUBZ-3TQCQ-UIR5Q-GVYXK-UBX6K-PVBMS','4QEBZ-C2HWP-VLBDE-V6LZK-DIM72-VWB34','4OFBZ-IVZKR-UXWWX-WTHNH-Q7KS5-MCBDD','4LDBZ-Z2QLC-WOD23-ASUUK-56TZ7-N2BTX','4KIBZ-2VEWJ-OIMFP-D3NBK-Q3XLE-W5F7Z','4H5BZ-RIEKQ-FOZ5K-BU4CI-BJNJE-3HBRM','4FKBZ-QBWKQ-3HT5N-2SHOO-QGYOQ-AOBYA','4DYBZ-2IJ6X-IEO45-Z4M7A-3IPS7-7IFUV','4ARBZ-RE4KJ-XSUF3-DCMEA-YYAHE-GLFVI','42DBZ-MDEK3-IKS3Q-3MI6O-YN2EE-NJFSL','3WOBZ-WUVKU-B2AV4-4BE6P-SVMDE-7UBOM','3QNBZ-MDCKC-5YS23-AH35L-QDYJS-R6B6T','3PFBZ-XNV67-ZZFXP-HROTO-DXXI3-LFFK4','3JQBZ-XLML4-YZWUG-X5JJY-RXYY2-IFFX4','3HHBZ-QJ6C6-PJSSA-ELG33-X3FVF-HMBNX','3H4BZ-5UXLO-3P2WE-SYGSW-KOUX5-SWFEN','3F7BZ-FTT3G-LFGQE-I7CAD-LIW47-PBBET','3EYBZ-MBJW4-ZMFUH-XHDPO-CUOOH-OOBQM','3DIBZ-KYXY3-GZW3C-OPJ5O-RRF62-7NBPU','37RBZ-6DN66-N2KSK-EH6MX-VAV3F-QLBYJ','36FBZ-PPF3S-UCCO6-6JYDP-EJUGJ-FLBV7','2Z4BZ-R7S6W-COZRH-OH35E-EM52T-FLBGX','2YZBZ-C7L3W-GPTRB-YOGKI-3I2XE-WCBBJ','2YUBZ-WXWLJ-55FFS-KWX4Q-BWXQS-WMFLS','2UBBZ-MKIWP-MNGDA-VGW72-VKZBH-2DFZR','2OOBZ-SPFE4-UJ7UB-KCSVO-POIU6-4VFME','2ODBZ-FEIK4-RHYUZ-XFUVG-X3DCF-7SB5K','2J5BZ-NFMR6-QO3SZ-M5S34-KXMRQ-MZFC7','2EVBZ-MGC6J-2THFU-XGYYL-CHH5T-5QBCB') then 'EcommerceC' else '其他' end as referer_type\nfrom \n(\nselect \nevent_time,platform,app_version,channel,uin,event_code,event_value,city,brand,device_id_type,bg,event_timestamp,referer\n,CASE WHEN path RLIKE '^qqmap://map/routeplan\\\\?type=\\\\w+$' THEN path\n WHEN INSTR(path, '?') > 0 THEN SUBSTR(path, 1, INSTR(path, '?') - 1)\n WHEN path = '' or path is null or path = 'NULL' THEN '未知'\n ELSE path end as path\n,is_first\nfrom internal_platform_db.t_ed_mapservice_user_open_start_path_dwd_di_query_engine_135\nwhere ds = 20260608\nand referer in ('com.foodchain_a.android.activity','FoodChainA','com.jooyum.s2pFlutter','com.jooyum.s2p','ZPVBZ-HDXWU-NQCVT-G76JZ-NMJ2H-M4FRN','ZDSBZ-HICKQ-YBW5C-4KX5E-QOXEZ-MPBI2','XTJBZ-F546Z-I6GXC-7NWJS-35WDV-RSFP5','WPRBZ-VIY6Q-NS45V-457XZ-3XUZJ-ZEFZH','U7VBZ-6XSWI-5VLGP-UYDPQ-EYNTF-4EFEJ','TUPBZ-M7GWQ-EYL5Q-2BYZ2-5WDQV-C7B7E','TOPBZ-WGE65-MNLI5-IGBOS-X3IHQ-YBBY4','RP5BZ-K5ZKZ-2CTXC-T3VKM-UQDO3-FRFYB','QB3BZ-KMC6W-G4NRU-YON5I-ORFV2-RCBFD','OZIBZ-GKVCN-ZHSFP-SAA5H-UO3ZV-D3F5Q','OZCBZ-ZN4KT-K7RXH-VFR3V-J4TPZ-OFBGJ','OW5BZ-QNACB-2RGUS-NV54M-4TEU2-JQB24','KBJBZ-UNHKM-KQH6E-67NMF-DDCGT-LLBWQ','KAWBZ-227KP-F73D6-L4JDM-6K6H5-SYFVU','IARBZ-EDBCA-BYCK7-CW7UG-LF5JS-DWFWO','HW3BZ-RQCLT-CKBXW-VWELQ-IIMGS-YVF7J','7YLBZ-2IKWM-65U64-66SIM平台Q-Y5SG7-MBBO6','3NVBZ-LALKB-A5CUC-N3IYU-S3FV6-TAFZY','3FABZ-UUIE7-TMAXI-HXWPA-XQONZ-IWBTP','2K2BZ-NVFKJ-7T3FU-DPCNP-X3IJO-N2FE6',\n'com.couriercob.huoyun','couriercob','topapp.couriercob.directionx','topapp.couriercob.direction',\n'com.delivery_d.mobile.android','EcommerceC秒送骑士','达达秒送骑士','达达骑士','com.dada.knight.hm','com.ecommerce_c.mall','ZZLBZ-PDU6F-POPJ3-NAMUM-GQJXV-WNBQI','ZX5BZ-53WHV-6QAP5-UZRK5-O3D5J-2PF2J','ZTABZ-76XRW-2ZRRR-OUCJW-47TS5-MXFIG','ZKKBZ-OFMWJ-DUWFN-FIM平台Q5U-ULITH-TXFCF','ZFVBZ-3P2KU-EKWVK-BN4O2-G6BWZ-Z2FIZ','Z6SBZ-ZB7CV-ZWUPO-5XZPI-6ZB4O-M2BZY','YVCBZ-PANKF-MQ5JM-N3HHT-TGW32-WXBYJ','YUNBZ-M5SWQ-5US5V-GJF6B-LU5X7-L6BS2','YRHBZ-7J2WV-GHFPD-5SS3Z-QXOC6-XJB2D','YLLBZ-3U5KJ-442FD-FM6LV-XOOCV-W5F7V','YKPBZ-3ZHKQ-EJN56-4WVGP-2UTD7-XXFPM','YHZBZ-6KUKG-IXYQH-IH2RF-AVZAJ-4LBVG','YEABZ-MA33X-2OR4T-TLTG6-ATGCV-DKBWY','Y4DBZ-OR5KP-CQIDE-VDFLC-CRFGK-ZNBBC','Y3LBZ-OVSRX-JTR4K-ZGEAY-VHWPZ-LPBGE','XZFBZ-ZL4KS-2KUO5-6S5LD-A47AV-BBF6Z','XXIBZ-EG3KS-EGNOH-6JPV5-LZQ3F-4MBTC','XX2BZ-U6C66-E2XSO-M4VV7-F5VE3-QUB3P','XUNBZ-Y5DK7-OOOXA-P5R7W-GNVOS-KHBJD','XSABZ-MKVC3-MMJ3U-R25R2-YZHCS-BTBZV','XRPBZ-GSQKQ-G3U5J-4NSC4-MXL4Q-Q7FFJ','XNTBZ-5NSWU-O32VI-2CV24-3TPBE-PBFTV','XJXBZ-AI5LU-AYSVB-BWHEJ-CGPZ6-XZBDA','XENBZ-NEH3J-I6HFS-K3WPP-IACAO-3KBLL','X6OBZ-JA3KJ-LYKFN-F6YQZ-YSIH3-MAB4L','X5PBZ-LS4K3-3GS3H-YGWU2-HSOWZ-C6BD3','WX4BZ-LBZC2-BA3UR-CJAWJ-6PVNS-S2F24','WWSBZ-ON3WX-BNQ4O-ZLAJA-4XPSJ-THFSC','WUZBZ-ENAWJ-2ZOFB-KAUKC-GSFMF-MAFAE','WQPBZ-RB7R2-TDLUB-CP4KZ-X4ZW3-NJBWN','WQKBZ-K3QHW-XVURR-37EXR-FIJ3E-U3BCG','WONBZ-ORHCL-5USP6-MNLYR-47Z2T-HNFUG','WLSBZ-5MKCU-L5IVM-2WFBE-CNNEZ-7QFQF','WLHBZ-JX6OW-KK5RL-YY63F-64JN3-XMFWG','WK6BZ-CHL6F-Q6JJX-J5BE4-JSN6K-VWFEB','WJ6BZ-JQJK3-VUI3J-YLLBJ-Y2DWS-FEFFM','WGQBZ-3HSR4-D7OUM-XWNS4-VDQ22-XCBYH','WF2BZ-JRCWW-YNVRX-3EOZC-QWXAJ-APFIO','WDPBZ-3IUKM-6IQ64-6YCC7-OQTD2-IIF5E','WC4BZ-RLGK5-LLAI2-IM平台QZZ7-HW47V-MMFIQ','WBLBZ-MPI33-KCS3K-Y3O56-IPXWH-UPBUQ','WBBBZ-GEPW6-I7DSA-MMCFV-LSCX7-VLB77','WB6BZ-7AOWK-PREJZ-AWMIR-JEXNO-5IBB4','WAWBZ-7HI3X-KUG4N-Z2Q5A-URJ6J-RZBT7','WA6BZ-3TN6F-PTYJH-N4U2N-WLJ35-2YFBT','W7FBZ-EVU65-ELVIZ-QZ3ES-PCKO6-CBFG7','W6JBZ-SZGK4-4KKUS-XL2WH-NC425-Z5BLY','W64BZ-QLMRW-ABPRE-OJP6G-5MZJJ-SCB54','VVZBZ-QGVKT-324XO-LRJPN-C7XDT-KDBGF','VN2BZ-O6YCJ-46SF4-KV7ND-CBM56-G6BE6','VKEBZ-S2SCK-5AMJU-ANYMZ-5F55H-ZVBUA','VJSBZ-JJVKR-S7YWV-WGCJ5-LMWPE-3FFJU','VEOBZ-KMYC6-4K7SJ-E42RI-VXGWQ-K2BYM','VB5BZ-URGWI-P46GJ-5TU4Z-6HAD6-RABYZ','VAYBZ-QVN6X-2GG4C-ZSRCY-P4A3J-PSBTJ','V4GBZ-NIZCG-SYYQH-IEHM2-6U2DV-HYBTJ','UWIBZ-DPEKD-KZ44R-HRQXO-TBYIZ-UOF3Z','URNBZ-XJ7CV-KXUPB-5BBOH-YSGG7-TRFER','UNIBZ-RG53P-EXPD3-V3K3J-MWD47-ZDBMO','UIWBZ-GMHE3-RMA3D-3QWOS-OOPW5-NLFNI','UI2BZ-JGQKS-SPJOW-6V7MA-7DACS-LMBJH','UDEBZ-AC6LV-5YEPU-UQPBQ-ZUQUQ-JBF4N','UALBZ-W数据仓库DWU-J47VQ-4KX4R-3UPW3-BEFYZ','U5WBZ-FCKWF-BLOJL-JCSMG-AKUY3-4IB55','U4ZBZ-PLQLU-LZ5VM-2A3YV-ROE2K-VSBNV','TWQBZ-QNWWM-W3Y6Y-6VQIY-GIDBF-7QFNJ','TVXBZ-WGC33-BFE35-3YMNI-MDJJ7-KUB4J','TUKBZ-5PRWF-MDNJ2-JLFXE-I6C72-JLBEX','TSVBZ-2TOWD-MLB4H-H6QND-BCDFF-UNBA6','TSSBZ-OYCWU-C3RVQ-4PTW6-MJ5XF-3PFB7','TQYBZ-BY464-CPWUZ-DN7UF-CXN4F-BJFU6','TMABZ-73FCT-QHDXC-L2FXB-WDW2F-MDB36','TM6BZ-MREWX-M674T-7Y577-HUHT5-73BRI','TLGBZ-ZQ2L5-5EYIW-QXWRQ-GZY7O-GRBJ7','TL7BZ-4E7KM-Q6Y6Y-6REVK-Z54RQ-OIBZ4','TJZBZ-UAZLJ-KDOFO-XZST5-LETF3-3PF6Q','TJ3BZ-2VN3D-6LW4P-P2V2R-J3SLK-OOFSS','THCBZ-HSY3J-YFEFB-F65JZ-GUAYH-7OFV5','TDMBZ-L7BWJ-XNOF3-F3J7H-7YVYE-BLBJ7','T6TBZ-34Z6Q-DCM55-2DWW7-PZDR3-QFF7W','T35BZ-FLSW5-6HTIH-IUMMI-D2MUH-ZOBXE','SZ6BZ-5PQWQ-BWO5M-BN2MP-KTUPJ-TNF57','SYSBZ-6FEC3-OYQ3L-OU7G6-74RZ2-IZFQA','SXTBZ-BOSWV-7R4PP-UJYEB-ZSF3F-3ABGZ','SUTBZ-2TOWC-HJR2P-ALIS3-MJC37-KNFHK','SU3BZ-ZYMYJ-IZ7FU-D3SCZ-P3W6J-4JFCZ','SS6BZ-BJQLS-7UEO7-63YPZ-CKIYV-LRBNP','SN4BZ-HJBWH-L3MD3-W5XNH-O2HR7-ZJFXW','SKJBZ-2NPCW-SYPR4-RDNEB-UPHP3-VNFF4','SJNBZ-DHWKD-DZ44H-HZTPA-5TGIE-3GFMK','SHNBZ-UQCKP-M5IDN-VZH5O-VEUEE-4SBGS','SGGBZ-L7BRL-NXRPA-EZOGT-TEYJ5-6EBNL','SFABZ-HQAKR-RRUWO-WPRRX-5RDYE-RTFPH','S5JBZ-I56K3-K2O3U-O3LKZ-VZBJ3-Y7BLH','S4YBZ-JXWE2-6RSUP-CJWMQ-JOBX2-6NF3D','S3DBZ-XUOCX-RDC4K-77XXV-RP262-NNBEB','RTDBZ-QWNWB-FRUUP-J4YBH-LVS5T-T7FC4','RICBZ-VHI65-IA4IB-QSTW5-SWUJK-H4B2G','RCNBZ-2A56D-CUZ4W-PRRI4-TMCFH-N5F7H','RAXBZ-CEZL3-VDN34-3QGSC-PXJVS-UCBFQ','RA4BZ-2UN6S-JVYO5-654A2-VVX42-CZBPI','R5XBZ-VPX3U-FV4VJ-2CCEG-M4PNF-R3FZR','R36BZ-5DXK6-2M4SI-MPQYI-CF4PO-IOB6Q','QZOBZ-XSAKU-FLFVN-BKHFO-KIKC3-IBBEV','QZIBZ-GGRLR-L2EWA-WJTQN-2YPBK-X7B3O','QUWBZ-A6JCJ-WY7FR-KMHQI-35GHO-RZBDJ','QRPBZ-5YLLU-GHMVC-BPOKS-N5KAE-FDF5R','QMCBZ-PLTC3-N443X-YS6EC-IS4YZ-NYBBT','QCFBZ-XFPHU-RLBVL-B7FZG-ALZOK-GGFXC','Q73BZ-DOGWQ-V3V5G-4ADG2-DTAZ3-QOFGC','PWTBZ-3QPCQ-ZMW53-GZA6H-YO7QF-5FFML','PVBBZ-ZYVCF-CI7J3-JZBV7-VXARZ-4MFU7','PRTBZ-2HZE4-TLHUA-D3KVI-T5GJQ-WFFAX','PQDBZ-O2B3H-4ZLDA-WTTJK-Q4CMF-RJB66','PJHBZ-EHDCN-R7FFD-SYVY4-IWH3H-VMBS5','PIXBZ-ZRREQ-O6G5D-2Y4K3-IMMAH-BXFB3','OW4BZ-MAZL7-LOTXV-HVTA3-XUWZK-2KBBO','OS3BZ-GC2CN-CL7FB-STVNJ-YW3S2-7MFIH','OQVBZ-WAD6X-RMY4Z-7XZJG-Q7AMH-FPFP6','OOUBZ-KKX3W-7JSR4-R2AQG-U6R6T-RXBMI','OMZBZ-EMQK4-DCIUU-DHOQA-XLPPK-3GFTM','OLVBZ-7L2HG-YPGQE-I3NON-J3X5Z-3CFQL','OL3BZ-ZBIKX-DHL4B-7EEWX-N33F6-N5FZQ','OH4BZ-RDVKP-RNSDY-VQKUA-SPQGE-7QFCY','OCKBZ-ZAGKK-RXLJR-A3PAM-YO7QH-V6FMJ','NZFBZ-EVYLZ-WQMXM-TYJRV-ZNYYF-W5FCZ','NYSBZ-EJLLC-HDT2X-A3ZPN-ISW3V-4JBBF','NU3BZ-JAPWV-VVNP7-5CEVQ-7NXXZ-R6BKN','NSKBZ-5VYKL-PFTPA-ESBZB-LGDF6-YEFKN','NRXBZ-PNV3R-LCPWU-WL562-YA427-NXBND','NQ4BZ-U7Y6D-7OM4W-HODRT-LK5Z6-DLBT4','NPFBZ-YZNKW-OIMR2-OIK23-OZPQ7-BVFWI','NMQBZ-WKRCQ-FFX5J-BFCGT-ORQHO-MFBXD','NJXBZ-ALDWU-HXSVU-27OKA-U4RE7-RQBGU','NIDBZ-A5TWU-G22V6-B25Y3-HQ6RV-MSFBQ','NENBZ-TUCW4-LL4U5-XGLVN-6YTPJ-CFBQ7','NDPBZ-SPFWW-2J6RH-RFUV3-CYPVK-XRFQ3','NC5BZ-4S2CP-UKODO-L4557-ZGPRO-DXBIE','NBWBZ-6URYV-Z6ZPL-5ISTO-TJW23-6TFNV','NAZBZ-5BYWL-JENPH-EV6GL-75ZMQ-L6B2Q','N7HBZ-ORS6J-AYQF3-KBXS3-VFRIV-QOBYY','N6VBZ-FLTWD-MAM4Q-HZR6Q-CVNV7-OOFE4','N6HBZ-6GSCU-R4YVE-BBFYK-KVP3T-F5BZJ','MVPBZ-KU7CP-YIPDZ-VFN4W-FDFMT-NTFMR','MVLBZ-FCW6Q-RIL5G-G5WTY-EV4PT-GQB4U','MPMBZ-ML5CU-V4OVT-BDVGM-K3NMQ-JIBRP','MFHBZ-S77KZ-N5YXF-TCKSB-HCOY6-PNF7K','MDIBZ-OZ6KU-REJV2-B5G46-HUJY7-IHFXS','MBCBZ-DE3LN-55AFX-SG2IE-2RYHT-ZJFQO','M6PBZ-QPUAF-KSJJD-JFNMG-NS5F2-UDB7F','LW7BZ-TK23O-SFQWS-SP6ZB-OD2J3-MNB6T','LVQBZ-N3PRG-VOTQC-I6MIR-EAAKK-TJBLZ','LUSBZ-HVG33-CXH3W-RCONB-6UMIK-ELBFL','LKMBZ-LVVK6-KG2SJ-E34GA-CHH7H-P5BIX','LHMBZ-R6CK2-V4FUE-CCFN7-AVGDF-SCFKF','LHKBZ-2IQ6U-HYRVB-45WJ7-KYKY3-67FHU','LBKBZ-ZP53Q-IBY5T-4TL3J-SDAM2-FKBYB','L6LBZ-Y3DLC-6UO2U-AJSTD-3TNR3-NLBOU','L4QBZ-4TOKG-7OKQE-QLF7O-IYCE3-S3F44','KZ2BZ-4S4RV-2TOP6-URXZA-MQD4T-6GBOK','KUEBZ-2OWCU-DP7VP-4QHTL-PMY66-RSFJC','KOHBZ-T3Q34-IBLU5-XWIEP-POSSO-SQBZV','K6IBZ-T4DCU-X5OVA-4GHZ6-WSYWO-K6BYJ','K2MBZ-AH2CR-6GWWL-WRT2W-QWLTT-O4FWV','JXJBZ-IORWR-CVDWX-WCZHK-M762V-RTFUU','JVSBZ-2KBW3-DK33H-33SVV-LYWVT-GDFAQ','JVKBZ-TN33Z-D2KXG-TJQDB-TCJNO-UKB6B','JUVBZ-FZYLJ-EMQFS-XZNK5-AT4UT-ASBDL','JQMBZ-UQ5ES-H6TON-6QLUQ-AM5P7-LXF7Z','JQHBZ-6T4RI-AHBGM-52MTT-UEKF7-WVFMR','JOEBZ-MTVHP-JR6D3-L6DVQ-RMXL7-RLFTI','JN2BZ-WX5C4-TFLUP-XCG3I-7NF2F-VLFEY','JKDBZ-QGTKO-GWFWF-SQ2ZZ-5S2GE-S4FVN','JJVBZ-JG4LV-4AAPM-UPFVK-MEW57-WXF2D','JG7BZ-VJBKO-HG7W7-SGOCJ-2YYYH-TUBFJ','JCVBZ-PHRW3-7VI3J-YXP72-HBHX2-VGB2Z','J4LBZ-W7SKW-HCGRQ-O3WEE-RI4K6-4QBLI','IXBBZ-IFKHF-CIM平台QJF-JBHXY-VP7S3-JVFOL','IWUBZ-SRQLF-KJSJ5-JIO4T-X3AVS-LSFB6','IV4BZ-TY2CV-NDRPU-U4MCE-RVSI5-2YFAA','IUMBZ-Z63W3-ZGS3J-OTXZX-5IAJ5-EZBRB','ITRBZ-PJEC4-JUIUL-XBAWG-OZKTK-3TF54','IOVBZ-R3S6Z-TJVXH-ZJ6QF-7UIUS-TRB6D','INNBZ-UVFWR-HXAW4-WAR6D-2KMDO-ZKBR3','INKBZ-PMMET-OPLX7-LE6XQ-IUNEZ-HSF6A','I6ZBZ-6NP36-W6OSU-MNXRW-RTAPQ-DWFUX','I5HBZ-2CQC4-WERUN-K5PCX-PTGUJ-AHBJY','I5ABZ-GVKHQ-HPF5Q-BLFQP-O6FPH-3XFHN','I2XBZ-H5PW5-HDKIC-IMWLW-4JT6O-QSBCK','HXPBZ-PHZWI-U5OGG-5JDIW-3OIKJ-3FBPR','HU2BZ-XXPC6-L3NSP-M3RDC-MMFP5-QRFPW','HSUBZ-2WS3K-RCLJG-AJRLN-666OK-2CFE6','HSKBZ-5A4C3-LN43L-OAIGR-JZCJJ-LZFKP','HO7BZ-WVQH3-YPC3A-OJE4P-DEQDT-CRF3Y','HJOBZ-EBJW3-Y6R3A-3TID4-CIMD3-CFB5F','HFEBZ-FBNCJ-FVEFY-FCVG2-TOQ5Z-L6FKL','HELBZ-6V5KJ-HEDFF-KZBRN-4XDF5-JFBCK','H7FBZ-DYMC6-4ERSD-MKEGK-PS5PH-6LBHI','H42WY-75WY3-Y4VSE-VXEO5-JWA7A','GWVBZ-7PCK2-XHBUZ-CTNHR-3TY45-7DBNP','GRSBZ-6YGCW-AHYRE-RSUQP-KKIVS-JPFN3','GQEBZ-GNUKS-7APOK-67QIV-Q2K2V-VCBA3','GPLBZ-N23WW-TSBRF-ROZNE-A5PQ3-Q2BUJ','GOOBZ-SDKWU-CNIV6-4CXMK-77YI7-I7BYN','GKEBZ-YYKC4-QLPU6-XNBQ5-CUY4E-22BXW','GANBZ-OWZLU-YJKVS-G5WBV-2FEGQ-P2B67','G2HBZ-YSLCD-BQS4K-PTUBH-AWJWJ-NDFHU','FYBBZ-OHOKN-HMBFJ-S7PG6-D5BZZ-NSBKK','FYABZ-ZLM3W-UM5RX-OZT4N-K5XSV-HTBKW','FRCBZ-CXMC3-YBG3U-YEJGU-YUPWO-ZRFOY','FQHBZ-RUQEJ-NUBFI-K6QF3-5MQ2J-6DFPD','FNJBZ-PM4K5-KAKIK-QJ5O3-WLU3S-PJBGV','FKXBZ-WZ36J-NIHF5-K2PVL-DMIWQ-YZBQ4','FJ5BZ-URIWP-TA5DK-V5AY7-S2DQS-ROF6C','FIUBZ-DSU6X-KUP4H-ZXFGL-W6SN2-UWFH7','FGRBZ-2FJCU-EAMVP-2G7QH-ZZN45-V7BL7','FEBBZ-3FUH2-AGDU2-CACFJ-OILEH-SYF6N','FCTBZ-2HMHJ-BDMFO-FT3FC-IPE3O-G7FLK','FBPBZ-A7Z3X-3MU4V-Z5VGB-53KG3-WEBC5','F6ZBZ-CJK3X-MT64P-TOOKY-GAPGH-TGB5D','F3ZBZ-TQAWX-42L4W-7LKDL-7PF6E-ZGB57','EZRBZ-27CRQ-VRQ5G-43QTK-ZOFK7-MBBCQ','EYHBZ-ENXW3-DHK3N-3AETB-TDFJ2-TWFLX','EXQBZ-NRYLD-KZB46-H4KUD-X63JJ-3BFNX','EVOBZ-EGIWB-PKRUO-NO4ST-RZAV6-GBB66','EQEBZ-N2FLD-MVV4U-HTQBV-43J57-WRBWZ','EM7BZ-OT3RZ-LP3X6-77G5Z-G7ONH-W3FJI','ECZBZ-6UBCF-RTVJT-NELGC-VS7D6-53F66','ECOBZ-VPKW4-AMDUB-XHLW4-5UYCO-BQBC5','EBVBZ-V553U-SGCV4-BONLC-37RRT-SOF56','E57BZ-II4EQ-ZRJ5V-252LK-QNUZO-AGF55','DZNBZ-6ZEWZ-NZCX4-7BIV5-TWU7J-RVBAN','DWGBZ-W3QWZ-E4WXE-7OQG5-GILJJ-SOBIX','DSHBZ-2IR65-SFHIN-QDW4K-R53TO-UMFKO','DOYBZ-2463Q-GMF5Y-BNKN2-3WNJT-6DFGU','DOEBZ-AZ6KS-7NZOQ-6R5WD-GJP5S-4ZFMP','DIDBZ-YFP2U-VKXVR-2FHE6-Z7ZJZ-EJFXZ','DH5BZ-V5N6K-DE4JB-AZNG6-C7SXV-Q2BNO','D4JBZ-XRXEX-XZO4W-TWL2P-66PWS-2YBVK','D24BZ-J7GLQ-T3G5T-GEUQ4-FPVMQ-R5F62','CZBBZ-KGDRT-HQUXZ-V7MLQ-CXNOK-37BGU','CZ7BZ-MXT6F-RC6J5-NY3LQ-WFP3F-OCFDD','CWUBZ-ONSH4-YBXUD-DIUOX-EHV42-RKFLA','CURBZ-YFVH3-66B35-YHMLK-Q53IH-SBFUO','CNDBZ-H4KKD-BNF45-P7NVU-6DRL3-NLFDY','CMUBZ-Z6OWF-57PJS-JCXUX-ZQCO6-44F2Q','CL7BZ-HUD6A-HMGKH-CWO2X-V2NO3-K7BN4','CJXBZ-5ZE3U-WYGVC-4IUHB-ROX3O-QVFWO','CGJBZ-FVWCT-TF7XX-VUDAR-XQYRE-Z3FHJ','CEYBZ-JABWZ-3FCXW-76VMJ-I3GGV-DZBFR','CA3BZ-CE4C7-RTKXM-HNHNO-N6QM5-3ZB3E','C6GBZ-UC7RK-LH2JM-AOZSC-RO2CQ-YSBGS','C6ABZ-VA63U-C7XVU-BNC67-ZQ3HO-F3FWB','C3WBZ-AZHCQ-2NO5C-BFVET-LRTSV-Y3BTM','BQRBZ-CBKKQ-A745F-4KR5E-3AVFT-ZAFFV','BPABZ-7E4LJ-5GCFE-FC645-RIXFJ-6PFRG','BNZBZ-MBPR3-KDB33-YNKYF-HK6AQ-GGBLD','BIBBZ-DUWE6-MGVSF-EZ6JP-OSVFZ-4LBUX','BH5BZ-VPT6Z-MCKXT-ZF2ME-4ZCUH-NEBGY','BCGBZ-IJQKG-H6PQV-INE5X-5QRPZ-2TBOV','BAZBZ-AKVCU-CKGV6-2GUBD-IZV75-MYFS2','AVLBZ-SC6KO-ACNWT-SGVGV-7H4F3-S5B4M','AVIBZ-YEXWI-A4KGK-5HBSA-KOUDJ-3CFRX','AVABZ-EIPWP-7RTDK-L6UQ3-SHYET-V5B6V','ATABZ-JVC6G-DQ7QT-I4INI-6JKLT-YZF24','AQUBZ-XIBWU-EGIV2-GBVYZ-TA3CS-2ABDS','ALMBZ-2OTKC-TXA25-ARGEJ-6OAQZ-4IFCT','AJPBZ-GSAKU-VPUV4-4ZE5K-IF7U2-S4F6Y','AETBZ-C5E64-RHOUO-FI6E2-J6VJZ-QOBIE','AE2BZ-M2FCQ-P6T5D-4NZHY-2Q7PH-GKBAB','AAUBZ-QIMWX-E2W4R-7BY7B-RAAJF-QKBA4','A7LBZ-LFGRZ-3CSX2-72TLZ-ZJZH5-UHB6K','A3TBZ-3GMKS-VXGON-6QKJ4-44752-ZTFJ5','A25BZ-QWECZ-IMRXP-7A55H-TQEPQ-YJFR5','7X4BZ-ZG4RF-RQMJS-NBS7N-UVJ75-G5BMX','7RJBZ-O6I64-XANUL-KKPHS-UOCAJ-EPFPU','7OKBZ-QB6KZ-LJ2XP-ZPBJA-455DQ-GTFRT','7MNBZ-XENKD-LUX4P-HOX5Q-IZB35-YHBVT','7L5BZ-MNBWK-3EGJ3-AMR2R-ETLV7-OTBEQ','7JOBZ-5OF3U-QUNVL-GYLKC-WCM73-U7BSJ','7IUBZ-DTMWI-3TMGU-5Y6UJ-7G2FJ-MHB7K','7FUBZ-HSMWV-7WPPQ-U6JSM-4HNPV-DRBGV','77KBZ-2XCC3-LKI3S-3C6VV-DTUEO-ESB6B','74EBZ-T35WQ-OZP57-GJQWS-LPEPQ-GWBJP','6VZBZ-J6Q6G-DN7QV-QVA4M-TGJMS-VMB6E','6TRBZ-7KN64-Y54U3-DYZ3U-5XCE3-H6BG7','6RQBZ-54BLD-XT74B-HNJC5-UXN4S-SNB2A','6Q5BZ-VGL3J-LRCF5-FCMF3-TJK3Z-XLBU2','6O2BZ-WI26J-QJ7FT-F7EBH-YJXGS-OQBFF','6N4BZ-EHK3X-WXI44-ZAKLI-DZE2K-B6FU3','6LWBZ-ZR7WL-JNUPI-EV4L2-NY3BJ-B3FZW','6FYBZ-3ULN3-4RX3X-3XJWY-2JGQT-NMFK5','6FIBZ-AWZL6-CILSN-EAND2-WZNTO-ZPF6J','6FDBZ-LW262-LMUUO-C6BDS-LWNM5-G5FMT','6BJBZ-SXG6C-BIA23-ASIXC-VPJEE-ESBG4','67ABZ-HLPRQ-XZM53-GNCSR-GNSXF-DSBDK','64HBZ-6M53I-DQ7GJ-5L2I6-6UJQS-QSBEC','63SBZ-2F7WZ-6X4XO-ZCCHG-NBTCE-T3BPH','62VBZ-ZPHCR-E6AWD-WL3XU-KLBRH-V3BG3','5YZBZ-MJH6W-7J5RS-3VYK7-MFSC7-RBBCZ','5V4BZ-KQBC6-V44ST-MBFLW-IJXQO-JRFBP','5POBZ-JFI3J-IY6FQ-KVKDL-BW7B7-56FDX','5PBBZ-A5PC4-77TUH-KHGMD-IQULE-BZFTG','5LZBZ-5JSWX-3CQ4A-ZINRT-FUDG7-7OFSU','5KUBZ-E3YKM-VTX6L-67DTE-ZOA2O-VFBW3','5KQBZ-YGR6P-EDSDJ-VAUU5-GIV23-6UFHO','5HKBZ-SRKCD-5CQ4C-PF56K-NUHCS-QKFKN','5G2BZ-K42CP-NI4DH-V4BHN-BL6BF-BWBL3','5FNBZ-EP2WJ-AK6FK-FUR5W-RKA6Z-RLBSQ','5EZBZ-BBHRW-WEBRF-O2F5N-J7MUS-I6FH7','5EYBZ-HMMCR-DETWU-W2QZL-V3PXT-UDB2J','57SBZ-BCG6P-6KRDU-VC4RA-376DO-YTFKB','55SBZ-ZK63U-AZ5VB-BJD33-XUUZF-FKBZI','55KBZ-V4RCW-4OERQ-O2EYS-D6ZSZ-S5BMP','552BZ-RXYW4-PIIU4-XFZ3V-WQWLJ-7WBLE','4YOBZ-BW7KQ-6WW5C-BLJGI-BZDN7-QABU4','4XCBZ-4GVCK-3EWJ3-A6CCD-CF5D7-XEB3Z','4WJBZ-CUILX-DK642-7BSIM平台Q-KODTZ-BEBCH','4WIBZ-BZRCU-MQHVK-4N62Y-ART3K-2JFTF','4QUBZ-J4FWT-RE3XR-VQUOB-NXO32-GGBOK','4QUBZ-3TQCQ-UIR5Q-GVYXK-UBX6K-PVBMS','4QEBZ-C2HWP-VLBDE-V6LZK-DIM72-VWB34','4OFBZ-IVZKR-UXWWX-WTHNH-Q7KS5-MCBDD','4LDBZ-Z2QLC-WOD23-ASUUK-56TZ7-N2BTX','4KIBZ-2VEWJ-OIMFP-D3NBK-Q3XLE-W5F7Z','4H5BZ-RIEKQ-FOZ5K-BU4CI-BJNJE-3HBRM','4FKBZ-QBWKQ-3HT5N-2SHOO-QGYOQ-AOBYA','4DYBZ-2IJ6X-IEO45-Z4M7A-3IPS7-7IFUV','4ARBZ-RE4KJ-XSUF3-DCMEA-YYAHE-GLFVI','42DBZ-MDEK3-IKS3Q-3MI6O-YN2EE-NJFSL','3WOBZ-WUVKU-B2AV4-4BE6P-SVMDE-7UBOM','3QNBZ-MDCKC-5YS23-AH35L-QDYJS-R6B6T','3PFBZ-XNV67-ZZFXP-HROTO-DXXI3-LFFK4','3JQBZ-XLML4-YZWUG-X5JJY-RXYY2-IFFX4','3HHBZ-QJ6C6-PJSSA-ELG33-X3FVF-HMBNX','3H4BZ-5UXLO-3P2WE-SYGSW-KOUX5-SWFEN','3F7BZ-FTT3G-LFGQE-I7CAD-LIW47-PBBET','3EYBZ-MBJW4-ZMFUH-XHDPO-CUOOH-OOBQM','3DIBZ-KYXY3-GZW3C-OPJ5O-RRF62-7NBPU','37RBZ-6DN66-N2KSK-EH6MX-VAV3F-QLBYJ','36FBZ-PPF3S-UCCO6-6JYDP-EJUGJ-FLBV7','2Z4BZ-R7S6W-COZRH-OH35E-EM52T-FLBGX','2YZBZ-C7L3W-GPTRB-YOGKI-3I2XE-WCBBJ','2YUBZ-WXWLJ-55FFS-KWX4Q-BWXQS-WMFLS','2UBBZ-MKIWP-MNGDA-VGW72-VKZBH-2DFZR','2OOBZ-SPFE4-UJ7UB-KCSVO-POIU6-4VFME','2ODBZ-FEIK4-RHYUZ-XFUVG-X3DCF-7SB5K','2J5BZ-NFMR6-QO3SZ-M5S34-KXMRQ-MZFC7','2EVBZ-MGC6J-2THFU-XGYYL-CHH5T-5QBCB'\n)\n)t1 \njoin \n(\nSELECT uin\nfrom internal_platform_db.t_ed_mapservice_user_q36_active_dwd_di_query_engine_135\nwhere ds= 20260608\ngroup by uin\n)t2 on t1.uin = t2.uin \n)\nselect\n referer_type\n ,if(grouping(referer) = 1,'total',referer) as referer \n ,if(grouping(path) = 1,'total',path) as path\n\t,count(distinct uin) \n\t,count(distinct case when is_first = 1 then uin else null end)\nfrom t\ngroup by referer_type,cube(referer,path)", "expected_csv": "referer_type,referer,path,uv,first_uv,ds\nFoodChainA,com.foodchain_a.android.activity,qqmap://map/routeplan?type=walk,1,1,20260608\nCourierCoB,couriercob,qqmap://map/navi,1,0,20260608\nCourierCoB,total,total,2,0,20260608\nCourierCoB,total,qqmap://map/search,1,0,20260608\nCourierCoB,total,qqmap://map/navi,1,0,20260608\nCourierCoB,couriercob,total,1,0,20260608\nEcommerceC,com.ecommerce_c.mall,未知,1,0,20260608\nEcommerceC,com.ecommerce_c.mall,total,1,0,20260608\nEcommerceC,com.delivery_d.mobile.android,total,1,1,20260608\nFoodChainA,FoodChainA,total,1,1,20260608\nFoodChainA,com.foodchain_a.android.activity,total,1,1,20260608\nEcommerceC,total,qqmap://map/routeplan?type=bus,1,0,20260608\nEcommerceC,com.delivery_d.mobile.android,qqmap://map/poi,1,1,20260608\nEcommerceC,total,qqmap://map/poi,1,1,20260608\nEcommerceC,com.dada.knight.hm,total,1,0,20260608\nCourierCoB,com.couriercob.huoyun,total,1,0,20260608\nEcommerceC,total,未知,1,0,20260608\nEcommerceC,com.dada.knight.hm,qqmap://map/routeplan?type=bus,1,0,20260608\nEcommerceC,total,total,2,1,20260608\nFoodChainA,FoodChainA,qqmap://map/routeplan?type=drive,1,1,20260608\nFoodChainA,total,qqmap://map/routeplan?type=drive,1,1,20260608\nFoodChainA,total,qqmap://map/routeplan?type=walk,1,1,20260608\nCourierCoB,com.couriercob.huoyun,qqmap://map/search,1,0,20260608\nFoodChainA,total,total,1,1,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数6 + 列名匹配\nC,C_row_alignment,row_consistency,15,\"行数比例 + key(referer_type,referer,path)覆盖率\"\nD,D_path_clean_referer_map,path_clean_referer_map,25,\"路径清洗+referer映射维度值逐行匹配(referer_type,referer,path)\"\nD,D_cube_aggregation,cube_aggregation,20,\"CUBE聚合指标逐行匹配(uv,first_uv)\"\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE 写入模式\nF,F_partition,partition,5,ds=20260608 分区正确\nF,F_grouping_total,grouping_total,5,CUBE汇总行grouping维度置为'total'\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,\"referer_type, referer, path\"\n# 预期列数,6\n# 输出表,internal_platform_db.t_md_mapservice_user_open_start_path_dwa_di_cand_query_engine_135", "path": "tasks/offline-compute/HiveSQL/hivesql_023_en"} {"task_id": "hivesql_024", "id": "offline-compute_HiveSQL_hivesql_024", "name": "从 internal_platform_db.dwd_relationship_strength_fe", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标\n基于好友关系特征数据计算关系强度推荐分数,输出每个用户对(uin, touin)的加权评分结果。\n\n输入\n- internal_platform_db.dwd_relationship_strength_features_v4_di_query_engine_138(无 Join,单表处理)\n\n处理规则\n1. 过滤条件:imp_date = 20260608,且 uin >= 10000 且 touin >= 10000\n2. 特征处理:\n - 对所有分数字段使用 COALESCE(field, 0) 填充空值\n - c2c_cnt_score、common_frd_num、frd_tag_num 使用 LOG(1 + field) 变换\n - age_diff 使用 LOG(100 - age_diff) 变换\n3. 加权求和公式:score = (0.0327 * log_frd_tag_num + 0.0386 * touser_id_active_layer + 0.0853 * (1 - is_same_city) + 0.0564 * c2c_score + 0.1895 * log_c2c_cnt_score + 0.2455 * socialzone_visit_score + 0.1055 * socialzone_like_score + 0.1514 * socialzone_comment_score + 0.1556 * profile_view_score + 0.1531 * profile_like_score) / 28\n4. 结果字段:raw_score = ROUND(score, 4),最终 score = 1 + ROUND(score, 4) * 10000\n\n输出要求\n- 字段顺序:imp_date(固定值 20260608)、uin、touin、score、raw_score\n- imp_date 作为分区字段\n- 不要求去重或聚合\n\n写入要求\n- 输出表:internal_platform_db.ads_qq_sq_frd_recommendation_result_list_df_cand_query_engine_138\n- 分区:imp_date = 20260608\n- 写入方式:INSERT OVERWRITE 覆盖写入该分区\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.ads_qq_sq_frd_recommendation_result_list_df_query_engine_138 PARTITION (imp_date = 20260608)\nWITH feature_modified_v2 AS (\nSELECT\n uin\n, touin\n, COALESCE(c2c_score, 0) AS c2c_score\n, COALESCE(LOG(1 + c2c_cnt_score), 0) AS log_c2c_cnt_score\n, COALESCE(socialzone_visit_score, 0) AS socialzone_visit_score\n, COALESCE(socialzone_like_score, 0) AS socialzone_like_score\n, COALESCE(socialzone_comment_score, 0) AS socialzone_comment_score\n, COALESCE(profile_view_score, 0) AS profile_view_score\n, COALESCE(profile_like_score, 0) AS profile_like_score\n, COALESCE(touser_id_active_layer, 0) AS touser_id_active_layer\n, COALESCE(LOG(100 - age_diff), 0) AS log_age_diff_complement\n, COALESCE(LOG(1 + common_frd_num), 0) AS log_common_frd\n, COALESCE(active_layer_score, 0) AS active_layer_score\n, COALESCE(LOG(1 + frd_tag_num), 0) AS log_frd_tag_num\n, COALESCE(is_same_city, 0) AS is_same_city\n, COALESCE(is_focus_frd, 0) AS is_focus_frd\n, COALESCE(comsg_score, 0) AS comsg_score\nFROM\ninternal_platform_db.dwd_relationship_strength_features_v4_di_query_engine_138\nWHERE\nimp_date = 20260608\n),\nweighted_score_v2 AS (\nSELECT\nfm.uin\n, fm.touin\n, (0.0327 * fm.log_frd_tag_num +\n0.0386 * fm.touser_id_active_layer +\n0.0853 * (1 - fm.is_same_city) +\n0.0564 * fm.c2c_score +\n0.1895 * fm.log_c2c_cnt_score +\n0.2455 * fm.socialzone_visit_score +\n0.1055 * fm.socialzone_like_score +\n0.1514 * fm.socialzone_comment_score +\n0.1556 * fm.profile_view_score +\n0.1531 * fm.profile_like_score) / 28 AS score\nFROM\nfeature_modified_v2 fm\n)\nSELECT\nws.uin\n, ws.touin\n, 1 + (ROUND(ws.score, 4) * 10000) AS score\n, ROUND(ws.score, 4) AS raw_score\nFROM\nweighted_score_v2 ws\nWHERE\nuin >= 10000\nAND touin >= 10000", "expected_csv": "uin,touin,score,raw_score\n10009,10010,570.0,0.0569\n10001,10002,307.0,0.0306\n10003,10004,238.0,0.0237\n10007,10008,31.0,0.003", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数5 + 列名匹配\nC,C_row_alignment,row_consistency,15,\"行数比例 + key(uin,touin)覆盖率\"\nD,D_score_correctness,score_correctness,25,最终得分列逐行匹配\nD,D_raw_score_correctness,raw_score_correctness,20,原始分列逐行匹配\nF,F_null_handling,null_handling,5,COALESCE 验证(无不当 NULL)\nF,F_boundary_filter,boundary_filter,5,uin>=10000 && touin>=10000\nF,F_insert_overwrite,insert_overwrite,3,写入模式+分区\nF,F_partition_value,partition_value,2,imp_date=20260608\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,\"uin, touin\"\n# 预期列数,\n# 输出表,internal_platform_db.ads_qq_sq_frd_recommendation_result_list_df_cand_query_engine_138", "path": "tasks/offline-compute/HiveSQL/hivesql_024"} {"task_id": "hivesql_025", "id": "offline-compute_HiveSQL_hivesql_025", "name": "任务:将两个商品数据源(精细采集和泛化采集)合并,对每个字段生成质量评分。输入表:ads_sec_ec_su", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n任务目标:将两个商品数据源(精细采集表 hi 和泛化采集表 extensive)按日期分区过滤后 UNION ALL 合并,对合并后的每条记录的每个字段生成质量评分(0/1),输出到评分结果表。\n\n输入:\n- internal_platform_db.ads_sec_ec_sup_ec_tele_item_hi_query_engine_140(精细采集表,小时分区 p_hour)\n- internal_platform_db.ads_sec_ec_sup_ec_tele_security_platform_lk_extensive_item_query_engine_140(泛化采集表,日分区 p_date)\n- 第三个输入表 internal_platform_db.ads_sec_ec_sup_ec_tele_item_score_query_engine_140 在本任务中不使用\n\n处理规则:\n1. 过滤条件:\n - hi 表:p_hour >= '2026060800' AND p_hour < '2026060900'\n - extensive 表:p_date = '20260608'\n\n2. UNION ALL 前的字段映射(两表字段不完全一致):\n - hi 表:使用 sale_price,新增 source_type='精细采集'\n - extensive 表:使用 price(映射为 sale_price),新增 source_type='泛化采集'\n - 其他字段直接对齐\n\n3. is_exp 派生规则(是否交付):\n - 精细采集来源:required_quality_score=1 AND status=1 → 1,否则 0\n - 泛化采集来源:required_quality_score=1 → 1,否则 0\n\n4. is_off_shelf 派生规则(是否下架):status<>1 → 1,否则 0\n\n5. 质量评分字段生成规则(所有字段名加 _score 后缀,除 uniqu_id 外):\n - STRING 类型字段(id/name/url/shop_uniqu_id/shop_name/shop_url/platform_name/task_id/batch_id):coalesce(field,'') <> '' → 1,否则 0\n - STRING 类型字段(property/sku_list/desc_info/main_image_url/sub_image_url/category_level1_name/category_level2_name/category_level3_name/shipping_address/price_text/detail_image_url/service_guarantee/brand_name/category_level1_original/category_level2_original/category_level3_original/brand_name_original/product_name/approval_number/ccc_certificate_number/efficacy/production_place/manufacturer/production_license_number/factory_name/factory_address/brand_authorization_image_url/main_image_ocr/sub_image_ocr/detail_image_ocr/industry_id/industry_name):coalesce(field,'') = '' → 0,否则 1\n - 非空判断字段(status/sale_price/sale_qty/stock_qty/category_level1_id/category_level2_id/category_level3_id/shop_id/platform_id/brand_id/comments_cnt/high_remark_cnt/med_remark_cnt/bad_remark_cnt/sku_cnt/license_collection_status/screenshot_url):field IS NOT NULL → 1,否则 0\n - 特殊字段:\n - logo_brand_score、similarity_img_url_score、data_method_keyword_score、task_name_score:固定 NULL\n - required_quality_score、core_quality_score、other_quality_score、platform_name、source_type、is_exp、is_off_shelf:直接传递,不生成评分\n\n输出要求:\n- 输出字段顺序(共 89 字段):p_date、uniqu_id、id_score、name_score、sub_title_score、property_score、sku_list_score、desc_info_score、url_score、status_score、price_score、sale_qty_score、stock_qty_score、main_image_url_score、sub_image_url_score、category_level1_id_score、category_level1_name_score、category_level2_id_score、category_level2_name_score、category_level3_id_score、category_level3_name_score、shop_uniqu_id_score、shop_id_score、shop_name_score、shop_url_score、platform_id_score、platform_name_score、shipping_address_score、price_text_score、flag_score、need_cutpic_score、is_ocr_score、soe_flag_score、data_channel_score、data_method_score、data_source_score、detail_image_url_score、service_guarantee_score、brand_id_score、brand_name_score、is_ad_score、is_selfoperated_score、create_time_score、task_id_score、batch_id_score、category_level1_original_score、category_level2_original_score、category_level3_original_score、brand_name_original_score、product_name_score、approval_number_score、ccc_certificate_number_score、efficacy_score、production_place_score、manufacturer_score、production_license_number_score、factory_name_score、factory_address_score、brand_authorization_image_url_score、is_virtual_score、is_invoice_score、is_guarantee_score、is_free_ship_score、comments_cnt_score、industry_id_score、industry_name_score、high_remark_cnt_score、med_remark_cnt_score、bad_remark_cnt_score、main_image_ocr_score、sub_image_ocr_score、detail_image_ocr_score、ml_category_tag_score、logo_brand_score、similarity_img_url_score、sku_cnt_score、license_collection_status_score、data_method_keyword_score、task_name_score、screenshot_url_score、required_quality_score、core_quality_score、other_quality_score、platform_name、source_type、is_exp、is_off_shelf\n\n写入要求:\n- 输出表:internal_platform_db.ads_sec_ec_sup_ec_tele_item_score_cand_query_engine_140\n- 写入方式:INSERT OVERWRITE,覆盖分区 p_date='20260608'\n- 分区字段:p_date='20260608'(硬编码,非从源表继承)\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "insert overwrite table internal_platform_db.ads_sec_ec_sup_ec_tele_item_score_query_engine_140 partition(p_date='20260608')\nwith view_union as (\nselect uniqu_id,\nid,\nname,\nsub_title,\nproperty,\nsku_list,\ndesc_info,\nurl,\nstatus,\nsale_price,\nsale_qty,\nstock_qty,\nmain_image_url,\nsub_image_url,\ncategory_level1_id,\ncategory_level1_name,\ncategory_level2_id,\ncategory_level2_name,\ncategory_level3_id,\ncategory_level3_name,\nshop_uniqu_id,\nshop_id,\nshop_name,\nshop_url,\nplatform_id,\nplatform_name,\nshipping_address,\nprice_text,\nflag,\nneed_cutpic,\nis_ocr,\nsoe_flag,\ndata_channel,\ndata_method,\ndata_source,\ndetail_image_url,\nservice_guarantee,\nbrand_id,\nbrand_name,\nis_ad,\nis_selfoperated,\ncreate_time,\ntask_id,\nbatch_id,\ncategory_level1_original,\ncategory_level2_original,\ncategory_level3_original,\nbrand_name_original,\nproduct_name,\napproval_number,\nccc_certificate_number,\nefficacy,\nproduction_place,\nmanufacturer,\nproduction_license_number,\nfactory_name,\nfactory_address,\nbrand_authorization_image_url,\nis_virtual,\nis_invoice,\nis_guarantee,\nis_free_ship,\ncomments_cnt,\nindustry_id,\nindustry_name,\nhigh_remark_cnt,\nmed_remark_cnt,\nbad_remark_cnt,\nmain_image_ocr,\nsub_image_ocr,\ndetail_image_ocr,\nml_category_tag,\nsku_cnt,\nlicense_collection_status,\nscreenshot_url,\nrequired_quality_score,\ncore_quality_score,\nother_quality_score,\n'精细采集' as source_type,\ncase when required_quality_score = 1 and status = 1 then 1 else 0 end is_exp\nfrom internal_platform_db.ads_sec_ec_sup_ec_tele_item_hi_query_engine_140\nWHERE p_hour>='2026060800' and p_hour<'2026060900'\nunion all\nselect uniqu_id,\nid,\nname,\nsub_title,\nproperty,\nsku_list,\ndesc_info,\nurl,\nstatus,\nprice as sale_price,\nsale_qty,\nstock_qty,\nmain_image_url,\nsub_image_url,\ncategory_level1_id,\ncategory_level1_name,\ncategory_level2_id,\ncategory_level2_name,\ncategory_level3_id,\ncategory_level3_name,\nshop_uniqu_id,\nshop_id,\nshop_name,\nshop_url,\nplatform_id,\nplatform_name,\nshipping_address,\nprice_text,\nflag,\nneed_cutpic,\nis_ocr,\nsoe_flag,\ndata_channel,\ndata_method,\ndata_source,\ndetail_image_url,\nservice_guarantee,\nbrand_id,\nbrand_name,\nis_ad,\nis_selfoperated,\ncreate_time,\ntask_id,\nbatch_id,\ncategory_level1_original,\ncategory_level2_original,\ncategory_level3_original,\nbrand_name_original,\nproduct_name,\napproval_number,\nccc_certificate_number,\nefficacy,\nproduction_place,\nmanufacturer,\nproduction_license_number,\nfactory_name,\nfactory_address,\nbrand_authorization_image_url,\nis_virtual,\nis_invoice,\nis_guarantee,\nis_free_ship,\ncomments_cnt,\nindustry_id,\nindustry_name,\nhigh_remark_cnt,\nmed_remark_cnt,\nbad_remark_cnt,\nmain_image_ocr,\nsub_image_ocr,\ndetail_image_ocr,\nml_category_tag,\nsku_cnt,\nlicense_collection_status,\nscreenshot_url,\nrequired_quality_score,\ncore_quality_score,\nother_quality_score,\n'泛化采集' as source_type,\ncase when required_quality_score=1 then 1 else 0 end as is_exp\nfrom internal_platform_db.ads_sec_ec_sup_ec_tele_security_platform_lk_extensive_item_query_engine_140\nwhere(p_date='20260608')\n)\nselect\nuniqu_id as uniqu_id,\ncase when coalesce(id,'') <> '' then 1 else 0 end as id_socre,\ncase when coalesce(name,'') <> '' then 1 else 0 end as name_socre,\ncase when coalesce(sub_title,'') <> '' then 1 else 0 end as sub_title_socre,\ncase when coalesce(property, '') = '' then 0 else 1 end as property_socre,\ncase when coalesce(sku_list, '') = '' then 0 else 1 end as sku_list_socre,\ncase when coalesce(desc_info, '') = '' then 0 else 1 end as desc_info_socre,\ncase when coalesce(url,'') <> '' then 1 else 0 end as url_socre,\ncase when status is not null then 1 else 0 end as status_socre,\ncase when sale_price is not null then 1 else 0 end as price_socre,\ncase when sale_qty is not null then 1 else 0 end as sale_qty_socre,\ncase when stock_qty is not null then 1 else 0 end as stock_qty_socre,\ncase when coalesce(main_image_url, '') = '' then 0 else 1 end as main_image_url_socre,\ncase when coalesce(sub_image_url, '') = '' then 0 else 1 end as sub_image_url_socre,\ncase when category_level1_id is not null then 1 else 0 end as category_level1_id_socre,\ncase when coalesce(category_level1_name, '') = '' then 0 else 1 end as category_level1_name_socre,\ncase when category_level2_id is not null then 1 else 0 end as category_level2_id_socre,\ncase when coalesce(category_level2_name, '') = '' then 0 else 1 end as category_level2_name_socre,\ncase when category_level3_id is not null then 1 else 0 end as category_level3_id_socre,\ncase when coalesce(category_level3_name, '') = '' then 0 else 1 end as category_level3_name_socre,\ncase when coalesce(shop_uniqu_id,'') <> '' then 1 else 0 end as shop_uniqu_id_socre,\ncase when coalesce(shop_id, '') = '' then 0 else 1 end as shop_id_socre,\ncase when coalesce(shop_name,'') <> '' then 1 else 0 end as shop_name_socre,\ncase when coalesce(shop_url,'') <> '' then 1 else 0 end as shop_url_socre,\ncase when platform_id is not null then 1 else 0 end as platform_id_socre,\ncase when coalesce(platform_name,'') <> '' then 1 else 0 end as platform_name_socre,\ncase when coalesce(shipping_address, '') = '' then 0 else 1 end as shipping_address_socre,\ncase when coalesce(price_text, '') = '' then 0 else 1 end as price_text_socre,\ncase when flag is not null then 1 else 0 end as flag_socre,\ncase when need_cutpic is not null then 1 else 0 end as need_cutpic_socre,\ncase when is_ocr is not null then 1 else 0 end as is_ocr_socre,\ncase when soe_flag is not null then 1 else 0 end as soe_flag_socre,\ncase when data_channel is not null then 1 else 0 end as data_channel_socre,\ncase when data_method is not null then 1 else 0 end as data_method_socre,\ncase when data_source is not null then 1 else 0 end as data_source_socre,\ncase when coalesce(detail_image_url, '') = '' then 0 else 1 end as detail_image_url_socre,\ncase when coalesce(service_guarantee, '') = '' then 0 else 1 end as service_guarantee_socre,\ncase when brand_id is not null then 1 else 0 end as brand_id_socre,\ncase when coalesce(brand_name, '') = '' then 0 else 1 end as brand_name_socre,\ncase when is_ad is not null then 1 else 0 end as is_ad_socre,\ncase when is_selfoperated is not null then 1 else 0 end as is_selfoperated_socre,\ncase when create_time is not null then 1 else 0 end as create_time_socre,\ncase when coalesce(task_id,'') <> '' then 1 else 0 end as task_id_socre,\ncase when coalesce(batch_id,'') <> '' then 1 else 0 end as batch_id_socre,\ncase when coalesce(category_level1_original, '') = '' then 0 else 1 end as category_level1_original_socre,\ncase when coalesce(category_level2_original, '') = '' then 0 else 1 end as category_level2_original_socre,\ncase when coalesce(category_level3_original, '') = '' then 0 else 1 end as category_level3_original_socre,\ncase when coalesce(brand_name_original, '') = '' then 0 else 1 end as brand_name_original_socre,\ncase when coalesce(product_name, '') = '' then 0 else 1 end as product_name_socre,\ncase when coalesce(approval_number, '') = '' then 0 else 1 end as approval_number_socre,\ncase when coalesce(ccc_certificate_number, '') = '' then 0 else 1 end as ccc_certificate_number_socre,\ncase when coalesce(efficacy, '') = '' then 0 else 1 end as efficacy_socre,\ncase when coalesce(production_place, '') = '' then 0 else 1 end as production_place_socre,\ncase when coalesce(manufacturer, '') = '' then 0 else 1 end as manufacturer_socre,\ncase when coalesce(production_license_number, '') = '' then 0 else 1 end as production_license_number_socre,\ncase when coalesce(factory_name, '') = '' then 0 else 1 end as factory_name_socre,\ncase when coalesce(factory_address, '') = '' then 0 else 1 end as factory_address_socre,\ncase when coalesce(brand_authorization_image_url, '') = '' then 0 else 1 end as brand_authorization_image_url_socre,\ncase when is_virtual is not null then 1 else 0 end as is_virtual_socre,\ncase when is_invoice is not null then 1 else 0 end as is_invoice_socre,\ncase when is_guarantee is not null then 1 else 0 end as is_guarantee_socre,\ncase when is_free_ship is not null then 1 else 0 end as is_free_ship_socre,\ncase when comments_cnt is not null then 1 else 0 end as comments_cnt_socre,\ncase when coalesce(industry_id, '') = '' then 0 else 1 end as industry_id_socre,\ncase when coalesce(industry_name, '') = '' then 0 else 1 end as industry_name_socre,\ncase when high_remark_cnt is not null then 1 else 0 end as high_remark_cnt_socre,\ncase when med_remark_cnt is not null then 1 else 0 end as med_remark_cnt_socre,\ncase when bad_remark_cnt is not null then 1 else 0 end as bad_remark_cnt_socre,\ncase when coalesce(main_image_ocr, '') = '' then 0 else 1 end as main_image_ocr_socre,\ncase when coalesce(sub_image_ocr, '') = '' then 0 else 1 end as sub_image_ocr_socre,\ncase when coalesce(detail_image_ocr, '') = '' then 0 else 1 end as detail_image_ocr_socre,\ncase when ml_category_tag is not null then 1 else 0 end as ml_category_tag_socre,\nnull as logo_brand_socre,\nnull as similarity_img_url_socre,\ncase when sku_cnt is not null then 1 else 0 end as sku_cnt_socre,\ncase when license_collection_status is not null then 1 else 0 end as license_collection_status_socre,\nnull as data_method_keyword_socre,\nnull as task_name_socre,\ncase when screenshot_url is not null then 1 else 0 end as screenshot_url_socre,\nrequired_quality_score,\ncore_quality_score,\nother_quality_score,\nplatform_name,\nsource_type,\nis_exp,\ncase when status <>1 then 1 else 0 end as is_off_shelf\nfrom view_union", "expected_csv": "uniqu_id,id_socre,name_socre,sub_title_socre,property_socre,sku_list_socre,desc_info_socre,url_socre,status_socre,price_socre,sale_qty_socre,stock_qty_socre,main_image_url_socre,sub_image_url_socre,category_level1_id_socre,category_level1_name_socre,category_level2_id_socre,category_level2_name_socre,category_level3_id_socre,category_level3_name_socre,shop_uniqu_id_socre,shop_id_socre,shop_name_socre,shop_url_socre,platform_id_socre,platform_name_socre,shipping_address_socre,price_text_socre,flag_socre,need_cutpic_socre,is_ocr_socre,soe_flag_socre,data_channel_socre,data_method_socre,data_source_socre,detail_image_url_socre,service_guarantee_socre,brand_id_socre,brand_name_socre,is_ad_socre,is_selfoperated_socre,create_time_socre,task_id_socre,batch_id_socre,category_level1_original_socre,category_level2_original_socre,category_level3_original_socre,brand_name_original_socre,product_name_socre,approval_number_socre,ccc_certificate_number_socre,efficacy_socre,production_place_socre,manufacturer_socre,production_license_number_socre,factory_name_socre,factory_address_socre,brand_authorization_image_url_socre,is_virtual_socre,is_invoice_socre,is_guarantee_socre,is_free_ship_socre,comments_cnt_socre,industry_id_socre,industry_name_socre,high_remark_cnt_socre,med_remark_cnt_socre,bad_remark_cnt_socre,main_image_ocr_socre,sub_image_ocr_socre,detail_image_ocr_socre,ml_category_tag_socre,logo_brand_socre,similarity_img_url_socre,sku_cnt_socre,license_collection_status_socre,data_method_keyword_socre,task_name_socre,screenshot_url_socre,required_quality_score,core_quality_score,other_quality_score,platform_name,source_type,is_exp,is_off_shelf,p_date\nuid_ext_001,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,,,1,1,,,1,18,12,8,PlatformB,泛化采集,0,0,20260608\nuid_hi_001,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,,,1,1,,,1,20,15,10,PlatformA,精细采集,0,0,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数87 + 列名匹配\nC,C_row_alignment,row_consistency,10,行数比例 + key(uniqu_id)覆盖率\nD,D_score_fields,score_fields,25,~80个0/1评分字段逐行正确率(均分)\nD,D_derived_flags,derived_flags,20,is_exp和is_off_shelf派生逻辑逐行正确率\nD,D_union_source,union_source,10,source_type两值(精细采集/泛化采集)覆盖率\nF,F_insert_overwrite,insert_overwrite,5,INSERT OVERWRITE + PARTITION\nF,F_partition_value,partition_value,5,p_date='20260608'\nF,F_union_completeness,union_completeness,5,UNION ALL两分支完整\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,HARD\n# 权重,\"product=0.7, process=0.3\"\n# 范式,new\n# Key列,uniqu_id\n# 预期列数,87\n# 输出表,internal_platform_db.ads_sec_ec_sup_ec_tele_item_score_cand_query_engine_140", "path": "tasks/offline-compute/HiveSQL/hivesql_025"} {"task_id": "hivesql_026_en", "id": "offline-compute_HiveSQL_hivesql_026", "name": "Merge 6 business detail tables from different scenarios (group, pd, socialzone, social_scene, profile_page, group", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n### Task Objective\nMerge 6 business detail tables from different scenarios using UNION ALL after date filtering, writing the results into a unified detail partitioned table.\n\n### Inputs\n- `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_group_di_query_engine_142`\n- `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_pd_di_query_engine_142`\n- `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_social_di_query_engine_142`\n- `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_social_scene_di_query_engine_142`\n- `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_profile_page_di_query_engine_142`\n- `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_group_profile_di_query_engine_142`\n\n### Processing Rules\n1. No joins, single-table processing\n2. Filter condition: `imp_date = 20260608` for all tables\n3. Field alignment rules:\n - 5 tables (group, socialzone, social_scene, profile_page, group_profile) use `SELECT *` to output all 13 fields\n - The `pd` table has 15 fields; explicitly list the first 13 fields: `imp_date`, `appid`, `message_id`, `puin`, `code`, `group_no`, `scene`, `sub_scene`, `hit_msg`, `is_punish_beat`, `new_reg_tag`, `payload_req`, `reg_date` (excluding the trailing `strategy_id` and `strategy_status`)\n4. Merge all results using UNION ALL, without deduplication\n\n### Output Requirements\nOutput field order: `imp_date`, `appid`, `message_id`, `puin`, `code`, `group_no`, `scene`, `sub_scene`, `hit_msg`, `is_punish_beat`, `new_reg_tag`, `payload_req`, `reg_date`\n\n### Write Requirements\n- Target table: `internal_platform_db.dwd_im_ads_businesses_core_scene_detail_di_cand_query_engine_142`\n- Write method: `INSERT OVERWRITE`\n- Partition field: `imp_date = 20260608`\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.dwd_im_ads_businesses_core_scene_detail_di_query_engine_142 PARTITION (imp_date = 20260608)\nselect appid, message_id, puin, code, group_no, scene, sub_scene, hit_msg, is_punish_beat, new_reg_tag, payload_req, reg_date\nfrom internal_platform_db.dwd_im_ads_businesses_core_scene_detail_group_di_query_engine_142\nwhere imp_date = 20260608\nunion all\nselect appid, message_id, puin, code, group_no, scene, sub_scene, hit_msg, is_punish_beat, new_reg_tag, payload_req, reg_date\nfrom internal_platform_db.dwd_im_ads_businesses_core_scene_detail_pd_di_query_engine_142\nwhere imp_date = 20260608\nunion all\nselect appid, message_id, puin, code, group_no, scene, sub_scene, hit_msg, is_punish_beat, new_reg_tag, payload_req, reg_date\nfrom internal_platform_db.dwd_im_ads_businesses_core_scene_detail_social_di_query_engine_142\nwhere imp_date = 20260608\nunion all\nselect appid, message_id, puin, code, group_no, scene, sub_scene, hit_msg, is_punish_beat, new_reg_tag, payload_req, reg_date\nfrom internal_platform_db.dwd_im_ads_businesses_core_scene_detail_social_scene_di_query_engine_142\nwhere imp_date = 20260608\nunion all\nselect appid, message_id, puin, code, group_no, scene, sub_scene, hit_msg, is_punish_beat, new_reg_tag, payload_req, reg_date\nfrom internal_platform_db.dwd_im_ads_businesses_core_scene_detail_profile_page_di_query_engine_142\nwhere imp_date = 20260608\nunion all\nselect appid, message_id, puin, code, group_no, scene, sub_scene, hit_msg, is_punish_beat, new_reg_tag, payload_req, reg_date\nfrom internal_platform_db.dwd_im_ads_businesses_core_scene_detail_group_profile_di_query_engine_142\nwhere imp_date = 20260608", "expected_csv": "appid,message_id,puin,code,group_no,scene,sub_scene,hit_msg,is_punish_beat,new_reg_tag,payload_req,reg_date,imp_date\napp001,msg_g1,puin001,1,grp001,scene_group,sub_group1,hit1,1,3,\"{\"\"key\"\":\"\"val1\"\"}\",20250101,20260608\napp006,msg_jb1,puin006,0,grp006,scene_social_scene,sub_jb1,,0,15,\"{\"\"key\"\":\"\"val6\"\"}\",20220601,20260608\napp002,msg_g2,puin002,0,grp002,scene_group,sub_group2,,0,7,\"{\"\"key\"\":\"\"val2\"\"}\",20240601,20260608\napp005,msg_qz1,puin005,1,grp005,scene_socialzone,sub_qz1,hit5,1,2,\"{\"\"key\"\":\"\"val5\"\"}\",20250301,20260608\napp007,msg_zl1,puin007,1,grp007,scene_profile_page,sub_zl1,hit7,1,1,\"{\"\"key\"\":\"\"val7\"\"}\",20250601,20260608\napp004,msg_pd2,puin004,0,grp004,scene_pd,sub_pd2,,0,10,\"{\"\"key\"\":\"\"val4\"\"}\",20231201,20260608\napp003,msg_pd1,puin003,1,grp003,scene_pd,sub_pd1,hit3,1,5,\"{\"\"key\"\":\"\"val3\"\"}\",20230901,20260608\napp008,msg_gp1,puin008,0,grp008,scene_gprofile,sub_gp1,,0,20,\"{\"\"key\"\":\"\"val8\"\"}\",20210301,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数13 + 列名匹配\nC,C_row_alignment,row_consistency,15,\"行数比例(7) + key(appid,message_id,imp_date)覆盖率(8)\"\nD,D_row_values,row_values,40,\"10个非key数据列逐行匹配(puin,code,group_no,scene,sub_scene,hit_msg,is_punish_beat,new_reg_tag,payload_req,reg_date)\"\nF,F_insert_overwrite,insert_overwrite,5,写入模式应为 INSERT OVERWRITE\nF,F_partition_value,partition_value,5,imp_date=20260608\nF,F_union_all_tables,union_all_tables,10,6个源表均在SQL中被引用\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)\n# 难度,EASY\n# 权重,\"product=0.5, process=0.5\"\n# 范式,new\n# Key列,\"appid, message_id, imp_date\"\n# 预期列数,\n# 输出表,internal_platform_db.dwd_im_ads_businesses_core_scene_detail_di_cand_query_engine_142", "path": "tasks/offline-compute/HiveSQL/hivesql_026_en"} {"task_id": "hivesql_027", "id": "offline-compute_HiveSQL_hivesql_027", "name": "从 dim_ds_org_info_d_ql_query_engine_143(机构信息)、dim_ds_project_info_d", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n1) 任务目标\n构建数字化工具平台数据日报,按日期+平台维度汇总机构、项目、用户、转账四类指标的累计值和新增值,用于平台运营分析。\n\n2) 输入\n- internal_platform_db.dim_ds_org_info_d_ql_query_engine_143:机构信息(分区 imp_date=20260608,is_test_org=0)\n- internal_platform_db.dim_ds_project_info_d_ql_query_engine_143:项目信息(分区 imp_date=20260608,is_test_project=0)\n- internal_platform_db.dim_ds_grantee_data_d_ql_query_engine_143:受助人数据(分区 imp_date=20260608,ds_grantee_state in (0,1))\n- internal_platform_db.dwd_project_ds_transfer_log_d_ql_query_engine_143:转账流水(分区 imp_date=20260608,transfer_state=2)\n\n3) 处理规则\n**平台维度**:fundraising_platform=2 为'慈善平台X',其他为'其他平台',同时需产出'所有平台'汇总行\n**机构-项目数据 org_pid_data**:\n- 机构表 LEFT JOIN 项目表 ON ds_org_id\n- 计算机构创建日期(substring(create_time,1,10))、项目创建日期\n- 按机构、项目维度生成各类 row_number,用于首次出现判断\n**用户数据 user_data**:\n- 受助人表 JOIN 项目表 ON ds_project_id\n- 平台W认证日期:取 platformw_auth_time 和 agent_platformw_auth_time 非空者最早日期\n- 是否平台W认证:open_id 或 agent_open_id 非空且对应 auth_time 非空\n- 是否银行认证:bank_account 非空\n- 按机构、项目、用户、代理人、认证维度生成各类 row_number\n**转账数据 transfer_data**:\n- 转账表 JOIN 项目表 ON ds_project_id\n- 转账日期:transfer_mode=1 用 trans_succ_time,否则用 create_time(substring 到日期)\n- 按机构、项目、用户、转账方式维度生成各类 row_number\n**累计指标计算**:通过窗口函数按平台维度计算累计总数(首次出现即 row_number=1 的实体计数)\n**新增指标计算**:按 stat_date 分组统计当日首次出现的实体数量或金额汇总\n**聚合方式**:先按各业务日期分组聚合,再 UNION ALL 多个维度(机构创建、项目创建、用户创建、平台W认证、转账)的结果,最后按 fundraising_platform+stat_date 再次聚合取 MAX\n\n4) 输出要求\n- 字段顺序:imp_date, fundraising_platform, stat_date, 然后是 52 个指标字段(total_* 26 个,new_* 26 个)\n- 52 个指标:机构数/项目机构数/项目数,用户机构数/项目数/用户数/代理人数/平台W认证用户数/银行认证用户数,转账金额/笔数/机构数/项目数/用户数(均分总计/平台W/银行三类)\n- imp_date 固定值 20260608\n- stat_date 为各业务日期(yyyy-MM-dd),部分行为 NULL(所有平台汇总行)\n- fundraising_platform 为'慈善平台X'/'其他平台'/'所有平台'\n\n5) 写入要求\n- 目标表:internal_platform_db.ads_gy_digital_tool_used_plat_data_d_ql_cand_query_engine_143\n- 写入方式:INSERT INTO\n- 输出需包含所有 fundraising_platform 与 stat_date 的组合(含 stat_date 为 NULL 的汇总行)\n\n请将最终 HiveSQL 写入 result.sql 并执行。", "ground_truth": "INSERT INTO TABLE internal_platform_db.ads_gy_digital_tool_used_plat_data_d_ql_query_engine_143\n(\nimp_date\n,`fundraising_platform`\n,`stat_date`\n,`total_org_cnt`\n,`total_pid_org_cnt`\n,`total_pid_cnt`\n,`total_user_org_cnt`\n,`total_user_pid_cnt`\n,`total_user_cnt`\n,`total_agent_cnt`\n,`total_platformw_auth_user_cnt`\n,`total_bank_auth_user_cnt`\n,`total_transfer_amount`\n,`total_platformw_transfer_amount`\n,`total_bank_transfer_amount`\n,`total_transfer_cnt`\n,`total_platformw_transfer_cnt`\n,`total_bank_transfer_cnt`\n,`total_transfer_org_cnt`\n,`total_platformw_transfer_org_cnt`\n,`total_bank_transfer_org_cnt`\n,`total_transfer_pid_cnt`\n,`total_platformw_transfer_pid_cnt`\n,`total_bank_transfer_pid_cnt`\n,`total_transfer_user_cnt`\n,`total_platformw_transfer_user_cnt`\n,`total_bank_transfer_user_cnt`\n,`new_org_cnt`\n,`new_pid_org_cnt`\n,`new_pid_cnt`\n,`new_user_org_cnt`\n,`new_user_pid_cnt`\n,`new_user_cnt`\n,`new_agent_cnt`\n,`new_platformw_auth_user_cnt`\n,`new_bank_auth_user_cnt`\n,`new_transfer_amount`\n,`new_platformw_transfer_amount`\n,`new_bank_transfer_amount`\n,`new_transfer_cnt`\n,`new_platformw_transfer_cnt`\n,`new_bank_transfer_cnt`\n,`new_transfer_org_cnt`\n,`new_platformw_transfer_org_cnt`\n,`new_bank_transfer_org_cnt`\n,`new_transfer_pid_cnt`\n,`new_platformw_transfer_pid_cnt`\n,`new_bank_transfer_pid_cnt`\n,`new_transfer_user_cnt`\n,`new_platformw_transfer_user_cnt`\n,`new_bank_transfer_user_cnt`\n)with org_pid_data as\n(\nselect\n*\n, row_number() over (partition by ds_org_id order by org_create_date) as org_rk\n, row_number() over (partition by fundraising_platform,ds_org_id order by org_create_date) as org_plat_rk\n, row_number() over (partition by ds_org_id,is_org_pid order by org_create_date) as org_pid_rk\n, row_number() over (partition by fundraising_platform,ds_org_id,is_org_pid order by org_create_date) as org_pid_plat_rk\n, row_number() over (partition by ds_project_id order by pid_create_date) as pid_rk\n, row_number() over (partition by fundraising_platform,ds_project_id order by pid_create_date) as pid_plat_rk\nfrom\n(\nselect\ncase when b.fundraising_platform = 2 then '慈善平台X' else '其他平台' end as fundraising_platform\n, b.ds_project_id\n, a.ds_org_id\n, substring(a.create_time,1,10) as org_create_date\n, substring(b.create_time,1,10) as pid_create_date\n, case when b.ds_project_id is not null then 1 else 0 end as is_org_pid\nfrom\n(\nselect\nds_org_id\n, create_time\nfrom\ninternal_platform_db.dim_ds_org_info_d_ql_query_engine_143\nwhere\nimp_date = 20260608\nand is_test_org = 0\n) a\nleft join\n(\nselect\nds_org_id\n, ds_project_id\n, create_time\n, fundraising_platform\nfrom\ninternal_platform_db.dim_ds_project_info_d_ql_query_engine_143\nwhere\nimp_date = 20260608\nand is_test_project = 0\n) b on a.ds_org_id = b.ds_org_id\n)\n),\nuser_data as\n(\nselect\n*\n, row_number() over (partition by ds_org_id order by user_create_date) as org_rk\n, row_number() over (partition by fundraising_platform,ds_org_id order by user_create_date) as org_plat_rk\n, row_number() over (partition by ds_project_id order by user_create_date) as pid_rk\n, row_number() over (partition by fundraising_platform,ds_project_id order by user_create_date) as pid_plat_rk\n, row_number() over (partition by ds_grantee_id order by user_create_date) as user_rk\n, row_number() over (partition by fundraising_platform,ds_grantee_id order by user_create_date) as user_plat_rk\n, row_number() over (partition by ds_grantee_id,is_platformw_auth order by platformw_auth_date) as user_auth_rk\n, row_number() over (partition by fundraising_platform,ds_grantee_id,is_platformw_auth order by platformw_auth_date) as user_plat_auth_rk\n, row_number() over (partition by ds_grantee_id,is_bank_auth order by user_create_date) as user_bank_auth_rk\n, row_number() over (partition by fundraising_platform,ds_grantee_id,is_bank_auth order by user_create_date) as user_plat_bank_auth_rk\n, row_number() over (partition by ds_agent_id order by user_create_date) as agent_rk\n, row_number() over (partition by fundraising_platform,ds_agent_id order by user_create_date) as agent_plat_rk\nfrom\n(\nselect\ncase when b.fundraising_platform = 2 then '慈善平台X' else '其他平台' end as fundraising_platform\n, b.ds_project_id\n, b.ds_org_id\n, a.ds_grantee_id\n, a.ds_agent_id\n, substring(a.create_time,1,10) as user_create_date\n, case when a.platformw_auth_time <> '' and a.agent_platformw_auth_time <> '' then least(substring(a.platformw_auth_time,1,10),substring(a.agent_platformw_auth_time,1,10))\nwhen a.platformw_auth_time <> '' and a.agent_platformw_auth_time = '' then substring(a.platformw_auth_time,1,10)\nelse substring(a.agent_platformw_auth_time,1,10) end as platformw_auth_date\n, case when coalesce(a.bank_account,'') != '' then 1 else 0 end as is_bank_auth\n, case when (coalesce(a.platformw_auth_time,'') != '' and coalesce(a.open_id,'') != '') or (coalesce(a.agent_platformw_auth_time,'') != '' and coalesce(a.agent_open_id,'') != '') then 1 else 0 end as is_platformw_auth\nfrom\ninternal_platform_db.dim_ds_grantee_data_d_ql_query_engine_143 a\njoin internal_platform_db.dim_ds_project_info_d_ql_query_engine_143 b on a.ds_project_id = b.ds_project_id\nwhere\na.imp_date = 20260608\nand b.imp_date = 20260608\nand a.ds_grantee_state in (0,1)\nand b.is_test_project = 0\n)\n),\ntransfer_data as\n(\nselect\n*\n, row_number() over (partition by ds_org_id order by transfer_date) as org_rk\n, row_number() over (partition by ds_org_id,transfer_mode order by transfer_date) as org_mode_rk\n, row_number() over (partition by fundraising_platform,ds_org_id order by transfer_date) as org_plat_rk\n, row_number() over (partition by fundraising_platform,ds_org_id,transfer_mode order by transfer_date) as org_plat_mode_rk\n, row_number() over (partition by ds_project_id order by transfer_date) as pid_rk\n, row_number() over (partition by ds_project_id,transfer_mode order by transfer_date) as pid_mode_rk\n, row_number() over (partition by fundraising_platform,ds_project_id order by transfer_date) as pid_plat_rk\n, row_number() over (partition by fundraising_platform,ds_project_id,transfer_mode order by transfer_date) as pid_plat_mode_rk\n, row_number() over (partition by ds_grantee_id order by transfer_date) as user_rk\n, row_number() over (partition by fundraising_platform,ds_grantee_id order by transfer_date) as user_plat_rk\n, row_number() over (partition by ds_grantee_id,transfer_mode order by transfer_date) as user_mode_rk\n, row_number() over (partition by fundraising_platform,ds_grantee_id,transfer_mode order by transfer_date) as user_plat_mode_rk\nfrom\n(\nselect\ncase when b.fundraising_platform = 2 then '慈善平台X' else '其他平台' end as fundraising_platform\n, case when a.transfer_mode = 1 then substring(a.trans_succ_time,1,10) else substring(a.create_time,1,10) end as transfer_date\n, b.ds_project_id\n, b.ds_org_id\n, a.ds_grantee_id\n, a.transfer_amount\n, a.transfer_mode\n, a.id\nfrom\ninternal_platform_db.dwd_project_ds_transfer_log_d_ql_query_engine_143 a\njoin internal_platform_db.dim_ds_project_info_d_ql_query_engine_143 b on a.ds_project_id = b.ds_project_id\nwhere\na.imp_date = 20260608\nand b.imp_date = 20260608\nand a.transfer_state = 2\nand b.is_test_project = 0\n)\n)\nselect\n20260608 as imp_date\n, fundraising_platform\n, stat_date\n, max(coalesce(total_org_cnt,0)) as total_org_cnt\n, max(coalesce(total_pid_org_cnt,0)) as total_pid_org_cnt\n, max(coalesce(total_pid_cnt,0)) as total_pid_cnt\n, max(coalesce(total_user_org_cnt,0)) as total_user_org_cnt\n, max(coalesce(total_user_pid_cnt,0)) as total_user_pid_cnt\n, max(coalesce(total_user_cnt,0)) as total_user_cnt\n, max(coalesce(total_agent_cnt,0)) as total_agent_cnt\n, max(coalesce(total_platformw_auth_user_cnt,0)) as total_platformw_auth_user_cnt\n, max(coalesce(total_bank_auth_user_cnt,0)) as total_bank_auth_user_cnt\n, max(coalesce(total_transfer_amount,0)) as total_transfer_amount\n, max(coalesce(total_platformw_transfer_amount,0)) as total_platformw_transfer_amount\n, max(coalesce(total_bank_transfer_amount,0)) as total_bank_transfer_amount\n, max(coalesce(total_transfer_cnt,0)) as total_transfer_cnt\n, max(coalesce(total_platformw_transfer_cnt,0)) as total_platformw_transfer_cnt\n, max(coalesce(total_bank_transfer_cnt,0)) as total_bank_transfer_cnt\n, max(coalesce(total_transfer_org_cnt,0)) as total_transfer_org_cnt\n, max(coalesce(total_platformw_transfer_org_cnt,0)) as total_platformw_transfer_org_cnt\n, max(coalesce(total_bank_transfer_org_cnt,0)) as total_bank_transfer_org_cnt\n, max(coalesce(total_transfer_pid_cnt,0)) as total_transfer_pid_cnt\n, max(coalesce(total_platformw_transfer_pid_cnt,0)) as total_platformw_transfer_pid_cnt\n, max(coalesce(total_bank_transfer_pid_cnt,0)) as total_bank_transfer_pid_cnt\n, max(coalesce(total_transfer_user_cnt,0)) as total_transfer_user_cnt\n, max(coalesce(total_platformw_transfer_user_cnt,0)) as total_platformw_transfer_user_cnt\n, max(coalesce(total_bank_transfer_user_cnt,0)) as total_bank_transfer_user_cnt\n, max(coalesce(new_org_cnt,0)) as new_org_cnt\n, max(coalesce(new_pid_org_cnt,0)) as new_pid_org_cnt\n, max(coalesce(new_pid_cnt,0)) as new_pid_cnt\n, max(coalesce(new_user_org_cnt,0)) as new_user_org_cnt\n, max(coalesce(new_user_pid_cnt,0)) as new_user_pid_cnt\n, max(coalesce(new_user_cnt,0)) as new_user_cnt\n, max(coalesce(new_agent_cnt,0)) as new_agent_cnt\n, max(coalesce(new_platformw_auth_user_cnt,0)) as new_platformw_auth_user_cnt\n, max(coalesce(new_bank_auth_user_cnt,0)) as new_bank_auth_user_cnt\n, max(coalesce(new_transfer_amount,0)) as new_transfer_amount\n, max(coalesce(new_platformw_transfer_amount,0)) as new_platformw_transfer_amount\n, max(coalesce(new_bank_transfer_amount,0)) as new_bank_transfer_amount\n, max(coalesce(new_transfer_cnt,0)) as new_transfer_cnt\n, max(coalesce(new_platformw_transfer_cnt,0)) as new_platformw_transfer_cnt\n, max(coalesce(new_bank_transfer_cnt,0)) as new_bank_transfer_cnt\n, max(coalesce(new_transfer_org_cnt,0)) as new_transfer_org_cnt\n, max(coalesce(new_platformw_transfer_org_cnt,0)) as new_platformw_transfer_org_cnt\n, max(coalesce(new_bank_transfer_org_cnt,0)) as new_bank_transfer_org_cnt\n, max(coalesce(new_transfer_pid_cnt,0)) as new_transfer_pid_cnt\n, max(coalesce(new_platformw_transfer_pid_cnt,0)) as new_platformw_transfer_pid_cnt\n, max(coalesce(new_bank_transfer_pid_cnt,0)) as new_bank_transfer_pid_cnt\n, max(coalesce(new_transfer_user_cnt,0)) as new_transfer_user_cnt\n, max(coalesce(new_platformw_transfer_user_cnt,0)) as new_platformw_transfer_user_cnt\n, max(coalesce(new_bank_transfer_user_cnt,0)) as new_bank_transfer_user_cnt\nfrom\n(\nselect\n'所有平台' as fundraising_platform\n, org_create_date as stat_date\n, max(total_org_cnt) as total_org_cnt\n, max(total_pid_org_cnt) as total_pid_org_cnt\n, max(total_pid_cnt) as total_pid_cnt\n, 0 as total_user_org_cnt\n, 0 as total_user_pid_cnt\n, 0 as total_user_cnt\n, 0 as total_agent_cnt\n, 0 as total_platformw_auth_user_cnt\n, 0 as total_bank_auth_user_cnt\n, 0 as total_transfer_amount\n, 0 as total_platformw_transfer_amount\n, 0 as total_bank_transfer_amount\n, 0 as total_transfer_cnt\n, 0 as total_platformw_transfer_cnt\n, 0 as total_bank_transfer_cnt\n, 0 as total_transfer_org_cnt\n, 0 as total_platformw_transfer_org_cnt\n, 0 as total_bank_transfer_org_cnt\n, 0 as total_transfer_pid_cnt\n, 0 as total_platformw_transfer_pid_cnt\n, 0 as total_bank_transfer_pid_cnt\n, 0 as total_transfer_user_cnt\n, 0 as total_platformw_transfer_user_cnt\n, 0 as total_bank_transfer_user_cnt\n, count(case when org_rk = 1 then ds_org_id end) as new_org_cnt\n, 0 as new_pid_org_cnt\n, 0 as new_pid_cnt\n, 0 as new_user_org_cnt\n, 0 as new_user_pid_cnt\n, 0 as new_user_cnt\n, 0 as new_agent_cnt\n, 0 as new_platformw_auth_user_cnt\n, 0 as new_bank_auth_user_cnt\n, 0 as new_transfer_amount\n, 0 as new_platformw_transfer_amount\n, 0 as new_bank_transfer_amount\n, 0 as new_transfer_cnt\n, 0 as new_platformw_transfer_cnt\n, 0 as new_bank_transfer_cnt\n, 0 as new_transfer_org_cnt\n, 0 as new_platformw_transfer_org_cnt\n, 0 as new_bank_transfer_org_cnt\n, 0 as new_transfer_pid_cnt\n, 0 as new_platformw_transfer_pid_cnt\n, 0 as new_bank_transfer_pid_cnt\n, 0 as new_transfer_user_cnt\n, 0 as new_platformw_transfer_user_cnt\n, 0 as new_bank_transfer_user_cnt\nfrom\n(\nselect\n*\n, count(case when org_rk = 1 then ds_org_id end) over (partition by 1) as total_org_cnt\n, count(case when is_org_pid = 1 and org_pid_rk = 1 then ds_org_id end) over (partition by 1) as total_pid_org_cnt\n, count(case when pid_rk = 1 then ds_project_id end) over (partition by 1) as total_pid_cnt\nfrom org_pid_data\n) a\ngroup by\norg_create_date\nunion all\nselect\nfundraising_platform\n, org_create_date as org_date\n, 0 as total_org_cnt\n, max(total_pid_org_cnt) as total_pid_org_cnt\n, max(total_pid_cnt) as total_pid_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, count(case when org_plat_rk = 1 then ds_org_id end) as new_org_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom\n(\nselect\n*\n, count(case when org_plat_rk = 1 then ds_org_id end) over (partition by fundraising_platform) as total_org_cnt\n, count(case when is_org_pid = 1 and org_pid_plat_rk = 1 then ds_org_id end) over (partition by fundraising_platform) as total_pid_org_cnt\n, count(case when pid_plat_rk = 1 then ds_project_id end) over (partition by fundraising_platform) as total_pid_cnt\nfrom org_pid_data\n) a\ngroup by\nfundraising_platform\n, org_create_date\nunion all\nselect\n'所有平台' as fundraising_platform\n, pid_create_date\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, 0\n, count(case when is_org_pid = 1 and org_pid_rk = 1 then ds_org_id end) as new_pid_org_cnt\n, count(case when pid_rk = 1 then ds_project_id end) as new_pid_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom\norg_pid_data\ngroup by\npid_create_date\nunion all\nselect\nfundraising_platform\n, pid_create_date\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, 0\n, count(case when is_org_pid = 1 and org_pid_plat_rk = 1 then ds_org_id end) as new_pid_org_cnt\n, count(case when pid_plat_rk = 1 then ds_project_id end) as new_pid_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom\norg_pid_data\ngroup by\nfundraising_platform\n, pid_create_date\nunion all\nselect\n'所有平台' as fundraising_platform\n, user_create_date as user_date\n, 0,0,0\n, max(total_user_org_cnt) as total_user_org_cnt\n, max(total_user_pid_cnt) as total_user_pid_cnt\n, max(total_user_cnt) as total_user_cnt\n, max(total_agent_cnt) as total_agent_cnt\n, max(total_platformw_auth_user_cnt) as total_platformw_auth_user_cnt\n, max(total_bank_auth_user_cnt) as total_bank_auth_user_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, 0,0,0\n, count(case when org_rk = 1 then ds_org_id end) as new_user_org_cnt\n, count(case when pid_rk = 1 then ds_project_id end) as new_user_pid_cnt\n, count(case when user_rk = 1 then ds_grantee_id end) as new_user_cnt\n, count(case when agent_rk = 1 then ds_agent_id end) as new_agent_cnt\n, 0 as new_platformw_auth_user_cnt\n, count(case when is_bank_auth = 1 and user_bank_auth_rk = 1 then ds_grantee_id end) as new_bank_auth_user_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom\n(\nselect\n*\n, count(case when org_rk = 1 then ds_org_id end) over (partition by 1) as total_user_org_cnt\n, count(case when pid_rk = 1 then ds_project_id end) over (partition by 1) as total_user_pid_cnt\n, count(case when user_rk = 1 then ds_grantee_id end) over (partition by 1) as total_user_cnt\n, count(case when agent_rk = 1 then ds_agent_id end) over (partition by 1) as total_agent_cnt\n, count(case when is_platformw_auth = 1 and user_auth_rk = 1 then ds_grantee_id end) over (partition by 1) as total_platformw_auth_user_cnt\n, count(case when is_bank_auth = 1 and user_bank_auth_rk = 1 then ds_grantee_id end) over (partition by 1) as total_bank_auth_user_cnt\nfrom user_data\n) a\ngroup by\nuser_create_date\nunion all\nselect\nfundraising_platform\n, user_create_date\n, 0,0,0\n, max(total_user_org_cnt) as total_user_org_cnt\n, max(total_user_pid_cnt) as total_user_pid_cnt\n, max(total_user_cnt) as total_user_cnt\n, max(total_agent_cnt) as total_agent_cnt\n, max(total_platformw_auth_user_cnt) as total_platformw_auth_user_cnt\n, max(total_bank_auth_user_cnt) as total_bank_auth_user_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, 0,0,0\n, count(case when org_plat_rk = 1 then ds_org_id end) as new_user_org_cnt\n, count(case when pid_plat_rk = 1 then ds_project_id end) as new_user_pid_cnt\n, count(case when user_plat_rk = 1 then ds_grantee_id end) as new_user_cnt\n, count(case when agent_plat_rk = 1 then ds_agent_id end) as new_agent_cnt\n, 0 as new_platformw_auth_user_cnt\n, count(case when is_bank_auth = 1 and user_plat_bank_auth_rk = 1 then ds_grantee_id end) as new_bank_auth_user_cnt\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom\n(\nselect\n*\n, count(case when org_plat_rk = 1 then ds_org_id end) over (partition by fundraising_platform) as total_user_org_cnt\n, count(case when pid_plat_rk = 1 then ds_project_id end) over (partition by fundraising_platform) as total_user_pid_cnt\n, count(case when user_plat_rk = 1 then ds_grantee_id end) over (partition by fundraising_platform) as total_user_cnt\n, count(case when agent_plat_rk = 1 then ds_agent_id end) over (partition by fundraising_platform) as total_agent_cnt\n, count(case when is_platformw_auth = 1 and user_plat_auth_rk = 1 then ds_grantee_id end) over (partition by fundraising_platform) as total_platformw_auth_user_cnt\n, count(case when is_bank_auth = 1 and user_plat_bank_auth_rk = 1 then ds_grantee_id end) over (partition by fundraising_platform) as total_bank_auth_user_cnt\nfrom user_data\n) a\ngroup by\nfundraising_platform\n, user_create_date\nunion all\nselect\n'所有平台' as fundraising_platform\n, platformw_auth_date\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, 0,0,0\n, 0,0,0,0\n, count(case when is_platformw_auth = 1 and user_plat_auth_rk = 1 then ds_grantee_id end) as new_platformw_auth_user_cnt\n, 0\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom user_data\ngroup by\nplatformw_auth_date\nunion all\nselect\nfundraising_platform\n, platformw_auth_date\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n, 0,0,0\n, 0,0,0,0\n, count(case when is_platformw_auth = 1 and user_plat_auth_rk = 1 then ds_grantee_id end) as new_platformw_auth_user_cnt\n, 0\n, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nfrom user_data\ngroup by\nfundraising_platform\n, platformw_auth_date\nunion all\nselect\n'所有平台' as fundraising_platform\n, transfer_date\n, 0,0,0,0,0,0,0,0,0\n, max(total_transfer_amount) as total_transfer_amount\n, max(total_platformw_transfer_amount) as total_platformw_transfer_amount\n, max(total_bank_transfer_amount) as total_bank_transfer_amount\n, max(total_transfer_cnt) as total_transfer_cnt\n, max(total_platformw_transfer_cnt) as total_platformw_transfer_cnt\n, max(total_bank_transfer_cnt) as total_bank_transfer_cnt\n, max(total_transfer_org_cnt) as total_transfer_org_cnt\n, max(total_platformw_transfer_org_cnt) as total_platformw_transfer_org_cnt\n, max(total_bank_transfer_org_cnt) as total_bank_transfer_org_cnt\n, max(total_transfer_pid_cnt) as total_transfer_pid_cnt\n, max(total_platformw_transfer_pid_cnt) as total_platformw_transfer_pid_cnt\n, max(total_bank_transfer_pid_cnt) as total_bank_transfer_pid_cnt\n, max(total_transfer_user_cnt) as total_transfer_user_cnt\n, max(total_platformw_transfer_user_cnt) as total_platformw_transfer_user_cnt\n, max(total_bank_transfer_user_cnt) as total_bank_transfer_user_cnt\n, 0,0,0,0,0,0,0,0,0\n, sum(transfer_amount) as transfer_amount\n, sum(case when transfer_mode = 1 then transfer_amount end) as platformw_transfer_amount\n, sum(case when transfer_mode = 2 then transfer_amount end) as bank_transfer_amount\n, count(id) as transfer_cnt\n, count(case when transfer_mode = 1 then id end) as platformw_transfer_cnt\n, count(case when transfer_mode = 2 then id end) as bank_transfer_cnt\n, count(case when org_rk = 1 then ds_org_id end) as new_transfer_org_cnt\n, count(case when transfer_mode = 1 and org_mode_rk = 1 then ds_org_id end) as new_platformw_transfer_org_cnt\n, count(case when transfer_mode = 2 and org_mode_rk = 1 then ds_org_id end) as new_bank_transfer_org_cnt\n, count(case when pid_rk = 1 then ds_project_id end) as new_transfer_pid_cnt\n, count(case when transfer_mode = 1 and pid_mode_rk = 1 then ds_project_id end) as new_platformw_transfer_pid_cnt\n, count(case when transfer_mode = 2 and pid_mode_rk = 1 then ds_project_id end) as new_bank_transfer_pid_cnt\n, count(case when user_rk = 1 then ds_grantee_id end) as new_transfer_user_cnt\n, count(case when transfer_mode = 1 and user_mode_rk = 1 then ds_grantee_id end) as new_platformw_transfer_user_cnt\n, count(case when transfer_mode = 2 and user_mode_rk = 1 then ds_grantee_id end) as new_bank_transfer_user_cnt\nfrom\n(\nselect\n*\n, sum(transfer_amount) over (partition by 1) as total_transfer_amount\n, sum(case when transfer_mode = 1 then transfer_amount end) over (partition by 1) as total_platformw_transfer_amount\n, sum(case when transfer_mode = 2 then transfer_amount end) over (partition by 1) as total_bank_transfer_amount\n, count(id) over (partition by 1) as total_transfer_cnt\n, count(case when transfer_mode = 1 then id end) over (partition by 1) as total_platformw_transfer_cnt\n, count(case when transfer_mode = 2 then id end) over (partition by 1) as total_bank_transfer_cnt\n, count(case when org_rk = 1 then ds_org_id end) over (partition by 1) as total_transfer_org_cnt\n, count(case when transfer_mode = 1 and org_mode_rk = 1 then ds_org_id end) over (partition by 1) as total_platformw_transfer_org_cnt\n, count(case when transfer_mode = 2 and org_mode_rk = 1 then ds_org_id end) over (partition by 1) as total_bank_transfer_org_cnt\n, count(case when pid_rk = 1 then ds_project_id end) over (partition by 1) as total_transfer_pid_cnt\n, count(case when transfer_mode = 1 and pid_mode_rk = 1 then ds_project_id end) over (partition by 1) as total_platformw_transfer_pid_cnt\n, count(case when transfer_mode = 2 and pid_mode_rk = 1 then ds_project_id end) over (partition by 1) as total_bank_transfer_pid_cnt\n, count(case when user_rk = 1 then ds_grantee_id end) over (partition by 1) as total_transfer_user_cnt\n, count(case when transfer_mode = 1 and user_mode_rk = 1 then ds_grantee_id end) over (partition by 1) as total_platformw_transfer_user_cnt\n, count(case when transfer_mode = 2 and user_mode_rk = 1 then ds_grantee_id end) over (partition by 1) as total_bank_transfer_user_cnt\nfrom transfer_data\n) a\ngroup by\ntransfer_date\nunion all\nselect\nfundraising_platform\n, transfer_date\n, 0,0,0,0,0,0,0,0,0\n, max(total_transfer_amount) as total_transfer_amount\n, max(total_platformw_transfer_amount) as total_platformw_transfer_amount\n, max(total_bank_transfer_amount) as total_bank_transfer_amount\n, max(total_transfer_cnt) as total_transfer_cnt\n, max(total_platformw_transfer_cnt) as total_platformw_transfer_cnt\n, max(total_bank_transfer_cnt) as total_bank_transfer_cnt\n, max(total_transfer_org_cnt) as total_transfer_org_cnt\n, max(total_platformw_transfer_org_cnt) as total_platformw_transfer_org_cnt\n, max(total_bank_transfer_org_cnt) as total_bank_transfer_org_cnt\n, max(total_transfer_pid_cnt) as total_transfer_pid_cnt\n, max(total_platformw_transfer_pid_cnt) as total_platformw_transfer_pid_cnt\n, max(total_bank_transfer_pid_cnt) as total_bank_transfer_pid_cnt\n, max(total_transfer_user_cnt) as total_transfer_user_cnt\n, max(total_platformw_transfer_user_cnt) as total_platformw_transfer_user_cnt\n, max(total_bank_transfer_user_cnt) as total_bank_transfer_user_cnt\n, 0,0,0,0,0,0,0,0,0\n, sum(transfer_amount) as transfer_amount\n, sum(case when transfer_mode = 1 then transfer_amount end) as platformw_transfer_amount\n, sum(case when transfer_mode = 2 then transfer_amount end) as bank_transfer_amount\n, count(id) as transfer_cnt\n, count(case when transfer_mode = 1 then id end) as platformw_transfer_cnt\n, count(case when transfer_mode = 2 then id end) as bank_transfer_cnt\n, count(case when org_plat_rk = 1 then ds_org_id end) as new_transfer_org_cnt\n, count(case when transfer_mode = 1 and org_plat_mode_rk = 1 then ds_org_id end) as new_platformw_transfer_org_cnt\n, count(case when transfer_mode = 2 and org_plat_mode_rk = 1 then ds_org_id end) as new_bank_transfer_org_cnt\n, count(case when pid_plat_rk = 1 then ds_project_id end) as new_transfer_pid_cnt\n, count(case when transfer_mode = 1 and pid_plat_mode_rk = 1 then ds_project_id end) as new_platformw_transfer_pid_cnt\n, count(case when transfer_mode = 2 and pid_plat_mode_rk = 1 then ds_project_id end) as new_bank_transfer_pid_cnt\n, count(case when user_plat_rk = 1 then ds_grantee_id end) as new_transfer_user_cnt\n, count(case when transfer_mode = 1 and user_plat_mode_rk = 1 then ds_grantee_id end) as new_platformw_transfer_user_cnt\n, count(case when transfer_mode = 2 and user_plat_mode_rk = 1 then ds_grantee_id end) as new_bank_transfer_user_cnt\nfrom\n(\nselect\n*\n, sum(transfer_amount) over (partition by fundraising_platform) as total_transfer_amount\n, sum(case when transfer_mode = 1 then transfer_amount end) over (partition by fundraising_platform) as total_platformw_transfer_amount\n, sum(case when transfer_mode = 2 then transfer_amount end) over (partition by fundraising_platform) as total_bank_transfer_amount\n, count(id) over (partition by fundraising_platform) as total_transfer_cnt\n, count(case when transfer_mode = 1 then id end) over (partition by fundraising_platform) as total_platformw_transfer_cnt\n, count(case when transfer_mode = 2 then id end) over (partition by fundraising_platform) as total_bank_transfer_cnt\n, count(case when org_plat_rk = 1 then ds_org_id end) over (partition by fundraising_platform) as total_transfer_org_cnt\n, count(case when transfer_mode = 1 and org_plat_mode_rk = 1 then ds_org_id end) over (partition by fundraising_platform) as total_platformw_transfer_org_cnt\n, count(case when transfer_mode = 2 and org_plat_mode_rk = 1 then ds_org_id end) over (partition by fundraising_platform) as total_bank_transfer_org_cnt\n, count(case when pid_plat_rk = 1 then ds_project_id end) over (partition by fundraising_platform) as total_transfer_pid_cnt\n, count(case when transfer_mode = 1 and pid_plat_mode_rk = 1 then ds_project_id end) over (partition by fundraising_platform) as total_platformw_transfer_pid_cnt\n, count(case when transfer_mode = 2 and pid_plat_mode_rk = 1 then ds_project_id end) over (partition by fundraising_platform) as total_bank_transfer_pid_cnt\n, count(case when user_plat_rk = 1 then ds_grantee_id end) over (partition by fundraising_platform) as total_transfer_user_cnt\n, count(case when transfer_mode = 1 and user_plat_mode_rk = 1 then ds_grantee_id end) over (partition by fundraising_platform) as total_platformw_transfer_user_cnt\n, count(case when transfer_mode = 2 and user_plat_mode_rk = 1 then ds_grantee_id end) over (partition by fundraising_platform) as total_bank_transfer_user_cnt\nfrom transfer_data\n) a\ngroup by\nfundraising_platform\n, transfer_date\n) t\ngroup by\nfundraising_platform\n, stat_date", "expected_csv": "imp_date,fundraising_platform,stat_date,total_org_cnt,total_pid_org_cnt,total_pid_cnt,total_user_org_cnt,total_user_pid_cnt,total_user_cnt,total_agent_cnt,total_platformw_auth_user_cnt,total_bank_auth_user_cnt,total_transfer_amount,total_platformw_transfer_amount,total_bank_transfer_amount,total_transfer_cnt,total_platformw_transfer_cnt,total_bank_transfer_cnt,total_transfer_org_cnt,total_platformw_transfer_org_cnt,total_bank_transfer_org_cnt,total_transfer_pid_cnt,total_platformw_transfer_pid_cnt,total_bank_transfer_pid_cnt,total_transfer_user_cnt,total_platformw_transfer_user_cnt,total_bank_transfer_user_cnt,new_org_cnt,new_pid_org_cnt,new_pid_cnt,new_user_org_cnt,new_user_pid_cnt,new_user_cnt,new_agent_cnt,new_platformw_auth_user_cnt,new_bank_auth_user_cnt,new_transfer_amount,new_platformw_transfer_amount,new_bank_transfer_amount,new_transfer_cnt,new_platformw_transfer_cnt,new_bank_transfer_cnt,new_transfer_org_cnt,new_platformw_transfer_org_cnt,new_bank_transfer_org_cnt,new_transfer_pid_cnt,new_platformw_transfer_pid_cnt,new_bank_transfer_pid_cnt,new_transfer_user_cnt,new_platformw_transfer_user_cnt,new_bank_transfer_user_cnt\n20260608,所有平台,2025-01-10,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-03-15,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-06-01,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-03-15,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-01-10,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,其他平台,2025-06-01,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-02-01,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,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-03-20,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,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-06-05,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,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-02-01,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,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,其他平台,2025-06-05,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,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-03-20,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,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-04-01,0,0,0,3,3,4,3,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-02-10,0,0,0,3,3,4,3,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-06-08,0,0,0,3,3,4,3,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-03-22,0,0,0,3,3,4,3,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-02-10,0,0,0,2,2,3,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-03-22,0,0,0,2,2,3,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,其他平台,2025-06-08,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,2025-04-01,0,0,0,2,2,3,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-06-10,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,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,,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,0,0\n20260608,所有平台,2025-02-15,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,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,慈善平台X,,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,0,0\n20260608,慈善平台X,2025-02-15,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,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,其他平台,2025-06-10,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,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n20260608,所有平台,2025-05-10,0,0,0,0,0,0,0,0,0,26000,8000,18000,4,2,2,3,1,2,3,1,2,4,2,2,0,0,0,0,0,0,0,0,0,3000,3000,0,1,1,0,0,0,0,0,0,0,1,1,0\n20260608,所有平台,2025-06-15,0,0,0,0,0,0,0,0,0,26000,8000,18000,4,2,2,3,1,2,3,1,2,4,2,2,0,0,0,0,0,0,0,0,0,10000,0,10000,1,0,1,1,0,1,1,0,1,1,0,1\n20260608,所有平台,2025-02-20,0,0,0,0,0,0,0,0,0,26000,8000,18000,4,2,2,3,1,2,3,1,2,4,2,2,0,0,0,0,0,0,0,0,0,5000,5000,0,1,1,0,1,1,0,1,1,0,1,1,0\n20260608,所有平台,2025-03-30,0,0,0,0,0,0,0,0,0,26000,8000,18000,4,2,2,3,1,2,3,1,2,4,2,2,0,0,0,0,0,0,0,0,0,8000,0,8000,1,0,1,1,0,1,1,0,1,1,0,1\n20260608,慈善平台X,2025-02-20,0,0,0,0,0,0,0,0,0,16000,8000,8000,3,2,1,2,1,1,2,1,1,3,2,1,0,0,0,0,0,0,0,0,0,5000,5000,0,1,1,0,1,1,0,1,1,0,1,1,0\n20260608,慈善平台X,2025-05-10,0,0,0,0,0,0,0,0,0,16000,8000,8000,3,2,1,2,1,1,2,1,1,3,2,1,0,0,0,0,0,0,0,0,0,3000,3000,0,1,1,0,0,0,0,0,0,0,1,1,0\n20260608,其他平台,2025-06-15,0,0,0,0,0,0,0,0,0,10000,0,10000,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,10000,0,10000,1,0,1,1,0,1,1,0,1,1,0,1\n20260608,慈善平台X,2025-03-30,0,0,0,0,0,0,0,0,0,16000,8000,8000,3,2,1,2,1,1,2,1,1,3,2,1,0,0,0,0,0,0,0,0,0,8000,0,8000,1,0,1,1,0,1,1,0,1,1,0,1", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,10,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数51 + 列名匹配\nC,C_row_alignment,row_consistency,10,\"行数比例 + key(fundraising_platform,stat_date)覆盖率\"\nD,D_cumulative_metrics,cumulative_metrics,30,26个total_*列逐行匹配\nD,D_incremental_metrics,incremental_metrics,25,26个new_*列逐行匹配\nF,F_platform_coverage,platform_coverage,5,'慈善平台X'+'其他平台'+'所有平台'\nF,F_join_completeness,join_completeness,3,4张源表都被引用\nF,F_insert_overwrite,insert_mode,4,INSERT INTO(非 OVERWRITE)\nF,F_partition_value,partition_value,3,imp_date=20260608\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(10) + B(10) + C(10) + D(55) + F(15)\n# 难度,EXPERT\n# 权重,\"product=0.8, process=0.2\"\n# 范式,new\n# Key列,\"fundraising_platform, stat_date\"\n# 预期列数,\n# 输出表,internal_platform_db.ads_gy_digital_tool_used_plat_data_d_ql_cand_query_engine_143", "path": "tasks/offline-compute/HiveSQL/hivesql_027"} {"task_id": "hivesql_028_en", "id": "offline-compute_HiveSQL_hivesql_028", "name": "From input table internal_platform_db.t_eis_feedaggregator2_feedforredd", "workload": "offline-compute", "engine": "HiveSQL", "category": "offline-compute/HiveSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nTask Objective: Extract qualifying records from the input table, parse the JSON array, and explode it into multiple rows, then output to the target table.\n\nInput:\n- `internal_platform_db.t_eis_feedaggregator2_feedforreddot_check_result_summary_classification_df_query_engine_152`\n\nProcessing Rules:\n1. Filter condition: `ds='20260608'`, `regexp_replace(second_update_date, '-', '') = ds`, `second_status in (1, 2)`\n2. Core transformation:\n - Extract `$.info.titles` from the `json_buffer_` field as a JSON array string\n - Remove the outermost square brackets of the array, replace `},{` with `}|{`, and split by `|` to obtain multiple JSON objects\n - Use `LATERAL VIEW explode` to expand into multiple rows, with one `title_obj` per row\n - Extract from each `title_obj`: `$.title`, `$.title_type`, `$.quality`\n3. No joins, single-table processing\n\nOutput Requirements:\n- Output field order: `ds`, `feedid`, `feedid_v1`, `type_source`, `classification`, `title`, `title_type`, `quality`, `second_status`\n- The `ds` field value is fixed as `20260608`\n- The `feedid_v1` field value equals `feedid`\n- No deduplication or aggregation required\n\nWrite Requirements:\n- Output table: `internal_platform_db.dws_rd_feedaggregator_feed_title_quality_di_cand_query_engine_152`\n- Partition field: `ds=20260608`\n- Write method: `INSERT OVERWRITE`\n\nPlease write the final HiveSQL to `result.sql` and execute it.", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.dws_rd_feedaggregator_feed_title_quality_di_query_engine_152 PARTITION (ds = '20260608')\nWITH tbl AS (\nSELECT\nfeedid,\ntype_source,\nclassification,\nsecond_status,\nget_json_object(json_buffer_, '$.info.titles') AS titles_info\nFROM internal_platform_db.t_eis_feedaggregator2_feedforreddot_check_result_summary_classification_df_query_engine_152\nWHERE ds='20260608'\nAND regexp_replace(second_update_date, '-', '') = ds\nAND second_status in (1, 2)\n)\nSELECT\nfeedid,\nfeedid as feedid_v1,\ntype_source,\nclassification,\nget_json_object(title_obj, '$.title') AS title,\nget_json_object(title_obj, '$.title_type') AS title_type,\nget_json_object(title_obj, '$.quality') AS quality,\nsecond_status\nFROM tbl\nLATERAL VIEW explode(\nsplit(\nregexp_replace(\nregexp_replace(\ntitles_info,\n'^\\\\[|\\\\]$',\n''\n),\n'\\\\}\\\\,\\\\{',\n'}\\\\|\\\\{'\n),\n'\\\\|'\n)\n) exploded AS title_obj", "expected_csv": "feedid,feedid_v1,type_source,classification,title,title_type,quality,second_status,ds\nfeed001,feed001,1,classA,Hello World,ocr,high,1,20260608\nfeed001,feed001,1,classA,Second Title,asr,medium,1,20260608\nfeed002,feed002,2,classB,Good Morning,manual,low,2,20260608", "grade_spec_csv": "维度,维度全名,子维度,满分,说明\nA,A_executability,executability,15,result.sql 能跑通且产出非空\nB,B_schema,schema,10,列数9 + 列名匹配\nC,C_row_alignment,row_consistency,15,\"行数比例 + key(feedid,title)覆盖率\"\nD,D_explode_correctness,explode_correctness,25,LATERAL VIEW展开行正确性(feedid+title组合匹配)\nD,D_json_field_values,json_field_values,20,title_type/quality等JSON提取字段逐行匹配\nF,F_insert_overwrite,insert_overwrite,5,写入模式+分区\nF,F_partition_value,partition_value,5,ds=20260608\nF,F_partition_value,partition_filter,5,源表分区过滤ds='20260608'\n\n总计,,,100,\n\n# 评分模板,评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)\n# 难度,MEDIUM\n# 权重,\"product=0.6, process=0.4\"\n# 范式,new\n# Key列,\"feedid, title\"\n# 预期列数,\n# 输出表,internal_platform_db.dws_rd_feedaggregator_feed_title_quality_di_cand_query_engine_152", "path": "tasks/offline-compute/HiveSQL/hivesql_028_en"} {"task_id": "mysql_001", "id": "offline-compute_MySQL_mysql_001", "name": "实时广告RPM数据过滤与列重命名", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,从实时广告 RPM 数据中筛选出指定分钟批次的记录,并对输出列进行重命名。\n\n**业务背景与目标**:广告系统定时将各子任务的 RPM 上报数据写入实时汇总表。下游消费方只需要 `imp_min = 202606090450` 这一批次的记录,并要求输出字段名称与下游表约定一致。本任务将输入表中满足条件的记录筛选出来,同时将 `expose_pv` 重命名为 `total_expose_pv`、`click_pv` 重命名为 `total_click_pv`,写入输出表。\n\n**输入表(全名 + 简要描述)**:\n- `internal_platform_db.t_ad_realtime_rpm_total_mysql_001`(实时广告RPM汇总明细表)\n\n(表结构与字段含义请自行连接数据库查询确认)\n\n**过滤条件**:\n- `imp_min = 202606090450`\n\n**列重命名规则**:\n- 输入列 `expose_pv` → 输出列 `total_expose_pv`\n- 输入列 `click_pv` → 输出列 `total_click_pv`\n- 其余列保持原名不变\n\n**输出要求**:\n- 目标表:`internal_platform_db.t_ad_realtime_rpm_cand_mysql_001`\n- 输出字段顺序:`sub_task_id`, `ptag`, `task_id`, `imp_min`, `expose_per_w`, `total_expose_pv`, `total_click_pv`, `ctime`, `mtime`\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_001 ground truth: 实时广告RPM数据过滤与列重命名\n\nTask:\n Filter input table WHERE imp_min = 202606090450,\n rename expose_pv -> total_expose_pv, click_pv -> total_click_pv,\n write to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"t_ad_realtime_rpm_total_mysql_001\"\nOUTPUT_TABLE = \"t_ad_realtime_rpm_cand_mysql_001\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (sub_task_id, ptag, task_id, imp_min, expose_per_w, total_expose_pv, total_click_pv, ctime, mtime)\nSELECT\n sub_task_id,\n ptag,\n task_id,\n imp_min,\n expose_per_w,\n expose_pv AS total_expose_pv,\n click_pv AS total_click_pv,\n ctime,\n mtime\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE imp_min = 202606090450\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n sub_task_id VARCHAR(64) NOT NULL,\n ptag VARCHAR(64) NOT NULL,\n task_id VARCHAR(64) NOT NULL,\n imp_min BIGINT NOT NULL,\n expose_per_w BIGINT NOT NULL,\n total_expose_pv BIGINT NOT NULL,\n total_click_pv BIGINT NOT NULL,\n ctime DATETIME NOT NULL,\n mtime DATETIME NOT NULL,\n PRIMARY KEY (sub_task_id)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_001 ground_truth done: 7 rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_001"} {"task_id": "mysql_002_en", "id": "offline-compute_MySQL_mysql_002", "name": "Inference Service Replica Forecast and Bias Coefficient Computation", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that, for inference services with autoscaling enabled, expands hourly expected pod counts to 10-minute granularity, clips them using configured upper and lower bounds, computes a bias correction coefficient based on the actual pod count over the past 24 hours, and labels the AHPA recommended status.\n\n**Business Objective**: For all inference services with autoscaling enabled (HPA or AHPA), expand the existing hourly expected pod counts to 10-minute intervals, and clip them using the service's configured replica upper and lower bounds (which must be multiplied by the machine count to convert to pod counts). Combined with the actual running pod count over the past 24 hours, compute a bias correction coefficient (actual pod count / clipped P90 expected value). Additionally, determine the AHPA service recommendation status (normal, degraded, no request). Write the final results to the target table for the partition `dt='2026050700'`.\n\n**Input Tables (full name + brief description)**:\n- `internal_platform_db.dwd_tj_model_service_hpa_mysql_002` (HPA configuration dimension table)\n- `internal_platform_db.nextgen_platform_dsl_autotune_rec_gpu_config_fht0_mysql_002` (AHPA recommendation fact table)\n- `internal_platform_db.dwd_aide_inferencev2_done_service_info_h_mysql_002` (service information dimension table)\n- `internal_platform_db.dwm_gputj_platform_hourly_expected_pod_mysql_002` (hourly expected pod count intermediate table)\n- `internal_platform_db.dwm_gputj_platform_gpu_base_feature_agg_v2_mysql_002` (actual pod count fact table)\n\n(Please connect to the database and query to confirm the table structures and field semantics.)\n\n**Key Filters and Joins**:\n- **Filters**: The service information table must select services where `status='done'`, not deleted (`deleted <> '1'`), and with HPA or AHPA enabled. The HPA configuration table takes the latest visible configuration (first row by `visible desc, id desc`). The AHPA recommendation table takes data from the last 10 minutes (current max timestamp - 600000ms). The hourly expected table takes the latest partition within the past 5 days. The actual pod count takes data from the past 24 hours (`dt >= '2026050600' and dt <= '2026050700'`) with `agg_type=2` and `avg_pod_count > 0`.\n- **Joins**: Join all tables primarily by `service_name`. The service information table is inner-joined with the hourly expected table, then left-joined with the HPA configuration table (via `service_id = serving_id`) and the AHPA status table. The hourly expected table must be cross-joined with a set of 6 time offsets (0, 10, 20, 30, 40, 50 minutes) to expand to 10-minute granularity.\n\n**Derived Logic and Business Semantics**:\n1. **Scale type**: If `ahpa_enable='true'`, then `'ahpa'`; if `hpa_enable='true'`, then `'hpa'`.\n2. **AHPA recommendation status**: For AHPA services, if there are no records in the last 10 minutes, the status is `'no_request'`; if there are records but all have `response_code` other than `'200'`, the status is `'degraded'`; otherwise, `'normal'`.\n3. **Pod count upper and lower bounds**: The `min_replicas` and `max_replicas` from the HPA/AHPA configuration must be multiplied by `host_num` (machine count) from the service information to obtain `hpa_min_pods`, `hpa_max_pods`, `ahpa_min_pods`, and `ahpa_max_pods`.\n4. **Expected value clipping**: All 8 expected pod count fields (e.g., `expected_pod_avg_qpm_p90`) must be clipped using the computed upper and lower bounds (`GREATEST(LEAST(original_value, upper_bound), lower_bound)`).\n5. **Bias coefficient**: Bias coefficient = `actual_pod_count` / clipped `expected_pod_avg_qpm_p90` value (use 1.0 when the denominator is 0).\n6. **Time expansion**: Expand the hourly prediction time to 6 time points at 0, 10, 20, 30, 40, and 50 minutes of each hour (constructed using `CONCAT(SUBSTRING(agg_time,1,14), LPAD(offset,2,'0'), ':00')`).\n\n**Output Requirements**:\n- Target table: `internal_platform_db.dwm_gputj_platform_replica_forecast_with_bias_cand_mysql_002`\n- Output field order: `service_name`, `instance_uuid`, `workload_name`, `namespace`, `agg_time`, `hour_of_day`, `scale_type`, `host_num`, `gpu_name`, `queue_name`, `hpa_min_pods`, `hpa_max_pods`, `ahpa_min_pods`, `ahpa_max_pods`, `ahpa_status`, `ahpa_response_code`, `expected_pod_avg_qpm_avg`, `expected_pod_avg_qpm_p50`, `expected_pod_avg_qpm_p90`, `expected_pod_max_qpm_avg`, `expected_pod_max_qpm_p50`, `expected_pod_max_qpm_p90`, `expected_pod_latest_avg_qpm`, `expected_pod_latest_max_qpm`, `actual_pod_count`, `bias_coefficient`, `dt`, `host_gpu_num`, `model_req_count`\n- `agg_time` format: `yyyy-MM-dd HH:mm:00`, at 10-minute granularity\n- `hour_of_day` format: `HH:00:00`\n- Write partition: `dt='2026050700'`\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects (do not use `INSERT OVERWRITE`; use `INSERT INTO ... SELECT`)\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_002 ground truth: 推理服务副本数预估与偏差系数计算\n\nTask:\n For services with HPA/AHPA enabled, expand hourly expected pod counts to\n 10-minute granularity, clamp with HPA/AHPA replica limits (× host_num),\n compute bias coefficient (actual / clamped p90), and mark AHPA status.\n Write to output table with dt='2026050700'.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\n\n# Input tables\nT_SVC_INFO = \"dwd_aide_inferencev2_done_service_info_h_mysql_002\"\nT_HPA = \"dwd_tj_model_service_hpa_mysql_002\"\nT_AHPA = \"nextgen_platform_dsl_autotune_rec_gpu_config_fht0_mysql_002\"\nT_EXPECTED = \"dwm_gputj_platform_hourly_expected_pod_mysql_002\"\nT_ACTUAL = \"dwm_gputj_platform_gpu_base_feature_agg_v2_mysql_002\"\n\n# Output table\nOUTPUT_TABLE = \"dwm_gputj_platform_replica_forecast_with_bias_cand_mysql_002\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE} (\n service_name, instance_uuid, workload_name, namespace,\n agg_time, hour_of_day, scale_type, host_num, gpu_name, queue_name,\n hpa_min_pods, hpa_max_pods, ahpa_min_pods, ahpa_max_pods,\n ahpa_status, ahpa_response_code,\n expected_pod_avg_qpm_avg, expected_pod_avg_qpm_p50, expected_pod_avg_qpm_p90,\n expected_pod_max_qpm_avg, expected_pod_max_qpm_p50, expected_pod_max_qpm_p90,\n expected_pod_latest_avg_qpm, expected_pod_latest_max_qpm,\n actual_pod_count, bias_coefficient, dt, host_gpu_num, model_req_count\n)\nWITH\n-- 1. 从服务信息表获取 hpa/ahpa 类型、host_num 和 service_id\nservice_info AS (\n SELECT\n name AS service_name,\n instance_uuid,\n service_id,\n CAST(host_num AS SIGNED) AS host_num,\n CAST(host_gpu_num AS SIGNED) AS host_gpu_num,\n gpu_name,\n queue_name,\n hpa_enable,\n ahpa_enable,\n CASE\n WHEN ahpa_enable = 'true' THEN 'ahpa'\n WHEN hpa_enable = 'true' THEN 'hpa'\n ELSE NULL\n END AS scale_type\n FROM {DB_NAME}.{T_SVC_INFO}\n WHERE dt = '2026050700'\n AND status = 'done'\n AND deleted <> '1'\n AND (hpa_enable = 'true' OR ahpa_enable = 'true')\n),\n\n-- 2. 从HPA表获取副本数上下限(按 serving_id 分组,取 visible desc, id desc 第一条)\nhpa_limits AS (\n SELECT\n serving_id,\n min_replicas,\n max_replicas,\n status AS hpa_status,\n visible\n FROM (\n SELECT\n id,\n serving_id,\n min_replicas,\n max_replicas,\n status,\n visible,\n ROW_NUMBER() OVER (PARTITION BY serving_id ORDER BY visible DESC, id DESC) AS rn\n FROM {DB_NAME}.{T_HPA}\n WHERE dt = '2026050700'\n ) t\n WHERE rn = 1\n),\n\n-- 3. 从AHPA推荐状态表判断最近连续10分钟的推荐状态\n-- 先用窗口函数取每个 service_name 最近一条的 response_code\nahpa_latest AS (\n SELECT\n service_name,\n cluster_id,\n namespace,\n workload_name,\n response_code,\n CAST(`timestamp` AS SIGNED) AS ts\n FROM (\n SELECT\n service_name,\n cluster_id,\n namespace,\n workload_name,\n response_code,\n `timestamp`,\n ROW_NUMBER() OVER (\n PARTITION BY service_name\n ORDER BY CAST(`timestamp` AS SIGNED) DESC\n ) AS rn\n FROM {DB_NAME}.{T_AHPA}\n WHERE databus_imp_date = '2026050700'\n AND CAST(`timestamp` AS SIGNED) >= (\n SELECT MAX(CAST(`timestamp` AS SIGNED)) - 600000\n FROM {DB_NAME}.{T_AHPA}\n WHERE databus_imp_date = '2026050700'\n )\n ) ranked\n WHERE rn = 1\n),\n\nahpa_rec_raw AS (\n SELECT\n service_name,\n MAX(cluster_id) AS cluster_id,\n MAX(namespace) AS namespace,\n MAX(workload_name) AS workload_name,\n COUNT(1) AS total_count,\n SUM(CASE WHEN response_code = '200' THEN 1 ELSE 0 END) AS success_count,\n MAX(CASE WHEN response_code IS NOT NULL THEN response_code ELSE NULL END) AS any_response_code\n FROM {DB_NAME}.{T_AHPA}\n WHERE databus_imp_date = '2026050700'\n AND CAST(`timestamp` AS SIGNED) >= (\n SELECT MAX(CAST(`timestamp` AS SIGNED)) - 600000\n FROM {DB_NAME}.{T_AHPA}\n WHERE databus_imp_date = '2026050700'\n )\n GROUP BY service_name\n),\n\n-- 以 service_info 中 ahpa 服务为基准,LEFT JOIN 推荐状态\nahpa_status AS (\n SELECT\n si.service_name,\n r.cluster_id,\n r.namespace,\n r.workload_name,\n al.response_code,\n CASE\n WHEN r.service_name IS NULL THEN 'no_request'\n WHEN r.success_count = 0 THEN 'degraded'\n ELSE 'normal'\n END AS ahpa_rec_status\n FROM (\n SELECT DISTINCT service_name\n FROM service_info\n WHERE scale_type = 'ahpa'\n ) si\n LEFT JOIN ahpa_rec_raw r ON si.service_name = r.service_name\n LEFT JOIN ahpa_latest al ON si.service_name = al.service_name\n),\n\n-- 4. 从步骤三获取预期pod数(取近5天内最近有产出的天级分区)\nlatest_expected_dt AS (\n SELECT MAX(dt) AS latest_dt\n FROM {DB_NAME}.{T_EXPECTED}\n WHERE dt >= '20260502' AND dt <= '20260507'\n),\n\nexpected_pod AS (\n SELECT\n ep.service_name,\n ep.instance_uuid,\n ep.workload_name,\n ep.namespace,\n ep.agg_time,\n ep.hour_of_day,\n ep.expected_pod_avg_qpm_avg,\n ep.expected_pod_avg_qpm_p50,\n ep.expected_pod_avg_qpm_p90,\n ep.expected_pod_max_qpm_avg,\n ep.expected_pod_max_qpm_p50,\n ep.expected_pod_max_qpm_p90,\n ep.expected_pod_latest_avg_qpm,\n ep.expected_pod_latest_max_qpm,\n ep.model_req_count\n FROM {DB_NAME}.{T_EXPECTED} ep\n JOIN latest_expected_dt led ON ep.dt = led.latest_dt\n),\n\n-- 4.5 构造10分钟间隔的偏移量(0,10,20,30,40,50)\ntime_slots AS (\n SELECT 0 AS minute_offset UNION ALL\n SELECT 10 UNION ALL\n SELECT 20 UNION ALL\n SELECT 30 UNION ALL\n SELECT 40 UNION ALL\n SELECT 50\n),\n\n-- 4.6 将小时粒度的预期pod数按10分钟展开\nexpected_pod_10min AS (\n SELECT\n ep.service_name,\n ep.instance_uuid,\n ep.workload_name,\n ep.namespace,\n CONCAT(\n SUBSTRING(ep.agg_time, 1, 14),\n LPAD(CAST(ts.minute_offset AS CHAR), 2, '0'),\n ':00'\n ) AS agg_time,\n ep.hour_of_day,\n ep.expected_pod_avg_qpm_avg,\n ep.expected_pod_avg_qpm_p50,\n ep.expected_pod_avg_qpm_p90,\n ep.expected_pod_max_qpm_avg,\n ep.expected_pod_max_qpm_p50,\n ep.expected_pod_max_qpm_p90,\n ep.expected_pod_latest_avg_qpm,\n ep.expected_pod_latest_max_qpm,\n ep.model_req_count\n FROM expected_pod ep\n CROSS JOIN time_slots ts\n),\n\n-- 5. 从特征表取近24小时的实际pod数(按service+小时维度)\nactual_pod AS (\n SELECT\n service_name,\n SUBSTRING_INDEX(agg_time, ' ', -1) AS hour_of_day,\n AVG(avg_pod_count) AS actual_pod_count\n FROM {DB_NAME}.{T_ACTUAL}\n WHERE dt >= '2026050600'\n AND dt <= '2026050700'\n AND agg_type = 2\n AND avg_pod_count > 0\n GROUP BY service_name, SUBSTRING_INDEX(agg_time, ' ', -1)\n),\n\n-- 6. 计算偏差系数\nbias AS (\n SELECT\n a.service_name,\n a.hour_of_day,\n a.actual_pod_count,\n e.clamped_pod_p90,\n CASE\n WHEN e.clamped_pod_p90 > 0 THEN a.actual_pod_count / e.clamped_pod_p90\n ELSE 1.0\n END AS bias_coefficient\n FROM actual_pod a\n LEFT JOIN (\n SELECT\n ep.service_name,\n ep.hour_of_day,\n AVG(\n GREATEST(\n LEAST(\n ep.expected_pod_avg_qpm_p90,\n CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num\n ),\n CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num\n )\n ) AS clamped_pod_p90\n FROM expected_pod_10min ep\n JOIN service_info si ON ep.service_name = si.service_name\n LEFT JOIN hpa_limits hl ON si.service_id = hl.serving_id\n GROUP BY ep.service_name, ep.hour_of_day\n ) e ON a.service_name = e.service_name AND a.hour_of_day = e.hour_of_day\n)\n\n-- 7. 最终结果\nSELECT\n si.service_name,\n si.instance_uuid,\n COALESCE(ep.workload_name, ast.workload_name) AS workload_name,\n COALESCE(ep.namespace, ast.namespace) AS namespace,\n ep.agg_time,\n ep.hour_of_day,\n si.scale_type,\n si.host_num,\n si.gpu_name,\n si.queue_name,\n CAST(hl.min_replicas AS SIGNED) * si.host_num AS hpa_min_pods,\n CAST(hl.max_replicas AS SIGNED) * si.host_num AS hpa_max_pods,\n CAST(hl.min_replicas AS SIGNED) * si.host_num AS ahpa_min_pods,\n CAST(hl.max_replicas AS SIGNED) * si.host_num AS ahpa_max_pods,\n COALESCE(ast.ahpa_rec_status, 'no_request') AS ahpa_status,\n ast.response_code AS ahpa_response_code,\n GREATEST(LEAST(ep.expected_pod_avg_qpm_avg, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_avg_qpm_avg,\n GREATEST(LEAST(ep.expected_pod_avg_qpm_p50, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_avg_qpm_p50,\n GREATEST(LEAST(ep.expected_pod_avg_qpm_p90, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_avg_qpm_p90,\n GREATEST(LEAST(ep.expected_pod_max_qpm_avg, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_max_qpm_avg,\n GREATEST(LEAST(ep.expected_pod_max_qpm_p50, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_max_qpm_p50,\n GREATEST(LEAST(ep.expected_pod_max_qpm_p90, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_max_qpm_p90,\n GREATEST(LEAST(ep.expected_pod_latest_avg_qpm, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_latest_avg_qpm,\n GREATEST(LEAST(ep.expected_pod_latest_max_qpm, CAST(hl.max_replicas AS DECIMAL(20,4)) * si.host_num), CAST(hl.min_replicas AS DECIMAL(20,4)) * si.host_num) AS expected_pod_latest_max_qpm,\n b.actual_pod_count,\n b.bias_coefficient,\n '2026050700' AS dt,\n si.host_gpu_num,\n ep.model_req_count\nFROM service_info si\nJOIN expected_pod_10min ep ON si.service_name = ep.service_name\nLEFT JOIN hpa_limits hl ON si.service_id = hl.serving_id\nLEFT JOIN ahpa_status ast ON si.service_name = ast.service_name\nLEFT JOIN bias b ON si.service_name = b.service_name AND ep.hour_of_day = b.hour_of_day\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n service_name VARCHAR(256),\n instance_uuid VARCHAR(256),\n workload_name VARCHAR(256),\n namespace VARCHAR(256),\n agg_time VARCHAR(256),\n hour_of_day VARCHAR(256),\n scale_type VARCHAR(256),\n host_num BIGINT,\n gpu_name VARCHAR(256),\n queue_name VARCHAR(256),\n hpa_min_pods BIGINT,\n hpa_max_pods BIGINT,\n ahpa_min_pods BIGINT,\n ahpa_max_pods BIGINT,\n ahpa_status VARCHAR(256),\n ahpa_response_code VARCHAR(256),\n expected_pod_avg_qpm_avg DOUBLE,\n expected_pod_avg_qpm_p50 DOUBLE,\n expected_pod_avg_qpm_p90 DOUBLE,\n expected_pod_max_qpm_avg DOUBLE,\n expected_pod_max_qpm_p50 DOUBLE,\n expected_pod_max_qpm_p90 DOUBLE,\n expected_pod_latest_avg_qpm DOUBLE,\n expected_pod_latest_max_qpm DOUBLE,\n actual_pod_count DOUBLE,\n bias_coefficient DOUBLE,\n dt VARCHAR(32),\n host_gpu_num BIGINT,\n model_req_count DOUBLE\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_002 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_002_en"} {"task_id": "mysql_003", "id": "offline-compute_MySQL_mysql_003", "name": "离线推理任务特征宽表构建", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,创建离线推理任务特征宽表,汇总dt='2026050700'分区内非终态或近期结束的静态模型JOB类型推理任务的特征信息,包含任务基本信息、各阶段耗时、数据集处理情况、实例排队等待时长、提交人和镜像版本。\n\n**输入**:\n1. `internal_platform_db.aide_offline_inference_info_fixed_mysql_003`(主表,按dt字段分区过滤)\n2. `internal_platform_db.aide_offline_inference_dataset_info_h_mysql_003`\n3. `internal_platform_db.aide_offline_inference_stage_info_h_mysql_003`\n4. `internal_platform_db.aide_offline_inference_pipeline_time_mysql_003`\n5. `internal_platform_db.aide_offline_inference_file_info_h_mysql_003`(按dt字段过滤当前小时分区)\n6. `internal_platform_db.aide_mould_h_mysql_003`\n7. `internal_platform_db.task_instance_wait_time_stats_mysql_003`(按dt字段取最新分区数据)\n\n**处理规则**:\n1. 主表过滤条件:处理dt='2026050700'分区数据;base='JOB';model_type='STATIC_MODEL';create_time早于dt解析后的下小时开始时间(即'2026-05-07 01:00:00');status为非终态(NOT IN ('FINISH','KILL','FAILED'))或update_time在dt解析前1小时内(即>='2026-05-06 23:00:00')\n2. 表关联方式:所有表通过任务ID(id、offline_inference_id、task_id、file_id)与主表LEFT JOIN,注意:stage_info_h和dataset_info_h与主表为一对多关系,LEFT JOIN不做聚合,同一主表行会产生多行输出(笛卡尔膨胀)\n3. 特殊关联规则:\n - 等待时长表:先用任务名和阶段ID拼接服务名(格式:任务名_阶段ID_OFFLINE),再与服务名关联\n - 模型表:从主表model_ids字段用JSON提取mould_id(JSON_EXTRACT(model_ids, '$.mould_id'))进行关联\n4. 聚合计算规则:\n - 流水线耗时按task_id分组:总耗时=SUM(time_cost_in_second);任务下发耗时=SUM(CASE WHEN step_desc='任务下发' THEN time_cost_in_second ELSE 0 END);离线推理耗时=SUM(CASE WHEN step_desc='离线推理' THEN time_cost_in_second ELSE 0 END);仅统计已完成步骤(end_time IS NOT NULL)\n - 实例等待时长按service_name分组:取最新分区数据;最大首次等待时长=MAX(first_wait_time);平均首次等待时长=AVG(first_wait_time)\n - 数据集统计:激活数、完成数、错误数按offline_inference_id分组计数\n - 文件信息:取当前小时分区下每个文件的最新一条记录(ROW_NUMBER按update_time降序)\n - 模型信息:从model_ids用JSON提取mould_id和mould_name\n - 服务名派生:CONCAT(任务名, '_', 阶段ID, '_OFFLINE')\n - 计数标识ct:固定值1\n5. 输出字段顺序:dt, create_time, ct, id, name, servingName, base, status, submit_type, mould_id, mould_name, time_cost_in_second, dataset_act_num, dataset_fin_num, dataset_err_num, max_instance_first_wait_time, avg_instance_first_wait_time, task_dispatch_time, offline_inference_time, inference_config, submit_operator, submit_time, image_tag\n\n**输出要求**:\n- 目标表:`internal_platform_db.dwd_aide_offline_inference_feature_cand_mysql_003`\n- 输出23个字段,字段类型根据源表推断\n- 如果目标表不存在,请先按MySQL InnoDB标准建表,再写入数据\n- 请使用标准MySQL语法,不要使用Hive/Spark SQL方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_003 ground truth: 离线推理任务特征宽表构建\n\nTask:\n Build an offline inference task feature wide table by joining 7 input tables,\n aggregating pipeline timing and wait time stats, extracting model info via JSON,\n and writing to the output table.\n\n WHERE conditions match the original Hive SQL:\n - a.dt = '2026050700'\n - a.base = 'JOB' AND a.model_type = 'STATIC_MODEL'\n - a.create_time < '2026-05-07 01:00:00' (dt parsed + 1 hour)\n - status NOT IN ('FINISH','KILL','FAILED') OR update_time >= '2026-05-06 23:00:00' (dt parsed - 1 hour)\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nOUTPUT_TABLE = \"dwd_aide_offline_inference_feature_cand_mysql_003\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, create_time, ct, id, name, servingName, base, status, submit_type,\n mould_id, mould_name, time_cost_in_second, dataset_act_num, dataset_fin_num,\n dataset_err_num, max_instance_first_wait_time, avg_instance_first_wait_time,\n task_dispatch_time, offline_inference_time, inference_config,\n submit_operator, submit_time, image_tag)\n\nWITH\n-- Step 1: Aggregate pipeline timing by task_id\npipeline_time_agg AS (\n SELECT\n task_id,\n SUM(time_cost_in_second) AS time_cost_in_second,\n CAST(SUM(CASE WHEN step_desc = '任务下发' THEN time_cost_in_second ELSE 0 END) AS SIGNED) AS task_dispatch_time,\n CAST(SUM(CASE WHEN step_desc = '离线推理' THEN time_cost_in_second ELSE 0 END) AS SIGNED) AS offline_inference_time\n FROM {DB_NAME}.aide_offline_inference_pipeline_time_mysql_003\n WHERE end_time IS NOT NULL\n GROUP BY task_id\n),\n\n-- Step 2: Aggregate wait time stats by service_name (latest partition)\nservice_wait_time_stats AS (\n SELECT\n service_name,\n CAST(MAX(first_wait_time) AS DOUBLE) AS max_instance_first_wait_time,\n CAST(AVG(first_wait_time) AS DOUBLE) AS avg_instance_first_wait_time\n FROM {DB_NAME}.task_instance_wait_time_stats_mysql_003\n WHERE dt = (SELECT MAX(dt) FROM {DB_NAME}.task_instance_wait_time_stats_mysql_003)\n AND first_wait_time IS NOT NULL\n GROUP BY service_name\n)\n\n-- Step 3: Join all tables and extract features\nSELECT\n '2026050700' AS dt,\n a.create_time,\n 1 AS ct,\n a.id,\n a.name AS `name`,\n CONCAT(a.name, '_', c.id, '_OFFLINE') AS servingName,\n a.base,\n a.status,\n a.submit_type,\n JSON_UNQUOTE(JSON_EXTRACT(a.model_ids, '$.mould_id')) AS mould_id,\n JSON_UNQUOTE(JSON_EXTRACT(a.model_ids, '$.mould_name')) AS mould_name,\n d.time_cost_in_second,\n b.dataset_act_num,\n b.dataset_fin_num,\n b.dataset_err_num,\n w.max_instance_first_wait_time,\n w.avg_instance_first_wait_time,\n d.task_dispatch_time,\n d.offline_inference_time,\n a.inference_config,\n e.operator AS submit_operator,\n e.create_time AS submit_time,\n f.image_tag\nFROM {DB_NAME}.aide_offline_inference_info_fixed_mysql_003 a\nLEFT JOIN {DB_NAME}.aide_offline_inference_dataset_info_h_mysql_003 b\n ON a.id = b.offline_inference_id\nLEFT JOIN {DB_NAME}.aide_offline_inference_stage_info_h_mysql_003 c\n ON a.id = c.offline_inference_id\nLEFT JOIN pipeline_time_agg d\n ON a.id = d.task_id\nLEFT JOIN service_wait_time_stats w\n ON CONCAT(a.name, '_', c.id, '_OFFLINE') = w.service_name\nLEFT JOIN (\n SELECT\n id,\n operator,\n create_time,\n ROW_NUMBER() OVER(PARTITION BY id ORDER BY update_time DESC) AS rn\n FROM {DB_NAME}.aide_offline_inference_file_info_h_mysql_003\n WHERE dt = '2026050700'\n) e ON a.file_id = e.id AND e.rn = 1\nLEFT JOIN {DB_NAME}.aide_mould_h_mysql_003 f\n ON CAST(JSON_UNQUOTE(JSON_EXTRACT(a.model_ids, '$.mould_id')) AS SIGNED) = f.id\nWHERE a.dt = '2026050700'\n AND a.base = 'JOB'\n AND a.model_type = 'STATIC_MODEL'\n AND a.create_time < '2026-05-07 01:00:00'\n AND (\n a.status NOT IN ('FINISH', 'KILL', 'FAILED')\n OR\n a.update_time >= '2026-05-06 23:00:00'\n )\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n dt VARCHAR(256) COMMENT '分区字段',\n create_time VARCHAR(256) COMMENT '创建时间',\n ct INT COMMENT '计数标识',\n id BIGINT COMMENT '离线推理任务ID',\n name VARCHAR(256) COMMENT '任务名称',\n servingName VARCHAR(256) COMMENT '服务名称',\n base VARCHAR(256) COMMENT '基础类型',\n status VARCHAR(256) COMMENT '状态',\n submit_type VARCHAR(256) COMMENT '提交类型',\n mould_id VARCHAR(256) COMMENT '模型ID',\n mould_name VARCHAR(256) COMMENT '模型名称',\n time_cost_in_second BIGINT COMMENT '总耗时(秒)',\n dataset_act_num BIGINT COMMENT '数据集激活数量',\n dataset_fin_num BIGINT COMMENT '数据集完成数量',\n dataset_err_num BIGINT COMMENT '数据集错误数量',\n max_instance_first_wait_time DOUBLE COMMENT '最大首次等待时长(秒)',\n avg_instance_first_wait_time DOUBLE COMMENT '平均首次等待时长(秒)',\n task_dispatch_time BIGINT COMMENT '任务下发耗时(秒)',\n offline_inference_time BIGINT COMMENT '离线推理耗时(秒)',\n inference_config VARCHAR(256) COMMENT '推理配置',\n submit_operator VARCHAR(256) COMMENT '提交人',\n submit_time VARCHAR(256) COMMENT '提交时间',\n image_tag VARCHAR(256) COMMENT '镜像标签'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_003 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_003"} {"task_id": "mysql_004_en", "id": "offline-compute_MySQL_mysql_004", "name": "Ceph Path Coldness Score Cluster-Level Statistics", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nPlease generate MySQL code based on the following requirements.\n\n1. Task Objective\nPerform cluster-level statistics on Ceph path coldness score data using three aggregation methods, and write the results to the target table.\n\n2. Input\n- Input table: `internal_platform_db.t_ceph_path_coldness_score_v2_mysql_004`\n- Filter condition: `dt='20260507'`\n\n3. Processing Rules\n3.1 Three path selection method definitions:\n- `level2_only`: Select only records where `path_level=2`\n- `max_available`: For each `cluster_name`, group by the first-level directory of `path_level2` (group key = the first segment obtained by removing the leading `/` from `path_level2` and splitting by `/`; for example, `/data/logs` and `/data/backup` both have the group key `data`). For each group, select the record with the maximum `path_level`.\n- `leaf_only`: Select leaf nodes (i.e., records for which no other record with the same `cluster_name` exists whose `path_level2` equals the parent path obtained by removing the last `/` and everything after it from the current record's `path_level2`; for example, if the current path is `/data/logs/app1`, the parent path is `/data/logs`, and if a record with this parent path exists, the current record is not a leaf).\n\n3.2 After merging the data from all three methods, aggregate by `cluster_name` and `agg_method`:\n- `total_path_count`: Total path count (count)\n- `total_size_tb`: Total capacity in TB (sum)\n- `total_access_count`: Total access count (sum)\n- `avg_coldness_score`: Average coldness score (mean)\n- `cluster_heat_category`: Categorize based on `avg_coldness_score`: >=60 is `'高热集群'` (high-heat cluster), >=40 is `'较热集群'` (warm cluster), >=20 is `'中等集群'` (moderate cluster), otherwise `'较冷集群'` (cool cluster)\n- `p0_count`/`p0_size_tb`: Path count/capacity where `governance_level='P0'`\n- `p1_count`/`p1_size_tb`: Path count/capacity where `governance_level='P1'`\n- `p2_count`/`p2_size_tb`: Path count/capacity where `governance_level='P2'`\n- `p3_count`/`p3_size_tb`: Path count/capacity where `governance_level='P3'`\n- `cold_path_pct`: (P0 path count + P1 path count) / total path count * 100\n- `cold_size_pct`: (P0 capacity + P1 capacity) / total capacity * 100\n\n4. Output Requirements\nOutput field order: `cluster_name` (VARCHAR(256)), `agg_method` (VARCHAR(256)), `total_path_count` (BIGINT), `total_size_tb` (DOUBLE), `total_access_count` (BIGINT), `avg_coldness_score` (DOUBLE), `cluster_heat_category` (VARCHAR(256)), `p0_count` (BIGINT), `p0_size_tb` (DOUBLE), `p1_count` (BIGINT), `p1_size_tb` (DOUBLE), `p2_count` (BIGINT), `p2_size_tb` (DOUBLE), `p3_count` (BIGINT), `p3_size_tb` (DOUBLE), `cold_path_pct` (DOUBLE), `cold_size_pct` (DOUBLE), `dt` (VARCHAR(256))\n\n5. Write Requirements\n- Output table: `internal_platform_db.t_ceph_coldness_cluster_stats_v2_cand_mysql_004`\n- Filter condition: `dt='20260507'`\n- No joins, single-table processing\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_004 ground truth: Ceph路径冷热评分集群级统计\n\nTask:\n 对 t_ceph_path_coldness_score_v2_mysql_004 进行三种聚合方式统计,\n 结果写入 t_ceph_coldness_cluster_stats_v2_cand_mysql_004\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"t_ceph_path_coldness_score_v2_mysql_004\"\nOUTPUT_TABLE = \"t_ceph_coldness_cluster_stats_v2_cand_mysql_004\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (cluster_name, agg_method, total_path_count, total_size_tb, total_access_count,\n avg_coldness_score, cluster_heat_category,\n p0_count, p0_size_tb, p1_count, p1_size_tb,\n p2_count, p2_size_tb, p3_count, p3_size_tb,\n cold_path_pct, cold_size_pct, dt)\n\nWITH all_scores AS (\n SELECT *\n FROM {DB_NAME}.{INPUT_TABLE}\n WHERE dt = '20260507'\n),\n\n-- Method 1: Fixed path_level=2\nlevel2_data AS (\n SELECT *, 'level2_only' AS agg_method\n FROM all_scores\n WHERE path_level = 2\n),\n\n-- Method 2: Maximum available level per path tree\nmax_avail_data AS (\n SELECT a.*, 'max_available' AS agg_method\n FROM all_scores a\n INNER JOIN (\n SELECT\n cluster_name,\n path_level2,\n path_level,\n ROW_NUMBER() OVER (\n PARTITION BY cluster_name,\n SUBSTRING_INDEX(TRIM(LEADING '/' FROM path_level2), '/', 1)\n ORDER BY path_level DESC, path_level2\n ) AS rn\n FROM all_scores\n ) b\n ON a.cluster_name = b.cluster_name\n AND a.path_level2 = b.path_level2\n AND a.path_level = b.path_level\n AND b.rn = 1\n),\n\n-- Method 3: Leaf nodes only (no deeper children)\nparent_paths AS (\n SELECT DISTINCT\n cluster_name,\n path_level - 1 AS parent_level,\n REGEXP_REPLACE(path_level2, '/[^/]+$', '') AS parent_path\n FROM all_scores\n WHERE path_level >= 2\n),\n\nleaf_data AS (\n SELECT a.*, 'leaf_only' AS agg_method\n FROM all_scores a\n LEFT JOIN parent_paths b\n ON a.cluster_name = b.cluster_name\n AND a.path_level = b.parent_level\n AND a.path_level2 = b.parent_path\n WHERE b.parent_path IS NULL\n),\n\n-- Combine three methods\nunion_all AS (\n SELECT * FROM level2_data\n UNION ALL\n SELECT * FROM max_avail_data\n UNION ALL\n SELECT * FROM leaf_data\n)\n\n-- Aggregate by cluster and method\nSELECT\n cluster_name,\n agg_method,\n COUNT(*) AS total_path_count,\n ROUND(SUM(size_tb), 2) AS total_size_tb,\n SUM(access_count) AS total_access_count,\n ROUND(AVG(coldness_score), 2) AS avg_coldness_score,\n\n CASE\n WHEN AVG(coldness_score) >= 60 THEN '高热集群'\n WHEN AVG(coldness_score) >= 40 THEN '较热集群'\n WHEN AVG(coldness_score) >= 20 THEN '中等集群'\n ELSE '较冷集群'\n END AS cluster_heat_category,\n\n SUM(CASE WHEN governance_level = 'P0' THEN 1 ELSE 0 END) AS p0_count,\n ROUND(SUM(CASE WHEN governance_level = 'P0' THEN size_tb ELSE 0 END), 2) AS p0_size_tb,\n SUM(CASE WHEN governance_level = 'P1' THEN 1 ELSE 0 END) AS p1_count,\n ROUND(SUM(CASE WHEN governance_level = 'P1' THEN size_tb ELSE 0 END), 2) AS p1_size_tb,\n SUM(CASE WHEN governance_level = 'P2' THEN 1 ELSE 0 END) AS p2_count,\n ROUND(SUM(CASE WHEN governance_level = 'P2' THEN size_tb ELSE 0 END), 2) AS p2_size_tb,\n SUM(CASE WHEN governance_level = 'P3' THEN 1 ELSE 0 END) AS p3_count,\n ROUND(SUM(CASE WHEN governance_level = 'P3' THEN size_tb ELSE 0 END), 2) AS p3_size_tb,\n\n ROUND(SUM(CASE WHEN governance_level IN ('P0','P1') THEN 1 ELSE 0 END)\n * 100.0 / COUNT(*), 2) AS cold_path_pct,\n ROUND(SUM(CASE WHEN governance_level IN ('P0','P1') THEN size_tb ELSE 0 END)\n * 100.0 / NULLIF(SUM(size_tb), 0), 2) AS cold_size_pct,\n\n '20260507' AS dt\n\nFROM union_all\nGROUP BY cluster_name, agg_method\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n cluster_name VARCHAR(256) COMMENT '集群名',\n agg_method VARCHAR(256) COMMENT '聚合方式',\n total_path_count BIGINT COMMENT '路径总数',\n total_size_tb DOUBLE COMMENT '总容量(TB)',\n total_access_count BIGINT COMMENT '总访问次数',\n avg_coldness_score DOUBLE COMMENT '平均冷热评分',\n cluster_heat_category VARCHAR(256) COMMENT '集群热度分类',\n p0_count BIGINT COMMENT 'P0路径数',\n p0_size_tb DOUBLE COMMENT 'P0容量TB',\n p1_count BIGINT COMMENT 'P1路径数',\n p1_size_tb DOUBLE COMMENT 'P1容量TB',\n p2_count BIGINT COMMENT 'P2路径数',\n p2_size_tb DOUBLE COMMENT 'P2容量TB',\n p3_count BIGINT COMMENT 'P3路径数',\n p3_size_tb DOUBLE COMMENT 'P3容量TB',\n cold_path_pct DOUBLE COMMENT '冷路径占比',\n cold_size_pct DOUBLE COMMENT '冷容量占比',\n dt VARCHAR(256) COMMENT '数据日期'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_004 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_004_en"} {"task_id": "mysql_005_en", "id": "offline-compute_MySQL_mysql_005", "name": "GPU Inference Platform P90 Traffic Forecast (Holiday/Workday Differentiation)", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that produces 14-day traffic and resource usage forecasts (P90 percentile) for each service on the GPU inference platform, differentiating between holidays and workdays, with mutual fallback when historical samples are insufficient, and outputting results at both 10-minute and hourly time granularities.\n\n**Business Background and Objective**: The GPU inference platform needs to forecast traffic and resource usage for each service over the next 14 days. The forecast is based on P90 percentile values from historical data, with differentiation between holidays and workdays. When historical samples for one category are insufficient, the other category is used as a fallback. The output includes forecast results at both 10-minute and hourly time granularities.\n\n**Input Tables (full name + brief description)**:\n- `internal_platform_db.dwm_gputj_platform_gpu_base_feature_agg_v2_mysql_005` (GPU feature aggregation fact table)\n- `internal_platform_db.dwd_aide_inferencev2_done_service_info_h_mysql_005` (service list dimension table)\n- `internal_platform_db.dim_holiday_list_mysql_005` (holiday dimension table)\n\n(Please connect to the database and query to confirm the table structures and field semantics.)\n\n**Processing Rules**:\n1. **Fact table data range**: Take partitions between `'20260420'` and `'20260507'`, excluding the anomalous period from `'20260504'` to `'20260504'`; traffic value `nv_inference_count_model_avg` >= 0; `agg_type` is 1 or 2.\n2. **Time point template**: Extracted from the fact table partitions `'20260502'` to `'20260507'` (exclusive).\n3. **Join logic**:\n - Cartesian product of the service list with all time points over the next 14 days (at 10-minute and hourly granularities).\n - Join with the historical fact table on join keys: `service_name`, `agg_type`, and the hour-minute portion of the time point.\n - Left join the holiday dimension table twice: once for the prediction date and once for the historical data date.\n4. **Derived fields**:\n - `is_holiday`: Whether the prediction date is a holiday (1/0).\n - `day_of_week`: Day of the week for the prediction date (1–7).\n - `prediction_type`: Fixed as `'request_model_count'`.\n - `statistic_time_count`: Number of historical time points used in the forecast, computed using the holiday/workday mutual fallback logic.\n - P90 forecast fields: Based on the prediction day type (holiday/workday), take the P90 value of each metric from the corresponding historical data, with fallback to the other type when insufficient.\n - `workload_name`, `namespace`, etc.: Take the maximum value per service from the historical fact table.\n\n**Output Requirements**:\n- **Output table**: `internal_platform_db.dws_gputj_platform_model_prediction_long_p90_mysql_005`\n- **Output fields (in order)**: `dt`, `instance_uuid`, `service_name`, `workload_name`, `namespace`, `agg_time`, `agg_type`, `is_holiday`, `day_of_week`, `prediction_type`, `nv_inference_count_model_avg_p90`, `statistic_time_count`, `nv_inference_request_duration_ms_model_avg`, `nv_inference_queue_duration_ms_model_avg`, `num_queued_reqs_model_avg`, `nv_inference_request_success_model_avg`, `nv_inference_request_failure_model_avg`, `nv_inference_request_duration_ms_perreq_avg`, `nv_inference_queue_duration_ms_perreq_avg`, `nv_inference_request_duration_ms_perreq_p95`, `nv_inference_queue_duration_ms_perreq_p95`, `nv_inference_request_success_model_max`, `nv_inference_request_failure_model_max`, `DCGM_FI_DEV_GPU_UTIL_pod_avg`, `k8s_container_bs_rate_cpu_core_used_request_pod_avg`, `k8s_container_rate_mem_working_set_request_pod_avg`, `k8s_dcgm_fi_dev_fb_util_pod_avg`, `k8s_container_vgpu_gpu_util_pod_avg`\n- **Write method**: DELETE + INSERT or TRUNCATE + INSERT INTO ... SELECT\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_005 ground truth: GPU推理平台P90流量预估\n\nTask:\n Generate P90 predictions for GPU inference platform services\n over the next 14 days, distinguishing holidays vs weekdays,\n with fallback logic when historical samples are insufficient.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE_FEATURE = \"dwm_gputj_platform_gpu_base_feature_agg_v2_mysql_005\"\nINPUT_TABLE_SERVICE = \"dwd_aide_inferencev2_done_service_info_h_mysql_005\"\nINPUT_TABLE_HOLIDAY = \"dim_holiday_list_mysql_005\"\nOUTPUT_TABLE = \"dws_gputj_platform_model_prediction_long_p90_mysql_005\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, instance_uuid, service_name, workload_name, namespace, agg_time, agg_type,\n is_holiday, day_of_week, prediction_type,\n nv_inference_count_model_avg_p90, statistic_time_count,\n nv_inference_request_duration_ms_model_avg, nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg, nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg, nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg, nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95, nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max, DCGM_FI_DEV_GPU_UTIL_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg, k8s_container_vgpu_gpu_util_pod_avg)\nWITH\n-- Generate 14 future dates starting from 2026-05-07\nfuture_dates AS (\n SELECT DATE_ADD(STR_TO_DATE('20260507', '%Y%m%d'), INTERVAL offset DAY) AS target_date\n FROM (\n SELECT 0 AS offset UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3\n UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7\n UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11\n UNION ALL SELECT 12 UNION ALL SELECT 13\n ) offsets\n),\n-- Extract time template (hour/10-min granularity time points)\ntime_template AS (\n SELECT SUBSTRING_INDEX(agg_time, ' ', -1) AS time_part, agg_type\n FROM {DB_NAME}.{INPUT_TABLE_FEATURE}\n WHERE dt >= '20260502' AND dt < '20260507' AND agg_time > ''\n GROUP BY SUBSTRING_INDEX(agg_time, ' ', -1), agg_type\n),\n-- Generate 14 days x all time points\ntime_list AS (\n SELECT CONCAT(DATE_FORMAT(fd.target_date, '%Y-%m-%d'), ' ', tt.time_part) AS agg_time,\n tt.agg_type, fd.target_date\n FROM future_dates fd\n CROSS JOIN time_template tt\n),\n-- Get distinct service names\nservice_list AS (\n SELECT DISTINCT name AS service_name\n FROM {DB_NAME}.{INPUT_TABLE_SERVICE}\n WHERE dt = IF('2026050723' >= '2025101512', '2026050723', '2025101512') AND name <> ''\n),\n-- Filter feature data\nfeature AS (\n SELECT service_name, instance_uuid,\n trial_job_name AS workload_name, namespace, agg_time, agg_type,\n nv_inference_count_model_avg,\n nv_inference_request_duration_ms_model_avg,\n nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg,\n nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg,\n nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg,\n nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95,\n nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max,\n dcgm_fi_dev_gpu_util_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg,\n k8s_container_vgpu_gpu_util_pod_avg\n FROM {DB_NAME}.{INPUT_TABLE_FEATURE}\n WHERE dt >= '20260420' AND dt <= '20260507'\n AND (dt < '20260504' OR dt > '20260504')\n AND nv_inference_count_model_avg >= 0\n AND agg_type IN (1, 2)\n),\n-- Core join + aggregation\nt1 AS (\n SELECT time_list.agg_time,\n feature.agg_type,\n MAX(feature.instance_uuid) AS instance_uuid,\n feature.service_name,\n MAX(feature.workload_name) AS workload_name,\n MAX(feature.namespace) AS namespace,\n MAX(CASE WHEN holiday_today.holiday_date > '' THEN 1 ELSE 0 END) AS today_holiday_date,\n MAX(feature.nv_inference_count_model_avg) AS nv_inference_count_model_avg,\n MAX(feature.nv_inference_request_duration_ms_model_avg) AS nv_inference_request_duration_ms_model_avg,\n MAX(feature.nv_inference_queue_duration_ms_model_avg) AS nv_inference_queue_duration_ms_model_avg,\n MAX(feature.num_queued_reqs_model_avg) AS num_queued_reqs_model_avg,\n MAX(feature.nv_inference_request_success_model_avg) AS nv_inference_request_success_model_avg,\n MAX(feature.nv_inference_request_failure_model_avg) AS nv_inference_request_failure_model_avg,\n MAX(feature.nv_inference_request_duration_ms_perreq_avg) AS nv_inference_request_duration_ms_perreq_avg,\n MAX(feature.nv_inference_queue_duration_ms_perreq_avg) AS nv_inference_queue_duration_ms_perreq_avg,\n MAX(feature.nv_inference_request_duration_ms_perreq_p95) AS nv_inference_request_duration_ms_perreq_p95,\n MAX(feature.nv_inference_queue_duration_ms_perreq_p95) AS nv_inference_queue_duration_ms_perreq_p95,\n MAX(feature.nv_inference_request_success_model_max) AS nv_inference_request_success_model_max,\n MAX(feature.nv_inference_request_failure_model_max) AS nv_inference_request_failure_model_max,\n MAX(feature.dcgm_fi_dev_gpu_util_pod_avg) AS dcgm_fi_dev_gpu_util_pod_avg,\n MAX(feature.k8s_container_bs_rate_cpu_core_used_request_pod_avg) AS k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n MAX(feature.k8s_container_rate_mem_working_set_request_pod_avg) AS k8s_container_rate_mem_working_set_request_pod_avg,\n MAX(feature.k8s_dcgm_fi_dev_fb_util_pod_avg) AS k8s_dcgm_fi_dev_fb_util_pod_avg,\n MAX(feature.k8s_container_vgpu_gpu_util_pod_avg) AS k8s_container_vgpu_gpu_util_pod_avg,\n MAX(CASE WHEN holiday_feature.holiday_date > '' THEN 1 ELSE 0 END) AS feature_holiday_date\n FROM service_list\n CROSS JOIN time_list\n JOIN feature\n ON service_list.service_name = feature.service_name\n AND time_list.agg_type = feature.agg_type\n AND SUBSTRING_INDEX(time_list.agg_time, ' ', -1) = SUBSTRING_INDEX(feature.agg_time, ' ', -1)\n LEFT JOIN {DB_NAME}.{INPUT_TABLE_HOLIDAY} holiday_today\n ON SUBSTRING_INDEX(time_list.agg_time, ' ', 1) = holiday_today.holiday_date\n LEFT JOIN {DB_NAME}.{INPUT_TABLE_HOLIDAY} holiday_feature\n ON SUBSTRING_INDEX(feature.agg_time, ' ', 1) = holiday_feature.holiday_date\n GROUP BY time_list.agg_time, feature.agg_time, feature.agg_type, feature.service_name\n),\nt2 AS (\n SELECT *,\n ROW_NUMBER() OVER (PARTITION BY service_name, agg_time, agg_type ORDER BY feature_holiday_date ASC, nv_inference_count_model_avg ASC) AS r,\n SUM(1) OVER (PARTITION BY service_name, agg_time, agg_type) AS total,\n SUM(feature_holiday_date) OVER (PARTITION BY service_name, agg_time, agg_type) AS feature_holiday_total\n FROM t1\n),\nt3 AS (\n SELECT *,\n total - feature_holiday_total AS feature_weekday_total,\n CEIL((total - feature_holiday_total) * 0.9) AS feature_weekday_index,\n CEIL(feature_holiday_total * 0.9) + (total - feature_holiday_total) AS feature_holiday_index\n FROM t2\n),\nbase AS (\n SELECT '20260507' AS dt,\n instance_uuid,\n service_name,\n workload_name,\n namespace,\n agg_time,\n agg_type,\n today_holiday_date,\n -- MySQL: DAYOFWEEK returns 1=Sunday..7=Saturday; we need 1=Monday..7=Sunday\n MOD(DATEDIFF(SUBSTRING_INDEX(agg_time, ' ', 1), '2019-12-30'), 7) + 1 AS day_of_week,\n 'request_model_count' AS prediction_type,\n nv_inference_count_model_avg,\n CASE\n WHEN today_holiday_date = 1 AND feature_holiday_total > 0 THEN feature_holiday_total\n WHEN today_holiday_date = 1 AND feature_holiday_total = 0 THEN feature_weekday_total\n WHEN today_holiday_date = 0 AND feature_weekday_total > 0 THEN feature_weekday_total\n WHEN today_holiday_date = 0 AND feature_weekday_total = 0 THEN feature_holiday_total\n END AS statistic_time_count,\n nv_inference_request_duration_ms_model_avg,\n nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg,\n nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg,\n nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg,\n nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95,\n nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max,\n dcgm_fi_dev_gpu_util_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg,\n k8s_container_vgpu_gpu_util_pod_avg\n FROM t3\n WHERE r = CASE\n WHEN today_holiday_date = 1 AND feature_holiday_total >= 1 THEN feature_holiday_index\n WHEN today_holiday_date = 1 AND feature_holiday_total < 1 THEN feature_weekday_index\n WHEN today_holiday_date = 0 AND feature_weekday_total >= 1 THEN feature_weekday_index\n WHEN today_holiday_date = 0 AND feature_weekday_total < 1 THEN feature_holiday_index\n END\n)\nSELECT dt, instance_uuid, service_name, workload_name, namespace, agg_time, agg_type,\n today_holiday_date AS is_holiday, day_of_week, prediction_type,\n nv_inference_count_model_avg AS nv_inference_count_model_avg_p90, statistic_time_count,\n nv_inference_request_duration_ms_model_avg, nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg, nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg, nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg, nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95, nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max, dcgm_fi_dev_gpu_util_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg, k8s_container_vgpu_gpu_util_pod_avg\nFROM base\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n `dt` VARCHAR(256) COMMENT '分区时间(YYYYMMDD)',\n `instance_uuid` VARCHAR(256) COMMENT '实例UUID',\n `service_name` VARCHAR(256) COMMENT '服务名称',\n `workload_name` VARCHAR(256) COMMENT '工作负载名称',\n `namespace` VARCHAR(256) COMMENT '命名空间',\n `agg_time` VARCHAR(256) COMMENT '预测时间点',\n `agg_type` BIGINT COMMENT '1:10分钟粒度,2:小时粒度',\n `is_holiday` BIGINT COMMENT '是否节假日:0-1',\n `day_of_week` BIGINT COMMENT '星期几:1-7',\n `prediction_type` VARCHAR(256) COMMENT '预测模型',\n `nv_inference_count_model_avg_p90` DOUBLE COMMENT '预估流量P90',\n `statistic_time_count` BIGINT COMMENT '参与预估的时间点个数',\n `nv_inference_request_duration_ms_model_avg` DOUBLE,\n `nv_inference_queue_duration_ms_model_avg` DOUBLE,\n `num_queued_reqs_model_avg` DOUBLE,\n `nv_inference_request_success_model_avg` DOUBLE,\n `nv_inference_request_failure_model_avg` DOUBLE,\n `nv_inference_request_duration_ms_perreq_avg` DOUBLE,\n `nv_inference_queue_duration_ms_perreq_avg` DOUBLE,\n `nv_inference_request_duration_ms_perreq_p95` DOUBLE,\n `nv_inference_queue_duration_ms_perreq_p95` DOUBLE,\n `nv_inference_request_success_model_max` DOUBLE,\n `nv_inference_request_failure_model_max` DOUBLE,\n `DCGM_FI_DEV_GPU_UTIL_pod_avg` DOUBLE,\n `k8s_container_bs_rate_cpu_core_used_request_pod_avg` DOUBLE,\n `k8s_container_rate_mem_working_set_request_pod_avg` DOUBLE,\n `k8s_dcgm_fi_dev_fb_util_pod_avg` DOUBLE,\n `k8s_container_vgpu_gpu_util_pod_avg` DOUBLE\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n\n # Verify row count\n with conn.cursor() as cur:\n cur.execute(f\"SELECT COUNT(*) FROM {DB_NAME}.{OUTPUT_TABLE}\")\n count = cur.fetchone()[0]\n print(f\"mysql_005 ground_truth done: {count} rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_005_en"} {"task_id": "mysql_006", "id": "offline-compute_MySQL_mysql_006", "name": "推理服务流量与资源预测-P90分位数与节假日降级", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,以20260507为预测基准日,为所有在线推理服务生成未来14天的流量与资源使用量预测数据。预测采用断点检测(CPD)结果之后的历史数据,区分节假日/工作日类型计算P90分位数,当某类型历史数据不足时降级使用另一类型数据,输出10分钟和小时两种时间粒度的预测结果。\n\n**输入表(全名 + 简要描述)**:\n\n1. `internal_platform_db.dwm_gputj_platform_gpu_base_feature_agg_v2_mysql_006`(历史特征事实表)\n2. `internal_platform_db.dwd_aide_inferencev2_done_service_info_h_mysql_006`(服务信息维表)\n3. `internal_platform_db.dwd_gputj_platform_metric_cpd_offline_v2_mysql_006`(断点检测结果表)\n4. `internal_platform_db.dim_holiday_list_mysql_006`(节假日维表)\n\n(各表结构与字段含义请自行连接数据库查询确认)\n\n**处理规则**:\n1. **数据过滤**:历史特征数据需满足`nv_inference_count_model_avg >= 0`且`agg_type IN (1, 2)`;断点数据需满足`msg = 'success'`;服务名不能为空。\n2. **关联逻辑**:\n - 生成未来14天所有时间点与服务列表的笛卡尔积。\n - 历史特征数据先与断点表内关联(`service_name`相等,`agg_time >= 断点时间`),只保留断点后记录。\n - 关联结果再与未来时间点关联,条件为`service_name`相等、`agg_type`相等、时间部分(HH:mm)相等。\n - 未来时间点日期和历史记录日期分别左关联节假日表判断日期类型。\n - 最终输出前左关联断点表获取`cpd_agg_time`。\n3. **P90计算与降级口径**:按服务、未来时间点、时间粒度分组后:\n - 组内对各项性能指标取`max`值。\n - 标记每条历史记录是否为节假日(1是0否),统计组内总记录数`total`、节假日记录数`feature_holiday_total`,计算工作日记录数`feature_weekday_total = total - feature_holiday_total`。\n - 按规则生成排名`r`:排序规则为`(是否为节假日 asc, nv_inference_count_model_avg asc)`。\n - **降级逻辑**:预测日为节假日且`feature_holiday_total >=1`时,取`r = CEIL(feature_holiday_total*0.9) + feature_weekday_total`;预测日为节假日但`feature_holiday_total <1`时,降级取`r = CEIL(feature_weekday_total*0.9)`;预测日为工作日且`feature_weekday_total >=1`时,取`r = CEIL(feature_weekday_total*0.9)`;预测日为工作日但`feature_weekday_total <1`时,降级取`r = CEIL(feature_holiday_total*0.9) + feature_weekday_total`。\n - 历史时间点数量`statistic_time_count`按降级逻辑取对应的`feature_holiday_total`或`feature_weekday_total`。\n4. **派生字段**:`is_holiday`根据未来时间点日期是否在节假日表判断(1是0否);`day_of_week`通过`MOD(DATEDIFF(预测日期, '2019-12-30'), 7) + 1`计算;`prediction_type`固定为'request_model_count'。\n\n**输出要求**:\n- 目标表:`internal_platform_db.dwm_gputj_platform_model_prediction_long_cpd_mysql_006`\n- 输出字段顺序:分区时间(YYYYMMDD)、实例UUID、服务名称、工作负载名称、命名空间、预测时间点、时间粒度(1:10分钟,2:小时)、是否节假日、周几、预测模型类型、预估流量(P90)、参与计算的历史时间点个数、请求持续时长均值、队列持续时长均值、排队请求数均值、请求成功率均值、请求失败率均值、单请求持续时长均值、单请求队列时长均值、单请求持续时长P95、单请求队列时长P95、请求成功率最大值、请求失败率最大值、GPU利用率均值、CPU使用率均值、内存使用率均值、GPU显存利用率均值、vGPU利用率均值、断点时间、历史特征总数、历史节假日特征数\n- 分区字段`dt`,本次任务分区值为'20260507'\n- 如果目标表不存在,请在`internal_platform_db`库下按MySQL InnoDB标准建表,再写入数据\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_006 ground truth: 推理服务流量与资源预测-P90分位数与节假日降级\n\nTask:\n 以20260507为预测基准日,为所有在线推理服务生成未来14天的流量与资源使用量预测数据。\n 预测采用断点检测(CPD)结果之后的历史数据,区分节假日/工作日类型计算P90分位数,\n 当某类型历史数据不足时降级使用另一类型数据,输出10分钟和小时两种时间粒度的预测结果。\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE_FEATURE = \"dwm_gputj_platform_gpu_base_feature_agg_v2_mysql_006\"\nINPUT_TABLE_SERVICE = \"dwd_aide_inferencev2_done_service_info_h_mysql_006\"\nINPUT_TABLE_CPD = \"dwd_gputj_platform_metric_cpd_offline_v2_mysql_006\"\nINPUT_TABLE_HOLIDAY = \"dim_holiday_list_mysql_006\"\nOUTPUT_TABLE = \"dwm_gputj_platform_model_prediction_long_cpd_mysql_006\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (instance_uuid, service_name, workload_name, namespace, agg_time, agg_type,\n is_holiday, day_of_week, prediction_type, nv_inference_count_model_avg_p90,\n statistic_time_count, nv_inference_request_duration_ms_model_avg,\n nv_inference_queue_duration_ms_model_avg, num_queued_reqs_model_avg,\n nv_inference_request_success_model_avg, nv_inference_request_failure_model_avg,\n nv_inference_request_duration_ms_perreq_avg, nv_inference_queue_duration_ms_perreq_avg,\n nv_inference_request_duration_ms_perreq_p95, nv_inference_queue_duration_ms_perreq_p95,\n nv_inference_request_success_model_max, nv_inference_request_failure_model_max,\n DCGM_FI_DEV_GPU_UTIL_pod_avg, k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg, k8s_dcgm_fi_dev_fb_util_pod_avg,\n k8s_container_vgpu_gpu_util_pod_avg, cpd_agg_time, feature_total, feature_holiday_total, dt)\nWITH RECURSIVE offsets AS (\n SELECT 0 AS n\n UNION ALL SELECT n + 1 FROM offsets WHERE n < 13\n),\nfuture_dates AS (\n SELECT DATE_ADD(STR_TO_DATE('20260507', '%Y%m%d'), INTERVAL n DAY) AS target_date\n FROM offsets\n),\ntime_template AS (\n SELECT SUBSTRING_INDEX(agg_time, ' ', -1) AS time_part, agg_type\n FROM {DB_NAME}.{INPUT_TABLE_FEATURE}\n WHERE dt >= '20260502' AND dt < '20260507' AND agg_time > ''\n GROUP BY SUBSTRING_INDEX(agg_time, ' ', -1), agg_type\n),\ntime_list AS (\n SELECT CONCAT(fd.target_date, ' ', tt.time_part) AS agg_time, tt.agg_type, fd.target_date\n FROM future_dates fd\n CROSS JOIN time_template tt\n),\nservice_list AS (\n SELECT DISTINCT name AS service_name\n FROM {DB_NAME}.{INPUT_TABLE_SERVICE}\n WHERE dt = '2026050723' AND name <> ''\n),\ncpd AS (\n SELECT service_name, agg_time\n FROM (\n SELECT service_name, agg_time,\n ROW_NUMBER() OVER (PARTITION BY service_name ORDER BY dt DESC, agg_time DESC) AS r1\n FROM (\n SELECT service_name, dt, agg_time,\n ROW_NUMBER() OVER (PARTITION BY service_name, dt, metric_name ORDER BY metric_value ASC) AS r\n FROM {DB_NAME}.{INPUT_TABLE_CPD}\n WHERE dt <= '20260507' AND dt >= '20260421'\n AND msg = 'success'\n AND agg_time < '20260507'\n ) t0\n WHERE r = 1\n ) t\n WHERE r1 = 1\n),\nfeature AS (\n SELECT t.service_name, instance_uuid, trial_job_name AS workload_name, namespace,\n t.agg_time, agg_type, nv_inference_count_model_avg,\n nv_inference_request_duration_ms_model_avg, nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg, nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg, nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg, nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95, nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max, dcgm_fi_dev_gpu_util_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg, k8s_container_vgpu_gpu_util_pod_avg\n FROM {DB_NAME}.{INPUT_TABLE_FEATURE} t\n JOIN cpd ON cpd.service_name = t.service_name AND cpd.agg_time <= t.agg_time\n WHERE dt >= '20260421' AND dt <= '20260507'\n AND nv_inference_count_model_avg >= 0\n AND agg_type IN (1, 2)\n),\nbase AS (\n SELECT '20260507' AS dt,\n instance_uuid, service_name, workload_name, namespace, agg_time, agg_type,\n today_holiday_date,\n MOD(DATEDIFF(SUBSTRING_INDEX(agg_time, ' ', 1), '2019-12-30'), 7) + 1 AS day_of_week,\n 'request_model_count' AS prediction_type,\n nv_inference_count_model_avg,\n CASE\n WHEN today_holiday_date = 1 AND feature_holiday_total > 0 THEN feature_holiday_total\n WHEN today_holiday_date = 1 AND feature_holiday_total = 0 THEN feature_weekday_total\n WHEN today_holiday_date = 0 AND feature_weekday_total > 0 THEN feature_weekday_total\n WHEN today_holiday_date = 0 AND feature_weekday_total = 0 THEN feature_holiday_total\n END AS statistic_time_count,\n nv_inference_request_duration_ms_model_avg, nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg, nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg, nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg, nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95, nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max, dcgm_fi_dev_gpu_util_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg, k8s_container_vgpu_gpu_util_pod_avg,\n total AS feature_total, feature_holiday_total\n FROM (\n SELECT *,\n total - feature_holiday_total AS feature_weekday_total,\n CEIL((total - feature_holiday_total) * 0.9) AS feature_weekday_index,\n CEIL(feature_holiday_total * 0.9) + (total - feature_holiday_total) AS feature_holiday_index\n FROM (\n SELECT *,\n ROW_NUMBER() OVER (PARTITION BY service_name, agg_time, agg_type\n ORDER BY feature_holiday_date ASC, nv_inference_count_model_avg ASC) AS r,\n COUNT(*) OVER (PARTITION BY service_name, agg_time, agg_type) AS total,\n SUM(feature_holiday_date) OVER (PARTITION BY service_name, agg_time, agg_type) AS feature_holiday_total\n FROM (\n SELECT time_list.agg_time, feature.agg_type,\n MAX(feature.instance_uuid) AS instance_uuid,\n feature.service_name,\n MAX(feature.workload_name) AS workload_name,\n MAX(feature.namespace) AS namespace,\n feature.agg_time AS feature_agg_time,\n MAX(CASE WHEN holiday_today.holiday_date > '' THEN 1 ELSE 0 END) AS today_holiday_date,\n MAX(feature.nv_inference_count_model_avg) AS nv_inference_count_model_avg,\n MAX(feature.nv_inference_request_duration_ms_model_avg) AS nv_inference_request_duration_ms_model_avg,\n MAX(feature.nv_inference_queue_duration_ms_model_avg) AS nv_inference_queue_duration_ms_model_avg,\n MAX(feature.num_queued_reqs_model_avg) AS num_queued_reqs_model_avg,\n MAX(feature.nv_inference_request_success_model_avg) AS nv_inference_request_success_model_avg,\n MAX(feature.nv_inference_request_failure_model_avg) AS nv_inference_request_failure_model_avg,\n MAX(feature.nv_inference_request_duration_ms_perreq_avg) AS nv_inference_request_duration_ms_perreq_avg,\n MAX(feature.nv_inference_queue_duration_ms_perreq_avg) AS nv_inference_queue_duration_ms_perreq_avg,\n MAX(feature.nv_inference_request_duration_ms_perreq_p95) AS nv_inference_request_duration_ms_perreq_p95,\n MAX(feature.nv_inference_queue_duration_ms_perreq_p95) AS nv_inference_queue_duration_ms_perreq_p95,\n MAX(feature.nv_inference_request_success_model_max) AS nv_inference_request_success_model_max,\n MAX(feature.nv_inference_request_failure_model_max) AS nv_inference_request_failure_model_max,\n MAX(feature.dcgm_fi_dev_gpu_util_pod_avg) AS dcgm_fi_dev_gpu_util_pod_avg,\n MAX(feature.k8s_container_bs_rate_cpu_core_used_request_pod_avg) AS k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n MAX(feature.k8s_container_rate_mem_working_set_request_pod_avg) AS k8s_container_rate_mem_working_set_request_pod_avg,\n MAX(feature.k8s_dcgm_fi_dev_fb_util_pod_avg) AS k8s_dcgm_fi_dev_fb_util_pod_avg,\n MAX(feature.k8s_container_vgpu_gpu_util_pod_avg) AS k8s_container_vgpu_gpu_util_pod_avg,\n MAX(CASE WHEN holiday_feature.holiday_date > '' THEN 1 ELSE 0 END) AS feature_holiday_date\n FROM service_list\n CROSS JOIN time_list\n JOIN feature ON service_list.service_name = feature.service_name\n AND time_list.agg_type = feature.agg_type\n AND SUBSTRING_INDEX(time_list.agg_time, ' ', -1) = SUBSTRING_INDEX(feature.agg_time, ' ', -1)\n LEFT JOIN {DB_NAME}.{INPUT_TABLE_HOLIDAY} holiday_today\n ON SUBSTRING_INDEX(time_list.agg_time, ' ', 1) = holiday_today.holiday_date\n LEFT JOIN {DB_NAME}.{INPUT_TABLE_HOLIDAY} holiday_feature\n ON SUBSTRING_INDEX(feature.agg_time, ' ', 1) = holiday_feature.holiday_date\n GROUP BY time_list.agg_time, feature.agg_time, feature.agg_type, feature.service_name\n ) t1\n ) t2\n ) t3\n WHERE r = CASE\n WHEN today_holiday_date = 1 AND feature_holiday_total >= 1 THEN feature_holiday_index\n WHEN today_holiday_date = 1 AND feature_holiday_total < 1 THEN feature_weekday_index\n WHEN today_holiday_date = 0 AND feature_weekday_total >= 1 THEN feature_weekday_index\n WHEN today_holiday_date = 0 AND feature_weekday_total < 1 THEN feature_holiday_index\n END\n)\nSELECT instance_uuid, base.service_name, base.workload_name, base.namespace,\n base.agg_time, agg_type, today_holiday_date, day_of_week, prediction_type,\n nv_inference_count_model_avg, statistic_time_count,\n nv_inference_request_duration_ms_model_avg, nv_inference_queue_duration_ms_model_avg,\n num_queued_reqs_model_avg, nv_inference_request_success_model_avg,\n nv_inference_request_failure_model_avg, nv_inference_request_duration_ms_perreq_avg,\n nv_inference_queue_duration_ms_perreq_avg, nv_inference_request_duration_ms_perreq_p95,\n nv_inference_queue_duration_ms_perreq_p95, nv_inference_request_success_model_max,\n nv_inference_request_failure_model_max, dcgm_fi_dev_gpu_util_pod_avg,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg,\n k8s_container_rate_mem_working_set_request_pod_avg,\n k8s_dcgm_fi_dev_fb_util_pod_avg, k8s_container_vgpu_gpu_util_pod_avg,\n cpd.agg_time AS cpd_agg_time, feature_total, feature_holiday_total, base.dt\nFROM base\nLEFT JOIN cpd ON base.service_name = cpd.service_name\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n instance_uuid VARCHAR(256),\n service_name VARCHAR(256),\n workload_name VARCHAR(256),\n namespace VARCHAR(256),\n agg_time VARCHAR(256),\n agg_type BIGINT,\n is_holiday BIGINT,\n day_of_week BIGINT,\n prediction_type VARCHAR(256),\n nv_inference_count_model_avg_p90 DOUBLE,\n statistic_time_count BIGINT,\n nv_inference_request_duration_ms_model_avg DOUBLE,\n nv_inference_queue_duration_ms_model_avg DOUBLE,\n num_queued_reqs_model_avg DOUBLE,\n nv_inference_request_success_model_avg DOUBLE,\n nv_inference_request_failure_model_avg DOUBLE,\n nv_inference_request_duration_ms_perreq_avg DOUBLE,\n nv_inference_queue_duration_ms_perreq_avg DOUBLE,\n nv_inference_request_duration_ms_perreq_p95 DOUBLE,\n nv_inference_queue_duration_ms_perreq_p95 DOUBLE,\n nv_inference_request_success_model_max DOUBLE,\n nv_inference_request_failure_model_max DOUBLE,\n DCGM_FI_DEV_GPU_UTIL_pod_avg DOUBLE,\n k8s_container_bs_rate_cpu_core_used_request_pod_avg DOUBLE,\n k8s_container_rate_mem_working_set_request_pod_avg DOUBLE,\n k8s_dcgm_fi_dev_fb_util_pod_avg DOUBLE,\n k8s_container_vgpu_gpu_util_pod_avg DOUBLE,\n cpd_agg_time VARCHAR(256),\n feature_total BIGINT,\n feature_holiday_total BIGINT,\n dt VARCHAR(256)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n\n # Verify row count\n with conn.cursor() as cur:\n cur.execute(f\"SELECT COUNT(*) FROM {DB_NAME}.{OUTPUT_TABLE}\")\n count = cur.fetchone()[0]\n print(f\"mysql_006 ground_truth done: {count} rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_006"} {"task_id": "mysql_007", "id": "offline-compute_MySQL_mysql_007", "name": "热表治理元数据宽表汇总", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,从表治理明细中筛选有热度的正式表,按库名+表名去重汇总治理指标,形成热表元数据宽表。\n\n**业务背景与目标**:数据平台需要从表治理明细表中筛选出有热度(heat > 0)的正式表(排除表名含 'temp' 的临时表和库名含 'test' 的测试库),按 db_name + table_name 分组去重,对其余所有字段取 MAX,形成热表元数据宽表写入输出表。\n\n**输入表(全名 + 简要描述)**:\n- `internal_platform_db.ads_gov_cost_table_govern_detail_df_mysql_007`(表治理明细表)\n\n(表结构与字段含义请自行连接数据库查询确认)\n\n**过滤条件**:\n- `imp_date = 20260507`\n- `heat > 0`\n- `table_name` 不包含 'temp'(即 `table_name NOT LIKE '%temp%'`)\n- `db_name` 不包含 'test'(即 `db_name NOT LIKE '%test%'`)\n\n**聚合逻辑**:\n- 按 `db_name`, `table_name` 分组\n- 对其余所有字段取 MAX\n\n**输出要求**:\n- 目标表:`internal_platform_db.dwd_hot_metadata_table_cand_mysql_007`\n- 输出字段及顺序:`dt`, `db_name`, `table_name`, `owner`, `storage_detail`, `heat`, `read_gap_days`, `write_gap_days`, `last_date_partition`, `is_table_no_comment`, `is_table_comment_irregular`, `is_all_column_no_comment`, `is_part_column_no_comment`, `table_first_group`, `table_second_group`, `dw_appgroup`, `appgroup_obs_product_id`, `appgroup_obs_plan_id`, `is_partition`, `create_days`\n- `dt` 字段值为 `'20260507'`\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据\n- 请使用标准 MySQL 语法(INSERT INTO ... SELECT),不要使用 Hive/Spark SQL 方言(如 INSERT OVERWRITE、STORED AS ORC 等)\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_007 ground truth: 热表治理元数据宽表汇总\n\nTask:\n Filter input table WHERE imp_date = 20260507 AND heat > 0\n AND table_name NOT LIKE '%temp%' AND db_name NOT LIKE '%test%',\n group by db_name, table_name, take MAX of all other fields,\n write to output table with dt = '20260507'.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"ads_gov_cost_table_govern_detail_df_mysql_007\"\nOUTPUT_TABLE = \"dwd_hot_metadata_table_cand_mysql_007\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, db_name, table_name, owner, storage_detail, heat,\n read_gap_days, write_gap_days, last_date_partition,\n is_table_no_comment, is_table_comment_irregular,\n is_all_column_no_comment, is_part_column_no_comment,\n table_first_group, table_second_group, dw_appgroup,\n appgroup_obs_product_id, appgroup_obs_plan_id,\n is_partition, create_days)\nSELECT\n '20260507' AS dt,\n db_name,\n table_name,\n MAX(owner) AS owner,\n MAX(storage_detail) AS storage_detail,\n MAX(heat) AS heat,\n MAX(read_gap_days) AS read_gap_days,\n MAX(write_gap_days) AS write_gap_days,\n MAX(last_date_partition) AS last_date_partition,\n MAX(is_table_no_comment) AS is_table_no_comment,\n MAX(is_table_comment_irregular) AS is_table_comment_irregular,\n MAX(is_all_column_no_comment) AS is_all_column_no_comment,\n MAX(is_part_column_no_comment) AS is_part_column_no_comment,\n MAX(table_first_group) AS table_first_group,\n MAX(table_second_group) AS table_second_group,\n MAX(dw_appgroup) AS dw_appgroup,\n MAX(appgroup_obs_product_id) AS appgroup_obs_product_id,\n MAX(appgroup_obs_plan_id) AS appgroup_obs_plan_id,\n MAX(is_partition) AS is_partition,\n MAX(create_days) AS create_days\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE imp_date = 20260507\n AND heat > 0\n AND table_name NOT LIKE '%temp%'\n AND db_name NOT LIKE '%test%'\nGROUP BY db_name, table_name\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n dt VARCHAR(16) DEFAULT NULL COMMENT '日期分区',\n db_name VARCHAR(256) DEFAULT NULL COMMENT '库名',\n table_name VARCHAR(256) DEFAULT NULL COMMENT '表名',\n owner VARCHAR(256) DEFAULT NULL COMMENT '第一责任人',\n storage_detail DOUBLE DEFAULT NULL COMMENT '存储大小含副本',\n heat BIGINT DEFAULT NULL COMMENT '90天热度',\n read_gap_days BIGINT DEFAULT NULL COMMENT '多久未读',\n write_gap_days BIGINT DEFAULT NULL COMMENT '多久未写',\n last_date_partition VARCHAR(256) DEFAULT NULL COMMENT '最后一个分区',\n is_table_no_comment BIGINT DEFAULT NULL COMMENT '表无描述',\n is_table_comment_irregular BIGINT DEFAULT NULL COMMENT '表描述过短或等于表名',\n is_all_column_no_comment BIGINT DEFAULT NULL COMMENT '所有字段都无描述',\n is_part_column_no_comment BIGINT DEFAULT NULL COMMENT '部分字段无描述',\n table_first_group VARCHAR(256) DEFAULT NULL COMMENT '一级应用组',\n table_second_group VARCHAR(256) DEFAULT NULL COMMENT '二级应用组',\n dw_appgroup VARCHAR(256) DEFAULT NULL COMMENT '数据仓库DW应用组',\n appgroup_obs_product_id VARCHAR(256) DEFAULT NULL COMMENT '运营产品ID',\n appgroup_obs_plan_id VARCHAR(256) DEFAULT NULL COMMENT '规划产品ID',\n is_partition BIGINT DEFAULT NULL COMMENT '是否分区表',\n create_days BIGINT DEFAULT NULL COMMENT '建表距今天数',\n PRIMARY KEY (db_name, table_name)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_007 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_007"} {"task_id": "mysql_008", "id": "offline-compute_MySQL_mysql_008", "name": "消费组治理项明细提取", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n任务目标:从消费特征增量表提取近90天有消费量且非 reader 类型的消费组治理项明细。\n\n**输入表**:`internal_platform_db.dws_mq_consumption_feature_d_increase_mysql_008`(消费特征增量表)\n\n(表结构与字段含义请自行连接数据库查询确认)\n\n**处理规则**:\n\n1. 过滤条件:`dt = '20260507'` AND `(total_consume_last_90d <> 0 AND total_consume_last_90d IS NOT NULL)` AND `is_reader = 0`\n2. 派生字段:\n - `mq_full_topic`:若 `tenant` 和 `namespaces` 均非 NULL,拼接 `'persistent://' + tenant + '/' + namespaces + '/' + topic`;否则取 `topic`\n - `app_group`:取自 `dw_appgroup`\n - `consumergroup_incharge`:`COALESCE(consumergroup_incharge, bid_incharge)`,即消费组负责人为空时取 bid 负责人\n - `consumergroup_description`:取自 `usage_desc`\n - `hitted_gov_items`:固定 NULL\n - `governance_benefit_estimate`:固定 NULL\n3. 无 Join,单表处理\n\n**输出要求**:\n\n- 目标表:`internal_platform_db.ads_mq_consumergroup_governance_item_d_cand_mysql_008`\n- 输出字段顺序为:`dt`、`business_id`、`business_name`、`cluster_set`、`mq_full_topic`、`topic`、`consumergroup`、`system_belong`、`bg`、`category_name`、`app_group`、`consumergroup_incharge`、`last_operator`、`consumergroup_description`、`create_time`、`modify_time`、`bid_incharge`、`cluster_id`、`has_metadata`、`total_produce_pkg_d`、`total_consume_pkg_d`、`consume_ratio`、`total_produce_pkg_last_7d`、`total_produce_pkg_last_30d`、`total_produce_pkg_last_90d`、`total_consume_last_7d`、`consume_ratio_last_7d`、`backlog_ratio_last_7d`、`total_consume_last_30d`、`consume_ratio_last_30d`、`backlog_ratio_last_30d`、`total_consume_last_90d`、`consume_ratio_last_90d`、`backlog_ratio_last_90d`、`backlog_days_last_30d`、`hitted_gov_items`、`governance_benefit_estimate`\n- 字段类型:\n - `dt` VARCHAR(8)\n - `mq_full_topic` VARCHAR(512)\n - `app_group` VARCHAR(256)\n - `consumergroup_incharge` VARCHAR(256)\n - `consumergroup_description` VARCHAR(256)\n - `has_metadata` TINYINT\n - `total_produce_pkg_d` BIGINT\n - `total_consume_pkg_d` BIGINT\n - `consume_ratio` VARCHAR(256)\n - `total_produce_pkg_last_7d` BIGINT\n - `total_produce_pkg_last_30d` BIGINT\n - `total_produce_pkg_last_90d` BIGINT\n - `total_consume_last_7d` BIGINT\n - `consume_ratio_last_7d` VARCHAR(256)\n - `backlog_ratio_last_7d` VARCHAR(256)\n - `total_consume_last_30d` BIGINT\n - `consume_ratio_last_30d` VARCHAR(256)\n - `backlog_ratio_last_30d` VARCHAR(256)\n - `total_consume_last_90d` BIGINT\n - `consume_ratio_last_90d` VARCHAR(256)\n - `backlog_ratio_last_90d` VARCHAR(256)\n - `backlog_days_last_30d` INT\n - `hitted_gov_items` VARCHAR(256)\n - `governance_benefit_estimate` DOUBLE\n - 其余字符串字段均为 VARCHAR(256)\n- 写入方式:使用 `INSERT INTO ... SELECT ...` 写入目标表\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_008 ground truth: 消费组治理项明细提取\n\nTask:\n Filter input table WHERE dt = '20260507'\n AND (total_consume_last_90d <> 0 AND total_consume_last_90d IS NOT NULL)\n AND is_reader = 0\n Derive mq_full_topic, app_group, consumergroup_incharge,\n consumergroup_description, hitted_gov_items, governance_benefit_estimate\n Write to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"dws_mq_consumption_feature_d_increase_mysql_008\"\nOUTPUT_TABLE = \"ads_mq_consumergroup_governance_item_d_cand_mysql_008\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, business_id, business_name, cluster_set, mq_full_topic, topic,\n consumergroup, system_belong, bg, category_name, app_group,\n consumergroup_incharge, last_operator, consumergroup_description,\n create_time, modify_time, bid_incharge, cluster_id, has_metadata,\n total_produce_pkg_d, total_consume_pkg_d, consume_ratio,\n total_produce_pkg_last_7d, total_produce_pkg_last_30d, total_produce_pkg_last_90d,\n total_consume_last_7d, consume_ratio_last_7d, backlog_ratio_last_7d,\n total_consume_last_30d, consume_ratio_last_30d, backlog_ratio_last_30d,\n total_consume_last_90d, consume_ratio_last_90d, backlog_ratio_last_90d,\n backlog_days_last_30d, hitted_gov_items, governance_benefit_estimate)\nSELECT\n '20260507' AS dt,\n business_id,\n business_name,\n cluster_set,\n IF(tenant IS NOT NULL AND namespaces IS NOT NULL,\n CONCAT('persistent://', tenant, '/', namespaces, '/', topic),\n topic) AS mq_full_topic,\n topic,\n consumergroup,\n system_belong,\n bg,\n category_name,\n dw_appgroup AS app_group,\n COALESCE(consumergroup_incharge, bid_incharge) AS consumergroup_incharge,\n last_operator,\n usage_desc AS consumergroup_description,\n create_time,\n modify_time,\n bid_incharge,\n cluster_id,\n has_metadata,\n total_produce_pkg_d,\n total_consume_pkg_d,\n consume_ratio,\n total_produce_pkg_last_7d,\n total_produce_pkg_last_30d,\n total_produce_pkg_last_90d,\n total_consume_last_7d,\n consume_ratio_last_7d,\n backlog_ratio_last_7d,\n total_consume_last_30d,\n consume_ratio_last_30d,\n backlog_ratio_last_30d,\n total_consume_last_90d,\n consume_ratio_last_90d,\n backlog_ratio_last_90d,\n backlog_days_last_30d,\n NULL AS hitted_gov_items,\n NULL AS governance_benefit_estimate\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE dt = '20260507'\n AND (total_consume_last_90d <> 0 AND total_consume_last_90d IS NOT NULL)\n AND is_reader = 0\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n dt VARCHAR(8) COMMENT '天分区',\n business_id VARCHAR(256) COMMENT '消费组所属的business_id',\n business_name VARCHAR(256) COMMENT 'business_name',\n cluster_set VARCHAR(256) COMMENT 'cluster_set',\n mq_full_topic VARCHAR(512) COMMENT 'mq的完整topic名',\n topic VARCHAR(256) COMMENT '消费组消费的topic',\n consumergroup VARCHAR(256) COMMENT '消费组',\n system_belong VARCHAR(256) COMMENT 'bid所属的系统(数据总线/流处理平台)',\n bg VARCHAR(256) COMMENT '消费组所属的bg',\n category_name VARCHAR(256) COMMENT '消费组所归属的产品',\n app_group VARCHAR(256) COMMENT '消费组所属的应用组',\n consumergroup_incharge VARCHAR(256) COMMENT '消费组负责人',\n last_operator VARCHAR(256) COMMENT '消费组最后一次的操作人',\n consumergroup_description VARCHAR(256) COMMENT '消费组使用描述',\n create_time VARCHAR(256) COMMENT '消费组创建时间',\n modify_time VARCHAR(256) COMMENT '消费组修改时间',\n bid_incharge VARCHAR(256) COMMENT 'bid负责人',\n cluster_id VARCHAR(256) COMMENT 'bid所属集群id',\n has_metadata TINYINT COMMENT '消费组是否在数据总线/流处理平台中有元数据',\n total_produce_pkg_d BIGINT COMMENT '当天上游的消息数的总量',\n total_consume_pkg_d BIGINT COMMENT '当天消费者消费的消息数的总量',\n consume_ratio VARCHAR(256) COMMENT '当天消费组的消费生产比例(%)',\n total_produce_pkg_last_7d BIGINT COMMENT '近7天topic生产的消息数的总量',\n total_produce_pkg_last_30d BIGINT COMMENT '近30天topic生产的消息数的总量',\n total_produce_pkg_last_90d BIGINT COMMENT '近90天topic生产的消息数的总量',\n total_consume_last_7d BIGINT COMMENT '消费组近7天总消费量',\n consume_ratio_last_7d VARCHAR(256) COMMENT '消费组近7天的生产消费比例(%)',\n backlog_ratio_last_7d VARCHAR(256) COMMENT '消费组近7天的生产积压比例(%)',\n total_consume_last_30d BIGINT COMMENT '消费组近30天总消费量',\n consume_ratio_last_30d VARCHAR(256) COMMENT '消费组近30天的生产消费比例(%)',\n backlog_ratio_last_30d VARCHAR(256) COMMENT '消费组近30天的生产积压比例(%)',\n total_consume_last_90d BIGINT COMMENT '消费组近90天总消费量',\n consume_ratio_last_90d VARCHAR(256) COMMENT '消费组近90天的生产消费比例(%)',\n backlog_ratio_last_90d VARCHAR(256) COMMENT '消费组近90天的生产积压比例(%)',\n backlog_days_last_30d INT COMMENT '消费组近30天有新增积压的天数',\n hitted_gov_items VARCHAR(256) COMMENT '命中治理项',\n governance_benefit_estimate DOUBLE COMMENT '预估治理收益(集群单元/月)'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_008 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_008"} {"task_id": "mysql_009_en", "id": "offline-compute_MySQL_mysql_009", "name": "数据总线 Consumer Group Cost Detail Data Aggregation and Column Renaming", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that summarizes packet count, size, and cost from 数据总线 consumer group cost raw data, grouped by consumer group + business ID + topic, to produce a consumer group cost detail table.\n\n**Business Background and Objective**: 数据总线 periodically writes cost data for each consumer group into a raw detail table. Downstream consumers only need records from the `dt = '20260507'` partition, grouped by `business_id`, `topic`, and `consumer_group`, with MAX aggregation applied to all other fields before writing to the output table. The output field names must also match the downstream table conventions. This task aggregates qualifying records from the input table, performs column renaming, and writes to the output table.\n\n**Input Table (full name + brief description)**:\n- `internal_platform_db.ods_t_databus_consume_cost_final_date_d_mysql_009` (数据总线 consumer group cost raw data table)\n\n(Please connect to the database and query to confirm the table structure and field semantics.)\n\n**Filter and Aggregation Rules**:\n- Filter condition: `dt = '20260507'`\n- Aggregation logic: Group by `business_id`, `topic`, `consumer_group`\n- Apply MAX to `systemname`, `dwproductname`, `dwappgroup`, `cityid`, `iset`, `pkgcnt`, `tubesize`, `total_cost`, and `in_charge`\n\n**Column Renaming Rules**:\n- Input column `systemname` → output column `system_belong`\n- Input column `dwproductname` → output column `category_name`\n- Input column `dwappgroup` → output column `dw_appgroup`\n- Input column `cityid` → output column `city_id`\n- Input column `iset` → output column `cluster_set`\n- Input column `consumer_group` → output column `consumergroup`\n- Input column `pkgcnt` → output column `pkg_cnt`\n- Input column `tubesize` → output column `data_size`\n- `business_id`, `topic`, `total_cost`, `in_charge` retain their original names\n\n**Output Requirements**:\n- Target table: `internal_platform_db.dwd_databus_consumergroup_cost_detail_d_cand_mysql_009`\n- Table comment: 数据总线 consumer group cost detail table, performing data cleansing on the ODS table\n- Output field order: `dt`, `system_belong`, `category_name`, `dw_appgroup`, `city_id`, `cluster_set`, `consumergroup`, `business_id`, `topic`, `pkg_cnt`, `data_size`, `total_cost`, `in_charge`\n- Field types: `dt` VARCHAR(256), `system_belong` VARCHAR(256), `category_name` VARCHAR(256), `dw_appgroup` VARCHAR(256), `city_id` VARCHAR(256), `cluster_set` VARCHAR(256), `consumergroup` VARCHAR(256), `business_id` VARCHAR(256), `topic` VARCHAR(256), `pkg_cnt` BIGINT, `data_size` BIGINT, `total_cost` DOUBLE, `in_charge` VARCHAR(256)\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_009 ground truth: 数据总线消费组成本明细数据聚合与列重命名\n\nTask:\n Filter input table WHERE dt = '20260507',\n GROUP BY business_id, topic, consumer_group,\n MAX() for systemname, dwproductname, dwappgroup, cityid, iset, pkgcnt, tubesize, total_cost, in_charge,\n rename columns, write to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"ods_t_databus_consume_cost_final_date_d_mysql_009\"\nOUTPUT_TABLE = \"dwd_databus_consumergroup_cost_detail_d_cand_mysql_009\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, system_belong, category_name, dw_appgroup, city_id, cluster_set,\n consumergroup, business_id, topic, pkg_cnt, data_size, total_cost, in_charge)\nSELECT\n '20260507' AS dt,\n MAX(systemname) AS system_belong,\n MAX(dwproductname) AS category_name,\n MAX(dwappgroup) AS dw_appgroup,\n MAX(cityid) AS city_id,\n MAX(iset) AS cluster_set,\n consumer_group AS consumergroup,\n business_id,\n topic,\n MAX(CAST(pkgcnt AS UNSIGNED)) AS pkg_cnt,\n MAX(CAST(tubesize AS UNSIGNED)) AS data_size,\n MAX(CAST(total_cost AS DOUBLE)) AS total_cost,\n MAX(in_charge) AS in_charge\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE dt = '20260507'\nGROUP BY business_id, topic, consumer_group\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n dt VARCHAR(256) NOT NULL COMMENT '天分区',\n system_belong VARCHAR(256) NOT NULL COMMENT '系统名',\n category_name VARCHAR(256) NOT NULL COMMENT '数据仓库DW产品名称',\n dw_appgroup VARCHAR(256) NOT NULL COMMENT '数据仓库DW应用组',\n city_id VARCHAR(256) NOT NULL COMMENT '城市ID',\n cluster_set VARCHAR(256) NOT NULL COMMENT '集群',\n consumergroup VARCHAR(256) NOT NULL COMMENT '消费组',\n business_id VARCHAR(256) NOT NULL COMMENT '业务ID',\n topic VARCHAR(256) NOT NULL COMMENT 'topic',\n pkg_cnt BIGINT NOT NULL COMMENT '包数',\n data_size BIGINT NOT NULL COMMENT '大小',\n total_cost DOUBLE NOT NULL COMMENT '总成本',\n in_charge VARCHAR(256) NOT NULL COMMENT '负责人'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据总线消费组成本明细表,ods表做数据清洗'\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_009 ground_truth done: 3 rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_009_en"} {"task_id": "mysql_010_en", "id": "offline-compute_MySQL_mysql_010", "name": "Table Heat Field Count and Query User Count Statistics with TOP Ranking", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that retrieves the current day's data from the heat table, counts the number of heat fields queried and the number of querying users per table, and lands the top 10000 rows ranked by heat in descending order.\n\n**Business Background and Objective**: Retrieve the current day's data from the heat table, count how many fields and how many users queried each table, and land the top 10000 rows ranked by heat in descending order into the output table.\n\n**Input Table (full name + brief description)**:\n- `internal_platform_db.sql_heat_column_to_ao_mysql_010` (table heat field summary table)\n\n(Please connect to the database and query to confirm the table structure and field semantics.)\n\n**Filter Condition**:\n- `imp_date = '20260507'`\n\n**Derived Field Rules**:\n- `column_count`: Take the JSON array length of the `column_list` field (i.e., the number of fields), which can be implemented using `JSON_LENGTH(column_list)`; equivalent method: remove brackets and quotes, then split by comma and take the length\n- `user_count`: Apply the same treatment to the `user_list` field, taking the JSON array length (i.e., the number of users)\n\n**Sorting and Limit**:\n- Sort by `heat DESC, column_count DESC, user_count DESC`\n- Take the first 10000 rows\n\n**Output Requirements**:\n- Target table: `internal_platform_db.sql_heat_column_to_ao_top_mysql_010`\n- Output field order: `imp_date` (VARCHAR), `databasename` (VARCHAR), `tablename` (VARCHAR), `column_list` (VARCHAR), `user_list` (VARCHAR), `heat` (VARCHAR), `column_count` (VARCHAR), `user_count` (VARCHAR)\n- No deduplication or aggregation\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_010 ground truth: 表热度字段数与查询用户数统计TOP排序\n\nTask:\n Filter input table WHERE imp_date = '20260507',\n derive column_count (length of JSON array in column_list) and\n user_count (length of JSON array in user_list),\n sort by heat DESC, column_count DESC, user_count DESC,\n limit 10000, write to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"sql_heat_column_to_ao_mysql_010\"\nOUTPUT_TABLE = \"sql_heat_column_to_ao_top_mysql_010\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\n# MySQL equivalent of Spark's size(split(regexp_replace(regexp_replace(regexp_replace(col, '\\\\[|\\\\]', ''), '\"', ''), ' ', ''), ','))\n# In MySQL: strip brackets/quotes/spaces, then count comma-separated items.\n# Helper: JSON_LENGTH works for valid JSON arrays; fallback to comma-count.\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (imp_date, databasename, tablename, column_list, user_list, heat, column_count, user_count)\nSELECT\n imp_date,\n databasename,\n tablename,\n column_list,\n user_list,\n CAST(heat AS CHAR) AS heat,\n CAST(JSON_LENGTH(column_list) AS CHAR) AS column_count,\n CAST(JSON_LENGTH(user_list) AS CHAR) AS user_count\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE imp_date = '20260507'\nORDER BY heat DESC, JSON_LENGTH(column_list) DESC, JSON_LENGTH(user_list) DESC\nLIMIT 10000\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n imp_date VARCHAR(256) NOT NULL COMMENT '数据日期',\n databasename VARCHAR(256) NOT NULL COMMENT '库名',\n tablename VARCHAR(256) NOT NULL COMMENT '表名',\n column_list VARCHAR(256) NOT NULL COMMENT '热度字段名',\n user_list VARCHAR(256) NOT NULL COMMENT '用户名',\n heat VARCHAR(256) NOT NULL COMMENT '表热度',\n column_count VARCHAR(256) NOT NULL COMMENT '列字段数',\n user_count VARCHAR(256) NOT NULL COMMENT '用户数'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n\n # Verify row count\n with conn.cursor() as cur:\n cur.execute(f\"SELECT COUNT(*) FROM {DB_NAME}.{OUTPUT_TABLE}\")\n count = cur.fetchone()[0]\n print(f\"mysql_010 ground_truth done: {count} rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_010_en"} {"task_id": "mysql_011_en", "id": "offline-compute_MySQL_mysql_011", "name": "Low-Value Task Benefit Aggregation Statistics by Application Group", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nTask Objective: Summarize the current day's actual and estimated benefit metrics for low-value tasks, grouped by planning product, operations product, OBS product, and application group dimensions.\n\n**Business Background and Objective**: Low-value task governance requires summarizing the current day's actual benefits (task count, runtime, CPU, memory) and estimated benefits (task count, runtime, CPU, memory) at the application group level to evaluate governance effectiveness. This task groups the detail data from the specified partition of the input table by four dimension fields, applies SUM aggregation to all metric fields, and writes the results to the output table.\n\n**Input Table (full name + brief description)**:\n- `internal_platform_db.dws_low_value_task_compute_statistics_day_mysql_011` (low-value task compute benefit detail daily table)\n\n(Please connect to the database and query to confirm the table structure and field semantics.)\n\n**Processing Rules**:\n- No joins, single-table processing\n- Filter condition: `dt = '20260507'`\n- Aggregation logic: Group by `plan_product_name`, `obs_product_name`, `product_name`, `dw_appgroup`, applying SUM to all metric fields (`actural_task_count`, `actural_time_sum_hour`, `actural_vcore_sum_vcore_hour`, `actural_memory_sum_gb_hour`, `estimated_task_count`, `estimated_time_sum_hour`, `estimated_vcore_sum_vcore_hour`, `estimated_memory_sum_gb_hour`)\n\n**Output Requirements**:\n- Target table: `internal_platform_db.dws_low_value_task_compute_appgroup_stats_day_cand_mysql_011`\n- Output field order: `dt`, `plan_product_name`, `obs_product_name`, `product_name`, `dw_appgroup`, `actural_task_count`, `actural_time_sum_hour`, `actural_vcore_sum_vcore_hour`, `actural_memory_sum_gb_hour`, `estimated_task_count`, `estimated_time_sum_hour`, `estimated_vcore_sum_vcore_hour`, `estimated_memory_sum_gb_hour`\n- `dt` field value: `'20260507'`\n- Types: `dt` VARCHAR(8), `plan_product_name` VARCHAR(256), `obs_product_name` VARCHAR(256), `product_name` VARCHAR(256), `dw_appgroup` VARCHAR(256), `actural_task_count` INT, `actural_time_sum_hour` DOUBLE, `actural_vcore_sum_vcore_hour` DOUBLE, `actural_memory_sum_gb_hour` DOUBLE, `estimated_task_count` INT, `estimated_time_sum_hour` DOUBLE, `estimated_vcore_sum_vcore_hour` DOUBLE, `estimated_memory_sum_gb_hour` DOUBLE\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects (e.g., `INSERT OVERWRITE`, `STORED AS ORC`, `PARTITIONED BY` are not supported)\n- Write method: Use `INSERT INTO ... SELECT ...` statements\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_011 ground truth: 低价值任务收益按应用组聚合统计\n\nTask:\n Filter input table WHERE dt = '20260507',\n GROUP BY plan_product_name, obs_product_name, product_name, dw_appgroup,\n SUM all metric fields, write to output table with dt = '20260507'.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"dws_low_value_task_compute_statistics_day_mysql_011\"\nOUTPUT_TABLE = \"dws_low_value_task_compute_appgroup_stats_day_cand_mysql_011\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, plan_product_name, obs_product_name, product_name, dw_appgroup,\n actural_task_count, actural_time_sum_hour, actural_vcore_sum_vcore_hour,\n actural_memory_sum_gb_hour, estimated_task_count, estimated_time_sum_hour,\n estimated_vcore_sum_vcore_hour, estimated_memory_sum_gb_hour)\nSELECT\n '20260507' AS dt,\n plan_product_name,\n obs_product_name,\n product_name,\n dw_appgroup,\n SUM(actural_task_count) AS actural_task_count,\n SUM(actural_time_sum_hour) AS actural_time_sum_hour,\n SUM(actural_vcore_sum_vcore_hour) AS actural_vcore_sum_vcore_hour,\n SUM(actural_memory_sum_gb_hour) AS actural_memory_sum_gb_hour,\n SUM(estimated_task_count) AS estimated_task_count,\n SUM(estimated_time_sum_hour) AS estimated_time_sum_hour,\n SUM(estimated_vcore_sum_vcore_hour) AS estimated_vcore_sum_vcore_hour,\n SUM(estimated_memory_sum_gb_hour) AS estimated_memory_sum_gb_hour\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE dt = '20260507'\nGROUP BY plan_product_name, obs_product_name, product_name, dw_appgroup\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n dt VARCHAR(8) NOT NULL COMMENT '天级分区',\n plan_product_name VARCHAR(256) DEFAULT NULL COMMENT '规划产品名',\n obs_product_name VARCHAR(256) DEFAULT NULL COMMENT '运营产品名',\n product_name VARCHAR(256) DEFAULT NULL COMMENT 'OBS产品名',\n dw_appgroup VARCHAR(256) DEFAULT NULL COMMENT '应用组',\n actural_task_count INT DEFAULT NULL COMMENT '实际收益-任务数',\n actural_time_sum_hour DOUBLE DEFAULT NULL COMMENT '实际收益-运行时间(hour)',\n actural_vcore_sum_vcore_hour DOUBLE DEFAULT NULL COMMENT '实际收益-CPU(vcore*hour)',\n actural_memory_sum_gb_hour DOUBLE DEFAULT NULL COMMENT '实际收益-内存(gb*hour)',\n estimated_task_count INT DEFAULT NULL COMMENT '预估收益-任务数',\n estimated_time_sum_hour DOUBLE DEFAULT NULL COMMENT '预估收益-运行时间(hour)',\n estimated_vcore_sum_vcore_hour DOUBLE DEFAULT NULL COMMENT '预估收益-CPU(vcore*hour)',\n estimated_memory_sum_gb_hour DOUBLE DEFAULT NULL COMMENT '预估收益-内存(gb*hour)'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_011 ground_truth done: 12 rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_011_en"} {"task_id": "mysql_012", "id": "offline-compute_MySQL_mysql_012", "name": "Notebook管道任务GPU利用率分钟级统计", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n任务目标:按任务实例+分钟粒度统计 Notebook 管道任务的 GPU 利用率,区分实例整体利用率与代码运行时段利用率。\n\n输入:\n- 表:`internal_platform_db.dwd_notebook_instance_pod_detail_d_mysql_012`(Notebook 实例 Pod 明细表)\n\n(表结构与字段含义请自行连接数据库查询确认)\n\n- 过滤条件:`dt = '20260507'`\n\n处理规则:\n- 无 Join,单表处理\n- 分组:按 `trace_id`, `p_date`, `pkg_agg_time` 分组\n- 聚合口径:\n - `datawd_project_id` ~ `apply_for_gpu_count`:取 `MAX`\n - `code_gpu_count`:`SUM(IF(gpu_util IS NOT NULL, COALESCE(gpu_count, 0), gpu_count))`\n - `instance_gpu_util`:`AVG(CASE WHEN gpu_count IS NOT NULL THEN COALESCE(gpu_util, 0) ELSE NULL END)`(注意:当分组内所有行的 gpu_count 均为 NULL 时,CASE 表达式均返回 NULL,AVG 无有效行参与,结果为 NULL)\n - `code_gpu_util`:`AVG(CASE WHEN code_start_time IS NOT NULL AND code_end_time IS NOT NULL AND pkg_agg_time >= code_start_time AND pkg_agg_time <= code_end_time AND gpu_count IS NOT NULL THEN COALESCE(gpu_util, 0) ELSE NULL END)`\n - `is_code_running`:`MAX(CASE WHEN code_start_time IS NOT NULL AND code_end_time IS NOT NULL AND pkg_agg_time >= code_start_time AND pkg_agg_time <= code_end_time THEN 1 ELSE 0 END)`\n - `used_gpu_count`:`SUM(COALESCE(gpu_util, 0) * COALESCE(gpu_count, 0) / 100)`\n - `code_used_gpu_count`:`SUM(CASE WHEN code_start_time IS NOT NULL AND code_end_time IS NOT NULL AND pkg_agg_time >= code_start_time AND pkg_agg_time <= code_end_time THEN COALESCE(gpu_util, 0) * COALESCE(gpu_count, 0) / 100 ELSE 0 END)`\n\n输出要求:\n- 输出表:`internal_platform_db.dws_notebook_instance_execute_minute_stat_d_cand_mysql_012`\n- 表注释:Notebook 管道任务实例分钟级运行统计信息\n- 输出字段(按顺序):`dt` VARCHAR(8)、`trace_id` VARCHAR(256)、`p_date` VARCHAR(256)、`pkg_agg_time` VARCHAR(256)、`datawd_project_id` VARCHAR(256)、`datawd_task_id` VARCHAR(256)、`datawd_task_instance_id` VARCHAR(256)、`compute_type` VARCHAR(256)、`status_code` INT、`instance_run_time` INT、`code_run_time` INT、`resource_wait_time` INT、`code_start_time` VARCHAR(256)、`code_end_time` VARCHAR(256)、`instance_start_time` VARCHAR(256)、`instance_end_time` VARCHAR(256)、`serving_id` VARCHAR(256)、`is_permanent` TINYINT(1)、`apply_for_gpu_count` INT、`code_gpu_count` INT、`instance_gpu_util` DOUBLE、`code_gpu_util` DOUBLE、`is_code_running` INT、`used_gpu_count` DOUBLE、`code_used_gpu_count` DOUBLE\n\n写入要求:\n- 使用 `INSERT INTO ... SELECT ...` 将结果写入输出表\n- 若目标表不存在,先按 MySQL InnoDB 标准建表(`ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`),再写入\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言(如不要使用 `INSERT OVERWRITE`、不要使用 `STORED AS ORC`、不要使用分区表语法)\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_012 ground truth: Notebook 管道任务实例分钟级 GPU 利用率统计\n\nTask:\n Filter input table WHERE dt = '20260507',\n group by trace_id, p_date, pkg_agg_time,\n aggregate MAX/SUM/AVG per the spec,\n write to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"dwd_notebook_instance_pod_detail_d_mysql_012\"\nOUTPUT_TABLE = \"dws_notebook_instance_execute_minute_stat_d_cand_mysql_012\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, trace_id, p_date, pkg_agg_time, datawd_project_id, datawd_task_id,\n datawd_task_instance_id, compute_type, status_code, instance_run_time,\n code_run_time, resource_wait_time, code_start_time, code_end_time,\n instance_start_time, instance_end_time, serving_id, is_permanent,\n apply_for_gpu_count, code_gpu_count, instance_gpu_util, code_gpu_util,\n is_code_running, used_gpu_count, code_used_gpu_count)\nSELECT\n '20260507' AS dt,\n trace_id,\n p_date,\n pkg_agg_time,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(status_code) AS status_code,\n MAX(instance_run_time) AS instance_run_time,\n MAX(code_run_time) AS code_run_time,\n MAX(resource_wait_time) AS resource_wait_time,\n MAX(code_start_time) AS code_start_time,\n MAX(code_end_time) AS code_end_time,\n MAX(instance_start_time) AS instance_start_time,\n MAX(instance_end_time) AS instance_end_time,\n MAX(serving_id) AS serving_id,\n MAX(is_permanent) AS is_permanent,\n MAX(apply_for_gpu_count) AS apply_for_gpu_count,\n SUM(IF(gpu_util IS NOT NULL, COALESCE(gpu_count, 0), gpu_count)) AS code_gpu_count,\n AVG(CASE WHEN gpu_count IS NOT NULL THEN COALESCE(gpu_util, 0) ELSE NULL END) AS instance_gpu_util,\n AVG(\n CASE\n WHEN code_start_time IS NOT NULL AND code_end_time IS NOT NULL\n AND pkg_agg_time >= code_start_time AND pkg_agg_time <= code_end_time\n AND gpu_count IS NOT NULL\n THEN COALESCE(gpu_util, 0)\n ELSE NULL\n END\n ) AS code_gpu_util,\n MAX(\n CASE\n WHEN code_start_time IS NOT NULL\n AND code_end_time IS NOT NULL\n AND pkg_agg_time >= code_start_time\n AND pkg_agg_time <= code_end_time\n THEN 1 ELSE 0\n END\n ) AS is_code_running,\n SUM(COALESCE(gpu_util, 0) * COALESCE(gpu_count, 0) / 100) AS used_gpu_count,\n SUM(\n CASE\n WHEN code_start_time IS NOT NULL AND code_end_time IS NOT NULL\n AND pkg_agg_time >= code_start_time AND pkg_agg_time <= code_end_time\n THEN COALESCE(gpu_util, 0) * COALESCE(gpu_count, 0) / 100\n ELSE 0\n END\n ) AS code_used_gpu_count\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE dt = '20260507'\nGROUP BY\n trace_id,\n p_date,\n pkg_agg_time\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n dt VARCHAR(8) COMMENT '天分区',\n trace_id VARCHAR(256) COMMENT '',\n p_date VARCHAR(256) COMMENT '',\n pkg_agg_time VARCHAR(256) COMMENT '分钟级时间戳',\n datawd_project_id VARCHAR(256) COMMENT '',\n datawd_task_id VARCHAR(256) COMMENT '',\n datawd_task_instance_id VARCHAR(256) COMMENT '',\n compute_type VARCHAR(256) COMMENT '',\n status_code INT COMMENT '',\n instance_run_time INT COMMENT '',\n code_run_time INT COMMENT '',\n resource_wait_time INT COMMENT '',\n code_start_time VARCHAR(256) COMMENT '',\n code_end_time VARCHAR(256) COMMENT '',\n instance_start_time VARCHAR(256) COMMENT '',\n instance_end_time VARCHAR(256) COMMENT '',\n serving_id VARCHAR(256) COMMENT '',\n is_permanent TINYINT(1) COMMENT '布尔型',\n apply_for_gpu_count INT COMMENT '',\n code_gpu_count INT COMMENT '',\n instance_gpu_util DOUBLE COMMENT '',\n code_gpu_util DOUBLE COMMENT '',\n is_code_running INT COMMENT '',\n used_gpu_count DOUBLE COMMENT '',\n code_used_gpu_count DOUBLE COMMENT ''\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n COMMENT='Notebook 管道任务实例分钟级运行统计信息'\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_012 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_012"} {"task_id": "mysql_013_en", "id": "offline-compute_MySQL_mysql_013", "name": "Notebook Cross-Day Instance Pod Runtime Detail", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that splits Notebook runner cross-day instances by day, joins with service instance, Pod, GPU aggregation, and engine information, to produce cross-day instance Pod runtime detail records.\n\n**Business Background and Objective**: Instances in the Notebook runner may run across multiple days. The detail records need to be split by day and joined with service instance mapping, Pod names, GPU aggregation metrics, and engine configuration information, ultimately producing detail records at the instance × Pod × day granularity.\n\n**Input Tables (full name + brief description)**:\n- `internal_platform_db.notebook_span_info_mysql_013` (Notebook span information table)\n- `internal_platform_db.dwd_gputj_service_instance_map_mysql_013` (service instance mapping table)\n- `internal_platform_db.dwd_ml_platform_instance_podname_mysql_013` (instance Pod name table)\n- `internal_platform_db.gputj_gpu_info_parsed_agg_1min_mysql_013` (GPU aggregation metrics table)\n- `internal_platform_db.notebook_engine_info_mysql_013` (engine configuration information table)\n\n(Please connect to the database and query to confirm the table structures and field semantics.)\n\n**Processing Rules**:\n1. Identify cross-day instances from `notebook_span_info` (`compute_type='ray'` AND `service_name='notebook-runner'` AND `span_name='runner.execute'`), split them by day, and generate detail records for each instance per day;\n2. Obtain `serving_id` via `notebook_engine_info`, then join with `dwd_gputj_service_instance_map` on `service_id` (i.e., `serving_id`) to obtain `instance_uuid`, and subsequently retrieve service instance mapping information;\n3. Join with `dwd_ml_platform_instance_podname` on `instance_uuid` to obtain Pod name information;\n4. Join with `gputj_gpu_info_parsed_agg_1min` on Pod name and time granularity to obtain GPU aggregation metrics;\n5. Join with `notebook_engine_info` on `trace_id` to obtain engine configuration information (`serving_id`, `is_permanent`, `apply_for_gpu_count`, etc.).\n\n**Output Requirements**:\n- Output granularity: instance × Pod × day;\n- Output fields: `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`\n- Sort by instance ID and date\n\n**Write Requirements**:\n- Target table: `internal_platform_db.dwd_notebook_instance_pod_cross_day_detail_d_cand_mysql_013`\n- Write mode: `INSERT INTO ... SELECT`\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_013 ground truth: Notebook跨天实例Pod运行明细\n\nTask:\n Split Notebook runner cross-day instances by day, join with service instance,\n Pod, GPU aggregation and engine info, produce cross-day instance Pod detail.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE_1 = \"notebook_span_info_mysql_013\"\nINPUT_TABLE_2 = \"dwd_gputj_service_instance_map_mysql_013\"\nINPUT_TABLE_3 = \"dwd_ml_platform_instance_podname_mysql_013\"\nINPUT_TABLE_4 = \"gputj_gpu_info_parsed_agg_1min_mysql_013\"\nINPUT_TABLE_5 = \"notebook_engine_info_mysql_013\"\nOUTPUT_TABLE = \"dwd_notebook_instance_pod_cross_day_detail_d_cand_mysql_013\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (trace_id, datawd_project_id, datawd_task_id, datawd_task_instance_id,\n compute_type, status_code, instance_run_time, code_run_time, resource_wait_time,\n code_start_time, code_end_time, instance_start_time, instance_end_time,\n serving_id, is_permanent, apply_for_gpu_count,\n pod_name, pkg_agg_time, gpu_util, gpu_count, p_date, dt)\nWITH\nbase_data_raw AS (\n SELECT DISTINCT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM {DB_NAME}.{INPUT_TABLE_1}\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (\n SELECT trace_id\n FROM {DB_NAME}.{INPUT_TABLE_1}\n WHERE databus_imp_date >= '2026050700'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n AND span_name = 'runner.execute'\n GROUP BY trace_id\n )\n AND (\n span_name = 'runner.execute'\n OR\n span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute', 'runner.killed')\n )\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'runner.killed'\n THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n CASE\n WHEN span_name = 'runner.execute'\n THEN MAX(CASE WHEN span_name IN ('runner.execute', 'runner.killed') THEN end_time END)\n OVER(PARTITION BY trace_id)\n ELSE end_time\n END AS end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM base_data_raw\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n DATE(FROM_UNIXTIME(CAST(start_time AS UNSIGNED) / 1000)) AS start_date,\n DATE(FROM_UNIXTIME(CAST(end_time AS UNSIGNED) / 1000)) AS end_date,\n DATEDIFF(DATE(FROM_UNIXTIME(CAST(end_time AS UNSIGNED) / 1000)), DATE(FROM_UNIXTIME(CAST(start_time AS UNSIGNED) / 1000))) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n DATE_ADD(b.start_date, INTERVAL s.pos DAY) AS calc_date,\n CASE WHEN s.pos = 0 THEN b.start_time\n ELSE CAST(UNIX_TIMESTAMP(CAST(DATE_ADD(b.start_date, INTERVAL s.pos DAY) AS DATETIME)) * 1000 AS CHAR)\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN b.end_time\n ELSE CAST((UNIX_TIMESTAMP(CAST(DATE_ADD(b.start_date, INTERVAL s.pos + 1 DAY) AS DATETIME)) * 1000) - 1 AS CHAR)\n END AS end_time,\n b.start_time AS span_start_time,\n b.end_time AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n CAST(ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN CAST(end_time AS UNSIGNED) END) -\n MIN(CASE WHEN span_name = 'runner.execute' THEN CAST(start_time AS UNSIGNED) END)) / 1000.0) AS SIGNED) AS instance_run_time,\n CAST(ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(end_time AS UNSIGNED) END) -\n MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(start_time AS UNSIGNED) END)) / 1000.0) AS SIGNED) AS code_run_time,\n CAST(ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN CAST(end_time AS UNSIGNED) END) -\n MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN CAST(start_time AS UNSIGNED) END)) / 1000.0) AS SIGNED) AS resource_wait_time,\n FROM_UNIXTIME(MIN(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(start_time AS UNSIGNED) END) / 1000) AS code_start_time,\n FROM_UNIXTIME(MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed' ) THEN CAST(end_time AS UNSIGNED) END) / 1000) AS code_end_time,\n FROM_UNIXTIME(MIN(CASE WHEN span_name = 'runner.execute' THEN CAST(span_start_time AS UNSIGNED) END) / 1000) AS instance_start_time,\n FROM_UNIXTIME(MAX(CASE WHEN span_name = 'runner.execute' THEN CAST(span_end_time AS UNSIGNED) END) / 1000) AS instance_end_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n),\ngputj_dim AS (\n SELECT\n t1.service_id,\n t2.pod_name\n FROM {DB_NAME}.{INPUT_TABLE_2} t1\n INNER JOIN {DB_NAME}.{INPUT_TABLE_3} t2\n ON t1.instance_uuid = t2.instance_uuid\n AND t1.dt = IF('2026050700' >= '2025080900', '2026050700', '2025080900')\n AND t2.dt = IF('2026050700' >= '2025060519', '2026050700', '2025060519')\n GROUP BY t1.service_id, t2.pod_name\n),\ngpu_metrics AS (\n SELECT\n pkg_agg_time,\n pod_name,\n k8s_container_vgpu_gpu_util_sum / k8s_container_vgpu_gpu_util_count AS gpu_util,\n k8s_container_resource_request_gpu_sum / k8s_container_resource_request_gpu_count AS gpu_count\n FROM {DB_NAME}.{INPUT_TABLE_4}\n WHERE dt >= '2026050400'\n AND dt <= '2026050700'\n AND ( k8s_container_vgpu_gpu_util_count > 0 OR k8s_container_resource_request_gpu_count > 0 )\n AND pod_name IS NOT NULL\n)\nSELECT\n t1.trace_id,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n t1.instance_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n t1.code_start_time,\n t1.code_end_time,\n t1.instance_start_time,\n t1.instance_end_time,\n t2.serving_id,\n t2.is_permanent,\n CAST(t2.apply_for_gpu_count AS SIGNED) AS apply_for_gpu_count,\n t3.pod_name,\n t4.pkg_agg_time,\n t4.gpu_util,\n t4.gpu_count,\n DATE(t1.calc_date) AS p_date,\n '20260507' AS dt\nFROM trace_time_metrics t1 LEFT JOIN (\n SELECT\n trace_id,\n MAX(serving_id) AS serving_id,\n MAX(CASE WHEN is_permanent = 'true' THEN 1 WHEN is_permanent = 'false' THEN 0 ELSE is_permanent END) AS is_permanent,\n SUM(CAST(replicas AS SIGNED) * CAST(num_gpu AS SIGNED)) AS apply_for_gpu_count\n FROM {DB_NAME}.{INPUT_TABLE_5}\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\nLEFT JOIN gputj_dim t3 ON CAST(t2.serving_id AS UNSIGNED) = t3.service_id\nLEFT JOIN gpu_metrics t4\n ON t3.pod_name = t4.pod_name\n AND (\n CASE\n WHEN t1.instance_start_time IS NOT NULL AND t1.instance_end_time IS NOT NULL\n THEN t4.pkg_agg_time >= t1.instance_start_time AND t4.pkg_agg_time <= t1.instance_end_time\n WHEN t1.code_start_time IS NOT NULL AND t1.code_end_time IS NOT NULL\n THEN t4.pkg_agg_time >= t1.code_start_time AND t4.pkg_agg_time <= t1.code_end_time\n ELSE FALSE\n END\n )\nORDER BY t1.trace_id, t1.calc_date\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Set timezone to Asia/Shanghai so FROM_UNIXTIME aligns with expected dates\n cur.execute(\"SET time_zone = '+08:00'\")\n\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n trace_id VARCHAR(256) NOT NULL COMMENT '追踪ID',\n datawd_project_id VARCHAR(256) DEFAULT NULL COMMENT '项目ID',\n datawd_task_id VARCHAR(256) DEFAULT NULL COMMENT '任务ID',\n datawd_task_instance_id VARCHAR(256) DEFAULT NULL COMMENT '任务实例ID',\n compute_type VARCHAR(256) DEFAULT NULL COMMENT '计算类型',\n status_code INT DEFAULT NULL COMMENT '状态码',\n instance_run_time INT DEFAULT NULL COMMENT '实例运行时长(秒)',\n code_run_time INT DEFAULT NULL COMMENT '代码运行时长(秒)',\n resource_wait_time INT DEFAULT NULL COMMENT '资源等待时长(秒)',\n code_start_time VARCHAR(256) DEFAULT NULL COMMENT '代码开始时间',\n code_end_time VARCHAR(256) DEFAULT NULL COMMENT '代码结束时间',\n instance_start_time VARCHAR(256) DEFAULT NULL COMMENT '实例开始时间',\n instance_end_time VARCHAR(256) DEFAULT NULL COMMENT '实例结束时间',\n serving_id VARCHAR(256) DEFAULT NULL COMMENT '服务ID',\n is_permanent TINYINT(1) DEFAULT NULL COMMENT '是否永久(0/1)',\n apply_for_gpu_count INT DEFAULT NULL COMMENT '申请GPU数量',\n pod_name VARCHAR(256) DEFAULT NULL COMMENT 'Pod名称',\n pkg_agg_time VARCHAR(256) DEFAULT NULL COMMENT 'GPU聚合时间',\n gpu_util DOUBLE DEFAULT NULL COMMENT 'GPU利用率',\n gpu_count DOUBLE DEFAULT NULL COMMENT 'GPU数量',\n p_date VARCHAR(256) DEFAULT NULL COMMENT '日期',\n dt VARCHAR(256) NOT NULL COMMENT '分区日期'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_013 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_013_en"} {"task_id": "mysql_014", "id": "offline-compute_MySQL_mysql_014", "name": "Notebook执行实例明细按天拆分与引擎关联", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,从 Notebook runner trace 数据中筛选出存在 execute.code 等代码执行 span 的 trace,按天拆分跨天运行记录,计算实例/代码/资源等待时长等指标,关联引擎信息,产出每日执行实例明细表。\n\n**业务背景与目标**:Notebook runner 在运行过程中会产生多个 trace span(如 runner.execute、execute.code、set.permanent.compute 等)。本任务需要筛选出包含代码执行 span 的 trace,对跨天运行的记录按天拆分,计算各 span 类别的运行时长,并左关联引擎信息(serving_id、is_permanent、GPU 申请数量),最终写入每日执行实例明细表。\n\n**输入表(全名 + 简要描述)**:\n- `internal_platform_db.notebook_span_info_mysql_014`(Notebook trace span 数据)\n- `internal_platform_db.notebook_engine_info_mysql_014`(引擎信息)\n\n(各表结构与字段含义请自行连接数据库查询确认)\n\n**处理规则**:\n1. 过滤 notebook_span_info:databus_imp_date 在 ['2026050400', '2026050700'] 范围内,且 trace_id 满足子查询条件(compute_type='ray'、service_name='notebook-runner'、span_name='runner.execute'),保留 span_name 为 'runner.execute' 或在 ['execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute', 'runner.killed'] 中的记录\n2. 时间修正:对 runner.killed span,其 start_time 取同 trace 内相关 span 的最小 start_time;对 runner.execute span,其 end_time 取同 trace 内相关 span 的最大 end_time\n3. 按天拆分:计算 span 跨天天数(DATEDIFF),使用 pos_series(0-3)展开,每条记录按天生成多行,start_time/end_time 按当天边界截断\n4. 时长计算(按 trace_id + calc_date 聚合):\n - instance_run_time:runner.execute span 的 (end_time - start_time) / 1000 秒\n - code_run_time:execute.code 等代码执行 span 的 (end_time - start_time) / 1000 秒\n - resource_wait_time:set.permanent.compute / create.non.permanent.compute span 的 (end_time - start_time) / 1000 秒\n - status_code:runner.execute 的 status_code 取 max\n5. 左关联 notebook_engine_info:按 trace_id 关联,聚合获取 serving_id(MAX)、is_permanent(MAX)、apply_for_gpu_count(SUM(replicas * num_gpu))\n\n**输出要求**:\n- 目标表:`internal_platform_db.dwd_notebook_execute_instance_detail_d_mysql_014`\n- 输出字段顺序:dt, 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\n- dt 为分区值 '20260507',p_date 为拆分后的日期\n- 时长字段取整(ROUND),时间字段转为字符串格式(YYYY-MM-DD HH:MM:SS)\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_014 ground truth: Notebook执行实例明细按天拆分与引擎关联\n\nTask:\n Filter notebook_span_info for traces with execute.code spans,\n split cross-day records, calculate time metrics, left join engine info,\n write to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE_1 = \"notebook_span_info_mysql_014\"\nINPUT_TABLE_2 = \"notebook_engine_info_mysql_014\"\nOUTPUT_TABLE = \"dwd_notebook_execute_instance_detail_d_mysql_014\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (dt, p_date, trace_id, datawd_project_id, datawd_task_id, datawd_task_instance_id,\n compute_type, status_code, instance_run_time, code_run_time, resource_wait_time,\n code_start_time, code_end_time, instance_start_time, instance_end_time,\n serving_id, is_permanent, apply_for_gpu_count)\nWITH\nbase_data_raw AS (\n SELECT DISTINCT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM {DB_NAME}.{INPUT_TABLE_1}\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND trace_id IN (\n SELECT trace_id\n FROM {DB_NAME}.{INPUT_TABLE_1}\n WHERE databus_imp_date >= '2026050700'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n AND span_name = 'runner.execute'\n GROUP BY trace_id\n )\n AND (\n span_name = 'runner.execute'\n OR\n span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'set.permanent.compute', 'create.non.permanent.compute', 'runner.killed')\n )\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'runner.killed'\n THEN MIN(CASE WHEN span_name IN ('execute.code', 'execute.code.cell', 'client.execute.code', 'runner.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n CASE\n WHEN span_name = 'runner.execute'\n THEN MAX(CASE WHEN span_name IN ('runner.execute', 'runner.killed') THEN end_time END)\n OVER(PARTITION BY trace_id)\n ELSE end_time\n END AS end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code\n FROM base_data_raw\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n DATE(FROM_UNIXTIME(CAST(start_time AS SIGNED) / 1000)) as start_date,\n DATE(FROM_UNIXTIME(CAST(end_time AS SIGNED) / 1000)) as end_date,\n DATEDIFF(DATE(FROM_UNIXTIME(CAST(end_time AS SIGNED) / 1000)), DATE(FROM_UNIXTIME(CAST(start_time AS SIGNED) / 1000))) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n datawd_project_id,\n datawd_task_id,\n datawd_task_instance_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n DATE_ADD(b.start_date, INTERVAL s.pos DAY) AS calc_date,\n CASE WHEN s.pos = 0 THEN CAST(b.start_time AS SIGNED)\n ELSE UNIX_TIMESTAMP(CAST(DATE_ADD(b.start_date, INTERVAL s.pos DAY) AS DATETIME)) * 1000\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN CAST(b.end_time AS SIGNED)\n ELSE (UNIX_TIMESTAMP(CAST(DATE_ADD(b.start_date, INTERVAL s.pos + 1 DAY) AS DATETIME)) * 1000) - 1\n END AS end_time,\n CAST(b.start_time AS SIGNED) AS span_start_time,\n CAST(b.end_time AS SIGNED) AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(datawd_project_id) AS datawd_project_id,\n MAX(datawd_task_id) AS datawd_task_id,\n MAX(datawd_task_instance_id) AS datawd_task_instance_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'runner.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n ROUND((MAX(CASE WHEN span_name = 'runner.execute' THEN end_time END) -\n MIN(CASE WHEN span_name = 'runner.execute' THEN start_time END)) / 1000.0) AS instance_run_time,\n ROUND((MAX(CASE WHEN span_name IN ('execute.code', 'client.execute.code', 'execute.code.cell', 'runner.killed') THEN end_time END) -\n 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,\n ROUND((MAX(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN end_time END) -\n MIN(CASE WHEN span_name IN ('set.permanent.compute', 'create.non.permanent.compute') THEN start_time END)) / 1000.0) AS resource_wait_time,\n 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,\n 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,\n FROM_UNIXTIME(MIN(CASE WHEN span_name = 'runner.execute' THEN span_start_time END) / 1000) AS instance_start_time,\n FROM_UNIXTIME(MAX(CASE WHEN span_name = 'runner.execute' THEN span_end_time END) / 1000) AS instance_end_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n)\nSELECT\n '20260507' AS dt,\n DATE_FORMAT(t1.calc_date, '%Y-%m-%d') AS p_date,\n t1.trace_id,\n t1.datawd_project_id,\n t1.datawd_task_id,\n t1.datawd_task_instance_id,\n t1.compute_type,\n t1.status_code,\n t1.instance_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n DATE_FORMAT(t1.code_start_time, '%Y-%m-%d %H:%i:%s') AS code_start_time,\n DATE_FORMAT(t1.code_end_time, '%Y-%m-%d %H:%i:%s') AS code_end_time,\n DATE_FORMAT(t1.instance_start_time, '%Y-%m-%d %H:%i:%s') AS instance_start_time,\n DATE_FORMAT(t1.instance_end_time, '%Y-%m-%d %H:%i:%s') AS instance_end_time,\n t2.serving_id,\n t2.is_permanent,\n t2.apply_for_gpu_count\nFROM trace_time_metrics t1\nLEFT JOIN (\n SELECT\n trace_id,\n MAX(serving_id) AS serving_id,\n MAX(is_permanent) AS is_permanent,\n SUM(CAST(replicas AS SIGNED) * CAST(num_gpu AS SIGNED)) AS apply_for_gpu_count\n FROM {DB_NAME}.{INPUT_TABLE_2}\n WHERE databus_imp_date >= '2026050400'\n AND databus_imp_date <= '2026050700'\n AND compute_type = 'ray'\n AND service_name = 'notebook-runner'\n GROUP BY trace_id\n ) t2 ON t1.trace_id = t2.trace_id\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Set timezone to Asia/Shanghai so FROM_UNIXTIME aligns with expected dates\n cur.execute(\"SET time_zone = '+08:00'\")\n\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n `dt` VARCHAR(256) COMMENT '天分区',\n `p_date` VARCHAR(256) COMMENT '拆分后日期',\n `trace_id` VARCHAR(256) COMMENT 'trace_id',\n `datawd_project_id` VARCHAR(256) COMMENT '项目ID',\n `datawd_task_id` VARCHAR(256) COMMENT '任务ID',\n `datawd_task_instance_id` VARCHAR(256) COMMENT '任务实例ID',\n `compute_type` VARCHAR(256) COMMENT '计算类型',\n `status_code` INT COMMENT '状态码',\n `instance_run_time` INT COMMENT '实例运行时长(秒)',\n `code_run_time` INT COMMENT '代码执行时长(秒)',\n `resource_wait_time` INT COMMENT '资源等待时长(秒)',\n `code_start_time` VARCHAR(256) COMMENT '代码开始时间',\n `code_end_time` VARCHAR(256) COMMENT '代码结束时间',\n `instance_start_time` VARCHAR(256) COMMENT '实例开始时间',\n `instance_end_time` VARCHAR(256) COMMENT '实例结束时间',\n `serving_id` VARCHAR(256) COMMENT 'serving_id',\n `is_permanent` VARCHAR(256) COMMENT '是否永久引擎',\n `apply_for_gpu_count` INT COMMENT 'GPU申请数量'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n\n # Verify row count\n with conn.cursor() as cur:\n cur.execute(f\"SELECT COUNT(*) FROM {DB_NAME}.{OUTPUT_TABLE}\")\n count = cur.fetchone()[0]\n\n print(f\"mysql_014 ground_truth done: {count} rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_014"} {"task_id": "mysql_015_en", "id": "offline-compute_MySQL_mysql_015", "name": "Exposure Log First Exposure Time Computation", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that computes the first exposure time for each advertisement from the exposure log table.\n\n**Business Background and Objective**: The advertising system periodically writes exposure logs into a summary table. Downstream consumers need to compute the first exposure time per ad ID dimension and output the corresponding minute-level timestamp string. This task filters records from the input table that meet the specified partition and conditions, groups by ad ID to obtain the minimum exposure time, formats it as a minute-level string, and writes the results to the output table.\n\n**Input Table (full name + brief description)**:\n- `internal_platform_db.etl_pageview_exposure_mysql_015` (exposure log detail table)\n\n(Please connect to the database and query to confirm the table structure and field semantics.)\n\n**Processing Rules**:\n- Single-table processing, no joins\n- Filter condition: `partition_time = 2026060914` AND `ad_data_model_version = 3` AND `ad_optimization_goal > 0`\n- Group by `ad_aid`, compute `MIN(action_imp_time)` as the first exposure time\n- Format the first exposure time (millisecond timestamp divided by 1000 to convert to seconds) as a `yyyyMMddHHmm` string\n\n**Column Mapping Rules**:\n- Input column `ad_aid` → output column `aid`\n- Aggregation result `MIN(action_imp_time)` → output column `first_time`\n- Formatted string `FROM_UNIXTIME(MIN(action_imp_time)/1000, '%Y%m%d%H%i')` → output column `first_fen`\n- Fixed value `2026060914` → output column `dt`\n\n**Output Requirements**:\n- Target table: `internal_platform_db.first_expo_time_cand_mysql_015`\n- Output field order: `aid`, `first_time`, `first_fen`, `dt`\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_015 ground truth: 曝光日志首次曝光时间计算\n\nTask:\n Filter input table WHERE partition_time = 2026060914\n AND ad_data_model_version = 3 AND ad_optimization_goal > 0,\n group by ad_aid, compute MIN(action_imp_time) as first_time,\n format as FROM_UNIXTIME(MIN/1000, '%Y%m%d%H%i') as first_fen,\n write to output table with dt = 2026060914.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"etl_pageview_exposure_mysql_015\"\nOUTPUT_TABLE = \"first_expo_time_cand_mysql_015\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (aid, first_time, first_fen, dt)\nSELECT\n ad_aid AS aid,\n MIN(action_imp_time) AS first_time,\n FROM_UNIXTIME(MIN(action_imp_time) / 1000, '%Y%m%d%H%i') AS first_fen,\n 2026060914 AS dt\nFROM {DB_NAME}.{INPUT_TABLE}\nWHERE partition_time = 2026060914\n AND ad_data_model_version = 3\n AND ad_optimization_goal > 0\nGROUP BY ad_aid\nORDER BY ad_aid\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure consistent timezone (Hive cluster was UTC+8)\n cur.execute(\"SET SESSION time_zone = '+08:00'\")\n\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n aid BIGINT NOT NULL,\n first_time BIGINT NOT NULL,\n first_fen VARCHAR(32) NOT NULL,\n dt BIGINT NOT NULL,\n PRIMARY KEY (aid, dt)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_015 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_015_en"} {"task_id": "mysql_016", "id": "offline-compute_MySQL_mysql_016", "name": "应用X模型与组织关系小时表全量迁移", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,将源表数据全量迁移至目标表,保持数据完整性。\n\n**业务背景与目标**:应用 X 模型与组织关系小时表记录了资产明细与组织架构的关联关系。本任务将输入表中的全量数据迁移至输出表,不做任何过滤、聚合或字段转换。\n\n**输入表(全名 + 简要描述)**:\n- `internal_platform_db.t_app_xmodel_and_org_relation_hour_src_mysql_016`(应用X模型与组织关系小时表)\n\n(表结构与字段含义请自行连接数据库查询确认)\n\n**处理规则**:\n- 无过滤条件,全量读取\n- 无 Join,单表处理\n- 无聚合、无去重\n- 保留所有字段,不做字段派生或转换\n\n**输出要求**:\n- 目标表:`internal_platform_db.t_app_xmodel_and_org_relation_hour_cand_mysql_016`\n- 输出字段与源表完全一致\n- 输出记录数与源表一致\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_016 ground truth: 应用X模型与组织关系小时表全量迁移\n\nTask:\n Full migration from source table to target table,\n no filtering, no transformation, all columns preserved.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"t_app_xmodel_and_org_relation_hour_src_mysql_016\"\nOUTPUT_TABLE = \"t_app_xmodel_and_org_relation_hour_cand_mysql_016\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (xsoa_id, principal, xsoa_org_principal, xsoa_team_name, xsoa_team_id,\n xsoa_center_name, xsoa_center_id, xsoa_dept_name, xsoa_dept_id,\n xsoa_principal_index, xsoa_dimension, ds)\nSELECT\n xsoa_id,\n principal,\n xsoa_org_principal,\n xsoa_team_name,\n xsoa_team_id,\n xsoa_center_name,\n xsoa_center_id,\n xsoa_dept_name,\n xsoa_dept_id,\n xsoa_principal_index,\n xsoa_dimension,\n ds\nFROM {DB_NAME}.{INPUT_TABLE}\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n xsoa_id VARCHAR(256) NOT NULL,\n principal VARCHAR(256) NOT NULL,\n xsoa_org_principal VARCHAR(256) NOT NULL,\n xsoa_team_name VARCHAR(256) NOT NULL,\n xsoa_team_id VARCHAR(256) NOT NULL,\n xsoa_center_name VARCHAR(256) NOT NULL,\n xsoa_center_id VARCHAR(256) NOT NULL,\n xsoa_dept_name VARCHAR(256) NOT NULL,\n xsoa_dept_id VARCHAR(256) NOT NULL,\n xsoa_principal_index BIGINT NOT NULL,\n xsoa_dimension VARCHAR(256) NOT NULL,\n ds BIGINT NOT NULL,\n PRIMARY KEY (xsoa_id)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_016 ground_truth done: 8 rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_016"} {"task_id": "mysql_017", "id": "offline-compute_MySQL_mysql_017", "name": "新闻曝光数据全量迁移", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n任务目标:将输入表数据同步至输出表,实现表间数据迁移。\n\n输入:\n- `internal_platform_db.dwd_news_dt_others_imp_hi_mysql_017`\n\n处理规则:\n- 无 Join,单表处理\n- 无过滤条件,保留全部记录\n- 无聚合操作\n- 字段全量映射,保留源表所有字段\n\n输出要求:\n- 输出表:`internal_platform_db.dwd_news_dt_others_imp_si_cand_mysql_017`\n- 输出字段顺序与输入表一致\n- 不去重,保留所有记录\n\n写入要求:\n- 写入模式:覆盖写入(先清空目标表再写入)\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_017 ground truth: 新闻曝光数据全量迁移\n\nTask:\n Copy all rows from input table to output table (full field mapping, no filter).\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"dwd_news_dt_others_imp_hi_mysql_017\"\nOUTPUT_TABLE = \"dwd_news_dt_others_imp_si_cand_mysql_017\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\nALL_COLUMNS = [\n \"iceberg_imp_date\", \"watermark_ts\", \"ftime\", \"imp_hour\", \"time_range\",\n \"platform_user_id\", \"device_id\", \"social_uid\", \"os\", \"network_type\", \"app_version\", \"callfrom\",\n \"page_start_from\", \"start_article_id\", \"start_article_type\", \"article_uuid\",\n \"article_page\", \"article_type\", \"article_pos\", \"article_real_pos\",\n \"rcmd_reason\", \"is_tagversion\", \"event_time\", \"client_ts\", \"server_time\",\n \"social_openid\", \"suid\", \"session_id\", \"session_ts\", \"brand\", \"manufacturer\",\n \"model\", \"login_type\", \"country\", \"province\", \"pgid\", \"ref_pgid\", \"media_id\",\n \"chl_id\", \"video_id\", \"article_id\", \"article_ptype\", \"article_cmt_id\",\n \"is_hotnews\", \"is_cpfans\", \"is_xiaoshipin\", \"is_coldstart\", \"is_minivideo\",\n \"imp_date\", \"is_landingpage\", \"article_imp_pv\", \"video_imp_pv\", \"imgtext_imp_pv\",\n \"eid\", \"tag_id\", \"pg_tag_id\", \"pg_tag_type\", \"pg_article_type\", \"pg_article_id\",\n \"is_major_upgrade\", \"idfv\", \"android_id\", \"tab_id\", \"context_type\",\n \"element_path\", \"p1_article_ptype\", \"refpg_article_type\", \"tag_type\",\n \"pg_tab_id\", \"brand_type\", \"fulltext_imp_pv\", \"scheme_type\", \"module\",\n \"cmt_replyid\", \"comment_imp_pv\", \"bubble_msg_type\", \"untitled\",\n \"hot_rank_imp_pv\", \"pg_tag_scene\", \"header_type\", \"window_open_from\",\n \"user_more_id\", \"section_id\", \"search_cell_type\", \"pg_source2\", \"bar_name\",\n \"scheme_url\", \"member_btn_id\", \"vert_cell_scheme_url\", \"article_title\",\n \"pg_article_title\", \"bigevent_type\", \"schedule_type\", \"pg_path\", \"ussn\",\n \"top_banner_type\", \"pendant_type\", \"banner_url\", \"sort_menu_id\", \"video_pid\",\n \"error_tips\", \"gameid\", \"ad_atype\", \"ad_action\", \"article_module_pos\",\n \"refpg_chl_id\", \"refpg_last_clck_ele\", \"live_article_id\", \"nav_item_id\",\n \"nav_item_name\", \"have_redpoint\", \"nav_pos\", \"undetermined\", \"pg_tab2_from\",\n \"scheme_scene_type\", \"is_reservable\", \"is_reserve\", \"pg_subtab_id\",\n \"pg_article_live_status\", \"pg_article_relate_event_type\", \"pg_search_keyword\",\n \"vert_cell_title\", \"mod_article_type\", \"pub_btn_type\", \"pg_hotask_type\",\n \"mod_article_ptype\", \"question_id\", \"answer_id\", \"is_answerer\",\n \"article_review_status\", \"banner_module_id\", \"article_live_status\",\n \"article_pay_status\", \"pg_article_pay_status\", \"tag_scene\", \"pg_detail_type\",\n \"column_type\", \"pg_column_type\", \"is_column_purchased\", \"pg_is_column_purchased\",\n \"pay_product_id\", \"huaci_type\", \"panel_btn_id\", \"is_user_self\", \"crepg_chl_id\",\n \"crepg_article_id\", \"crepg_article_type\", \"dt_cre_pgid\", \"crepg_last_clck_ele\",\n \"dialog_type\", \"pg_subtab_name\", \"e_pos\", \"sug_word\", \"e_from\", \"e_type\",\n \"article_list_pos\", \"pg_article_bool_parad_platform\", \"city_level\", \"has_authority\",\n \"pg_is_audio\", \"etl_pgid\", \"search_keyword\", \"cardpanel_type\", \"mod_article_page\",\n \"mod_alg_info\", \"mod_article_real_pos\", \"article_id_list\", \"e_state\", \"user_suid\",\n \"pg_login_from\", \"pg_last_login_type\", \"is_ad\", \"hometown_adcode\",\n \"user_service_id\", \"user_cpcenter_id\", \"agent_id\", \"e_title\", \"tab_setid\",\n \"pg_page_start_from\", \"is_flash_keyword\", \"search_query_from\",\n \"is_query_from_cache\", \"p1_search_cell_type\", \"pg_search_query_from\",\n \"refpg_search_query_from\",\n]\n\ncol_list = \", \".join(ALL_COLUMNS)\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE} ({col_list})\nSELECT {col_list}\nFROM {DB_NAME}.{INPUT_TABLE}\n\"\"\"\n\n# Output table DDL (same schema as input)\nOUTPUT_DDL = f\"\"\"\nCREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n `_id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增代理主键',\n `iceberg_imp_date` TEXT NOT NULL COMMENT '分区时间',\n `watermark_ts` BIGINT NOT NULL COMMENT 'watermark时间毫秒',\n `ftime` TEXT NOT NULL COMMENT '数据上报时间',\n `imp_hour` TEXT NOT NULL COMMENT '时间分区',\n `time_range` TEXT NOT NULL COMMENT '时段分类',\n `platform_user_id` VARCHAR(256) NOT NULL COMMENT '用户platform_user_id',\n `device_id` TEXT NOT NULL COMMENT '用户device_id',\n `social_uid` TEXT NOT NULL COMMENT 'social user id',\n `os` TEXT NOT NULL COMMENT '操作系统',\n `network_type` TEXT NOT NULL COMMENT '网络类型',\n `app_version` TEXT NOT NULL COMMENT 'app版本号',\n `callfrom` TEXT NOT NULL COMMENT '启动方式',\n `page_start_from` TEXT NOT NULL COMMENT '落地页拉起来源',\n `start_article_id` TEXT NOT NULL COMMENT '外部拉起时的文章id',\n `start_article_type` TEXT NOT NULL COMMENT '外部拉起时的文章类型',\n `article_uuid` TEXT NOT NULL COMMENT '文章唯一uuid',\n `article_page` BIGINT NOT NULL COMMENT '刷次',\n `article_type` TEXT NOT NULL COMMENT '文章类型',\n `article_pos` BIGINT NOT NULL COMMENT '文章位置',\n `article_real_pos` BIGINT NOT NULL COMMENT '文章真实位置',\n `rcmd_reason` TEXT NOT NULL COMMENT '推荐理由',\n `is_tagversion` TEXT NOT NULL COMMENT '是否tag新版本',\n `event_time` TEXT NOT NULL COMMENT '事件时间',\n `client_ts` TEXT NOT NULL COMMENT '事件时间戳',\n `server_time` TEXT NOT NULL COMMENT '上报时间',\n `social_openid` TEXT NOT NULL COMMENT '平台openid',\n `suid` TEXT NOT NULL COMMENT '用户登陆ID',\n `session_id` TEXT NOT NULL COMMENT '会话ID',\n `session_ts` TEXT NOT NULL COMMENT '会话时间戳',\n `brand` TEXT NOT NULL COMMENT '设备品牌',\n `manufacturer` TEXT NOT NULL COMMENT '设备制造商',\n `model` TEXT NOT NULL COMMENT '设备型号',\n `login_type` TEXT NOT NULL COMMENT '登陆类型',\n `country` TEXT NOT NULL COMMENT '国家',\n `province` TEXT NOT NULL COMMENT '省份',\n `pgid` TEXT NOT NULL COMMENT '页面类型',\n `ref_pgid` TEXT NOT NULL COMMENT '上一级页面类型',\n `media_id` TEXT NOT NULL COMMENT '用户媒体ID',\n `chl_id` TEXT NOT NULL COMMENT '频道ID',\n `video_id` TEXT NOT NULL COMMENT '视频ID',\n `article_id` TEXT NOT NULL COMMENT '文章ID',\n `article_ptype` TEXT NOT NULL COMMENT '展示样式类型',\n `article_cmt_id` TEXT NOT NULL COMMENT '文章评论ID',\n `is_hotnews` TEXT NOT NULL COMMENT '是否热点文章',\n `is_cpfans` TEXT NOT NULL COMMENT '是否关注状态',\n `is_xiaoshipin` TEXT NOT NULL COMMENT '是否小视频(接入层)',\n `is_coldstart` TEXT NOT NULL COMMENT '是否冷启动',\n `is_minivideo` TEXT NOT NULL COMMENT '是否小视频(内平)',\n `imp_date` TEXT NOT NULL COMMENT '日期',\n `is_landingpage` TEXT NOT NULL COMMENT '是否落地页',\n `article_imp_pv` BIGINT NOT NULL COMMENT '文章曝光pv',\n `video_imp_pv` BIGINT NOT NULL COMMENT '视频文章曝光pv',\n `imgtext_imp_pv` BIGINT NOT NULL COMMENT '图文文章曝光pv',\n `eid` TEXT NOT NULL COMMENT '元素id',\n `tag_id` TEXT NOT NULL COMMENT 'tag_id',\n `pg_tag_id` TEXT NOT NULL COMMENT '页面的tag_id',\n `pg_tag_type` TEXT NOT NULL COMMENT 'tag类型',\n `pg_article_type` TEXT NOT NULL COMMENT '页面文章类型',\n `pg_article_id` TEXT NOT NULL COMMENT '页面文章id',\n `is_major_upgrade` TEXT NOT NULL COMMENT 'NoComment',\n `idfv` TEXT NOT NULL COMMENT 'idfv',\n `android_id` TEXT NOT NULL COMMENT 'android_id',\n `tab_id` TEXT NOT NULL COMMENT '底部导航Tab Id',\n `context_type` TEXT NOT NULL COMMENT 'NoComment',\n `element_path` TEXT NOT NULL COMMENT '元素路径',\n `p1_article_ptype` TEXT NOT NULL COMMENT '父级文章展示类型',\n `refpg_article_type` TEXT NOT NULL COMMENT '上一级页面的文章类型',\n `tag_type` TEXT NOT NULL COMMENT 'tag类型',\n `pg_tab_id` TEXT NOT NULL COMMENT '来源页面底部导航Tab Id',\n `brand_type` TEXT NOT NULL COMMENT 'brand_type',\n `fulltext_imp_pv` BIGINT NOT NULL COMMENT '展开全文按钮真实曝光',\n `scheme_type` TEXT NOT NULL COMMENT 'scheme类型',\n `module` TEXT NOT NULL COMMENT '模块',\n `cmt_replyid` TEXT NOT NULL COMMENT '评论id',\n `comment_imp_pv` BIGINT NOT NULL COMMENT '评论曝光pv',\n `bubble_msg_type` TEXT NOT NULL COMMENT '气泡类型',\n `untitled` TEXT NOT NULL COMMENT '待更名',\n `hot_rank_imp_pv` BIGINT NOT NULL COMMENT '热榜入口曝光',\n `pg_tag_scene` TEXT NOT NULL COMMENT '页面tag场景类型',\n `header_type` TEXT NOT NULL COMMENT '头部类型',\n `window_open_from` TEXT NOT NULL COMMENT '弹窗来源',\n `user_more_id` TEXT NOT NULL COMMENT 'user_more_id',\n `section_id` TEXT NOT NULL COMMENT 'section_id',\n `search_cell_type` TEXT NOT NULL COMMENT '搜索页模块种类',\n `pg_source2` TEXT NOT NULL COMMENT '长视频流量来源',\n `bar_name` TEXT NOT NULL COMMENT '提示条名称',\n `scheme_url` TEXT NOT NULL COMMENT 'scheme_url',\n `member_btn_id` TEXT NOT NULL COMMENT '元素id',\n `vert_cell_scheme_url` TEXT NOT NULL COMMENT 'vert元素的url',\n `article_title` TEXT NOT NULL COMMENT '元素名称标识',\n `pg_article_title` TEXT NOT NULL COMMENT '页面或者文章标题',\n `bigevent_type` TEXT NOT NULL COMMENT '大事件类型',\n `schedule_type` TEXT NOT NULL COMMENT '赛程类型',\n `pg_path` TEXT NOT NULL COMMENT '页面路径',\n `ussn` TEXT NOT NULL COMMENT '新版session_id',\n `top_banner_type` TEXT NOT NULL COMMENT '顶部banner类型',\n `pendant_type` TEXT NOT NULL COMMENT '挂件类型',\n `banner_url` TEXT NOT NULL COMMENT 'banner跳转的URL',\n `sort_menu_id` TEXT NOT NULL COMMENT '分类菜单id',\n `video_pid` TEXT NOT NULL COMMENT 'video_pid',\n `error_tips` TEXT NOT NULL COMMENT '敏感词拦截提示文案',\n `gameid` TEXT NOT NULL COMMENT '游戏ID',\n `ad_atype` TEXT NOT NULL COMMENT '广告类型',\n `ad_action` TEXT NOT NULL COMMENT '广告动作类型',\n `article_module_pos` TEXT NOT NULL COMMENT '模块位置',\n `refpg_chl_id` TEXT NOT NULL COMMENT '来源页面chl_id',\n `refpg_last_clck_ele` TEXT NOT NULL COMMENT '上一级页面业务私参',\n `live_article_id` TEXT NOT NULL COMMENT '直播文章id',\n `nav_item_id` TEXT NOT NULL COMMENT '导航id',\n `nav_item_name` TEXT NOT NULL COMMENT '导航名称',\n `have_redpoint` TEXT NOT NULL COMMENT '是否带红点',\n `nav_pos` TEXT NOT NULL COMMENT '频道位置',\n `undetermined` TEXT NOT NULL COMMENT '废弃字段',\n `pg_tab2_from` TEXT NOT NULL COMMENT 'tab2来源',\n `scheme_scene_type` TEXT NOT NULL COMMENT '短带长类型',\n `is_reservable` TEXT NOT NULL COMMENT '是否带预约按钮',\n `is_reserve` TEXT NOT NULL COMMENT '是否预约状态',\n `pg_subtab_id` TEXT NOT NULL COMMENT '底层页子tab的id',\n `pg_article_live_status` TEXT NOT NULL COMMENT '直播状态',\n `pg_article_relate_event_type` TEXT NOT NULL COMMENT '关联事件类型',\n `pg_search_keyword` TEXT NOT NULL COMMENT '搜索词',\n `vert_cell_title` TEXT NOT NULL COMMENT 'cell 标题',\n `mod_article_type` TEXT NOT NULL COMMENT '模块文章类型',\n `pub_btn_type` TEXT NOT NULL COMMENT '发布按钮类型',\n `pg_hotask_type` TEXT NOT NULL COMMENT '热问页面类型',\n `mod_article_ptype` TEXT NOT NULL COMMENT '模块文章展示样式类型',\n `question_id` TEXT NOT NULL COMMENT '问题 id',\n `answer_id` TEXT NOT NULL COMMENT '外显回答 id',\n `is_answerer` TEXT NOT NULL COMMENT '是否答主',\n `article_review_status` TEXT NOT NULL COMMENT '回答状态',\n `banner_module_id` TEXT NOT NULL COMMENT 'banner模块 id',\n `article_live_status` TEXT NOT NULL COMMENT '文章直播状态',\n `article_pay_status` TEXT NOT NULL COMMENT '文章付费状态',\n `pg_article_pay_status` TEXT NOT NULL COMMENT '文章付费状态(页面参数)',\n `tag_scene` TEXT NOT NULL COMMENT 'tag场景类型',\n `pg_detail_type` TEXT NOT NULL COMMENT '底层页类型',\n `column_type` TEXT NOT NULL COMMENT '专栏类型',\n `pg_column_type` TEXT NOT NULL COMMENT '页面专栏类型',\n `is_column_purchased` TEXT NOT NULL COMMENT '是否购买专栏',\n `pg_is_column_purchased` TEXT NOT NULL COMMENT '页面是否购买专栏',\n `pay_product_id` TEXT NOT NULL COMMENT '支付时所选的产品ID',\n `huaci_type` TEXT NOT NULL COMMENT '划词类型',\n `panel_btn_id` TEXT NOT NULL COMMENT '面板按钮ID',\n `is_user_self` TEXT NOT NULL COMMENT '是否用户本人',\n `crepg_chl_id` TEXT NOT NULL COMMENT '跳转起始页面频道ID',\n `crepg_article_id` TEXT NOT NULL COMMENT '跳转起始页面文章ID',\n `crepg_article_type` TEXT NOT NULL COMMENT '跳转起始页面文章类型',\n `dt_cre_pgid` TEXT NOT NULL COMMENT '创造页页面ID',\n `crepg_last_clck_ele` TEXT NOT NULL COMMENT '创造页上一次点击元素信息',\n `dialog_type` TEXT NOT NULL COMMENT '对话类型',\n `pg_subtab_name` TEXT NOT NULL COMMENT '子 tab名称',\n `e_pos` TEXT NOT NULL COMMENT '元素位置',\n `sug_word` TEXT NOT NULL COMMENT '建议词条',\n `e_from` TEXT NOT NULL COMMENT '元素来源',\n `e_type` TEXT NOT NULL COMMENT '元素类型',\n `article_list_pos` TEXT NOT NULL COMMENT '绝对位置',\n `pg_article_bool_parad_platform` TEXT NOT NULL COMMENT '文章携带的布尔参数',\n `city_level` TEXT NOT NULL COMMENT '城市等级',\n `has_authority` TEXT NOT NULL COMMENT '是否同意隐私协议',\n `pg_is_audio` TEXT NOT NULL COMMENT '是否是音频',\n `etl_pgid` TEXT NOT NULL COMMENT 'ETL页面id',\n `search_keyword` TEXT NOT NULL COMMENT '搜索关键词',\n `cardpanel_type` TEXT NOT NULL COMMENT '卡片面板类型',\n `mod_article_page` TEXT NOT NULL COMMENT '模块文章所在刷次',\n `mod_alg_info` TEXT NOT NULL COMMENT '模块文章推荐信息',\n `mod_article_real_pos` TEXT NOT NULL COMMENT '模块文章在刷次中的位置',\n `article_id_list` TEXT NOT NULL COMMENT '文章id集合',\n `e_state` TEXT NOT NULL COMMENT '元素状态',\n `user_suid` TEXT NOT NULL COMMENT '用户suid',\n `pg_login_from` TEXT NOT NULL COMMENT '登录页来源',\n `pg_last_login_type` TEXT NOT NULL COMMENT '上次登录类型',\n `is_ad` TEXT NOT NULL COMMENT '是否广告',\n `hometown_adcode` TEXT NOT NULL COMMENT '家乡code',\n `user_service_id` TEXT NOT NULL COMMENT '用户service id',\n `user_cpcenter_id` TEXT NOT NULL COMMENT '用户中心id',\n `agent_id` TEXT NOT NULL COMMENT '智能体ID',\n `e_title` TEXT NOT NULL COMMENT '元素文本',\n `tab_setid` TEXT NOT NULL COMMENT '发布按钮setid',\n `pg_page_start_from` TEXT NOT NULL COMMENT '落地页拉起来源(页面参数)',\n `is_flash_keyword` TEXT NOT NULL COMMENT '轮播词query是否无价值曝光',\n `search_query_from` TEXT NOT NULL COMMENT '搜索发起来源',\n `is_query_from_cache` TEXT NOT NULL COMMENT 'query是否缓存',\n `p1_search_cell_type` TEXT NOT NULL COMMENT '文章所在模块的cell类型',\n `pg_search_query_from` TEXT NOT NULL COMMENT '页面搜索发起来源',\n `refpg_search_query_from` TEXT NOT NULL COMMENT '来源页面发起搜索的方式',\n KEY `idx_platform_user_id` (`platform_user_id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(OUTPUT_DDL)\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_017 ground_truth done: all rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_017"} {"task_id": "mysql_018_en", "id": "offline-compute_MySQL_mysql_018", "name": "URL Safety Detection Multi-Dimensional Access Statistics Report", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that computes multi-dimensional access statistics from the URL safety detection detail table, producing a URL access statistics report.\n\n**Business Background and Objective**: The URL safety detection system collects URL access records for each `taid` daily. It needs to compute UV and its 1d/7d/30d/1m periodic metrics across multiple dimensions (taid, taid+url, taid+domain/site, taid+cgi), and output a single-row summary result to the report table.\n\n**Input Tables (full name + brief description)**:\n- `internal_platform_db.t_dws_urlsafe_rela_mobile_browser_taid_url_di_mysql_018` (URL safety detection detail table)\n- Historical partition data: Historical records in the output table itself where `ds = 20260531, channel = 'mobile_browser'` (left join source, used to obtain 1m metrics)\n\n(Please connect to the database and query to confirm the table structures and field semantics.)\n\n**Filter Condition**:\n- Input table: `ds > 20260509 AND ds <= 20260608`\n\n**Processing Rules**:\n### Subquery a (taid-level UV statistics)\n- Group by `taid`, compute:\n - `uv_1d = COUNT(IF(ds_max = 20260608, 1, NULL))`\n - `uv_avg_7d = (COUNT(state_6d=1) + ... + COUNT(state_daily=1)) / 7`, where `state_*d = MAX(IF(ds = corresponding_date, 1, 0))`\n - `uv_7d = COUNT(IF(ds_max > 20260601, 1, NULL))`\n - `uv_30d = COUNT(1)`\n\n### Subquery c (taid+url-level statistics)\n- Group by `taid`, `url` and aggregate, computing `userid_url_1d`/`avg_7d`/`7d`/`30d` using the same logic as above\n\n### Subquery d (taid+domain/site-level statistics)\n- First group by `taid`, `site` and aggregate `domain`, `ds_max`, `state_*d`\n - Domain value rule: Under the same taid+site, if multiple domains exist, take `MAX(domain)` (lexicographically largest value) as the domain attribution for that site\n- Then group by `taid`, `domain` and aggregate, computing:\n - `userid_domain_1d`/`avg_7d`/`7d`/`30d`\n - `userid_site_1d = SUM(site_cnt_daily)`\n - `userid_site_avg_7d = (SUM(site_cnt_6d) + ... + SUM(site_cnt_daily)) / 7`\n - `userid_site_7d = SUM(site_cnt_7d)`\n - `userid_site_30d = SUM(site_cnt)`\n\n### Subquery e (taid+cgi-level statistics)\n- Group by `taid`, `cgi` and aggregate, computing `userid_cgi_1d`/`avg_7d`/`7d`/`30d` using the same logic as above\n\n### Join Logic\n- `a LEFT JOIN b` (historical partition, joined on `data_par`): `IFNULL(b.uv_1m, 0)` and 4 other fields\n- `a JOIN c, d, e` (all inner joins, joined on `data_par`)\n\n### Final Output Fields (in order)\n- `access_type = '网址检测API'`\n- `access_channel = '手机IM平台Q浏览器'`\n- `uv_1d`, `uv_avg_7d` (`ROUND(x, 0)`), `uv_7d`, `uv_30d`, `uv_1m`\n- `userid_url_1d`, `userid_url_avg_7d` (ROUND), `userid_url_7d`, `userid_url_30d`, `userid_url_1m`\n- `userid_domain_1d`, `userid_domain_avg_7d` (ROUND), `userid_domain_7d`, `userid_domain_30d`, `userid_domain_1m`\n- `userid_site_1d`, `userid_site_avg_7d` (ROUND), `userid_site_7d`, `userid_site_30d`, `userid_site_1m`\n- `userid_cgi_1d`, `userid_cgi_avg_7d` (ROUND), `userid_cgi_7d`, `userid_cgi_30d`, `userid_cgi_1m`\n\n**Output Requirements**:\n- Target table: `internal_platform_db.t_app_urlsafe_report_url_access_stat_di_cand_mysql_018`\n- Single-row result, 27 fields\n- All avg fields retain 0 decimal places (using ROUND)\n- 1m fields use IFNULL to handle NULL as 0\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_018 ground truth: 网址安全检测多维度访问统计报表\n\nTask:\n From URL safety detection detail table, compute multi-dimensional\n access statistics (UV metrics at taid/url/domain/site/cgi levels),\n join with historical partition data, and write single-row result\n to output table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE = \"t_dws_urlsafe_rela_mobile_browser_taid_url_di_mysql_018\"\nOUTPUT_TABLE = \"t_app_urlsafe_report_url_access_stat_di_mysql_018\"\nCAND_TABLE = \"t_app_urlsafe_report_url_access_stat_di_cand_mysql_018\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\n# MySQL-adapted GT SQL:\n# - INSERT OVERWRITE -> INSERT INTO ... SELECT\n# - NVL -> IFNULL\n# - to_char(date_sub(...)) -> hardcoded 20260531\n# - PARTITION columns become regular columns\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{CAND_TABLE}\n (access_type, access_channel,\n uv_1d, uv_avg_7d, uv_7d, uv_30d, uv_1m,\n userid_url_1d, userid_url_avg_7d, userid_url_7d, userid_url_30d, userid_url_1m,\n userid_domain_1d, userid_domain_avg_7d, userid_domain_7d, userid_domain_30d, userid_domain_1m,\n userid_site_1d, userid_site_avg_7d, userid_site_7d, userid_site_30d, userid_site_1m,\n userid_cgi_1d, userid_cgi_avg_7d, userid_cgi_7d, userid_cgi_30d, userid_cgi_1m,\n ds, channel)\nSELECT\n '网址检测API' AS access_type,\n '手机IM平台Q浏览器' AS access_channel,\n a.uv_1d,\n ROUND(a.uv_avg_7d, 0) AS uv_avg_7d,\n a.uv_7d,\n a.uv_30d,\n IFNULL(b.uv_1m, 0) AS uv_1m,\n c.userid_url_1d,\n ROUND(c.userid_url_avg_7d, 0) AS userid_url_avg_7d,\n c.userid_url_7d,\n c.userid_url_30d,\n IFNULL(b.userid_url_1m, 0) AS userid_url_1m,\n d.userid_domain_1d,\n ROUND(d.userid_domain_avg_7d, 0) AS userid_domain_avg_7d,\n d.userid_domain_7d,\n d.userid_domain_30d,\n IFNULL(b.userid_domain_1m, 0) AS userid_domain_1m,\n d.userid_site_1d,\n ROUND(d.userid_site_avg_7d, 0) AS userid_site_avg_7d,\n d.userid_site_7d,\n d.userid_site_30d,\n IFNULL(b.userid_site_1m, 0) AS userid_site_1m,\n e.userid_cgi_1d,\n ROUND(e.userid_cgi_avg_7d, 0) AS userid_cgi_avg_7d,\n e.userid_cgi_7d,\n e.userid_cgi_30d,\n IFNULL(b.userid_cgi_1m, 0) AS userid_cgi_1m,\n 20260608 AS ds,\n 'mobile_browser' AS channel\nFROM\n(\n SELECT 20260608 AS data_par,\n COUNT(IF(ds_max = 20260608, 1, NULL)) AS uv_1d,\n (COUNT(IF(state_6d=1,1,NULL))+COUNT(IF(state_5d=1,1,NULL))+COUNT(IF(state_4d=1,1,NULL))+COUNT(IF(state_3d=1,1,NULL))+COUNT(IF(state_2d=1,1,NULL))+COUNT(IF(state_1d=1,1,NULL))+COUNT(IF(state_daily=1,1,NULL)))/7 AS uv_avg_7d,\n COUNT(IF(ds_max > 20260601, 1, NULL)) AS uv_7d,\n COUNT(1) AS uv_30d\n FROM\n (\n SELECT taid,\n MAX(ds) AS ds_max,\n MAX(IF(ds = 20260602,1,0)) AS state_6d,\n MAX(IF(ds = 20260603,1,0)) AS state_5d,\n MAX(IF(ds = 20260604,1,0)) AS state_4d,\n MAX(IF(ds = 20260605,1,0)) AS state_3d,\n MAX(IF(ds = 20260606,1,0)) AS state_2d,\n MAX(IF(ds = 20260607,1,0)) AS state_1d,\n MAX(IF(ds = 20260608,1,0)) AS state_daily\n FROM {DB_NAME}.{INPUT_TABLE}\n WHERE ds > 20260509 AND ds <= 20260608\n GROUP BY taid\n ) t\n) a\nLEFT JOIN\n(\n SELECT 20260608 AS data_par,\n uv_30d AS uv_1m,\n userid_url_30d AS userid_url_1m,\n userid_domain_30d AS userid_domain_1m,\n userid_site_30d AS userid_site_1m,\n userid_cgi_30d AS userid_cgi_1m\n FROM {DB_NAME}.{OUTPUT_TABLE}\n WHERE ds = 20260531\n AND channel = 'mobile_browser'\n) b ON a.data_par = b.data_par\nJOIN\n(\n SELECT 20260608 AS data_par,\n COUNT(IF(ds_max = 20260608, 1, NULL)) AS userid_url_1d,\n (COUNT(IF(state_6d=1,1,NULL))+COUNT(IF(state_5d=1,1,NULL))+COUNT(IF(state_4d=1,1,NULL))+COUNT(IF(state_3d=1,1,NULL))+COUNT(IF(state_2d=1,1,NULL))+COUNT(IF(state_1d=1,1,NULL))+COUNT(IF(state_daily=1,1,NULL)))/7 AS userid_url_avg_7d,\n COUNT(IF(ds_max > 20260601, 1, NULL)) AS userid_url_7d,\n COUNT(1) AS userid_url_30d\n FROM\n (\n SELECT taid,\n url,\n MAX(ds) AS ds_max,\n MAX(IF(ds = 20260602,1,0)) AS state_6d,\n MAX(IF(ds = 20260603,1,0)) AS state_5d,\n MAX(IF(ds = 20260604,1,0)) AS state_4d,\n MAX(IF(ds = 20260605,1,0)) AS state_3d,\n MAX(IF(ds = 20260606,1,0)) AS state_2d,\n MAX(IF(ds = 20260607,1,0)) AS state_1d,\n MAX(IF(ds = 20260608,1,0)) AS state_daily\n FROM {DB_NAME}.{INPUT_TABLE}\n WHERE ds > 20260509 AND ds <= 20260608\n GROUP BY taid, url\n ) t\n) c ON a.data_par = c.data_par\nJOIN\n(\n SELECT 20260608 AS data_par,\n COUNT(IF(ds_max = 20260608, 1, NULL)) AS userid_domain_1d,\n (COUNT(IF(state_6d=1,1,NULL))+COUNT(IF(state_5d=1,1,NULL))+COUNT(IF(state_4d=1,1,NULL))+COUNT(IF(state_3d=1,1,NULL))+COUNT(IF(state_2d=1,1,NULL))+COUNT(IF(state_1d=1,1,NULL))+COUNT(IF(state_daily=1,1,NULL)))/7 AS userid_domain_avg_7d,\n COUNT(IF(ds_max > 20260601, 1, NULL)) AS userid_domain_7d,\n COUNT(1) AS userid_domain_30d,\n SUM(site_cnt_daily) AS userid_site_1d,\n (SUM(site_cnt_6d)+SUM(site_cnt_5d)+SUM(site_cnt_4d)+SUM(site_cnt_3d)+SUM(site_cnt_2d)+SUM(site_cnt_1d)+SUM(site_cnt_daily))/7 AS userid_site_avg_7d,\n SUM(site_cnt_7d) AS userid_site_7d,\n SUM(site_cnt) AS userid_site_30d\n FROM\n (\n SELECT taid,\n domain,\n MAX(ds_max) AS ds_max,\n MAX(IF(state_6d=1,1,0)) AS state_6d,\n MAX(IF(state_5d=1,1,0)) AS state_5d,\n MAX(IF(state_4d=1,1,0)) AS state_4d,\n MAX(IF(state_3d=1,1,0)) AS state_3d,\n MAX(IF(state_2d=1,1,0)) AS state_2d,\n MAX(IF(state_1d=1,1,0)) AS state_1d,\n MAX(IF(state_daily=1,1,0)) AS state_daily,\n COUNT(1) AS site_cnt,\n COUNT(IF(state_6d=1,1,NULL)) AS site_cnt_6d,\n COUNT(IF(state_5d=1,1,NULL)) AS site_cnt_5d,\n COUNT(IF(state_4d=1,1,NULL)) AS site_cnt_4d,\n COUNT(IF(state_3d=1,1,NULL)) AS site_cnt_3d,\n COUNT(IF(state_2d=1,1,NULL)) AS site_cnt_2d,\n COUNT(IF(state_1d=1,1,NULL)) AS site_cnt_1d,\n COUNT(IF(ds_max = 20260608,1,NULL)) AS site_cnt_daily,\n COUNT(IF(ds_max > 20260601,1,NULL)) AS site_cnt_7d\n FROM\n (\n SELECT taid,\n site,\n MAX(domain) AS domain,\n MAX(ds) AS ds_max,\n MAX(IF(ds = 20260602,1,0)) AS state_6d,\n MAX(IF(ds = 20260603,1,0)) AS state_5d,\n MAX(IF(ds = 20260604,1,0)) AS state_4d,\n MAX(IF(ds = 20260605,1,0)) AS state_3d,\n MAX(IF(ds = 20260606,1,0)) AS state_2d,\n MAX(IF(ds = 20260607,1,0)) AS state_1d,\n MAX(IF(ds = 20260608,1,0)) AS state_daily\n FROM {DB_NAME}.{INPUT_TABLE}\n WHERE ds > 20260509 AND ds <= 20260608\n GROUP BY taid, site\n ) t1\n GROUP BY taid, domain\n ) t\n) d ON a.data_par = d.data_par\nJOIN\n(\n SELECT 20260608 AS data_par,\n COUNT(IF(ds_max = 20260608, 1, NULL)) AS userid_cgi_1d,\n (COUNT(IF(state_6d=1,1,NULL))+COUNT(IF(state_5d=1,1,NULL))+COUNT(IF(state_4d=1,1,NULL))+COUNT(IF(state_3d=1,1,NULL))+COUNT(IF(state_2d=1,1,NULL))+COUNT(IF(state_1d=1,1,NULL))+COUNT(IF(state_daily=1,1,NULL)))/7 AS userid_cgi_avg_7d,\n COUNT(IF(ds_max > 20260601, 1, NULL)) AS userid_cgi_7d,\n COUNT(1) AS userid_cgi_30d\n FROM\n (\n SELECT taid,\n cgi,\n MAX(ds) AS ds_max,\n MAX(IF(ds = 20260602,1,0)) AS state_6d,\n MAX(IF(ds = 20260603,1,0)) AS state_5d,\n MAX(IF(ds = 20260604,1,0)) AS state_4d,\n MAX(IF(ds = 20260605,1,0)) AS state_3d,\n MAX(IF(ds = 20260606,1,0)) AS state_2d,\n MAX(IF(ds = 20260607,1,0)) AS state_1d,\n MAX(IF(ds = 20260608,1,0)) AS state_daily\n FROM {DB_NAME}.{INPUT_TABLE}\n WHERE ds > 20260509 AND ds <= 20260608\n GROUP BY taid, cgi\n ) t1\n) e ON a.data_par = e.data_par\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{CAND_TABLE} (\n access_type VARCHAR(256) DEFAULT NULL COMMENT '访问类型',\n access_channel VARCHAR(256) DEFAULT NULL COMMENT '访问渠道',\n uv_1d BIGINT DEFAULT NULL COMMENT '1日UV',\n uv_avg_7d BIGINT DEFAULT NULL COMMENT '7日平均UV',\n uv_7d BIGINT DEFAULT NULL COMMENT '7日UV',\n uv_30d BIGINT DEFAULT NULL COMMENT '30日UV',\n uv_1m BIGINT DEFAULT NULL COMMENT '1月UV',\n userid_url_1d BIGINT DEFAULT NULL COMMENT 'URL维度1日用户数',\n userid_url_avg_7d BIGINT DEFAULT NULL COMMENT 'URL维度7日平均用户数',\n userid_url_7d BIGINT DEFAULT NULL COMMENT 'URL维度7日用户数',\n userid_url_30d BIGINT DEFAULT NULL COMMENT 'URL维度30日用户数',\n userid_url_1m BIGINT DEFAULT NULL COMMENT 'URL维度1月用户数',\n userid_domain_1d BIGINT DEFAULT NULL COMMENT '域名维度1日用户数',\n userid_domain_avg_7d BIGINT DEFAULT NULL COMMENT '域名维度7日平均用户数',\n userid_domain_7d BIGINT DEFAULT NULL COMMENT '域名维度7日用户数',\n userid_domain_30d BIGINT DEFAULT NULL COMMENT '域名维度30日用户数',\n userid_domain_1m BIGINT DEFAULT NULL COMMENT '域名维度1月用户数',\n userid_site_1d BIGINT DEFAULT NULL COMMENT '站点维度1日用户数',\n userid_site_avg_7d BIGINT DEFAULT NULL COMMENT '站点维度7日平均用户数',\n userid_site_7d BIGINT DEFAULT NULL COMMENT '站点维度7日用户数',\n userid_site_30d BIGINT DEFAULT NULL COMMENT '站点维度30日用户数',\n userid_site_1m BIGINT DEFAULT NULL COMMENT '站点维度1月用户数',\n userid_cgi_1d BIGINT DEFAULT NULL COMMENT 'CGI维度1日用户数',\n userid_cgi_avg_7d BIGINT DEFAULT NULL COMMENT 'CGI维度7日平均用户数',\n userid_cgi_7d BIGINT DEFAULT NULL COMMENT 'CGI维度7日用户数',\n userid_cgi_30d BIGINT DEFAULT NULL COMMENT 'CGI维度30日用户数',\n userid_cgi_1m BIGINT DEFAULT NULL COMMENT 'CGI维度1月用户数',\n ds BIGINT DEFAULT NULL COMMENT '日期分区',\n channel VARCHAR(256) DEFAULT NULL COMMENT '渠道分区'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{CAND_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_018 ground_truth done: 1 row written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_018_en"} {"task_id": "mysql_019", "id": "offline-compute_MySQL_mysql_019", "name": "传感器事件宽表关联用户组帖子分类圈组维度", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\n我需要你生成一段 MySQL 代码,将传感器事件数据关联用户组、帖子、分类和圈组维度,生成帖子事件明细宽表。\n\n**业务背景与目标**:传感器事件明细表记录了用户在社区中的各种行为(浏览帖子、点赞、收藏、评论等)。需要将事件数据与圈组成员关系、帖子信息、分类信息和圈组信息进行关联,生成一张帖子事件明细宽表,供下游分析使用。\n\n**输入表(全名 + 简要描述)**:\n\n- `internal_platform_db.dwd_knowledge_base_sensors_event_di_mysql_019`(传感器事件明细表)\n- `internal_platform_db.dwv_knowledge_base_groups_users_df_mysql_019`(圈组成员关系表)\n- `internal_platform_db.dwv_kb_posts_df_mysql_019`(帖子信息表)\n- `internal_platform_db.dwv_kb_categories_df_mysql_019`(分类信息表)\n- `internal_platform_db.dwv_knowledge_base_groups_df_mysql_019`(圈组信息表)\n\n(各表结构与字段含义请自行连接数据库查询确认)\n\n**处理规则**:\n\n1. 主表 t1 从 `dwd_knowledge_base_sensors_event_di_mysql_019` 筛选:\n - `concat(year,month,day)='20260608'`\n - `lower(event) in ('postdetailview','postdigg','postbooknowledge_baseark','postrecommend','commentsend','postcomment')`\n - `(group_id is not null or show_groups is not null)`\n - `post_id is not null and post_id != ''`\n - 派生字段:\n - `time as event_time`\n - `pc_or_mobile = if(lower(platform_type) in ('ios','android','h5'), 'mobile', 'pc')`\n - `group_id = ifnull(show_groups, group_id)`\n\n2. 左关联 t2(来自 `dwv_knowledge_base_groups_users_df_mysql_019`):\n - 筛选条件:`concat(year,month,day)='20260608'` 且 `enabled=1`\n - 关联条件:`t1.distinct_id = t2.nick` 且 `t1.group_id = t2.group_id`\n - 派生字段:`is_group_member = IF(t2.nick is null, 0, 1)`\n\n3. 左关联 t3(`dwv_kb_posts_df_mysql_019` 左关联 `dwv_kb_categories_df_mysql_019`):\n - t3 内部 tt1 来自 `dwv_kb_posts_df_mysql_019`,分区 `concat(year,month,day)='20260608'`\n - t3 内部 tt2 来自 `dwv_kb_categories_df_mysql_019`,分区 `concat(year,month,day)='20260608'`\n - tt1 和 tt2 通过 `tt1.category_id = tt2.id` 关联\n - t3 与 t1 通过 `post_id = id` 关联\n - 输出字段:`post_authorship`(来自 authorship), `posts_category_id`(来自 category_id), `posts_category_name`(来自 category_name 即 tt2.name)\n\n4. 左关联 t4(来自 `dwv_knowledge_base_groups_df_mysql_019`):\n - 筛选条件:`concat(year,month,day)='20260608'`\n - 关联条件:`t1.group_id = t4.code`\n - 输出字段:`t4_group_id`(来自 t4.id)\n\n5. 最终 `group_id` 字段取值:`ifnull(t4_group_id, group_id)`\n\n**输出要求**:\n- 目标表:`internal_platform_db.dwd_knowledge_base_k_bar_posts_event_di_cand_mysql_019`\n- 输出字段顺序:`event`, `distinct_id`, `appname`, `user_id`, `event_time`, `receive_time`, `os`, `track_signup_original_id`, `author_nick`, `platform_type`, `target_type`, `target_id`, `ip`, `post_id`, `show_groups`, `group_id`(解析后), `source_page`, `source_module`, `operation_type`, `pc_or_mobile`, `is_group_member`, `post_authorship`, `posts_category_id`, `posts_category_name`\n- 如果目标表不存在,请先按 MySQL InnoDB 标准建表,再写入数据\n- 请使用标准 MySQL 语法,不要使用 Hive/Spark SQL 方言(如 `INSERT OVERWRITE`、`STORED AS ORC`、`PARTITIONED BY` 等)\n\n**环境与执行说明**:\n- 你的最终产出必须写入文件 `/tmp_workspace/result.py`,不能写 result.sql\n- 本机 MySQL 已在 localhost:3306 运行,用户名 root,密码 root123\n- 请使用 Python pymysql 在 result.py 中执行 SQL(不要用 mysql 命令行)\n- 脚本需要包含完整的建表(如目标表不存在)+ 写入数据的逻辑\n- 写出 result.py 后,你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_019 ground truth: 传感器事件宽表关联用户组帖子分类圈组维度\n\nTask:\n Join sensor events with groups_users, posts+categories, and groups\n to produce a posts event detail wide table.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE_SENSORS = \"dwd_knowledge_base_sensors_event_di_mysql_019\"\nINPUT_TABLE_GROUPS_USERS = \"dwv_knowledge_base_groups_users_df_mysql_019\"\nINPUT_TABLE_POSTS = \"dwv_kb_posts_df_mysql_019\"\nINPUT_TABLE_CADEPT_TORIES = \"dwv_kb_categories_df_mysql_019\"\nINPUT_TABLE_GROUPS = \"dwv_knowledge_base_groups_df_mysql_019\"\nOUTPUT_TABLE = \"dwd_knowledge_base_k_bar_posts_event_di_cand_mysql_019\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (event, distinct_id, appname, user_id, event_time, receive_time, os,\n track_signup_original_id, author_nick, platform_type, target_type, target_id,\n ip, post_id, show_groups, group_id, source_page, source_module, operation_type,\n pc_or_mobile, is_group_member, post_authorship, posts_category_id, posts_category_name,\n year, month, day)\nSELECT\n event,\n distinct_id,\n appname,\n user_id,\n event_time,\n receive_time,\n os,\n track_signup_original_id,\n author_nick,\n platform_type,\n target_type,\n target_id,\n ip,\n post_id,\n show_groups,\n IFNULL(t4_group_id, group_id) AS group_id,\n source_page,\n source_module,\n operation_type,\n pc_or_mobile,\n IF(t2.nick IS NULL, 0, 1) AS is_group_member,\n post_authorship,\n posts_category_id,\n posts_category_name,\n '2026' AS year,\n '06' AS month,\n '08' AS day\nFROM (\n SELECT\n event,\n distinct_id,\n appname,\n user_id,\n time AS event_time,\n receive_time,\n os,\n track_signup_original_id,\n author_nick,\n platform_type,\n target_type,\n target_id,\n ip,\n post_id,\n show_groups,\n IFNULL(show_groups, group_id) AS group_id,\n source_page,\n source_module,\n operation_type,\n IF(LOWER(platform_type) IN ('ios', 'android', 'h5'), 'mobile', 'pc') AS pc_or_mobile\n FROM\n {DB_NAME}.{INPUT_TABLE_SENSORS}\n WHERE\n CONCAT(year, month, day) = '20260608'\n AND LOWER(event) IN ('postdetailview', 'postdigg', 'postbooknowledge_baseark',\n 'postrecommend', 'commentsend', 'postcomment')\n AND (group_id IS NOT NULL OR show_groups IS NOT NULL)\n AND post_id IS NOT NULL AND post_id != ''\n) t1\nLEFT JOIN (\n SELECT\n nick,\n group_id AS t2_group_id\n FROM\n {DB_NAME}.{INPUT_TABLE_GROUPS_USERS}\n WHERE\n CONCAT(year, month, day) = '20260608'\n AND enabled = 1\n) t2\nON t1.distinct_id = t2.nick AND t1.group_id COLLATE utf8mb4_unicode_ci = CONVERT(t2.t2_group_id, CHAR) COLLATE utf8mb4_unicode_ci\nLEFT JOIN (\n SELECT\n id AS t3_id,\n authorship AS post_authorship,\n category_id AS posts_category_id,\n category_name AS posts_category_name\n FROM (\n SELECT\n id,\n authorship,\n category_id\n FROM\n {DB_NAME}.{INPUT_TABLE_POSTS}\n WHERE\n CONCAT(year, month, day) = '20260608'\n ) tt1\n LEFT JOIN (\n SELECT\n id AS tt2_id,\n name AS category_name\n FROM\n {DB_NAME}.{INPUT_TABLE_CADEPT_TORIES}\n WHERE\n CONCAT(year, month, day) = '20260608'\n ) tt2\n ON tt1.category_id = tt2.tt2_id\n) t3\nON t1.post_id COLLATE utf8mb4_unicode_ci = CONVERT(t3.t3_id, CHAR) COLLATE utf8mb4_unicode_ci\nLEFT JOIN (\n SELECT\n id AS t4_group_id,\n code AS t4_group_code\n FROM\n {DB_NAME}.{INPUT_TABLE_GROUPS}\n WHERE\n CONCAT(year, month, day) = '20260608'\n) t4\nON t1.group_id = t4.t4_group_code\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n event VARCHAR(256) DEFAULT NULL,\n distinct_id VARCHAR(256) DEFAULT NULL,\n appname VARCHAR(256) DEFAULT NULL,\n user_id VARCHAR(256) DEFAULT NULL,\n event_time VARCHAR(256) DEFAULT NULL,\n receive_time VARCHAR(256) DEFAULT NULL,\n os VARCHAR(256) DEFAULT NULL,\n track_signup_original_id VARCHAR(256) DEFAULT NULL,\n author_nick VARCHAR(256) DEFAULT NULL,\n platform_type VARCHAR(256) DEFAULT NULL,\n target_type VARCHAR(256) DEFAULT NULL,\n target_id VARCHAR(256) DEFAULT NULL,\n ip VARCHAR(256) DEFAULT NULL,\n post_id VARCHAR(256) DEFAULT NULL,\n show_groups VARCHAR(256) DEFAULT NULL,\n group_id VARCHAR(256) DEFAULT NULL,\n source_page VARCHAR(256) DEFAULT NULL,\n source_module VARCHAR(256) DEFAULT NULL,\n operation_type VARCHAR(256) DEFAULT NULL,\n pc_or_mobile VARCHAR(256) DEFAULT NULL,\n is_group_member INT DEFAULT NULL,\n post_authorship VARCHAR(256) DEFAULT NULL,\n posts_category_id BIGINT DEFAULT NULL,\n posts_category_name VARCHAR(256) DEFAULT NULL,\n year VARCHAR(256) DEFAULT NULL,\n month VARCHAR(256) DEFAULT NULL,\n day VARCHAR(256) DEFAULT NULL\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_019 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_019"} {"task_id": "mysql_020_en", "id": "offline-compute_MySQL_mysql_020", "name": "Build Volume-Lift Candidate Ad List", "workload": "offline-compute", "engine": "MySQL", "category": "offline-compute/MySQL", "language": "en", "modality": "pure-text", "timeout_seconds": 1800, "prompt": "## Prompt\nI need you to generate a MySQL script that builds a volume-lift candidate ad list, outputting to table `internal_platform_db.dwm_union_raise_candidate_new_ads_hf_cand_mysql_020` with partition key `p_partition='2026060905'`.\n\n**Business Background and Objective**: The ad volume-lift system needs to jointly filter qualifying ads from multiple dimensions (creative, ad group, ecology budget, advertiser, conversion link, volume-lift configuration, creative platform) to generate a candidate list for downstream consumption. This task requires multi-table JOINs, aggregation, window function ranking, and filtering across 7 input tables, ultimately writing to the output table.\n\n**Input Tables (full name + brief description)**:\n- `internal_platform_db.dim_creative_info_f_mysql_020` (creative information)\n- `internal_platform_db.dim_adgroup_info_f_mysql_020` (ad group information)\n- `internal_platform_db.dim_adgroup_ecology_budget_info_di_mysql_020` (ecology budget information)\n- `internal_platform_db.f_union_dim_advertiser_info_d_mysql_020` (advertiser information)\n- `internal_platform_db.t_daily_conv_link_tid_dimension_mysql_020` (conversion link dimension)\n- `internal_platform_db.dim_union_ad_raised_config_hf_mysql_020` (volume-lift configuration)\n- `internal_platform_db.dim_tbl_creative_f_mysql_020` (creative platform information)\n\n(Please connect to the database and query to confirm the table structures and field semantics.)\n\n**Processing Rules**:\n1. Main table a (`dim_creative_info_f`): `creative_id > 0`, aggregate by `creative_id` taking `MAX(adgroup_id)`, `MAX(advertiser_id)`, `MAX(landing_page_type)`\n2. Subquery e (`dim_adgroup_info_f`) INNER JOIN:\n - Filter `adgroup_id > 0`\n - Filter `placement_group_id_list` containing 15 or 136 (using the `FIND_IN_SET` function)\n - `begin_time >= MIN(begintime)` from the config table AND `<= MAX(endtime)`, config table conditions: `partition_time = 2026060905`, `strategyid > 0`, `20260609` within the `begintime-endtime` range (use `FROM_UNIXTIME` to convert unix timestamps to date format `yyyyMMdd` for comparison)\n - Aggregate by `adgroup_id` taking `MAX(product_id)`, `MAX(optimization_goal)`, `MAX(second_optimization_goal)`, `MAX(deep_conversion_optimization_goal)`, `MAX(marketing_target_id)`, `MAX(begin_time)`, `MAX(end_time)`, `MAX(created_time)`, `MAX(exploration_strategy_id)`, `MAX(placement_group_id_list)`\n3. Subquery b (`dim_adgroup_ecology_budget_info_di`) LEFT JOIN: `partition_time` between 20260607–20260608, take the latest partition's `ecology_level2_id` per `creative_id` (using the `ROW_NUMBER` window function ranked by `partition_time DESC`, taking rn=1)\n4. Subquery c (`f_union_dim_advertiser_info_d`) LEFT JOIN: `partition_time` between 20260607–20260608, first aggregate by `advertiser_id + partition_time` taking `MAX(operation_industry_name) AS team`, `MAX(short_advertiser_name)`, then take the latest partition's `team`, `short_advertiser_name` per `advertiser_id` (ROW_NUMBER)\n5. Subquery d (`t_daily_conv_link_tid_dimension`) LEFT JOIN: `partition_time` between 20260607–20260608, first aggregate by `tid + partition_time` taking `MAX(landingpage_link_type)`, then take the latest partition's `landingpage_link_type` per `tid` (ROW_NUMBER), join condition `a.creative_id = d.tid`\n6. Subquery f (`dim_tbl_creative_f`) LEFT JOIN: `ftid > 0`, aggregate by `ftid` taking `MAX(fsmartdeliveryplatform) AS smart_delivery_platform`, join condition `a.creative_id = f.ftid`\n7. Final SELECT: `partition_time = 2026060905`, `adgroup_id`, `COALESCE(advertiser_id, 0)`, `COALESCE(product_id, '')`, `CONCAT(COALESCE(optimization_goal, 0), '_', COALESCE(second_optimization_goal, 0), '_', COALESCE(deep_conversion_optimization_goal, 0)) AS mix_goal`, `COALESCE(landing_page_type, '')`, `COALESCE(marketing_target_id, 0)`, `COALESCE(ecology_level2_id, 0)`, `COALESCE(team, '')`, `COALESCE(short_advertiser_name, '')`, `COALESCE(landingpage_link_type, '')`, `COALESCE(begin_time, 0)`, `COALESCE(end_time, 0)`, `COALESCE(created_time, 0)`, `COALESCE(smart_delivery_platform, 0)`, `COALESCE(exploration_strategy_id, 0)`, `COALESCE(placement_group_id_list, '')`\n\n**Output Requirements**:\n- Target table: `internal_platform_db.dwm_union_raise_candidate_new_ads_hf_cand_mysql_020`\n- Output field order: `partition_time`, `adgroup_id`, `advertiser_id`, `product_id`, `mix_goal`, `landing_page_type`, `marketing_target_id`, `ecology_level2_id`, `team`, `short_advertiser_name`, `landingpage_link_type`, `begin_time`, `end_time`, `created_time`, `smart_delivery_platform`, `exploration_strategy_id`, `placement_group_id_list`, `p_partition`\n- `mix_goal` is generated by concatenating three optimization goal fields with underscores; null values are replaced with defaults using COALESCE (0 for numeric, empty string for string)\n- Final deduplication by GROUP BY on all non-`partition_time` fields\n- `p_partition` is fixed as `'2026060905'`\n- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data\n- Use standard MySQL syntax; do not use Hive/Spark SQL dialects (e.g., `INSERT OVERWRITE`, `ARRAY` type, `array_contains`, `concat_ws` for arrays, and other Hive-specific functions are not supported)\n\n**Environment and Execution Notes**:\n- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`\n- The local MySQL is running at localhost:3306, username `root`, password `root123`\n- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)\n- The script must include complete table creation (if the target table does not exist) and data writing logic\n- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data", "ground_truth": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmysql_020 ground truth: 构建提量候选广告列表\n\nTask:\n Build raise-candidate ad list from 7 input tables via multi-table JOIN,\n aggregation, window functions, and filtering, write to output table\n with p_partition='2026060905'.\n\"\"\"\nimport pymysql\nimport sys\n\nDB_NAME = \"internal_platform_db\"\nINPUT_TABLE_CREATIVE = \"dim_creative_info_f_mysql_020\"\nINPUT_TABLE_ADGROUP = \"dim_adgroup_info_f_mysql_020\"\nINPUT_TABLE_ECOLOGY = \"dim_adgroup_ecology_budget_info_di_mysql_020\"\nINPUT_TABLE_ADVERTISER = \"f_union_dim_advertiser_info_d_mysql_020\"\nINPUT_TABLE_CONV_LINK = \"t_daily_conv_link_tid_dimension_mysql_020\"\nINPUT_TABLE_CONFIG = \"dim_union_ad_raised_config_hf_mysql_020\"\nINPUT_TABLE_CREATIVE_PLATFORM = \"dim_tbl_creative_f_mysql_020\"\nOUTPUT_TABLE = \"dwm_union_raise_candidate_new_ads_hf_cand_mysql_020\"\n\nMYSQL_CONFIG = {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"root123\",\n \"charset\": \"utf8mb4\",\n}\n\ngt_sql = f\"\"\"\nINSERT INTO {DB_NAME}.{OUTPUT_TABLE}\n (partition_time, adgroup_id, advertiser_id, product_id, mix_goal,\n landing_page_type, marketing_target_id, ecology_level2_id, team,\n short_advertiser_name, landingpage_link_type, begin_time, end_time,\n created_time, smart_delivery_platform, exploration_strategy_id,\n placement_group_id_list, p_partition)\nSELECT\n 2026060905 AS partition_time,\n a.adgroup_id,\n COALESCE(a.advertiser_id, 0) AS advertiser_id,\n COALESCE(e.product_id, '') AS product_id,\n CONCAT(COALESCE(e.optimization_goal, 0), '_',\n COALESCE(e.second_optimization_goal, 0), '_',\n COALESCE(e.deep_conversion_optimization_goal, 0)) AS mix_goal,\n COALESCE(a.landing_page_type, '') AS landing_page_type,\n COALESCE(e.marketing_target_id, 0) AS marketing_target_id,\n COALESCE(b.ecology_level2_id, 0) AS ecology_level2_id,\n COALESCE(c.team, '') AS team,\n COALESCE(c.short_advertiser_name, '') AS short_advertiser_name,\n COALESCE(d.landingpage_link_type, '') AS landingpage_link_type,\n COALESCE(e.begin_time, 0) AS begin_time,\n COALESCE(e.end_time, 0) AS end_time,\n COALESCE(e.created_time, 0) AS created_time,\n COALESCE(f.smart_delivery_platform, 0) AS smart_delivery_platform,\n COALESCE(e.exploration_strategy_id, 0) AS exploration_strategy_id,\n COALESCE(e.placement_group_id_list, '') AS placement_group_id_list,\n '2026060905' AS p_partition\nFROM (\n SELECT creative_id,\n MAX(adgroup_id) AS adgroup_id,\n MAX(advertiser_id) AS advertiser_id,\n MAX(landing_page_type) AS landing_page_type\n FROM {DB_NAME}.{INPUT_TABLE_CREATIVE}\n WHERE creative_id > 0\n GROUP BY creative_id\n) a\nLEFT JOIN (\n SELECT creative_id, ecology_level2_id\n FROM (\n SELECT creative_id, partition_time, ecology_level2_id,\n ROW_NUMBER() OVER (PARTITION BY creative_id ORDER BY partition_time DESC) AS rn\n FROM {DB_NAME}.{INPUT_TABLE_ECOLOGY}\n WHERE partition_time BETWEEN 20260607 AND 20260608\n ) ranked\n WHERE rn = 1\n) b ON a.creative_id = b.creative_id\nLEFT JOIN (\n SELECT advertiser_id, team, short_advertiser_name\n FROM (\n SELECT advertiser_id, partition_time, team, short_advertiser_name,\n ROW_NUMBER() OVER (PARTITION BY advertiser_id ORDER BY partition_time DESC) AS rn\n FROM (\n SELECT advertiser_id, partition_time,\n MAX(operation_industry_name) AS team,\n MAX(short_advertiser_name) AS short_advertiser_name\n FROM {DB_NAME}.{INPUT_TABLE_ADVERTISER}\n WHERE partition_time BETWEEN 20260607 AND 20260608\n GROUP BY advertiser_id, partition_time\n ) agg\n ) ranked\n WHERE rn = 1\n) c ON a.advertiser_id = c.advertiser_id\nLEFT JOIN (\n SELECT tid, landingpage_link_type\n FROM (\n SELECT tid, partition_time, landingpage_link_type,\n ROW_NUMBER() OVER (PARTITION BY tid ORDER BY partition_time DESC) AS rn\n FROM (\n SELECT tid, partition_time,\n MAX(landingpage_link_type) AS landingpage_link_type\n FROM {DB_NAME}.{INPUT_TABLE_CONV_LINK}\n WHERE partition_time BETWEEN 20260607 AND 20260608\n GROUP BY tid, partition_time\n ) agg\n ) ranked\n WHERE rn = 1\n) d ON a.creative_id = d.tid\nJOIN (\n SELECT adgroup_id,\n MAX(product_id) AS product_id,\n MAX(optimization_goal) AS optimization_goal,\n MAX(second_optimization_goal) AS second_optimization_goal,\n MAX(deep_conversion_optimization_goal) AS deep_conversion_optimization_goal,\n MAX(marketing_target_id) AS marketing_target_id,\n MAX(begin_time) AS begin_time,\n MAX(end_time) AS end_time,\n MAX(created_time) AS created_time,\n MAX(exploration_strategy_id) AS exploration_strategy_id,\n MAX(placement_group_id_list) AS placement_group_id_list\n FROM {DB_NAME}.{INPUT_TABLE_ADGROUP}\n WHERE adgroup_id > 0\n AND (FIND_IN_SET(15, placement_group_id_list) > 0 OR FIND_IN_SET(136, placement_group_id_list) > 0)\n AND begin_time >= (\n SELECT MIN(begintime)\n FROM {DB_NAME}.{INPUT_TABLE_CONFIG}\n WHERE partition_time = 2026060905\n AND strategyid > 0\n AND 20260609 >= DATE_FORMAT(FROM_UNIXTIME(begintime), '%Y%m%d')\n AND 20260609 <= DATE_FORMAT(FROM_UNIXTIME(endtime), '%Y%m%d')\n )\n AND begin_time <= (\n SELECT MAX(endtime)\n FROM {DB_NAME}.{INPUT_TABLE_CONFIG}\n WHERE partition_time = 2026060905\n AND strategyid > 0\n AND 20260609 >= DATE_FORMAT(FROM_UNIXTIME(begintime), '%Y%m%d')\n AND 20260609 <= DATE_FORMAT(FROM_UNIXTIME(endtime), '%Y%m%d')\n )\n GROUP BY adgroup_id\n) e ON a.adgroup_id = e.adgroup_id\nLEFT JOIN (\n SELECT ftid,\n MAX(fsmartdeliveryplatform) AS smart_delivery_platform\n FROM {DB_NAME}.{INPUT_TABLE_CREATIVE_PLATFORM}\n WHERE ftid > 0\n GROUP BY ftid\n) f ON a.creative_id = f.ftid\nGROUP BY\n a.adgroup_id,\n COALESCE(a.advertiser_id, 0),\n COALESCE(e.product_id, ''),\n CONCAT(COALESCE(e.optimization_goal, 0), '_',\n COALESCE(e.second_optimization_goal, 0), '_',\n COALESCE(e.deep_conversion_optimization_goal, 0)),\n COALESCE(a.landing_page_type, ''),\n COALESCE(e.marketing_target_id, 0),\n COALESCE(b.ecology_level2_id, 0),\n COALESCE(c.team, ''),\n COALESCE(c.short_advertiser_name, ''),\n COALESCE(d.landingpage_link_type, ''),\n COALESCE(e.begin_time, 0),\n COALESCE(e.end_time, 0),\n COALESCE(e.created_time, 0),\n COALESCE(f.smart_delivery_platform, 0),\n COALESCE(e.exploration_strategy_id, 0),\n COALESCE(e.placement_group_id_list, '')\n\"\"\"\n\n\ndef main():\n conn = pymysql.connect(**MYSQL_CONFIG)\n\n try:\n with conn.cursor() as cur:\n # Ensure output table exists\n cur.execute(f\"\"\"\n CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (\n partition_time BIGINT NOT NULL COMMENT '分区时间',\n adgroup_id BIGINT NOT NULL COMMENT '广告组ID',\n advertiser_id BIGINT NOT NULL COMMENT '广告主ID',\n product_id VARCHAR(256) NOT NULL COMMENT '产品ID',\n mix_goal VARCHAR(256) NOT NULL COMMENT '混合优化目标',\n landing_page_type VARCHAR(256) NOT NULL COMMENT '落地页类型',\n marketing_target_id BIGINT NOT NULL COMMENT '营销目标ID',\n ecology_level2_id INT NOT NULL COMMENT '生态二级ID',\n team VARCHAR(256) NOT NULL COMMENT '团队',\n short_advertiser_name VARCHAR(256) NOT NULL COMMENT '广告主简称',\n landingpage_link_type VARCHAR(256) NOT NULL COMMENT '落地页链接类型',\n begin_time BIGINT NOT NULL COMMENT '开始时间',\n end_time BIGINT NOT NULL COMMENT '结束时间',\n created_time BIGINT NOT NULL COMMENT '创建时间',\n smart_delivery_platform INT NOT NULL COMMENT '智能投放平台',\n exploration_strategy_id BIGINT NOT NULL COMMENT '探索策略ID',\n placement_group_id_list VARCHAR(256) NOT NULL COMMENT '广告位组ID列表',\n p_partition VARCHAR(256) NOT NULL COMMENT '分区键'\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n \"\"\")\n\n # Truncate + insert\n cur.execute(f\"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}\")\n cur.execute(gt_sql)\n\n conn.commit()\n print(\"mysql_020 ground_truth done: rows written to output table\")\n except Exception as e:\n print(f\"ground_truth error: {e}\", file=sys.stderr)\n conn.rollback()\n sys.exit(1)\n finally:\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/MySQL/mysql_020_en"} {"task_id": "prestosql_001", "id": "offline-compute_PrestoSQL_prestosql_001", "name": "安全扫描实例明细分析", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n任务目标:从安全扫描 span 信息和资源分配信息关联产出安全扫描实例运行明细表。\n\n输入:\n- internal_platform_db.t_security_scan_span_prestosql_001\n- internal_platform_db.t_security_resource_info_prestosql_001\n\n处理规则:\n- 两表关联查询,关联条件需基于表结构确定\n- 具体过滤条件和字段选择需基于表结构确定\n\n输出要求:\n- 输出表:internal_platform_db.t_security_scan_instance_detail_cand_prestosql_001\n- 输出字段需基于目标表结构确定\n\n写入要求:\n- 写入目标表\n\n请将最终 Presto/Trino SQL 写入 result.sql 并执行。", "ground_truth": "INSERT INTO internal_platform_db.t_security_scan_instance_detail_prestosql_001\nWITH base_trace AS (\n SELECT trace_id\n FROM internal_platform_db.t_security_scan_span_prestosql_001\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n AND span_name IN ('scan.completed', 'scan.failed')\n GROUP BY trace_id\n HAVING\n COUNT(CASE WHEN span_name = 'scan.failed' THEN 1 END) > 0\n AND\n COUNT(CASE WHEN span_name = 'scan.completed' THEN 1 END) = 0\n),\ncombined_spans AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n security_project_id,\n security_task_id,\n scan_type,\n status_code\n FROM internal_platform_db.t_security_scan_span_prestosql_001\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('scan.failed', 'scan.start', 'scan.execute', 'scan.cleanup', 'resource.allocate')\n\n UNION ALL\n\n SELECT\n trace_id,\n 'scan.completed' AS span_name,\n MAX(CASE WHEN span_name = 'scan.start' THEN start_time END) AS start_time,\n MAX(CASE WHEN span_name = 'scan.failed' THEN end_time END) AS end_time,\n MAX(CASE WHEN span_name = 'scan.failed' THEN security_project_id END) AS security_project_id,\n MAX(CASE WHEN span_name = 'scan.failed' THEN security_task_id END) AS security_task_id,\n MAX(CASE WHEN span_name = 'scan.failed' THEN scan_type END) AS scan_type,\n 2 AS status_code\n FROM internal_platform_db.t_security_scan_span_prestosql_001\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('scan.start', 'scan.failed')\n GROUP BY trace_id\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'scan.failed'\n THEN MIN(CASE WHEN span_name IN ('scan.execute', 'scan.failed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n end_time,\n security_project_id,\n security_task_id,\n scan_type,\n status_code\n FROM combined_spans\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n security_project_id,\n security_task_id,\n scan_type,\n status_code,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) AS start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) AS end_date,\n date_diff('day', from_unixtime(CAST(start_time AS BIGINT) / 1000), from_unixtime(CAST(end_time AS BIGINT) / 1000)) AS diff_days,\n CAST(CAST(start_time AS BIGINT) / 86400000 AS BIGINT) * 86400000 AS start_day_midnight_ms\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n b.trace_id,\n b.span_name,\n b.security_project_id,\n b.security_task_id,\n b.scan_type,\n b.status_code,\n b.start_date,\n b.end_date,\n b.diff_days,\n date_add('day', s.pos, b.start_date) AS calc_date,\n CASE WHEN s.pos = 0 THEN b.start_time\n ELSE CAST(b.start_day_midnight_ms + s.pos * 86400000 AS VARCHAR)\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN b.end_time\n ELSE CAST(b.start_day_midnight_ms + (s.pos + 1) * 86400000 - 1 AS VARCHAR)\n END AS end_time,\n b.start_time AS span_start_time,\n b.end_time AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n t.trace_id,\n t.calc_date,\n MAX(t.security_project_id) AS security_project_id,\n MAX(t.security_task_id) AS security_task_id,\n MAX(t.scan_type) AS scan_type,\n MAX(MAX(CASE WHEN t.span_name = 'scan.completed' THEN t.status_code END)) OVER(PARTITION BY t.trace_id) AS status_code,\n CAST(ROUND((MAX(CASE WHEN t.span_name = 'scan.execute' THEN CAST(t.end_time AS BIGINT) END) -\n MIN(CASE WHEN t.span_name = 'scan.execute' THEN CAST(t.start_time AS BIGINT) END)) / 1000.0) AS INT) AS scan_run_time,\n CAST(ROUND((MAX(CASE WHEN t.span_name IN ('scan.execute', 'scan.cleanup') THEN CAST(t.end_time AS BIGINT) END) -\n MIN(CASE WHEN t.span_name IN ('scan.execute', 'scan.cleanup') THEN CAST(t.start_time AS BIGINT) END)) / 1000.0) AS INT) AS code_run_time,\n CAST(ROUND((MAX(CASE WHEN t.span_name = 'resource.allocate' THEN CAST(t.end_time AS BIGINT) END) -\n MIN(CASE WHEN t.span_name = 'resource.allocate' THEN CAST(t.start_time AS BIGINT) END)) / 1000.0) AS INT) AS resource_wait_time\n FROM daily_split_spans t\n GROUP BY t.trace_id, t.calc_date\n)\nSELECT\n date_format(t1.calc_date, '%Y-%m-%d') AS p_date,\n t1.trace_id,\n t1.security_project_id,\n t1.security_task_id,\n t1.scan_type,\n t1.status_code,\n t1.scan_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n t2.resource_id,\n CAST(t2.is_dedicated AS BOOLEAN) AS is_dedicated,\n t2.apply_for_cpu_count\nFROM trace_time_metrics t1\nLEFT JOIN (\n SELECT\n trace_id,\n MAX(resource_id) AS resource_id,\n MAX(is_dedicated) AS is_dedicated,\n MAX(cpu_cores) AS apply_for_cpu_count\n FROM internal_platform_db.t_security_resource_info_prestosql_001\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\n;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_001"} {"task_id": "prestosql_002_en", "id": "offline-compute_PrestoSQL_prestosql_002", "name": "Ad ASA Attribution Migration", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**Task Objective**: From the ad attribution raw logs, filter valid records of two attribution types (ad_attribution and huawei), aggregate the log count and deduplicated user count by version and media dimensions, and write the results to the output table.\n\n**Input Table**:\n- `internal_platform_db.t_sh_event_log_v2_06000061157_prestosql_002` (ad attribution raw logs)\n - `ftime` STRING — time\n - `extinfo` STRING — extended information\n - `ad_version` STRING — ad version (ad_attribution/huawei)\n - `guid` STRING — user identifier\n - `ch` STRING — channel\n - `first_date` STRING — first date\n - `last_date` STRING — last date\n - `click_date` STRING — click date\n - `attribution` STRING — attribution flag\n - `conversion_date` STRING — conversion date\n - `conversion_type` STRING — conversion type\n - `creativeset_id` STRING — creative set ID\n - `org_id` STRING — organization ID\n - `campaign_id` STRING — campaign ID\n - `adgroup_id` STRING — ad group ID\n - `keyword_id` STRING — keyword ID\n - `country_oregion` STRING — country/region\n - `enter_ag_time` STRING — ad group entry time\n - `installed_finish_time` STRING — installation completion time\n - `start_download_time` STRING — download start time\n - `sub_channel` STRING — sub-channel\n - `callback` STRING — callback information\n - `task_id` STRING — task ID\n - `sub_task_id` STRING — sub-task ID\n - `rta_id` STRING — RTA identifier\n - `device_id` STRING — device_id identifier\n - `ext_info1` STRING — extended information 1\n - `ext_info2` STRING — extended information 2\n - `caid` STRING — CAID\n - `claim_type` STRING — claim type\n - `ai_assistant_device_id` STRING — YB device_id\n - `ds` STRING — partition field\n\n**Filter Conditions**:\n- `ds = '2026060919'`\n- Valid record condition: `(ad_version = 'ad_attribution' AND attribution = 'true') OR (ad_version = 'phonebrandh' AND callback != '')`\n\n**Output Requirements**:\n- Target table: `internal_platform_db.t_my_ads_tracking_log_metrics_cand_prestosql_002`\n- Output fields and order: `ds` BIGINT, `ad_version` STRING, `media_id` INT, `log_num` BIGINT, `log_num_qimei` BIGINT\n- `ds`: Cast the original table's `ds` field to BIGINT\n- `media_id`: `CASE ad_version WHEN 'ad_attribution' THEN 39 WHEN 'phonebrandh' THEN 28 END`\n- `log_num`: `COUNT(*)` log count\n- `log_num_qimei`: `COUNT(DISTINCT device_id)` deduplicated user count\n- Group by `ds`, `ad_version`\n- If the target table does not exist, first create the table, then write the data\n- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Presto is running, connected via the Hive catalog\n- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.t_my_ads_tracking_log_metrics_prestosql_002\nSELECT\n CAST(ds AS BIGINT) AS ds,\n ad_version,\n CASE ad_version WHEN 'ad_attribution' THEN 39 WHEN 'phonebrandh' THEN 28 END AS media_id,\n COUNT(*) AS log_num,\n COUNT(DISTINCT device_id) AS log_num_qimei\nFROM internal_platform_db.t_sh_event_log_v2_06000061157_prestosql_002\nWHERE ds = '2026060919'\n AND ((ad_version = 'ad_attribution' AND attribution = 'true')\n OR (ad_version = 'phonebrandh' AND callback != ''))\nGROUP BY ds, ad_version", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_002_en"} {"task_id": "prestosql_003", "id": "offline-compute_PrestoSQL_prestosql_003", "name": "IM平台Q群离线报告子分区过滤", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**任务目标**:从IM平台Q群离线报告原始日志中,筛选指定appid下包含\"诈骗\"标签的记录,提取关键字段写入输出表。\n\n**输入表**:\n- `internal_platform_db.dwd_t_event_log_v1_05900072467_with_subpartition_hi_prestosql_003`(IM平台Q群离线报告原始日志)\n - `databus_imp_date` STRING — 数据日期\n - `ftime` STRING — 时间\n - `appid` STRING — 应用ID\n - `message_id` STRING — 消息ID\n - `reqbody` STRING — 请求体(JSON)\n - `content` STRING — 内容\n - `model_id` STRING — 模型ID\n - `group_num` STRING — 群号\n - `punish_path_name` STRING — 处罚路径名称\n - `ext_field1` STRING — 扩展字段1\n - `ext_field2` STRING — 扩展字段2\n - `ds` BIGINT — 分区字段\n\n**过滤条件**:\n- `appid = '100553'`\n- `reqbody IS NOT NULL`\n- `get_json_object(reqbody, '$.tag_info') IS NOT NULL`\n- `get_json_object(reqbody, '$.tag_info.tag_result_text') LIKE '%诈骗-%'`\n- `ftime = '20250324'`\n\n**输出要求**:\n- 目标表: `internal_platform_db.dwd_qqgroup_offline_report_cand_prestosql_003`\n- 输出字段及顺序: `ftime` STRING, `appid` STRING, `model_id` STRING, `message_id` STRING, `databus_imp_date` STRING, `group_num` STRING, `punish_path_name` STRING, `content` STRING\n- appid 固定值 '101069'\n- model_id 固定值 'IM平台Qgroup_zhapian_report_1049'\n- 如果目标表不存在,请先建表再写入数据\n- 请使用Presto/Trino SQL语法,不要使用Hive/Spark SQL方言\n- 注意:Presto中使用json_extract_scalar代替get_json_object\n\n**环境与执行说明**:\n- Presto已启动,通过Hive catalog连接\n- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- 写出result.sql后,必须自己执行验证它能成功运行并产出正确数据", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.dwd_qqgroup_offline_report_prestosql_003\nSELECT\n ftime,\n '101069' AS appid,\n 'IM平台Qgroup_zhapian_report_1049' AS model_id,\n message_id,\n databus_imp_date,\n group_num,\n punish_path_name,\n content\nFROM internal_platform_db.dwd_t_event_log_v1_05900072467_with_subpartition_hi_prestosql_003\nWHERE appid = '100553'\n AND reqbody IS NOT NULL\n AND get_json_object(reqbody, '$.tag_info') IS NOT NULL\n AND get_json_object(reqbody, '$.tag_info.tag_result_text') LIKE '%诈骗-%'\n AND ftime = '20250324'", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_003"} {"task_id": "prestosql_004", "id": "offline-compute_PrestoSQL_prestosql_004", "name": "小说UDS算法书籍关系筛选", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**任务目标**:从小说UDS算法书籍关系表中,筛选指定事件类型的记录,根据事件类型映射为操作类型,提取关键字段写入输出表。\n\n**输入表**:\n- `internal_platform_db.t_oh_novel_uds_algorithm_book_rel_prestosql_004`(小说UDS算法书籍关系表)\n - `ftime` STRING — 时间\n - `event_code` STRING — 事件编码\n - `book_id` STRING — 书籍ID\n - `guid` STRING — 用户标识\n - `reqid` STRING — 请求ID\n - `traceid` STRING — 追踪ID\n - `report_time` STRING — 上报时间\n - `ds` BIGINT — 分区字段\n\n**过滤条件**:\n- `ds = 2026060906`\n- `length(book_id) = 10`\n- `event_code IN ('expose', 'click', 'real_read', 'add_0', 'add_1', 'shelf_add', 'share', 'comment', 'like')`\n\n**输出要求**:\n- 目标表: `internal_platform_db.t_od_novel_user_action_detail_cand_prestosql_004`\n- 输出字段及顺序: `reqid` STRING, `guid` STRING, `bookid` STRING, `traceid` STRING, `action` STRING, `ftime` STRING, `report_time` STRING\n- action: CASE event_code WHEN 'expose' THEN 'expose' WHEN 'click' THEN 'click' WHEN 'real_read' THEN 'real_read' WHEN 'add_0' THEN 'add_0' WHEN 'add_1' THEN 'add_1' ELSE event_code END\n- bookid: book_id\n- traceid: substr(traceid, 1, 4)\n- 如果目标表不存在,请先建表再写入数据\n- 请使用Presto/Trino SQL语法,不要使用Hive/Spark SQL方言\n\n**环境与执行说明**:\n- Presto已启动,通过Hive catalog连接\n- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- 写出result.sql后,必须自己执行验证它能成功运行并产出正确数据", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.t_od_novel_user_action_detail_prestosql_004\nSELECT\n reqid,\n guid,\n book_id AS bookid,\n substr(traceid, 1, 4) AS traceid,\n CASE event_code\n WHEN 'expose' THEN 'expose'\n WHEN 'click' THEN 'click'\n WHEN 'real_read' THEN 'real_read'\n WHEN 'add_0' THEN 'add_0'\n WHEN 'add_1' THEN 'add_1'\n ELSE event_code\n END AS action,\n ftime,\n report_time\nFROM internal_platform_db.t_oh_novel_uds_algorithm_book_rel_prestosql_004\nWHERE ds = 2026060906\n AND length(book_id) = 10\n AND event_code IN ('expose', 'click', 'real_read', 'add_0', 'add_1', 'shelf_add', 'share', 'comment', 'like')", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_004"} {"task_id": "prestosql_005_en", "id": "offline-compute_PrestoSQL_prestosql_005", "name": "Hot Table Governance Metadata Wide Table Aggregation", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**Task Objective**: From the hot table governance metadata detail table, filter valid hot table records (heat > 0, excluding temporary/test tables), aggregate by database name and table name to take the maximum of each metric, and write the results to the output table.\n\n**Input Table**:\n- `internal_platform_db.ads_gov_cost_table_govern_detail_df_prestosql_005` (hot table governance metadata detail table)\n - `imp_date` BIGINT — date partition\n - `db_name` STRING — database name\n - `table_name` STRING — table name\n - `heat` BIGINT — heat\n - `owner` STRING — owner\n - `storage_detail` DOUBLE — storage detail\n - `task_cnt` BIGINT — task count\n - `table_type` STRING — table type\n - `govern_status` STRING — governance status\n - `last_access_time` STRING — last access time\n - `table_comment` STRING — table comment\n - `partition_cnt` BIGINT — partition count\n - `file_format` STRING — file format\n - `table_size` DOUBLE — table size\n - `avg_file_size` DOUBLE — average file size\n - `is_partitioned` INT — whether partitioned\n - `lifecycle_days` INT — lifecycle days\n - `create_time` STRING — creation time\n - `modify_time` STRING — modification time\n - `project_name` STRING — project name\n\n**Filter Conditions**:\n- `imp_date = 20260507`\n- `heat > 0`\n- `table_name NOT LIKE '%temp%'`\n- `db_name NOT LIKE '%test%'`\n\n**Output Requirements**:\n- Target table: `internal_platform_db.dwd_hot_metadata_table_cand_prestosql_005`\n- Output fields and order: `dt` STRING, `db_name` STRING, `table_name` STRING, `owner` STRING, `storage_detail` DOUBLE, `heat` BIGINT, `task_cnt` BIGINT, `table_type` STRING, `govern_status` STRING, `last_access_time` STRING, `table_comment` STRING, `partition_cnt` BIGINT, `file_format` STRING, `table_size` DOUBLE, `avg_file_size` DOUBLE, `is_partitioned` INT, `lifecycle_days` INT, `create_time` STRING, `modify_time` STRING, `project_name` STRING\n- `dt`: Fixed value `'20260507'`\n- Group by `db_name`, `table_name`, apply `MAX()` to all other fields\n- If the target table does not exist, first create the table, then write the data\n- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Presto is running, connected via the Hive catalog\n- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.dwd_hot_metadata_table_prestosql_005\nSELECT\n '20260507' AS dt,\n db_name,\n table_name,\n MAX(owner) AS owner,\n MAX(storage_detail) AS storage_detail,\n MAX(heat) AS heat,\n MAX(task_cnt) AS task_cnt,\n MAX(table_type) AS table_type,\n MAX(govern_status) AS govern_status,\n MAX(last_access_time) AS last_access_time,\n MAX(table_comment) AS table_comment,\n MAX(partition_cnt) AS partition_cnt,\n MAX(file_format) AS file_format,\n MAX(table_size) AS table_size,\n MAX(avg_file_size) AS avg_file_size,\n MAX(is_partitioned) AS is_partitioned,\n MAX(lifecycle_days) AS lifecycle_days,\n MAX(create_time) AS create_time,\n MAX(modify_time) AS modify_time,\n MAX(project_name) AS project_name\nFROM internal_platform_db.ads_gov_cost_table_govern_detail_df_prestosql_005\nWHERE imp_date = 20260507\n AND heat > 0\n AND table_name NOT LIKE '%temp%'\n AND db_name NOT LIKE '%test%'\nGROUP BY db_name, table_name", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_005_en"} {"task_id": "prestosql_006_en", "id": "offline-compute_PrestoSQL_prestosql_006", "name": "News Plugin Send Process Multi-Dimensional Aggregation", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**Task Objective**: From the news plugin send process flow table, aggregate and compute metrics such as send count, send UV, panel exposure count, panel exposure UV, inner-page PV, and inner-page UV by the scene (`pos_desc`) dimension, across two time windows — current day and last 1 hour — and write the results to the output table.\n\n**Input Table**:\n- `internal_platform_db.dwm_news_plugin_ai_assistant_send_process_flow_hi_prestosql_006` (news plugin send process flow table)\n - `imp_hour` BIGINT — hourly partition\n - `user_id` STRING — user ID\n - `content_id` STRING — content ID\n - `push_id` STRING — push ID\n - `pos` STRING — position\n - `send_cnt` BIGINT — send count\n - `panel_exp_cnt` BIGINT — panel exposure count\n - `pgin_pv` BIGINT — inner-page PV\n - `pos_desc` STRING — position description (scene)\n - `account_code` STRING — business code\n\n**Output Requirements**:\n- Target table: `internal_platform_db.ads_news_plugin_ai_assistant_hourly_report_cand_prestosql_006`\n- Output fields and order:\n - `imp_hour` BIGINT — hourly partition\n - `scene` STRING — scene (`pos_desc`)\n - `send_cnt_dth` BIGINT — current day send count (`SUM(send_cnt) WHERE imp_hour <= current hour`)\n - `send_uv_dth` BIGINT — current day send UV (`COUNT(DISTINCT user_id) WHERE imp_hour <= current hour`)\n - `panel_exp_cnt_dth` BIGINT — current day panel exposure count (`SUM(panel_exp_cnt) WHERE imp_hour <= current hour`)\n - `panel_exp_uv_dth` BIGINT — current day panel exposure UV (`COUNT(DISTINCT user_id) WHERE panel_exp_cnt > 0 AND imp_hour <= current hour`)\n - `pgin_pv_dth` BIGINT — current day inner-page PV (`SUM(pgin_pv) WHERE imp_hour <= current hour`)\n - `pgin_uv_dth` BIGINT — current day inner-page UV (`COUNT(DISTINCT user_id) WHERE pgin_pv > 0 AND imp_hour <= current hour`)\n - `send_cnt_1h` BIGINT — last 1 hour send count (`SUM(send_cnt) WHERE imp_hour = current hour`)\n - `send_uv_1h` BIGINT — last 1 hour send UV\n - `panel_exp_cnt_1h` BIGINT — last 1 hour panel exposure count\n - `panel_exp_uv_1h` BIGINT — last 1 hour panel exposure UV\n - `pgin_pv_1h` BIGINT — last 1 hour inner-page PV\n - `pgin_uv_1h` BIGINT — last 1 hour inner-page UV\n\n- Simplified explanation: For each `imp_hour` + `pos_desc` combination, compute the current day cumulative (dth) and current hour (1h) aggregation metrics\n- If the target table does not exist, first create the table, then write the data\n- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Presto is running, connected via the Hive catalog\n- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.ads_news_plugin_ai_assistant_hourly_report_prestosql_006\nSELECT\n h.imp_hour,\n h.pos_desc AS scene,\n h.send_cnt_dth,\n h.send_uv_dth,\n h.panel_exp_cnt_dth,\n h.panel_exp_uv_dth,\n h.pgin_pv_dth,\n h.pgin_uv_dth,\n h.send_cnt_1h,\n h.send_uv_1h,\n h.panel_exp_cnt_1h,\n h.panel_exp_uv_1h,\n h.pgin_pv_1h,\n h.pgin_uv_1h\nFROM (\n SELECT\n t1.imp_hour,\n t1.pos_desc,\n t1.send_cnt AS send_cnt_dth,\n t1.send_uv AS send_uv_dth,\n t1.panel_exp_cnt AS panel_exp_cnt_dth,\n t1.panel_exp_uv AS panel_exp_uv_dth,\n t1.pgin_pv AS pgin_pv_dth,\n t1.pgin_uv AS pgin_uv_dth,\n t2.send_cnt AS send_cnt_1h,\n t2.send_uv AS send_uv_1h,\n t2.panel_exp_cnt AS panel_exp_cnt_1h,\n t2.panel_exp_uv AS panel_exp_uv_1h,\n t2.pgin_pv AS pgin_pv_1h,\n t2.pgin_uv AS pgin_uv_1h\n FROM (\n SELECT\n a.imp_hour,\n a.pos_desc,\n SUM(b.send_cnt) AS send_cnt,\n COUNT(DISTINCT b.user_id) AS send_uv,\n SUM(b.panel_exp_cnt) AS panel_exp_cnt,\n COUNT(DISTINCT CASE WHEN b.panel_exp_cnt > 0 THEN b.user_id END) AS panel_exp_uv,\n SUM(b.pgin_pv) AS pgin_pv,\n COUNT(DISTINCT CASE WHEN b.pgin_pv > 0 THEN b.user_id END) AS pgin_uv\n FROM (SELECT DISTINCT imp_hour, pos_desc FROM internal_platform_db.dwm_news_plugin_ai_assistant_send_process_flow_hi_prestosql_006) a\n JOIN internal_platform_db.dwm_news_plugin_ai_assistant_send_process_flow_hi_prestosql_006 b\n ON a.pos_desc = b.pos_desc AND b.imp_hour <= a.imp_hour\n GROUP BY a.imp_hour, a.pos_desc\n ) t1\n JOIN (\n SELECT\n imp_hour,\n pos_desc,\n SUM(send_cnt) AS send_cnt,\n COUNT(DISTINCT user_id) AS send_uv,\n SUM(panel_exp_cnt) AS panel_exp_cnt,\n COUNT(DISTINCT CASE WHEN panel_exp_cnt > 0 THEN user_id END) AS panel_exp_uv,\n SUM(pgin_pv) AS pgin_pv,\n COUNT(DISTINCT CASE WHEN pgin_pv > 0 THEN user_id END) AS pgin_uv\n FROM internal_platform_db.dwm_news_plugin_ai_assistant_send_process_flow_hi_prestosql_006\n GROUP BY imp_hour, pos_desc\n ) t2 ON t1.imp_hour = t2.imp_hour AND t1.pos_desc = t2.pos_desc\n) h", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_006_en"} {"task_id": "prestosql_007_en", "id": "offline-compute_PrestoSQL_prestosql_007", "name": "APK Threat Scan Instance GPU Card-Hour 5-Minute Window Statistics", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**Task Objective**: Compute the GPU card-hour consumption of APK scan instances, aggregated by 5-minute time windows, joining with Pod mapping and task instance GPU configuration information, and write the results to the output table.\n\n**Input Tables**:\n- `internal_platform_db.t_gpu_monitor_parsed_prestosql_007` (GPU monitoring data table)\n - `container` STRING — container name\n - `pod_name` STRING — Pod name\n - `pkg_time` STRING — reporting time (epoch second string)\n - `gpu_name` STRING — GPU model\n - `metric` STRING — metric name\n - `value` STRING — metric value\n - `dt` STRING — partition field (format `'2026060800'`)\n\n- `internal_platform_db.dwd_scan_instance_podname_prestosql_007` (Pod-to-scan-instance mapping table)\n - `dt` STRING — partition field\n - `instance_uuid` STRING — instance unique identifier\n - `pod_name` STRING — Pod name\n - `pod_phase` STRING — Pod phase\n - `namespace` STRING — namespace\n\n- `internal_platform_db.dwd_scan_task_instance_prestosql_007` (task instance GPU configuration table 1)\n - `databus_imp_date` STRING — partition field\n - `instance_uuid` STRING — instance unique identifier\n - `host_gpu_num` DOUBLE — host GPU card count\n - `host_num` DOUBLE — host count\n - `last_modify` DOUBLE — last modification timestamp\n - `gpu_name` STRING — GPU model\n\n- `internal_platform_db.scan_task_instance_prestosql_007` (scan task instance GPU configuration table 2)\n - `databus_imp_date` STRING — partition field\n - `instance_uuid` STRING — instance unique identifier\n - `host_gpu_num` DOUBLE — host GPU card count\n - `host_num` DOUBLE — host count\n - `last_modify` DOUBLE — last modification timestamp\n - `gpu_name` STRING — GPU model\n - `scan_type` STRING — scan type\n\n**Computation Logic**:\n1. Filter specified metrics from the GPU monitoring data, and compute runtime per Pod in 5-minute time windows\n2. Join with the Pod-to-instance mapping to aggregate the GPU runtime and Pod count per instance per 5-minute window\n3. Retrieve the latest GPU configuration information for each task instance\n4. Compute the GPU card-hours (GPU-hour) per instance per 5-minute window\n5. The specific time window bucketing method, join conditions, aggregation logic, and GPU-hour computation formula must be determined based on the table structures and business semantics\n\n**Output Requirements**:\n- Target table: `internal_platform_db.t_scan_instance_gpu_time_stats_cand_prestosql_007`\n- Output fields and order: `instance_uuid` STRING, `time_5min` BIGINT, `host_gpu_num` DOUBLE, `sum_run_time_m` DOUBLE, `gpu_hour` DOUBLE, `gpu_name` STRING, `pod_count` BIGINT, `host_num` DOUBLE\n- If the target table does not exist, first create the table, then write the data\n- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Presto is running, connected via the Hive catalog\n- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data", "ground_truth": "INSERT INTO internal_platform_db.t_scan_instance_gpu_time_stats_prestosql_007\nWITH\n-- Step 1: From GPU monitoring data, extract pod run records with minute-level dedup\npod_run_minutes AS (\n SELECT\n pod_name,\n gpu_name,\n FLOOR(CAST(pkg_time AS BIGINT) / 60) * 60 AS minute_timestamp,\n FLOOR(CAST(pkg_time AS BIGINT) / 300) * 300 AS time_5min\n FROM internal_platform_db.t_gpu_monitor_parsed_prestosql_007\n WHERE dt = '2026060800'\n AND metric IN ('k8s_container_vgpu_gpu_mem_usage', 'k8s_dcgm_fi_dev_fb_util')\n GROUP BY pod_name, gpu_name, FLOOR(CAST(pkg_time AS BIGINT) / 60) * 60, FLOOR(CAST(pkg_time AS BIGINT) / 300) * 300\n),\n\n-- Step 2: Aggregate run minutes per pod per 5-minute window\npod_run_time AS (\n SELECT\n pod_name,\n MAX(gpu_name) AS gpu_name,\n time_5min,\n CAST(COUNT(DISTINCT minute_timestamp) AS DOUBLE) AS run_time_m\n FROM pod_run_minutes\n GROUP BY pod_name, time_5min\n),\n\n-- Step 3: Join pod-to-instance mapping, aggregate per instance per window\ninstance_run_time AS (\n SELECT\n p.time_5min,\n m.instance_uuid,\n MAX(p.gpu_name) AS gpu_name,\n CAST(SUM(p.run_time_m) AS DOUBLE) AS sum_run_time_m,\n COUNT(DISTINCT m.pod_name) AS pod_count\n FROM pod_run_time p\n INNER JOIN internal_platform_db.dwd_scan_instance_podname_prestosql_007 m\n ON p.pod_name = m.pod_name\n AND m.dt = '2026060800'\n GROUP BY p.time_5min, m.instance_uuid\n),\n\n-- Step 4: Get latest GPU config per instance from dual-table UNION ALL + ROW_NUMBER dedup\nlatest_task_config AS (\n SELECT\n instance_uuid,\n CAST(host_gpu_num AS DOUBLE) AS host_gpu_num,\n CAST(host_num AS DOUBLE) AS host_num,\n gpu_name\n FROM (\n SELECT\n instance_uuid,\n host_gpu_num,\n host_num,\n gpu_name,\n last_modify,\n ROW_NUMBER() OVER (PARTITION BY instance_uuid ORDER BY last_modify DESC) AS rn\n FROM (\n SELECT\n instance_uuid,\n host_gpu_num,\n host_num,\n gpu_name,\n last_modify\n FROM internal_platform_db.dwd_scan_task_instance_prestosql_007\n WHERE databus_imp_date = (\n SELECT MAX(databus_imp_date)\n FROM internal_platform_db.dwd_scan_task_instance_prestosql_007\n )\n\n UNION ALL\n\n SELECT\n instance_uuid,\n host_gpu_num,\n host_num,\n gpu_name,\n last_modify\n FROM internal_platform_db.scan_task_instance_prestosql_007\n WHERE databus_imp_date = (\n SELECT MAX(databus_imp_date)\n FROM internal_platform_db.scan_task_instance_prestosql_007\n )\n ) combined\n ) ranked\n WHERE rn = 1\n)\n\n-- Step 5: Join instance run time with GPU config, compute GPU-hour\nSELECT\n i.instance_uuid,\n i.time_5min,\n t.host_gpu_num,\n i.sum_run_time_m,\n CASE\n WHEN t.host_gpu_num IS NOT NULL AND i.sum_run_time_m IS NOT NULL\n THEN t.host_gpu_num * i.sum_run_time_m / 60.0\n ELSE NULL\n END AS gpu_hour,\n i.gpu_name,\n i.pod_count,\n t.host_num\nFROM instance_run_time i\nLEFT JOIN latest_task_config t\n ON i.instance_uuid = t.instance_uuid\n;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_007_en"} {"task_id": "prestosql_008_en", "id": "offline-compute_PrestoSQL_prestosql_008", "name": "Report WUID Detail Filtering", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**Task Objective**: From the ad report WUID detail wide table, filter target ad delivery records based on multi-dimensional filter conditions, extract key fields, and write the results to the output table.\n\n**Input Table**:\n- `internal_platform_db.t_report_wuid_detail_d_prestosql_008` (report WUID detail table)\n - `wuid` STRING — user identifier\n - `product_id` STRING — product ID\n - `adgroup_id` BIGINT — ad group ID\n - `action_time` BIGINT — action time\n - `crm_id` BIGINT — CRM ID\n - `creative_id` BIGINT — creative ID\n - `ocpx_conversion_cnt` BIGINT — oCpx conversion count\n - `optimization_goal` INT — optimization goal\n - `second_optimization_goal` INT — second-level optimization goal\n - `roi_goal` INT — ROI goal\n - `product_type` INT — product type\n - `site_set` INT — site set\n - `crm_advertiser_industry_id` BIGINT — CRM advertiser industry ID\n - `label` INT — label\n - `partition_time` BIGINT — partition time\n - `ds` BIGINT — partition field\n\n**Filter Conditions**:\n- `partition_time = 20260608`\n- `ocpx_conversion_cnt = 0`\n- `optimization_goal IN (105, 603)`\n- `second_optimization_goal = 0`\n- `roi_goal = 7`\n- `product_type = 46`\n- `site_set = 21`\n- `product_id IS NOT NULL`\n- `crm_advertiser_industry_id != 0`\n- `creative_id != 0`\n\n**Output Requirements**:\n- Target table: `internal_platform_db.sdk_sample_pay_neg_mini_cand_prestosql_008`\n- Output fields and order: `wuid` STRING, `product_id` STRING, `adgroup_id` BIGINT, `action_time` BIGINT, `crm_id` BIGINT, `creative_id` BIGINT, `label` INT, `product_type` INT, `optimization_goal` INT, `roi_goal` INT, `partition_time` BIGINT\n- If the target table does not exist, first create the table, then write the data\n- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Presto is running, connected via the Hive catalog\n- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.sdk_sample_pay_neg_mini_prestosql_008\nSELECT\n wuid,\n product_id,\n adgroup_id,\n action_time,\n crm_id,\n creative_id,\n label,\n product_type,\n optimization_goal,\n roi_goal,\n partition_time\nFROM internal_platform_db.t_report_wuid_detail_d_prestosql_008\nWHERE partition_time = 20260608\n AND ocpx_conversion_cnt = 0\n AND optimization_goal IN (105, 603)\n AND second_optimization_goal = 0\n AND roi_goal = 7\n AND product_type = 46\n AND site_set = 21\n AND product_id IS NOT NULL\n AND crm_advertiser_industry_id != 0\n AND creative_id != 0", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_008_en"} {"task_id": "prestosql_009", "id": "offline-compute_PrestoSQL_prestosql_009", "name": "Data Pipeline Killed Instance Analysis", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nJoin pipeline span info and resource info tables to produce killed instance detail table. Specific filtering conditions and field selection need to be determined based on table structure.\n\n**输入表**:\n- `internal_platform_db.t_pipeline_span_info_prestosql_009`(Pipeline span信息表)\n - `databus_imp_date` STRING — 日期分区\n - `trace_id` STRING — 链路标识\n - `span_name` STRING — span名称\n - `start_time` STRING — 开始时间(epoch毫秒)\n - `end_time` STRING — 结束时间(epoch毫秒)\n - `status_code` INT — 状态码\n - `project_id` STRING — 项目ID\n - `task_id` STRING — 任务ID\n - `compute_type` STRING — 计算类型\n\n- `internal_platform_db.t_pipeline_resource_info_prestosql_009`(Pipeline资源信息表)\n - `databus_imp_date` STRING — 日期分区\n - `trace_id` STRING — 链路标识\n - `compute_type` STRING — 计算类型\n - `resource_id` STRING — 资源ID\n - `is_dedicated` STRING — 是否独占\n - `cpu_cores` INT — CPU核数\n\n**输出要求**:\n- 目标表: `internal_platform_db.t_pipeline_killed_instance_detail_cand_prestosql_009`\n- 具体过滤条件、字段选择、计算逻辑需根据表结构和数据特征自行分析确定\n- 如果目标表不存在,请先建表再写入数据\n- 请使用Presto/Trino SQL语法,不要使用Hive/Spark SQL方言\n\n**环境与执行说明**:\n- Presto已启动,通过Hive catalog连接\n- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- 写出result.sql后,必须自己执行验证它能成功运行并产出正确数据", "ground_truth": "INSERT INTO internal_platform_db.t_pipeline_killed_instance_detail_prestosql_009\nWITH base_trace AS (\n SELECT trace_id\n FROM internal_platform_db.t_pipeline_span_info_prestosql_009\n WHERE databus_imp_date = '20260608'\n AND span_name IN ('pipeline.execute', 'pipeline.killed')\n GROUP BY trace_id\n HAVING\n COUNT(CASE WHEN span_name = 'pipeline.killed' THEN 1 END) > 0\n AND\n COUNT(CASE WHEN span_name = 'pipeline.execute' THEN 1 END) = 0\n),\ncombined_spans AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n project_id,\n task_id,\n compute_type,\n status_code\n FROM internal_platform_db.t_pipeline_span_info_prestosql_009\n WHERE databus_imp_date = '20260608'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('pipeline.killed', 'pipeline.start', 'task.run', 'task.compile', 'resource.request')\n\n UNION ALL\n\n SELECT\n trace_id,\n 'pipeline.execute' AS span_name,\n MAX(CASE WHEN span_name = 'pipeline.start' THEN start_time END) AS start_time,\n MAX(CASE WHEN span_name = 'pipeline.killed' THEN end_time END) AS end_time,\n MAX(CASE WHEN span_name = 'pipeline.killed' THEN project_id END) AS project_id,\n MAX(CASE WHEN span_name = 'pipeline.killed' THEN task_id END) AS task_id,\n MAX(CASE WHEN span_name = 'pipeline.killed' THEN compute_type END) AS compute_type,\n 2 AS status_code\n FROM internal_platform_db.t_pipeline_span_info_prestosql_009\n WHERE databus_imp_date = '20260608'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('pipeline.start', 'pipeline.killed')\n GROUP BY trace_id\n),\nbase_data_time_fixed AS (\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'pipeline.killed'\n THEN MIN(CASE WHEN span_name IN ('task.run', 'pipeline.killed') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n end_time,\n project_id,\n task_id,\n compute_type,\n status_code\n FROM combined_spans\n),\nbase_data AS (\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n project_id,\n task_id,\n compute_type,\n status_code,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) AS start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) AS end_date,\n date_diff('day', CAST(from_unixtime(CAST(start_time AS BIGINT) / 1000) AS TIMESTAMP), CAST(from_unixtime(CAST(end_time AS BIGINT) / 1000) AS TIMESTAMP)) AS diff_days\n FROM base_data_time_fixed\n),\npos_series AS (\n SELECT 0 AS pos UNION ALL SELECT 1 AS pos UNION ALL SELECT 2 AS pos UNION ALL SELECT 3 AS pos\n),\ndaily_split_spans AS (\n SELECT\n trace_id,\n span_name,\n project_id,\n task_id,\n compute_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n CAST(date_add('day', s.pos, CAST(b.start_date AS TIMESTAMP)) AS VARCHAR) AS calc_date,\n CASE WHEN s.pos = 0 THEN b.start_time\n ELSE CAST(CAST(to_unixtime(CAST(date_add('day', s.pos, CAST(b.start_date AS TIMESTAMP)) AS TIMESTAMP)) AS BIGINT) * 1000 AS VARCHAR)\n END AS start_time,\n CASE WHEN s.pos = b.diff_days THEN b.end_time\n ELSE CAST(CAST(to_unixtime(CAST(date_add('day', s.pos + 1, CAST(b.start_date AS TIMESTAMP)) AS TIMESTAMP)) AS BIGINT) * 1000 - 1 AS VARCHAR)\n END AS end_time,\n b.start_time AS span_start_time,\n b.end_time AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\ntrace_time_metrics AS (\n SELECT\n trace_id,\n calc_date,\n MAX(project_id) AS project_id,\n MAX(task_id) AS task_id,\n MAX(compute_type) AS compute_type,\n MAX(MAX(CASE WHEN span_name = 'pipeline.execute' THEN status_code END)) OVER(PARTITION BY trace_id) AS status_code,\n CAST(ROUND((MAX(CASE WHEN span_name = 'pipeline.execute' THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name = 'pipeline.execute' THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS INT) AS instance_run_time,\n CAST(ROUND((MAX(CASE WHEN span_name IN ('task.run', 'task.compile', 'pipeline.killed') THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name IN ('task.run', 'task.compile', 'pipeline.killed') THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS INT) AS code_run_time,\n CAST(ROUND((MAX(CASE WHEN span_name = 'resource.request' THEN CAST(end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name = 'resource.request' THEN CAST(start_time AS BIGINT) END)) / 1000.0) AS INT) AS resource_wait_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n)\nSELECT\n t1.calc_date AS p_date,\n t1.trace_id,\n t1.project_id,\n t1.task_id,\n t1.compute_type,\n t1.status_code,\n t1.instance_run_time,\n t1.code_run_time,\n t1.resource_wait_time,\n t2.resource_id,\n CAST(t2.is_dedicated AS BOOLEAN) AS is_dedicated\nFROM trace_time_metrics t1 LEFT JOIN (\n SELECT\n trace_id,\n MAX(resource_id) AS resource_id,\n MAX(is_dedicated) AS is_dedicated\n FROM internal_platform_db.t_pipeline_resource_info_prestosql_009\n WHERE databus_imp_date = '20260608'\n GROUP BY trace_id\n) t2 ON t1.trace_id = t2.trace_id\n;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_009"} {"task_id": "prestosql_010", "id": "offline-compute_PrestoSQL_prestosql_010", "name": "IOC MTTD指标计算", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**任务目标**:从API指标表和威胁情报IOC表中,通过JSON解析提取IOC值,与IOC表关联计算MTTD(平均检测时间)指标,写入输出表。\n\n**输入表**:\n- `internal_platform_db.t_app_ti_entity_api_metrics_prod_hi_prestosql_010`(API指标表)\n - `timestamp` BIGINT — 时间戳\n - `username` STRING — 用户名\n - `appid` BIGINT — 应用ID\n - `path` STRING — 路径\n - `request` STRING — 请求体(JSON)\n - `response` STRING — 响应体\n - `ds` BIGINT — 分区字段\n\n- `internal_platform_db.t_sh_threat_intel_lab_breakingti_soc_endpoint_security_format_output_prod_prestosql_010`(威胁情报IOC表)\n - `ioctype` STRING — IOC类型\n - `ioc` STRING — IOC值\n - `port` STRING — 端口\n - `producer` STRING — 生产者\n - `stamp` STRING — 时间戳\n - `category` STRING — 分类\n - `family` STRING — 家族\n - `apt_org` STRING — APT组织\n - `weapon` STRING — 武器\n - `usefor` STRING — 用途\n - `ttps` STRING — TTPs\n - `confidence` INT — 置信度\n - `context` STRING — 上下文\n - `intelligence_investigation` STRING — 情报调查\n - `match_subdomains` INT — 匹配子域名\n - `bdelete` INT — 删除标记\n - `deleted_time` STRING — 删除时间\n - `first_occur_time` STRING — 首次出现时间\n - `last_occur_time` STRING — 最后出现时间\n - `ds` BIGINT — 分区字段\n\n**计算逻辑**:\n1. 从API指标表提取: json_extract_scalar(request, '$.entity_value') AS ioc_value, 按ioc_value分组取MIN(timestamp) AS earliest_timestamp, 过滤ds=20260608\n2. 从IOC表过滤: ioctype='DOMAIN' AND bdelete=0, 过滤ds=20260608\n3. JOIN条件: ioc = ioc_value\n4. time_diff_days = GREATEST(0, (unix_timestamp(first_occur_time) - earliest_timestamp) / 86400.0)\n\n**输出要求**:\n- 目标表: `internal_platform_db.t_app_breaking_ti_mttd_metric_cand_prestosql_010`\n- 输出字段及顺序: `IOC` STRING, `IOCTYPE` STRING, `PORT` STRING, `first_occur_time` STRING, `earliest_timestamp` BIGINT, `family` STRING, `match_subdomains` INT, `time_diff_days` DOUBLE, `ds` BIGINT\n- ds: 固定值 20260608\n- 注意Presto中用json_extract_scalar代替get_json_object,用to_unixtime代替unix_timestamp(需配合FROM_UNIXTIME相关的转换)\n- 如果目标表不存在,请先建表再写入数据\n- 请使用Presto/Trino SQL语法,不要使用Hive/Spark SQL方言\n\n**环境与执行说明**:\n- Presto已启动,通过Hive catalog连接\n- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- 写出result.sql后,必须自己执行验证它能成功运行并产出正确数据", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.t_app_breaking_ti_mttd_metric_prestosql_010\nWITH api_metrics AS (\n SELECT\n get_json_object(request, '$.entity_value') AS ioc_value,\n MIN(`timestamp`) AS earliest_timestamp\n FROM internal_platform_db.t_app_ti_entity_api_metrics_prod_hi_prestosql_010\n WHERE ds = 20260608\n GROUP BY get_json_object(request, '$.entity_value')\n),\nfiltered_main AS (\n SELECT *\n FROM internal_platform_db.t_sh_threat_intel_lab_breakingti_soc_endpoint_security_format_output_prod_prestosql_010\n WHERE ioctype = 'DOMAIN' AND bdelete = 0 AND ds = 20260608\n)\nSELECT\n f.ioc AS IOC,\n f.ioctype AS IOCTYPE,\n f.port AS PORT,\n f.first_occur_time,\n a.earliest_timestamp,\n f.family,\n f.match_subdomains,\n GREATEST(0, (unix_timestamp(f.first_occur_time) - a.earliest_timestamp) / 86400.0) AS time_diff_days,\n 20260608 AS ds\nFROM filtered_main f\nJOIN api_metrics a ON f.ioc = a.ioc_value", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_010"} {"task_id": "prestosql_011", "id": "offline-compute_PrestoSQL_prestosql_011", "name": "安全平台PG敏感接口2表UNION+聚合", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**任务目标**:将两个安全平台PG敏感接口数据表合并,排除黑名单域名后,按日期、域名和接口路径聚合,将匹配规则名拼接为逗号分隔字符串,写入输出表。\n\n**输入表**:(2个表结构相同)\n- `internal_platform_db.internal_sec_radept_secpg_data_result2_prestosql_011`\n- `internal_platform_db.internal_sec_radept_secpg_data_result4_prestosql_011`\n\n各表字段:\n - `databus_imp_date` INT — 数据日期\n - `insert_time` STRING — 插入时间\n - `src_ip` STRING — 源IP\n - `employeename` STRING — 员工名\n - `http_host` STRING — 域名\n - `http_cgi` STRING — 接口路径\n - `http_param` STRING — 请求参数\n - `http_user_agent` STRING — 用户代理\n - `http_referer` STRING — 来源\n - `http_body` STRING — 请求体\n - `http_head` STRING — 请求头\n - `httpsrsp_body` STRING — 响应体\n - `httpsrsp_content_length` STRING — 响应内容长度\n - `https_method` STRING — HTTPS方法\n - `scan_group` STRING — 扫描组\n - `rule_name` STRING — 规则名\n - `match_string` STRING — 匹配字符串\n - `match_type` STRING — 匹配类型\n - `scan_comment` STRING — 扫描备注\n\n**过滤条件**:\n- `databus_imp_date = 20260608`\n- `http_host NOT IN ('api.im-platform.example.com', 'mp.im-platform.example.com', 'open.im-platform.example.com', 'wx.im.example.com', 'wx2.im.example.com', 'wx8.im.example.com', 'web.im-platform.example.com', 'login.im-platform.example.com', 'long.open.im-platform.example.com', 'ext.im.example.com', 'proxy.svc.example.com', 'resolver.svc.example.com', 'cloud.provider.example.com', 'console.cloud.provider.example.com', 'csec.cloud.provider.example.com')`\n\n**输出要求**:\n- 目标表: `internal_platform_db.secpg_sensitive_interface_cand_prestosql_011`\n- 输出字段及顺序: `databus_imp_date` INT, `http_host` STRING, `http_cgi` STRING, `con_con` STRING\n- con_con: listagg(rule_name, ',') 或 array_join(array_agg(DISTINCT rule_name), ',') 聚合规则名\n- 按 databus_imp_date, http_host, http_cgi 分组\n- 如果目标表不存在,请先建表再写入数据\n- 请使用Presto/Trino SQL语法,不要使用Hive/Spark SQL方言\n\n**环境与执行说明**:\n- Presto已启动,通过Hive catalog连接\n- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- 写出result.sql后,必须自己执行验证它能成功运行并产出正确数据", "ground_truth": "INSERT OVERWRITE TABLE internal_platform_db.secpg_sensitive_interface_prestosql_011\nSELECT\n databus_imp_date,\n http_host,\n http_cgi,\n concat_ws(',', collect_set(rule_name)) AS con_con\nFROM (\n SELECT databus_imp_date, http_host, http_cgi, rule_name\n FROM internal_platform_db.internal_sec_radept_secpg_data_result2_prestosql_011\n WHERE databus_imp_date = 20260608\n AND http_host NOT IN ('api.im-platform.example.com', 'mp.im-platform.example.com', 'open.im-platform.example.com', 'wx.im.example.com', 'wx2.im.example.com', 'wx8.im.example.com', 'web.im-platform.example.com', 'login.im-platform.example.com', 'long.open.im-platform.example.com', 'ext.im.example.com', 'proxy.svc.example.com', 'resolver.svc.example.com', 'cloud.provider.example.com', 'console.cloud.provider.example.com', 'csec.cloud.provider.example.com')\n UNION ALL\n SELECT databus_imp_date, http_host, http_cgi, rule_name\n FROM internal_platform_db.internal_sec_radept_secpg_data_result4_prestosql_011\n WHERE databus_imp_date = 20260608\n AND http_host NOT IN ('api.im-platform.example.com', 'mp.im-platform.example.com', 'open.im-platform.example.com', 'wx.im.example.com', 'wx2.im.example.com', 'wx8.im.example.com', 'web.im-platform.example.com', 'login.im-platform.example.com', 'long.open.im-platform.example.com', 'ext.im.example.com', 'proxy.svc.example.com', 'resolver.svc.example.com', 'cloud.provider.example.com', 'console.cloud.provider.example.com', 'csec.cloud.provider.example.com')\n) combined\nGROUP BY databus_imp_date, http_host, http_cgi", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_011"} {"task_id": "prestosql_012_en", "id": "offline-compute_PrestoSQL_prestosql_012", "name": "Data Quality Check Pipeline Instance GPU Card-Hour Analysis", "workload": "offline-compute", "engine": "PrestoSQL", "category": "offline-compute/PrestoSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n**Task Objective**: Analyze the runtime of data quality check pipeline instances. For some abnormally terminated instances, their completion records need to be backfilled. Compute the runtime duration of each instance per date shard, and combined with GPU monitoring data, compute the GPU card-hour consumption, ultimately outputting a detail table.\n\n**Business Background**:\nThe data quality check pipeline produces various span records, including check.start, check.completed, check.aborted, data.scan, rule.evaluate, resource.allocate, etc. Some instances only record check.aborted without check.completed. For these instances, a synthetic check.completed record must be constructed based on their start and aborted times to correctly compute the runtime duration.\n\nGPU monitoring data is collected in 5-minute windows and must be mapped to instances via Pod names. Combined with the GPU count from the task configuration, the card-hours are computed (gpu_hour = host_gpu_num * total_run_minutes / 60.0).\n\n**Input Tables**:\n- `internal_platform_db.t_quality_check_span_prestosql_012` (quality check span table)\n - `databus_imp_date` STRING — data date\n - `trace_id` STRING — trace ID\n - `span_name` STRING — span name\n - `start_time` STRING — start time (epoch milliseconds)\n - `end_time` STRING — end time (epoch milliseconds)\n - `status_code` INT — status code\n - `project_id` STRING — project ID\n - `task_id` STRING — task ID\n - `check_type` STRING — check type\n\n- `internal_platform_db.t_quality_gpu_monitor_prestosql_012` (GPU monitoring table)\n - `pod_name` STRING — Pod name\n - `pkg_time` STRING — collection time (epoch seconds)\n - `gpu_name` STRING — GPU model\n - `metric` STRING — monitoring metric\n - `value` STRING — metric value\n - `dt` STRING — date partition\n\n- `internal_platform_db.dwd_quality_podname_prestosql_012` (Pod-to-instance mapping table)\n - `dt` STRING — date partition\n - `instance_uuid` STRING — instance UUID\n - `pod_name` STRING — Pod name\n - `pod_phase` STRING — Pod phase\n\n- `internal_platform_db.dwd_quality_task_config_prestosql_012` (task GPU configuration table 1)\n - `databus_imp_date` STRING — data date\n - `instance_uuid` STRING — instance UUID\n - `host_gpu_num` DOUBLE — GPU count\n - `host_num` DOUBLE — host count\n - `last_modify` DOUBLE — last modification time\n - `gpu_name` STRING — GPU model\n - `resource_id` STRING — resource ID\n - `is_dedicated` STRING — whether dedicated\n\n- `internal_platform_db.quality_task_config_prestosql_012` (task GPU configuration table 2)\n - `databus_imp_date` STRING — data date\n - `instance_uuid` STRING — instance UUID\n - `host_gpu_num` DOUBLE — GPU count\n - `host_num` DOUBLE — host count\n - `last_modify` DOUBLE — last modification time\n - `gpu_name` STRING — GPU model\n - `resource_id` STRING — resource ID\n - `is_dedicated` STRING — whether dedicated\n - `scan_type` STRING — scan type\n\n**Key Logic Notes**:\n1. Identify trace_ids that have only check.aborted without check.completed, and synthesize a check.completed record for them\n2. Spans running across days must be split by day, generating one record per day\n3. GPU monitoring data must be deduplicated by 5-minute windows to compute running minutes, and mapped to instances via Pod mapping\n4. The two GPU configuration tables must be combined with UNION ALL, then use ROW_NUMBER to take the latest configuration per instance\n5. gpu_hour = host_gpu_num * total_run_minutes / 60.0\n\n**Output Requirements**:\n- Target table: `internal_platform_db.t_quality_check_gpu_instance_detail_cand_prestosql_012`\n- Output fields: `p_date` STRING, `trace_id` STRING, `project_id` STRING, `task_id` STRING, `check_type` STRING, `status_code` INT, `instance_run_time` INT, `code_run_time` INT, `gpu_hour` DOUBLE, `resource_id` STRING, `is_dedicated` BOOLEAN\n- If the target table does not exist, first create the table, then write the data\n- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects\n\n**Environment and Execution Notes**:\n- Presto is running, connected via the Hive catalog\n- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`\n- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data", "ground_truth": "INSERT INTO internal_platform_db.t_quality_check_gpu_instance_detail_prestosql_012\nWITH base_trace AS (\n -- Step 1: Find trace_ids with check.aborted but NOT check.completed (HAVING inverted condition)\n SELECT trace_id\n FROM internal_platform_db.t_quality_check_span_prestosql_012\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n AND span_name IN ('check.aborted', 'check.completed')\n GROUP BY trace_id\n HAVING COUNT(CASE WHEN span_name = 'check.aborted' THEN 1 END) > 0\n AND COUNT(CASE WHEN span_name = 'check.completed' THEN 1 END) = 0\n),\ncombined_spans AS (\n -- Step 2: All original spans for ALL traces + synthetic check.completed for aborted-only traces\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n status_code,\n project_id,\n task_id,\n check_type\n FROM internal_platform_db.t_quality_check_span_prestosql_012\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n AND span_name IN ('check.aborted', 'check.start', 'check.completed', 'data.scan', 'rule.evaluate', 'resource.allocate')\n\n UNION ALL\n\n SELECT\n trace_id,\n 'check.completed' AS span_name,\n MAX(CASE WHEN span_name = 'check.start' THEN start_time END) AS start_time,\n MAX(CASE WHEN span_name = 'check.aborted' THEN end_time END) AS end_time,\n 2 AS status_code,\n MAX(CASE WHEN span_name = 'check.aborted' THEN project_id END) AS project_id,\n MAX(CASE WHEN span_name = 'check.aborted' THEN task_id END) AS task_id,\n MAX(CASE WHEN span_name = 'check.aborted' THEN check_type END) AS check_type\n FROM internal_platform_db.t_quality_check_span_prestosql_012\n WHERE databus_imp_date >= '2026060600'\n AND databus_imp_date <= '2026060800'\n AND trace_id IN (SELECT trace_id FROM base_trace)\n AND span_name IN ('check.start', 'check.aborted')\n GROUP BY trace_id\n),\nbase_data_time_fixed AS (\n -- Step 3: Fix check.aborted start_time -> earliest of code-related spans\n SELECT\n trace_id,\n span_name,\n CASE\n WHEN span_name = 'check.aborted'\n THEN MIN(CASE WHEN span_name IN ('data.scan', 'rule.evaluate', 'check.aborted') THEN start_time END)\n OVER(PARTITION BY trace_id)\n ELSE start_time\n END AS start_time,\n end_time,\n status_code,\n project_id,\n task_id,\n check_type\n FROM combined_spans\n),\nbase_data AS (\n -- Step 4: Convert timestamps, compute diff_days for cross-day splitting\n SELECT\n trace_id,\n span_name,\n start_time,\n end_time,\n status_code,\n project_id,\n task_id,\n check_type,\n from_unixtime(CAST(start_time AS BIGINT) / 1000) AS start_date,\n from_unixtime(CAST(end_time AS BIGINT) / 1000) AS end_date,\n date_diff('day', from_unixtime(CAST(start_time AS BIGINT) / 1000),\n from_unixtime(CAST(end_time AS BIGINT) / 1000)) AS diff_days,\n CAST(CAST(start_time AS BIGINT) / 86400000 AS BIGINT) * 86400000 AS start_day_midnight_ms\n FROM base_data_time_fixed\n),\npos_series AS (\n -- Step 5: Position series for cross-day expansion\n SELECT 0 AS pos UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3\n),\ndaily_split_spans AS (\n -- Step 6: INNER JOIN with pos_series, compute boundary timestamps per day\n SELECT\n trace_id,\n span_name,\n project_id,\n task_id,\n check_type,\n status_code,\n start_date,\n end_date,\n diff_days,\n date_add('day', s.pos, start_date) AS calc_date,\n CASE WHEN s.pos = 0 THEN start_time\n ELSE CAST(start_day_midnight_ms + s.pos * 86400000 AS VARCHAR)\n END AS split_start_time,\n CASE WHEN s.pos = diff_days THEN end_time\n ELSE CAST(start_day_midnight_ms + (s.pos + 1) * 86400000 - 1 AS VARCHAR)\n END AS split_end_time,\n start_time AS span_start_time,\n end_time AS span_end_time\n FROM base_data b\n INNER JOIN pos_series s ON s.pos <= b.diff_days\n),\nspan_metrics AS (\n -- Step 7: GROUP BY trace_id, calc_date -> compute instance_run_time, code_run_time, status_code\n SELECT\n trace_id,\n calc_date,\n MAX(project_id) AS project_id,\n MAX(task_id) AS task_id,\n MAX(check_type) AS check_type,\n MAX(MAX(CASE WHEN span_name = 'check.completed' THEN status_code END))\n OVER(PARTITION BY trace_id) AS status_code,\n CAST(ROUND(\n (MAX(CASE WHEN span_name = 'check.completed' THEN CAST(split_end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name = 'check.completed' THEN CAST(split_start_time AS BIGINT) END)) / 1000.0\n ) AS INT) AS instance_run_time,\n CAST(ROUND(\n (MAX(CASE WHEN span_name IN ('data.scan', 'rule.evaluate', 'check.aborted') THEN CAST(split_end_time AS BIGINT) END) -\n MIN(CASE WHEN span_name IN ('data.scan', 'rule.evaluate', 'check.aborted') THEN CAST(split_start_time AS BIGINT) END)) / 1000.0\n ) AS INT) AS code_run_time\n FROM daily_split_spans\n GROUP BY trace_id, calc_date\n),\ngpu_stats AS (\n -- Step 8: FLOOR 5-min window bucketing + pod mapping + ROW_NUMBER config dedup + gpu_hour\n SELECT\n ig.instance_uuid,\n lc.host_gpu_num * ig.total_run_time_m / 60.0 AS gpu_hour,\n ig.gpu_name,\n lc.resource_id,\n CASE WHEN lc.is_dedicated = 'true' THEN true ELSE false END AS is_dedicated\n FROM (\n -- Aggregate GPU run time per instance\n SELECT\n m.instance_uuid,\n MAX(p.gpu_name) AS gpu_name,\n SUM(p.run_time_m) AS total_run_time_m\n FROM (\n -- pod_run_time: count distinct minutes per (pod_name, time_5min)\n SELECT\n pod_name,\n MAX(gpu_name) AS gpu_name,\n time_5min,\n CAST(COUNT(DISTINCT minute_timestamp) AS DOUBLE) AS run_time_m\n FROM (\n -- pod_run_minutes: FLOOR bucketing dedup\n SELECT\n pod_name,\n gpu_name,\n FLOOR(CAST(pkg_time AS BIGINT) / 60) * 60 AS minute_timestamp,\n FLOOR(CAST(pkg_time AS BIGINT) / 300) * 300 AS time_5min\n FROM internal_platform_db.t_quality_gpu_monitor_prestosql_012\n WHERE metric IN ('k8s_container_vgpu_gpu_mem_usage', 'k8s_dcgm_fi_dev_fb_util')\n GROUP BY pod_name, gpu_name,\n FLOOR(CAST(pkg_time AS BIGINT) / 60) * 60,\n FLOOR(CAST(pkg_time AS BIGINT) / 300) * 300\n ) pod_run_minutes\n GROUP BY pod_name, time_5min\n ) p\n INNER JOIN internal_platform_db.dwd_quality_podname_prestosql_012 m\n ON p.pod_name = m.pod_name\n GROUP BY m.instance_uuid\n ) ig\n LEFT JOIN (\n -- latest_task_config: ROW_NUMBER dedup from UNION ALL of two config tables\n SELECT\n instance_uuid,\n host_gpu_num,\n resource_id,\n is_dedicated\n FROM (\n SELECT\n instance_uuid,\n host_gpu_num,\n resource_id,\n is_dedicated,\n ROW_NUMBER() OVER (PARTITION BY instance_uuid ORDER BY last_modify DESC) AS rn\n FROM (\n SELECT instance_uuid, host_gpu_num, last_modify, resource_id, is_dedicated\n FROM internal_platform_db.dwd_quality_task_config_prestosql_012\n WHERE databus_imp_date = (\n SELECT MAX(databus_imp_date)\n FROM internal_platform_db.dwd_quality_task_config_prestosql_012\n )\n UNION ALL\n SELECT instance_uuid, host_gpu_num, last_modify, resource_id, is_dedicated\n FROM internal_platform_db.quality_task_config_prestosql_012\n WHERE databus_imp_date = (\n SELECT MAX(databus_imp_date)\n FROM internal_platform_db.quality_task_config_prestosql_012\n )\n ) combined\n ) ranked\n WHERE rn = 1\n ) lc ON ig.instance_uuid = lc.instance_uuid\n)\n-- Final: JOIN span_metrics with gpu_stats\nSELECT\n date_format(sm.calc_date, '%Y-%m-%d') AS p_date,\n sm.trace_id,\n sm.project_id,\n sm.task_id,\n sm.check_type,\n sm.status_code,\n sm.instance_run_time,\n sm.code_run_time,\n gs.gpu_hour,\n gs.resource_id,\n gs.is_dedicated\nFROM span_metrics sm\nLEFT JOIN gpu_stats gs ON sm.trace_id = gs.instance_uuid\n;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PrestoSQL/prestosql_012_en"} {"task_id": "pyspark_001", "id": "offline-compute_PySpark_pyspark_001", "name": "被动客服满意度归因环比对比", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,产出\"被动客服会话满意度归因因素\"的环比对比表。\n\n**业务背景与目标**:被动客服每天都会按 reason / reason_detail / session_type 维度产出一份满意度归因明细(dwd_ww_kf_session_satify_attrib)。运营希望对每一条归因因素同时做两个维度的对比:(1) 与 14 天前同一 reason+reason_detail+session_type 的指标做差值;(2) 与上月相同类型日期(工作日 vs 工作日、周末 vs 周末)的平均指标做差值。本任务把当天、14 天前、上月这三组数据拉齐后,逐条计算满意度差值、占比差值、贡献率,输出到下游对比表里供运营复盘。\n\n**输入表**:\n- `internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_v3`\n\n**数据范围与过滤条件(业务说法)**:\n- 运行日期 statdate 固定为 '20260513'(沙箱化日期,原任务由调度框架传入)。\n- 14 天前日期 = statdate - 14 天 = '20260429'。\n- 上月相同类型日期:根据 statdate 的工作日/周末属性,从上一个自然月里取出所有同类型日期组成日期列表(例如 statdate 是周三,则取上月所有工作日);用该列表 IN 过滤主表得到\"上月同类型样本\"。\n- 三组切片都从同一张明细表过滤得到,分别注册成临时视图 today / 14d / month_avg。\n\n**表关联关系**:\n- left join:当天视图 t0 ⋈ 14 天前视图 t1 on (t0.reason=t1.reason AND t0.reason_detail=t1.reason_detail AND t0.session_type=t1.session_type) → df_compare_14d。\n- left join:当天视图 t0 ⋈ 上月平均视图 t1 on 同上 → df_compare_month。\n- df_compare_14d 与 df_compare_month 通过 union all 拼接成 df_all 一次性写入。\n\n**聚合与计算规则(需体现在 SQL/PySpark 中)**:\n1. **上月平均聚合**:对上月切片,先按 session_type 计算月级总量 `all_month_session_cnt = sum(all_session_cnt)` 和加权满意度 `all_month_session_score = sum(all_session_satify_score*all_session_cnt) / sum(all_session_cnt)`;再按 (session_type, reason, reason_detail) 聚合,得到月度 satify_score = sum(session_cnt*satify_score)/sum(session_cnt)、session_rate = sum(session_cnt)/all_month_session_cnt、satify_attrib = (sum(session_cnt*satify_score*session_rate/100)/sum(session_cnt))/all_month_session_score - 1。\n2. **派生差值字段**(每条 reason+reason_detail+session_type 行同时计算 14 天对比和上月对比两组):\n - all_session_satify_diff = t0.all_session_satify_score - t1.all_session_satify_score\n - satify_score_diff = t0.satify_score - t1.satify_score\n - session_rate_diff = t0.session_rate - t1.session_rate\n - satify_attrib_diff = (t0.satify_score*t0.session_rate - t1.satify_score*t1.session_rate) / 100\n - satify_attrib_rate = satify_attrib_diff / all_session_satify_diff(贡献率)\n - self_satify_attrib_rate = (t0.satify_score*t0.session_rate) / (t1.satify_score*t1.session_rate) - 1(自身环比)\n - compare_satify_attrib_diff = t0.satify_attrib - t1.satify_attrib\n3. **compare_interval 字段**:14 天对比那批固定写 '14天前';上月对比那批固定写 '上月'。\n4. **输出 imp_date** 全部填当天 statdate '20260513'。\n\n**输出要求**:\n- 目标表:`internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_compare_v3`\n- 写入策略:INSERT OVERWRITE TABLE,使用显式列名清单(22 列)避免列序错位。\n- 如果目标表不存在,请先按 Hive 标准建表(ORC 存储),再写入数据。", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\ncaseR1: 被动客服满意度归因 - 14天/上月对比 (SparkBase -> SparkSession 改写)\n- 沙箱无分区版:原 part_name=last14day / part_name=part_names 改成 WHERE imp_date='...' / WHERE imp_date IN (...)\n- 原 self.statdate 硬编码为 '20260513'(沙箱化日期)\n- 原 self.save_dw_data 改为 spark.sql INSERT OVERWRITE TABLE\n\"\"\"\n\nimport datetime\nfrom pyspark.sql import SparkSession\n\nspark = (\n SparkSession.builder\n .appName('caseR1_satify_attrib_compare')\n .enableHiveSupport()\n .getOrCreate()\n)\n\n# 沙箱化运行日期(fixture 模板硬编码)\nstatdate = '20260513'\n\n# ---------------------------- 14 天前 ----------------------------\nlast14day = (datetime.datetime.strptime(statdate, \"%Y%m%d\") - datetime.timedelta(days=14)).strftime(\"%Y%m%d\")\nprint(statdate, last14day)\n\n# 当天视图\nspark.sql(\"\"\"\nSELECT * FROM internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_v3\nWHERE imp_date = '{0}'\n\"\"\".format(statdate)).createOrReplaceTempView(\"dwd_ww_kf_session_satify_attrib_today\")\n\n# 14 天前视图\nspark.sql(\"\"\"\nSELECT * FROM internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_v3\nWHERE imp_date = '{0}'\n\"\"\".format(last14day)).createOrReplaceTempView(\"dwd_ww_kf_session_satify_attrib_14d\")\n\nsql_14d = \"\"\"\nSELECT\n \"{0}\" AS imp_date\n ,'14天前' AS compare_interval\n ,t0.reason\n ,t0.reason_detail\n ,CAST(t0.session_cnt AS DOUBLE) AS session_cnt\n ,t0.satify_score\n ,t0.session_rate\n ,t0.all_session_satify_score\n ,t0.satify_attrib\n ,t1.all_session_satify_score AS compare_all_session_satify_score\n ,t1.satify_score AS compare_satify_score\n ,t1.session_rate AS compare_session_rate\n ,t0.all_session_satify_score - t1.all_session_satify_score AS all_session_satify_diff\n ,t0.satify_score - t1.satify_score AS satify_score_diff\n ,t0.session_rate - t1.session_rate AS session_rate_diff\n ,(t0.satify_score*t0.session_rate - t1.satify_score*t1.session_rate)/100 AS satify_attrib_diff\n ,((t0.satify_score*t0.session_rate - t1.satify_score*t1.session_rate)/100)/(t0.all_session_satify_score - t1.all_session_satify_score) AS satify_attrib_rate\n ,(t0.satify_score*t0.session_rate)/(t1.satify_score*t1.session_rate) - 1 AS self_satify_attrib_rate\n ,CAST(t1.session_cnt AS DOUBLE) AS compare_session_cnt\n ,t1.satify_attrib AS compare_satify_attrib\n ,t0.satify_attrib - t1.satify_attrib AS compare_satify_attrib_diff\n ,t0.session_type\nFROM dwd_ww_kf_session_satify_attrib_today t0\nLEFT JOIN dwd_ww_kf_session_satify_attrib_14d t1\n ON t0.reason = t1.reason AND t0.reason_detail = t1.reason_detail AND t0.session_type = t1.session_type\n\"\"\".format(statdate)\ndf_compare_14d = spark.sql(sql_14d).cache()\n\n# ---------------------------- 上月对比 ----------------------------\n# 纯 datetime 实现 lastmonth_firstday,避免依赖 dateutil\n_today = datetime.datetime.strptime(statdate, \"%Y%m%d\")\n_thismonth_first = _today.replace(day=1)\n# 上月第 1 天 = 本月第 1 天 - 1 天 → 取该日期所在月的第 1 天\n_lastmonth_anchor = _thismonth_first - datetime.timedelta(days=1)\nlastmonth_firstday = _lastmonth_anchor.replace(day=1).strftime(\"%Y%m%d\")\nthismonth_firstday = statdate[0:6] + \"01\"\ninterval = (datetime.datetime.strptime(thismonth_firstday, \"%Y%m%d\")\n - datetime.datetime.strptime(lastmonth_firstday, \"%Y%m%d\"))\n\nweekday_list = []\nholiday_list = []\nfor i in range(interval.days):\n date = (datetime.datetime.strptime(lastmonth_firstday, \"%Y%m%d\")\n + datetime.timedelta(days=i)).strftime(\"%Y%m%d\")\n week_flag = datetime.datetime.strptime(date, \"%Y%m%d\").weekday()\n if week_flag in (0, 1, 2, 3, 4):\n weekday_list.append(date)\n else:\n holiday_list.append(date)\n\ntoday_week = datetime.datetime.strptime(statdate, \"%Y%m%d\").weekday()\npart_names = weekday_list if today_week in (0, 1, 2, 3, 4) else holiday_list\n\n# 上月对应类型日期视图(多分区联合)\nin_clause = \",\".join([\"'%s'\" % d for d in part_names])\nspark.sql(\"\"\"\nSELECT * FROM internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_v3\nWHERE imp_date IN ({0})\n\"\"\".format(in_clause)).createOrReplaceTempView(\"dwd_ww_kf_session_satify_attrib_lastmonth\")\n\n# 上月统计\nspark.sql(\"\"\"\nSELECT\n session_type\n ,count(distinct imp_date) AS date_cnt\n ,sum(all_session_cnt) AS all_month_session_cnt\n ,sum(all_session_satify_score*all_session_cnt)/sum(all_session_cnt) AS all_month_session_score\nFROM (\n SELECT DISTINCT imp_date,session_type,all_session_satify_score,all_session_cnt\n FROM dwd_ww_kf_session_satify_attrib_lastmonth\n)\nGROUP BY session_type\n\"\"\").createOrReplaceTempView(\"lastmonth_stat\")\n\n# 每类因素的上月平均\nspark.sql(\"\"\"\nSELECT\n t0.session_type\n ,reason\n ,reason_detail\n ,all_month_session_cnt\n ,all_month_session_score AS all_session_satify_score\n ,sum_session_cnt\n ,sum_session_cnt/date_cnt session_cnt\n ,satify_score\n ,sum_session_cnt*100/all_month_session_cnt AS session_rate\n ,(satify_score - all_month_session_score)*(sum_session_cnt/all_month_session_cnt) AS satify_attrib\nFROM (\n SELECT\n session_type\n ,reason\n ,reason_detail\n ,sum(session_cnt) sum_session_cnt\n ,sum(session_cnt*satify_score)/sum(session_cnt) AS satify_score\n FROM dwd_ww_kf_session_satify_attrib_lastmonth\n GROUP BY session_type,reason,reason_detail\n) t0\nLEFT JOIN lastmonth_stat t1 ON t0.session_type = t1.session_type\n\"\"\").createOrReplaceTempView(\"month_avg_stat\")\n\nsql_month = \"\"\"\nSELECT\n \"{0}\" AS imp_date\n ,'上月' AS compare_interval\n ,t0.reason\n ,t0.reason_detail\n ,CAST(t0.session_cnt AS DOUBLE) AS session_cnt\n ,t0.satify_score\n ,t0.session_rate\n ,t0.all_session_satify_score\n ,t0.satify_attrib\n ,t1.all_session_satify_score AS compare_all_session_satify_score\n ,t1.satify_score AS compare_satify_score\n ,t1.session_rate AS compare_session_rate\n ,t0.all_session_satify_score - t1.all_session_satify_score AS all_session_satify_diff\n ,t0.satify_score - t1.satify_score AS satify_score_diff\n ,t0.session_rate - t1.session_rate AS session_rate_diff\n ,(t0.satify_score*t0.session_rate - t1.satify_score*t1.session_rate)/100 AS satify_attrib_diff\n ,((t0.satify_score*t0.session_rate - t1.satify_score*t1.session_rate)/100)/(t0.all_session_satify_score - t1.all_session_satify_score) AS satify_attrib_rate\n ,(t0.satify_score*t0.session_rate)/(t1.satify_score*t1.session_rate) - 1 AS self_satify_attrib_rate\n ,CAST(t1.session_cnt AS DOUBLE) AS compare_session_cnt\n ,t1.satify_attrib AS compare_satify_attrib\n ,t0.satify_attrib - t1.satify_attrib AS compare_satify_attrib_diff\n ,t0.session_type\nFROM dwd_ww_kf_session_satify_attrib_today t0\nLEFT JOIN month_avg_stat t1\n ON t0.reason = t1.reason AND t0.reason_detail = t1.reason_detail AND t0.session_type = t1.session_type\n\"\"\".format(statdate)\ndf_compare_month = spark.sql(sql_month).cache()\n\ndf_all = df_compare_month.union(df_compare_14d)\ndf_all.createOrReplaceTempView(\"df_all_view\")\n\n# 确保输出表以正确 schema 存在(agent 可能未建表或建了错误 schema)\nspark.sql(\"DROP TABLE IF EXISTS internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_compare_v3\")\nspark.sql('''\nCREATE TABLE internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_compare_v3 (\n `compare_interval` STRING,\n `reason` STRING,\n `reason_detail` STRING,\n `session_cnt` DOUBLE,\n `satify_score` DOUBLE,\n `session_rate` DOUBLE,\n `all_session_satify_score` DOUBLE,\n `satify_attrib` DOUBLE,\n `compare_all_session_satify_score` DOUBLE,\n `compare_satify_score` DOUBLE,\n `compare_session_rate` DOUBLE,\n `all_session_satify_diff` DOUBLE,\n `satify_score_diff` DOUBLE,\n `session_rate_diff` DOUBLE,\n `satify_attrib_diff` DOUBLE,\n `satify_attrib_rate` DOUBLE,\n `self_satify_attrib_rate` DOUBLE,\n `compare_session_cnt` DOUBLE,\n `compare_satify_attrib` DOUBLE,\n `compare_satify_attrib_diff` DOUBLE,\n `session_type` BIGINT,\n `imp_date` STRING\n) STORED AS ORC\n''')\n\n# 落地:DDL 列序 (compare_interval, reason, ..., session_type, imp_date)\nspark.sql(\"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.caseR1_dwd_ww_kf_session_satify_attrib_compare_v3\n(\n compare_interval, reason, reason_detail, session_cnt, satify_score, session_rate,\n all_session_satify_score, satify_attrib, compare_all_session_satify_score,\n compare_satify_score, compare_session_rate, all_session_satify_diff, satify_score_diff,\n session_rate_diff, satify_attrib_diff, satify_attrib_rate, self_satify_attrib_rate,\n compare_session_cnt, compare_satify_attrib, compare_satify_attrib_diff, session_type, imp_date\n)\nSELECT\n compare_interval, reason, reason_detail, session_cnt, satify_score, session_rate,\n all_session_satify_score, satify_attrib, compare_all_session_satify_score,\n compare_satify_score, compare_session_rate, all_session_satify_diff, satify_score_diff,\n session_rate_diff, satify_attrib_diff, satify_attrib_rate, self_satify_attrib_rate,\n compare_session_cnt, compare_satify_attrib, compare_satify_attrib_diff, session_type, imp_date\nFROM df_all_view\n\"\"\")\n\nprint(\"caseR1 done\")", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_001"} {"task_id": "pyspark_002", "id": "offline-compute_PySpark_pyspark_002", "name": "代码review的note diff按天同步到DWV层", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,按天把代码评审场景下\"代码 note 的 diff 文件明细\"从 ODS 层同步到 DWV 层。\n\n**业务背景与目标**:上游 databus 每天会落一份当天产生的 note diff 明细到 ods 表(每行 = 一条 note 评论 + 它附带的 diff 文本)。下游 DWV 层希望按 year/month/day 三级日期分区组织,方便日期回溯,且要对一天内出现的重复行(同一个 note id 配同一段 diff 文本)做去重。\n\n**输入表**:\n- `internal_platform_db.case5_ods_code_v2_note_diff_files_diff_v3`\n\n**数据范围与过滤条件(业务说法)**:\n- 只取业务日期等于本次运行日期 ds 的数据。\n- ds 固定为 '20260513'(沙箱化日期,原任务通过 sys.argv[1] 传入;TaskType=63 不传命令行参数,所以硬编码避免 IndexError)。\n\n**表关联关系**:\n(无 Join,单表抽取。)\n\n**聚合与计算规则(需体现在 SQL 中)**:\n- 直接 SELECT id, diff 两列,并做 DISTINCT 去重(同一天内同 id 同 diff 只保留一条)。\n- 在 SELECT 头部追加三列分区字段,由 ds 拆分得到:year='2026'、month='05'、day='13'。\n- 使用 INSERT OVERWRITE TABLE 全表覆盖写入。\n\n**输出要求**:\n- 目标表:`internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3`\n- 输出表 schema(按此顺序写入,类型与业务含义如下):\n 1. year STRING:年,原为分区列\n 2. month STRING:月,原为分区列\n 3. day STRING:日,原为分区列\n 4. id BIGINT:note id\n 5. diff STRING:diff 文本内容\n- 写入策略:INSERT OVERWRITE 全表覆盖,本次写入 year='2026', month='05', day='13'。\n- 沙箱化说明:原任务在生产环境写 PARTITION(year, month, day) 分区表;沙箱版三列分区列已沙箱化为普通列。\n- 如果目标表不存在,请先按 Hive 标准建表(ORC 存储),再写入数据。", "ground_truth": "#!/usr/bin/env bash\nfrom __future__ import print_function\n\nimport re\nimport sys\nimport os\nimport json\n\nimport datetime\n\nfrom pyspark.sql import SparkSession\n\nif __name__ == \"__main__\":\n\n print('PythonSQL start')\n #yyyyMMdd\n ds = '20260513' # was: sys.argv[1]\n match = re.match(r\"([\\d]{4})([\\d]{2})([\\d]{2})\", ds)\n daySub = match.group(1, 2, 3)\n\n ds_year = daySub[0]\n ds_month = daySub[1]\n ds_day = daySub[2]\n\n last_day = datetime.datetime(\n int(daySub[0]), int(daySub[1]), int(daySub[2]))\n last_day_str = last_day.strftime('%Y%m%d')\n\n print('last_day_str=%s' % last_day_str)\n print('ds_year=%s' % ds_year)\n print('ds_month=%s' % ds_month)\n print('ds_day=%s' % ds_day)\n\n spark = SparkSession.builder.appName('case5_dwv_code_v2_note_diff_files_diff_d_f').enableHiveSupport().getOrCreate()\n\n # 确保输出表以正确 schema 存在(agent 可能未建表或建了错误 schema)\n spark.sql(\"DROP TABLE IF EXISTS internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3\")\n spark.sql('''\nCREATE TABLE internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3 (\n `year` STRING COMMENT '年,原为分区列',\n `month` STRING COMMENT '月,原为分区列',\n `day` STRING COMMENT '日,原为分区列',\n `id` BIGINT COMMENT '-',\n `diff` STRING COMMENT '-'\n) STORED AS ORC\n''')\n\n sql = '''\n insert overwrite table internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3\n SELECT\n DISTINCT\n '$year' AS year, '$month' AS month, '$day' AS day, id ,diff\n FROM internal_platform_db.case5_ods_code_v2_note_diff_files_diff_v3 where databus_imp_date='$ds'\n '''\n\n sql = sql.replace('$ds', last_day_str)\n sql = sql.replace('$year', ds_year)\n sql = sql.replace('$month', ds_month)\n sql = sql.replace('$day', ds_day)\n\n print(sql)\n result = spark.sql(sql)\n print(result.show())\n spark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_002"} {"task_id": "pyspark_003_en", "id": "offline-compute_PySpark_pyspark_003", "name": "Sync Code Review review-diff from ODS to DWV Layer by Day", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that synchronizes the \"code review diff file details\" from the ODS layer to the DWV layer by day for the code review scenario.\n\n**Business Background and Objective**: The upstream databus produces a daily review diff detail (one row = one review comment + corresponding diff text) that lands in the ODS table. The downstream DWV layer wants to organize the data with a three-level date partition (year/month/day) for convenient date-based retrieval, and to deduplicate rows with the same id and diff within the same day. This task has the same structure as case5 (note diff), except the source/target tables are the review series.\n\n**Input Table**:\n- `internal_platform_db.case6_ods_code_v2_review_diff_files_diff_v3`\n\n**Data Range and Filter Conditions (business description)**:\n - Only take data where the business date equals the current run date `ds`.\n - `ds` is fixed as `'20260513'` (sandboxed date; the original task passes this via `sys.argv[1]`; TaskType=63 does not pass command-line arguments, so it is hardcoded to avoid IndexError).\n\n**Table Join Relationships**: (No joins, single-table extraction.)\n\n**Aggregation and Computation Rules (must be reflected in the SQL)**:\n - Directly SELECT `id`, `diff` columns, and apply `DISTINCT` deduplication (only one row is retained for the same id and diff within the same day).\n - Prepend three partition columns at the beginning of the SELECT, derived by splitting `ds`: `year='2026'`, `month='05'`, `day='13'`.\n - Use `INSERT OVERWRITE TABLE` to overwrite the entire table.\n\n**Output Requirements**:\n - Target table: `internal_platform_db.case6_dwv_code_v2_review_diff_files_diff_v3`\n - Output table schema (write in this order, types and business semantics as follows):\n 1. `year` STRING: year, originally a partition column\n 2. `month` STRING: month, originally a partition column\n 3. `day` STRING: day, originally a partition column\n 4. `id` BIGINT: review id\n 5. `diff` STRING: diff text content\n - Write strategy: `INSERT OVERWRITE` full table overwrite, this write targets `year='2026'`, `month='05'`, `day='13'`.\n - Sandbox note: The original task writes to a `PARTITION(year, month, day)` partitioned table in production; in the sandbox version, the three partition columns have been sandboxed as regular columns.\n - If the target table does not exist, first create it using standard Hive format (ORC storage), then write the data.", "ground_truth": "# data-mocker rewrite-gt\n# source: pyspark_0428_desensitized.jsonl idx=43924\n# task_name: dwv_code_v2_review_diff_files_diff_d_f\n# rewrite rules:\n# 1) dept_t_yg_code.ods_code_v2_review_diff_files_diff_d_f\n# -> internal_platform_db.case6_ods_code_v2_review_diff_files_diff_v3\n# 2) code.dwv_code_v2_review_diff_files_diff_d_f\n# -> internal_platform_db.case6_dwv_code_v2_review_diff_files_diff_v3\n# 3) INSERT OVERWRITE TABLE ... PARTITION(year=...,month=...,day=...) SELECT id,diff\n# -> INSERT OVERWRITE TABLE ... SELECT '$year' AS year, '$month' AS month, '$day' AS day, id, diff\n# (沙箱用无分区表,分区列改为普通列)\n# 4) sys.argv[1] -> 硬编码 '20260513'\n# (datawd PySpark TaskType=63 不直传命令行参数,硬编码避免 IndexError)\n# ---\n#!/usr/bin/env bash\nfrom __future__ import print_function\n\nimport re\nimport sys\nimport os\nimport json\n\nimport datetime\n\nfrom pyspark.sql import SparkSession\n\nif __name__ == \"__main__\":\n\n print('PythonSQL start')\n #yyyyMMdd\n ds = '20260513' # was: sys.argv[1]\n match = re.match(r\"([\\d]{4})([\\d]{2})([\\d]{2})\", ds)\n daySub = match.group(1, 2, 3)\n\n ds_year = daySub[0]\n ds_month = daySub[1]\n ds_day = daySub[2]\n\n last_day = datetime.datetime(\n int(daySub[0]), int(daySub[1]), int(daySub[2]))\n last_day_str = last_day.strftime('%Y%m%d')\n\n print('last_day_str=%s' % last_day_str)\n print('ds_year=%s' % ds_year)\n print('ds_month=%s' % ds_month)\n print('ds_day=%s' % ds_day)\n\n spark = SparkSession.builder.appName('case6_dwv_code_v2_review_diff_files_diff_d_f').enableHiveSupport().getOrCreate()\n\n # 确保输出表以正确 schema 存在(agent 可能未建表或建了错误 schema)\n spark.sql(\"DROP TABLE IF EXISTS internal_platform_db.case6_dwv_code_v2_review_diff_files_diff_v3\")\n spark.sql('''\nCREATE TABLE internal_platform_db.case6_dwv_code_v2_review_diff_files_diff_v3 (\n `year` STRING COMMENT '年,原为分区列',\n `month` STRING COMMENT '月,原为分区列',\n `day` STRING COMMENT '日,原为分区列',\n `id` BIGINT COMMENT '-',\n `diff` STRING COMMENT '-'\n) STORED AS ORC\n''')\n\n sql = '''\n insert overwrite table internal_platform_db.case6_dwv_code_v2_review_diff_files_diff_v3\n SELECT\n DISTINCT\n '$year' AS year, '$month' AS month, '$day' AS day, id ,diff \n FROM internal_platform_db.case6_ods_code_v2_review_diff_files_diff_v3 where databus_imp_date='$ds'\n '''\n\n sql = sql.replace('$ds', last_day_str)\n sql = sql.replace('$year', ds_year)\n sql = sql.replace('$month', ds_month)\n sql = sql.replace('$day', ds_day)\n\n print(sql)\n result = spark.sql(sql)\n print(result.show())\n spark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_003_en"} {"task_id": "pyspark_004", "id": "offline-compute_PySpark_pyspark_004", "name": "销售线索企业邮品牌明细", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,产出\"销售线索企业邮品牌明细\"。\n\n**业务背景与目标**:线下销售团队有一份三非企业的销售线索表(含 corpid 唯一键),数据仓库侧有一份每月统计的邮箱平台画像表(每个 corpid 多行,按 top_domain / domain_isp 维度统计当月被唤醒的不同别名邮箱数量)。运营想要的是:对每一个三非线索企业,把它的活跃邮箱(domain_alias_monthwakeup_uniq >= 1)提取出来,并且把底层细粒度的 domain_isp 字段(如 'cloud_a'、'mail_provider_n'、'biz' 等)映射成业务可识别的标准品牌('电商平台A'、'邮件平台N'、'企业邮品牌C' 等),最终落到 DWD 层供下游使用。\n\n**输入表**:\n- `internal_platform_db.project_alpha_ods_tele_sale_clue_info_mysql_v3`\n- `internal_platform_db.project_alpha_dws_ww_corpstat_usermail_v3`\n\n**数据范围与过滤条件(业务说法)**:\n - 只保留有活跃邮箱的企业,即 b.domain_alias_monthwakeup_uniq >= 1。\n - 服务商不能为空,即 b.domain_isp IS NOT NULL。\n - 运行日期 ds 固定为 '20260513',写到输出 imp_date 列。\n\n**表关联关系**:\n - 子查询 a:`SELECT DISTINCT corpid FROM project_alpha_ods_tele_sale_clue_info_mysql_v3`(拿到所有三非线索企业的 corpid)。\n - inner join:a ⋈ project_alpha_dws_ww_corpstat_usermail_v3 b on a.corpid = b.corpid。\n\n**聚合与计算规则(需体现在 SQL 中)**:\n 1. 派生列 `domain_mx`(邮箱品牌),用 CASE WHEN 把 domain_isp 映射到标准品牌:    - 'other_zijian' → '其他自建'    - 'coremail_local' → 'coremail本地版'    - 'mail_provider_n' → '邮件平台N'    - IN ('outlook','outlook_cn') → 'outlook'    - IN ('cloud_a','ali','ecommerce_a','ecommerce_a') → '电商平台A'    - 'eyou_local' → '亿邮本地版'    - 'exchange_local' → 'exchange'    - 'coremail' → 'coremail saas版'    - IN ('263','263mail') → '263'    - 'postfix_local' → 'postfix本地版'    - 'collabf' → '协作平台F'    - 'biz' → '企业邮品牌C'    - ELSE → '其他saas'\n 2. imp_date 字段固定填 '20260513'。\n\n**输出要求**:\n - 目标表:`internal_platform_db.project_alpha_dwd_ww_tele_sale_corp_domain_mx_v3`\n - 输出表 schema(按此顺序、含义如下,5 列显式写出):   1. imp_date STRING:运行日期 YYYYMMDD = '20260513'   2. corpid BIGINT:企业 ID   3. top_domain STRING:最多人使用的邮箱域名   4. domain_isp STRING:邮箱服务商底层标识(保留原值)   5. domain_mx STRING:CASE WHEN 派生的标准品牌\n - 写入策略:INSERT OVERWRITE TABLE,使用显式列名清单。\n - 沙箱化说明:原任务由 SparkBase 框架封装(job.load_dw_data + selectExpr 链路 + job.save_dw_data);沙箱版改写为顶层 SparkSession + 一段 INNER JOIN + WHERE + CASE WHEN 的 SQL。\n - 如果目标表不存在,请先按 Hive 标准建表(ORC 存储),再写入数据。", "ground_truth": "# project_alpha rewrite-gt\n# source: data/v7_gt_codes/case_row08_case_0028.py (v7 row 7, manifest_row 8)\n# task_name: t_dwd_ww_tele_sale_corp_domain_mx_copilot\n# rewrite rules:\n# 1) internal_platform_db.ods_tele_sale_clue_info_mysql_copilot\n# -> internal_platform_db.project_alpha_ods_tele_sale_clue_info_mysql_v3\n# 2) internal_platform_db.dws_ww_corpstat_usermail_copilot\n# -> internal_platform_db.project_alpha_dws_ww_corpstat_usermail_v3\n# 3) internal_platform_db.dwd_ww_tele_sale_corp_domain_mx_copilot\n# -> internal_platform_db.project_alpha_dwd_ww_tele_sale_corp_domain_mx_v3\n# 4) 删除 dw_spark_base_python3.SparkBase(沙箱无):\n# - job = SparkBase() -> spark = SparkSession.builder...getOrCreate()\n# - job.load_dw_data(db, tbl).select/join/where/selectExpr 链路\n# -> 直接 spark.sql 写 INNER JOIN + WHERE + CASE WHEN 的完整 SELECT\n# - job.save_dw_data(df, db, tbl) -> spark.sql('INSERT OVERWRITE TABLE ...')\n# - job.statdate -> 硬编码 '20260513'\n# 5) INSERT 用显式列名清单(5 列)避免列序错位\n# 6) 沙箱表无分区,原 imp_date 分区列已沙箱化为普通列;本 GT 不读它\n# (原 GT 也不过滤 imp_date,是从全表读 → 沙箱表只灌目标 ds 即可)\n# ---\nfrom __future__ import print_function\n\nimport sys\nfrom pyspark.sql import SparkSession\n\n\nif __name__ == \"__main__\":\n ds = '20260513'\n\n spark = (\n SparkSession.builder\n .appName(\"project_alpha_dwd_ww_tele_sale_corp_domain_mx\")\n .enableHiveSupport()\n .getOrCreate()\n )\n\n # 确保输出表以正确 schema 存在\n spark.sql(\"DROP TABLE IF EXISTS internal_platform_db.project_alpha_dwd_ww_tele_sale_corp_domain_mx_v3\")\n spark.sql('''\nCREATE TABLE internal_platform_db.project_alpha_dwd_ww_tele_sale_corp_domain_mx_v3 (\n `imp_date` STRING COMMENT '运行日期(YYYYMMDD)',\n `corpid` BIGINT COMMENT 'corpid',\n `top_domain` STRING COMMENT '最多人邮箱域名',\n `domain_isp` STRING COMMENT '邮箱服务商',\n `domain_mx` STRING COMMENT 'CASE WHEN 派生品牌'\n) STORED AS ORCFILE\n''')\n\n # 销售线索企业邮品牌明细\n sql = \"\"\"\n INSERT OVERWRITE TABLE internal_platform_db.project_alpha_dwd_ww_tele_sale_corp_domain_mx_v3 (\n imp_date, corpid, top_domain, domain_isp, domain_mx\n )\n SELECT\n '{0}' as imp_date,\n b.corpid,\n b.top_domain,\n b.domain_isp,\n (CASE\n WHEN b.domain_isp = 'other_zijian' THEN '其他自建'\n WHEN b.domain_isp = 'coremail_local' THEN 'coremail本地版'\n WHEN b.domain_isp = 'mail_provider_n' THEN '邮件平台N'\n WHEN b.domain_isp IN ('outlook','outlook_cn') THEN 'outlook'\n WHEN b.domain_isp IN ('cloud_a','ali','ecommerce_a','ecommerce_a') THEN '电商平台A'\n WHEN b.domain_isp = 'eyou_local' THEN '亿邮本地版'\n WHEN b.domain_isp = 'exchange_local' THEN 'exchange'\n WHEN b.domain_isp = 'coremail' THEN 'coremail saas版'\n WHEN b.domain_isp IN ('263','263mail') THEN '263'\n WHEN b.domain_isp = 'postfix_local' THEN 'postfix本地版'\n WHEN b.domain_isp = 'collabf' THEN '协作平台F'\n WHEN b.domain_isp = 'biz' THEN '企业邮品牌C'\n ELSE '其他saas'\n END) AS domain_mx\n FROM (\n SELECT DISTINCT corpid\n FROM internal_platform_db.project_alpha_ods_tele_sale_clue_info_mysql_v3\n ) a\n INNER JOIN internal_platform_db.project_alpha_dws_ww_corpstat_usermail_v3 b\n ON a.corpid = b.corpid\n WHERE b.domain_alias_monthwakeup_uniq >= 1\n AND b.domain_isp IS NOT NULL\n \"\"\".format(ds)\n print(\"sql:\")\n print(sql)\n spark.sql(sql)\n print(\"saved\")\n\n spark.stop()\n sys.exit(0)", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_004"} {"task_id": "pyspark_005_en", "id": "offline-compute_PySpark_pyspark_005", "name": "AI Search Parse Quality Daily Detail (case9 version)", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nBusiness Background: Compute daily details of AI search web page parse quality by site + directory dimensions. Take data from the past few days, aggregate success rate, index page ratio, short content ratio, and failure step counts by the (date_key, host, fld) dimension, and join with the Top500 site priority labels.\n\n**Input Tables**:\n- `internal_platform_db.ai_engine_classify_parse_result_daily_copilot_v3`\n- `internal_platform_db.sec_app_hy_top_500_sites_tag_v1_copilot_v3`\n\n Data Range:\n - Fact table filter: `date_key >= '20260508' AND date_key <= '20260513'` (hardcoded, today='20260513', looking back 5 days)\n - Dimension table participates in full\n\n Processing Logic:\n\n 1. Field preparation: Select the following columns from the fact table:\n\n - `date_key` retained as-is\n\n - `host` → renamed to `source_host`\n\n - `fld` → renamed to `source_fld`\n\n - `when(col(\"is_error\") == 0, 1).otherwise(0)` → `success` (note: `is_error` is STRING; comparing with `== 0` triggers implicit type conversion in Spark)\n\n - `when(col(\"is_error\") == 1, 1).otherwise(0)` → `failure`\n\n - `web_type` retained as-is\n\n - `from_json(col(\"parse_html\"), schema_of_json('{\"content\": \"string\"}')).getField(\"content\")` → `content`\n\n - `error_step` retained as-is\n\n - Then `withColumn(\"content_length\", length(col(\"content\")))`\n 2. Four aggregations (all grouped by `date_key`, `source_host`, `source_fld`):\n\n\n - summary: `sum(success)` → `successful_parses`, `sum(failure)` → `failed_parses`, `count(*)` → `total_parses`\n\n - index_page_ratio: `sum(when(web_type=='索引页', 1).otherwise(0))` → `index_page_count`\n\n\n - content_length_ratio: first `filter(success==1)`, then `sum(when(content_length<50, 1).otherwise(0))` → `short_content_count`\n\n - error_reasons: first `filter(failure==1)`, then separately `sum(when(error_step==1/2/3, 1).otherwise(0))` → `error_step_1/2/3_count`; additionally `sum(when(error_step.isNotNull(), 1).otherwise(0))` → `total_error_steps` (this field is not used subsequently)\n 3. Merge: Left join the four aggregation results on `[date_key, source_host, source_fld]` to form `final_result`\n 4. Compute ratios:\n\n - `index_page_count_rate = index_page_count / total_parses`\n\n - `short_content_count_rate = short_content_count / successful_parses` (no divide-by-zero protection; produces null when `successful_parses=0`)\n 5. Hardcoded empty fields:\n\n\n - `withColumn(\"error_info_list\", lit(\"\"))` — no `collect_list`, directly fixed as empty string\n\n - `withColumn(\"is_host\", lit(\"\"))` — not taken from the dimension table, directly fixed as empty string\n\n 6. Join dimension table (key: OR condition):\n `final_result.join(`\n\n`priority_info`, — contains only `host`, `fld`, `priority` columns\n\n`(final_result.source_fld == priority_info.fld) OR`\n\n`(final_result.source_host == priority_info.host),`\n\n`\"left\"`\n\n `)`\n 6. Note: The join condition is OR (matching on either fld or host), not AND. This may cause one main table record to match multiple rows in the dimension table.\n 7. Final select (16 columns, in this order):\n\n - `date_key`, `source_host`→`host`, `source_fld`→`fld`, `is_host` (from step 5's `lit(\"\")`), `priority` (from dimension table join), `successful_parses`, `failed_parses`, `total_parses`, `index_page_count`, `index_page_count_rate`, `short_content_count`,\n `short_content_count_rate`, `error_step_1_count`, `error_step_2_count`, `error_step_3_count`, `error_info_list` (from step 5's `lit(\"\")`)\n 8. Deduplication: `dropDuplicates([\"date_key\", \"host\", \"fld\", \"priority\", \"successful_parses\", \"total_parses\", \"index_page_count\"])`\n\n - Note: Because the OR join may produce multiple rows (one main table row matching multiple dimension table rows), deduplication is used to converge the inflated rows\n 9. Write: `final_result.write.mode(\"overwrite\").insertInto(target table)`\n\n Output table: `internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot_v3`", "ground_truth": "# data-mocker rewrite-gt\n# source: 离线计算pyspark例子_v7.xlsx 工作表1 row=10 col=3\n# row_idx: 9\n# intent_short: 帮我做个AI搜索引擎解析质量的每日明细统计,按站点和目录维度算一下成功率、索引页占比、短内容占比,还有各环节的失败分布。另外需要把Top500站点的优先级标签关联上\n# v3 tables: internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot_v3, internal_platform_db.ai_engine_classify_parse_result_daily_copilot_v3, internal_platform_db.sec_app_hy_top_500_sites_tag_v1_copilot_v3\n# extra fqns scanned from GT (not in v7_rows.tables): internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot\n# rewrite rule: -> _v3 (covers bare / `fqn` / db.`tbl`)\n# ---\n#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col, count, when, length, sum as _sum, from_json, schema_of_json\nfrom pyspark.sql.types import StringType\nfrom datetime import datetime, timedelta\nfrom pyspark.sql.functions import lit\nfrom pyspark.sql import functions as F\n# 创建SparkSession\nspark = (\n \n SparkSession.builder.enableHiveSupport()\n \n .config(\"spark.driver.memory\", \"6g\")\n .config(\"spark.executor.cores\", 6)\n \n .config(\"spark.executor.memory\", \"12g\")\n .getOrCreate()\n)\n\n# 确保输出表以正确 schema 存在\nspark.sql(\"DROP TABLE IF EXISTS internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot_v3\")\nspark.sql('''\nCREATE TABLE internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot_v3 (\n`date_key` STRING COMMENT '-',\n`host` STRING COMMENT '-',\n`fld` STRING COMMENT '-',\n`is_host` STRING COMMENT '-',\n`priority` STRING COMMENT '-',\n`successful_parses` BIGINT COMMENT '-',\n`failed_parses` BIGINT COMMENT '-',\n`total_parses` BIGINT COMMENT '-',\n`index_page_count` BIGINT COMMENT '-',\n`index_page_count_rate` DOUBLE COMMENT '-',\n`short_content_count` BIGINT COMMENT '-',\n`short_content_count_rate` DOUBLE COMMENT '-',\n`error_step_1_count` BIGINT COMMENT '-',\n`error_step_2_count` BIGINT COMMENT '-',\n`error_step_3_count` BIGINT COMMENT '-',\n`error_info_list` STRING COMMENT '-'\n) STORED AS ORCFILE\n''')\n\n \n\n# # 获取今天的日期,并计算10天前的日期\n# today = datetime.now()\n# ten_days_ago = today - timedelta(days=5)\n\n# # 将日期格式化为 YYYYMMDD\n# today_str = today.strftime('%Y%m%d')\n# ten_days_ago_str = ten_days_ago.strftime('%Y%m%d')\ntoday_str = '20260513'\nten_days_ago_str = '20260508'\nprint(today_str, ten_days_ago_str)\n\n# 读取 priority 信息\npriority_info = spark.table(\"internal_platform_db.sec_app_hy_top_500_sites_tag_v1_copilot_v3\").select(\n \"host\", \"fld\", \n \"priority\"\n)\n\n# 读取数据,从今天往前10天的数据\ndf = spark.table(\"internal_platform_db.ai_engine_classify_parse_result_daily_copilot_v3\").filter(\n (col(\"date_key\") >= ten_days_ago_str) & (col(\"date_key\") <= today_str)\n)\n\n# 解析数据\nparsed_data = df.select(\n \"date_key\",\n \n col(\"host\").alias(\"source_host\") ,\n when(col(\"is_error\") == 0, 1).otherwise(0).alias(\"success\"),\n when(col(\"is_error\") == 1, 1).otherwise(0).alias(\"failure\"),\n \"web_type\",\n # 从 parse_html 中提取 content 字段\n \n from_json(col(\"parse_html\"), schema_of_json('{\"content\": \"string\"}')).getField(\"content\").alias(\"content\"),\n \"error_step\",\n col(\"fld\").alias(\"source_fld\") # 使用别名避免歧义\n)\n\n# 计算内容长度\nparsed_data = parsed_data.withColumn(\"content_length\", length(col(\"content\")))\n\n# 在 summary_copilot 中保留 source_fld 字段\nsummary = parsed_data.groupBy(\"date_key\", \"source_host\", \"source_fld\").agg( # 使用别名\n _sum(\"success\").alias(\"successful_parses\"),\n \n _sum(\"failure\").alias(\"failed_parses\"),\n count(\"*\").alias(\"total_parses\")\n)\n\n# 计算索引页比例\nindex_page_ratio = parsed_data.groupBy(\"date_key\",\"source_host\", \"source_fld\").agg( # 使用别名\n \n _sum(when(col(\"web_type\") == \"索引页\", 1).otherwise(0)).alias(\"index_page_count\")\n)\n\n# 计算内容长度比例\ncontent_length_ratio = parsed_data.filter(col(\"success\") == 1).groupBy(\"date_key\",\"source_host\", \"source_fld\").agg( # 使用别名\n \n _sum(when(col(\"content_length\") < 50, 1).otherwise(0)).alias(\"short_content_count\")\n)\n\n# 计算错误原因\nerror_reasons = parsed_data.filter(col(\"failure\") == 1).groupBy(\"date_key\", \"source_host\", \"source_fld\").agg( # 使用别名\n \n _sum(when(col(\"error_step\") == 1, 1).otherwise(0)).alias(\"error_step_1_count\"),\n _sum(when(col(\"error_step\") == 2, 1).otherwise(0)).alias(\"error_step_2_count\"),\n \n _sum(when(col(\"error_step\") == 3, 1).otherwise(0)).alias(\"error_step_3_count\"),\n \n _sum(when(col(\"error_step\").isNotNull(), 1).otherwise(0)).alias(\"total_error_steps\")\n)\n\n# 最终合并\nfinal_result = summary.join(index_page_ratio, [\"date_key\", \"source_host\", \"source_fld\"], \"left\") \\\n .join(content_length_ratio, [\"date_key\",\"source_host\", \"source_fld\"], \"left\") \\\n .join(error_reasons, [\"date_key\",\"source_host\", \"source_fld\"], \"left\")\n\n# 计算比例\nfinal_result = final_result.withColumn(\n \n \"index_page_count_rate\",\n col(\"index_page_count\") / col(\"total_parses\")\n).withColumn(\n \n \"short_content_count_rate\",\n \n col(\"short_content_count\") / col(\"successful_parses\")\n)\n\n\n# 添加 error_info_list 字段\nfinal_result = final_result.withColumn(\"error_info_list\", lit(\"\"))\nfinal_result = final_result.withColumn(\"is_host\", lit(\"\"))\n\n\n\n####fld存在500tag则扩散对应的ccdata的host组合---host存在则直接匹配host\n \n\nfinal_result = final_result.join(\n priority_info,\n (final_result.source_fld == priority_info.fld) |\n (final_result.source_host == priority_info.host),\n \"left\"\n)\n# 选择所需的列\nfinal_result = final_result.select(\n \"date_key\",\n \n F.col(\"source_host\").alias(\"host\"), \n \n F.col(\"source_fld\").alias(\"fld\"), # 使用 source_fld\n \"is_host\",\n \"priority\",\n \"successful_parses\",\n \"failed_parses\",\n \"total_parses\",\n \"index_page_count\",\n \n \"index_page_count_rate\",\n \n \"short_content_count\",\n \n \"short_content_count_rate\",\n \"error_step_1_count\",\n \n \"error_step_2_count\",\n \n \"error_step_3_count\",\n \"error_info_list\"\n)\n\nfinal_result = final_result.dropDuplicates([\"date_key\", \"host\", \"fld\",\"priority\",\"successful_parses\",\"total_parses\",\"index_page_count\"])\n# 将结果写入目标表\nfinal_result.write.mode(\"overwrite\").insertInto(\"internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot_v3\")", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_005_en"} {"task_id": "pyspark_006_en", "id": "offline-compute_PySpark_pyspark_006", "name": "AI Search Parse Quality Daily Detail", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that produces the \"AI Search Parse Quality Daily Detail\".\n\nBusiness Background: Compute daily details of AI search web page parse quality by site + directory dimensions. Take data from the past few days, aggregate success rate, index page ratio, short content ratio, and failure step counts by the (date_key, host, fld) dimension, and join with the Top500 site priority labels.\n\n**Input Tables**:\n- `internal_platform_db.case10_ai_engine_classify_parse_result_daily_v3`\n- `internal_platform_db.case10_sec_app_hy_top_500_sites_tag_v1_v3`\n\n Data Range:\n\n - Fact table filter: `date_key >= '20260508' AND date_key <= '20260513'` (hardcoded, today='20260513', looking back 5 days)\n - Dimension table participates in full, no pre-filtering\n\n Processing Logic:\n\n 1. Field preparation: Select the following columns from the fact table:\n\n - `date_key` as-is\n\n - `host` → renamed `source_host`\n\n - `when(col(\"is_error\") == 0, 1).otherwise(0)` → `success` (`is_error` is STRING; relies on Spark implicit conversion to compare with integer 0)\n\n - `when(col(\"is_error\") == 1, 1).otherwise(0)` → `failure`\n\n - `web_type` as-is\n\n - `from_json(col(\"parse_html\"), schema_of_json('{\"content\": \"string\"}')).getField(\"content\")` → `content`\n\n - `error_step` as-is\n\n - `fld` → renamed `source_fld`\n\n - Then `withColumn`: `content_length = length(content)`\n 2. Four independent aggregations (all grouped by `date_key`, `source_host`, `source_fld`):\n\n - summary: `sum(success)` → `successful_parses`, `sum(failure)` → `failed_parses`, `count(*)` → `total_parses`\n\n - index_page_ratio: `sum(when(web_type=='索引页', 1).otherwise(0))` → `index_page_count`\n\n - content_length_ratio: first `filter(success==1)`, then `sum(when(content_length<50, 1).otherwise(0))` → `short_content_count`\n\n - error_reasons: first `filter(failure==1)`, then:\n\n- `sum(when(error_step==1, 1).otherwise(0))` → `error_step_1_count`\n\n- `sum(when(error_step==2, 1).otherwise(0))` → `error_step_2_count`\n\n- `sum(when(error_step==3, 1).otherwise(0))` → `error_step_3_count`\n\n- `sum(when(error_step.isNotNull(), 1).otherwise(0))` → `total_error_steps` (this field is not used or output subsequently)\n 3. Merge: Left join the four aggregation results sequentially on `[date_key, source_host, source_fld]`\n\n 4. Compute ratios:\n\n - `index_page_count_rate = index_page_count / total_parses`\n\n\n - `short_content_count_rate = short_content_count / successful_parses` (no divide-by-zero protection; produces null when `successful_parses=0`)\n 5. Hardcoded empty fields:\n\n - `withColumn(\"error_info_list\", lit(\"\"))` — fixed empty string, no `collect_list`\n\n - `withColumn(\"is_host\", lit(\"\"))` — fixed empty string, not obtained from dimension table\n 6. Join dimension table (OR condition):\n `final_result.join(`\n\n`priority_info`, — contains only `host`, `fld`, `priority`\n\n`(source_fld == priority_info.fld) OR (source_host == priority_info.host),`\n\n`\"left\"`\n\n `)`\n 6. Key: The condition is OR (matching on either fld or host), not AND. One main table record may match multiple dimension table rows, causing row inflation.\n 7. Final select (16 columns, in this order):\n `date_key`, `source_host`→`host`, `source_fld`→`fld`, `is_host` (step5's `lit(\"\")`), `priority` (from dimension table join), `successful_parses`, `failed_parses`, `total_parses`, `index_page_count`, `index_page_count_rate`, `short_content_count`, `short_content_count_rate`,\n `error_step_1_count`, `error_step_2_count`, `error_step_3_count`, `error_info_list` (step5's `lit(\"\")`)\n 8. Deduplication: `dropDuplicates([\"date_key\", \"host\", \"fld\", \"priority\", \"successful_parses\", \"total_parses\", \"index_page_count\"])` (to converge inflated rows from the OR join)\n 9. Write: Write via `createOrReplaceTempView` + `INSERT OVERWRITE TABLE`, explicitly specifying column name order (the output table DDL column order differs from the DataFrame column order):\n\n - Output table column order: `host`, `fld`, `is_host`, `priority`, `successful_parses`, `failed_parses`, `total_parses`, `index_page_count`, `index_page_count_rate`, `short_content_count`, `short_content_count_rate`, `error_step_1_count`, `error_step_2_count`,\n `error_step_3_count`, `error_info_list`, `date_key`\n\n - All fields are written with `CAST AS STRING`\n\n Output table: `internal_platform_db.case10_ai_engine_classify_parse_result_daily_detail_v3`\n - Output table DDL column order (note that `date_key` is last): `host`, `fld`, `is_host`, `priority`, `successful_parses`, `failed_parses`, `total_parses`, `index_page_count`, `index_page_count_rate`, `short_content_count`, `short_content_count_rate`, `error_step_1_count`,\n `error_step_2_count`, `error_step_3_count`, `error_info_list`, `date_key`\n - All column types are STRING", "ground_truth": "# case10 rewrite-gt\n# source: data/v7_gt_codes/case_row10_case_0043.py (v7 row 9, manifest_row 10)\n# task_name: ai_engine_classify_parse_result_daily_detail\n# rewrite rules:\n# 1) internal_platform_db.ai_engine_classify_parse_result_daily_copilot\n# -> internal_platform_db.case10_ai_engine_classify_parse_result_daily_v3\n# 2) internal_platform_db.sec_app_hy_top_500_sites_tag_v1_copilot\n# -> internal_platform_db.case10_sec_app_hy_top_500_sites_tag_v1_v3\n# 3) internal_platform_db.ai_engine_classify_parse_result_daily_detail_copilot\n# -> internal_platform_db.case10_ai_engine_classify_parse_result_daily_detail_v3\n# 4) today = datetime.now() -> 硬编码 today_str = '20260513'\n# ten_days_ago_str = '20260508'(today - 5 天,与原 timedelta(days=5) 一致)\n# 5) 沙箱主表去 date_key 分区(thive UI 建分区表 INSERT VALUES 全 silent no-op)\n# -> 改为普通 STRING 列;GT 仍按 date_key 范围过滤\n# 6) 末尾 final_result.write.mode(\"overwrite\").insertInto(...) -> 改为\n# createOrReplaceTempView + spark.sql('INSERT OVERWRITE TABLE ... SELECT ...')\n# 显式列名清单(16 列)避免 DataFrame select 列序与 output DDL 列序错位\n# ---\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col, count, when, length, sum as _sum, from_json, schema_of_json\nfrom pyspark.sql.types import StringType\nfrom datetime import datetime, timedelta\nfrom pyspark.sql.functions import lit\nfrom pyspark.sql import functions as F\n\nspark = (\n SparkSession.builder\n .appName(\"case10_ai_engine_classify_parse_result_daily_detail\")\n .enableHiveSupport()\n .config(\"spark.driver.memory\", \"6g\")\n .config(\"spark.executor.cores\", 6)\n .config(\"spark.executor.memory\", \"12g\")\n .getOrCreate()\n)\n\n# 确保输出表以正确 schema 存在\nspark.sql(\"DROP TABLE IF EXISTS internal_platform_db.case10_ai_engine_classify_parse_result_daily_detail_v3\")\nspark.sql('''\nCREATE TABLE internal_platform_db.case10_ai_engine_classify_parse_result_daily_detail_v3 (\n `host` STRING,\n `fld` STRING,\n `is_host` STRING,\n `priority` STRING,\n `successful_parses` STRING,\n `failed_parses` STRING,\n `total_parses` STRING,\n `index_page_count` STRING,\n `index_page_count_rate` STRING,\n `short_content_count` STRING,\n `short_content_count_rate` STRING,\n `error_step_1_count` STRING,\n `error_step_2_count` STRING,\n `error_step_3_count` STRING,\n `error_info_list` STRING,\n `date_key` STRING\n) STORED AS ORCFILE\n''')\n\n# 沙箱化运行日期(原 today=datetime.now(),ten_days_ago=today-timedelta(days=5))\ntoday_str = '20260513'\nten_days_ago_str = '20260508'\nprint(today_str, ten_days_ago_str)\n\n# 读取 priority 信息\npriority_info = spark.table(\"internal_platform_db.case10_sec_app_hy_top_500_sites_tag_v1_v3\").select(\n \"host\", \"fld\", \"priority\"\n)\n\n# 读取数据,从今天往前 5 天的数据\ndf = spark.table(\"internal_platform_db.case10_ai_engine_classify_parse_result_daily_v3\").filter(\n (col(\"date_key\") >= ten_days_ago_str) & (col(\"date_key\") <= today_str)\n)\n\n# 解析数据\nparsed_data = df.select(\n \"date_key\",\n col(\"host\").alias(\"source_host\"),\n when(col(\"is_error\") == 0, 1).otherwise(0).alias(\"success\"),\n when(col(\"is_error\") == 1, 1).otherwise(0).alias(\"failure\"),\n \"web_type\",\n from_json(col(\"parse_html\"), schema_of_json('{\"content\": \"string\"}')).getField(\"content\").alias(\"content\"),\n \"error_step\",\n col(\"fld\").alias(\"source_fld\"),\n)\n\n# 计算内容长度\nparsed_data = parsed_data.withColumn(\"content_length\", length(col(\"content\")))\n\nsummary = parsed_data.groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(\"success\").alias(\"successful_parses\"),\n _sum(\"failure\").alias(\"failed_parses\"),\n count(\"*\").alias(\"total_parses\"),\n)\n\nindex_page_ratio = parsed_data.groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(when(col(\"web_type\") == \"索引页\", 1).otherwise(0)).alias(\"index_page_count\")\n)\n\ncontent_length_ratio = parsed_data.filter(col(\"success\") == 1).groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(when(col(\"content_length\") < 50, 1).otherwise(0)).alias(\"short_content_count\")\n)\n\nerror_reasons = parsed_data.filter(col(\"failure\") == 1).groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(when(col(\"error_step\") == 1, 1).otherwise(0)).alias(\"error_step_1_count\"),\n _sum(when(col(\"error_step\") == 2, 1).otherwise(0)).alias(\"error_step_2_count\"),\n _sum(when(col(\"error_step\") == 3, 1).otherwise(0)).alias(\"error_step_3_count\"),\n _sum(when(col(\"error_step\").isNotNull(), 1).otherwise(0)).alias(\"total_error_steps\"),\n)\n\nfinal_result = summary.join(index_page_ratio, [\"date_key\", \"source_host\", \"source_fld\"], \"left\") \\\n .join(content_length_ratio, [\"date_key\", \"source_host\", \"source_fld\"], \"left\") \\\n .join(error_reasons, [\"date_key\", \"source_host\", \"source_fld\"], \"left\")\n\nfinal_result = final_result.withColumn(\n \"index_page_count_rate\",\n col(\"index_page_count\") / col(\"total_parses\"),\n).withColumn(\n \"short_content_count_rate\",\n col(\"short_content_count\") / col(\"successful_parses\"),\n)\n\nfinal_result = final_result.withColumn(\"error_info_list\", lit(\"\"))\nfinal_result = final_result.withColumn(\"is_host\", lit(\"\"))\n\n# fld 存在 500tag 则扩散 host 组合 / host 存在则直接匹配 host\nfinal_result = final_result.join(\n priority_info,\n (final_result.source_fld == priority_info.fld) |\n (final_result.source_host == priority_info.host),\n \"left\",\n)\n\nfinal_result = final_result.select(\n \"date_key\",\n F.col(\"source_host\").alias(\"host\"),\n F.col(\"source_fld\").alias(\"fld\"),\n \"is_host\",\n \"priority\",\n \"successful_parses\",\n \"failed_parses\",\n \"total_parses\",\n \"index_page_count\",\n \"index_page_count_rate\",\n \"short_content_count\",\n \"short_content_count_rate\",\n \"error_step_1_count\",\n \"error_step_2_count\",\n \"error_step_3_count\",\n \"error_info_list\",\n)\n\nfinal_result = final_result.dropDuplicates([\n \"date_key\", \"host\", \"fld\", \"priority\",\n \"successful_parses\", \"total_parses\", \"index_page_count\",\n])\n\n# INSERT OVERWRITE 显式列名(16 列);output DDL 列序:host, fld, is_host, priority, ..., date_key\nfinal_result.createOrReplaceTempView(\"case10_final_result_view\")\ninsert_sql = \"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.case10_ai_engine_classify_parse_result_daily_detail_v3 (\n host, fld, is_host, priority,\n successful_parses, failed_parses, total_parses,\n index_page_count, index_page_count_rate,\n short_content_count, short_content_count_rate,\n error_step_1_count, error_step_2_count, error_step_3_count,\n error_info_list, date_key\n)\nSELECT\n CAST(host AS STRING),\n CAST(fld AS STRING),\n CAST(is_host AS STRING),\n CAST(priority AS STRING),\n CAST(successful_parses AS STRING),\n CAST(failed_parses AS STRING),\n CAST(total_parses AS STRING),\n CAST(index_page_count AS STRING),\n CAST(index_page_count_rate AS STRING),\n CAST(short_content_count AS STRING),\n CAST(short_content_count_rate AS STRING),\n CAST(error_step_1_count AS STRING),\n CAST(error_step_2_count AS STRING),\n CAST(error_step_3_count AS STRING),\n CAST(error_info_list AS STRING),\n CAST(date_key AS STRING)\nFROM case10_final_result_view\n\"\"\"\nprint(\"insert_sql:\")\nprint(insert_sql)\nspark.sql(insert_sql)\nprint(\"saved\")\n\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_006_en"} {"task_id": "pyspark_007_en", "id": "offline-compute_PySpark_pyspark_007", "name": "Sync Cloud-Check User Active Status to Application Layer", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that synchronizes the \"user cloud-check active status\" detail from ODS to the application layer DWV, and applies compliance encryption to the phone number to generate a unionid.\n\n**Business Background and Objective**: In the upstream ODS, the `phone_enc` field is the bottom-layer encrypted phone number. The downstream application layer wants to further convert it into a `unionid` column (referred to as `phone` in business terms) using a deterministic one-way encryption. In addition to encryption, the active status fields (inactive days, sleep flag, first/recent/last cloud-check dates) must be passed through as-is, written out by `ds`.\n\n**Input Table**:\n- `internal_platform_db.case15_ods_phone_active_df_v3`\n\n**Data Range and Filter Conditions (business description)**:\n - Only take the `ds` = current day partition; for this run, `ds` is fixed as `'20260513'` (the original task passes this via `sys.argv[1]`; TaskType=63 does not pass command-line arguments, so it is hardcoded to avoid IndexError).\n\n**Table Join Relationships**: (No joins, single-table extraction.)\n\n**Aggregation and Computation Rules (must be reflected in the SQL)**:\n 1. Derived column `phone`: The original task encrypts `phone_enc` via the `OpenidCrypt` UDF; this UDF's jar (`hdfs://cluster-alpha/...`) is unavailable in the sandbox (tested exit code 1), so `sha2(phone_enc, 256)` is used as a replacement — also a deterministic one-way encryption, with equivalent business semantics.\n 2. Column renaming (alias during passthrough):\n - `his_call_date_cloud` → `his_call_date_total`\n - `first_call_date_cloud` → `first_call_date_total`\n - `last_call_date_cloud` → `last_call_date_total`\n 3. Other fields (`phone_type`, `not_active_days`, `is_sleep_flag`, `ds`) are passed through as-is.\n\n**Output Requirements**:\n - Target table: `internal_platform_db.case15_dwv_phone_regul_unionid_df_v3`\n - Output table schema (in this order, with the following semantics):\n 1. `phone` STRING: encrypted unionid\n 2. `phone_type` STRING: phone number type\n 3. `not_active_days` INT: recent consecutive inactive days\n 4. `is_sleep_flag` STRING: whether currently in sleep state\n 5. `his_call_date_total` STRING: historical first query date\n 6. `first_call_date_total` STRING: recent first query date\n 7. `last_call_date_total` STRING: last query date\n 8. `ds` BIGINT: business date (originally a partition column, sandboxed as a regular column)\n - Write strategy: `INSERT OVERWRITE TABLE`, using an explicit column name list (8 columns) to avoid column order misalignment; config `spark.sql.storeAssignmentPolicy=LEGACY` to accommodate implicit type conversion.\n - Sandbox note: The original `PARTITION(ds={ds})` write is changed to a regular column + `WHERE ds = {ds}` regular column filter; the `OpenidCrypt` UDF is replaced with `sha2(phone_enc, 256)`; `jar_addr` addJar and `registerJavaFunction` are removed.\n - If the target table does not exist, first create it using standard Hive format (ORC storage), then write the data.", "ground_truth": "# data-mocker rewrite-gt\n# source: v7 xlsx row 16 (case15)\n# task_name: t_app_regul_user_comm_security_cloud_active_status_phone_uid_df_copilot\n# rewrite rules:\n# 1) internal_platform_db.t_app_comm_security_user_cloud_active_status_phone_df_copilot\n# -> internal_platform_db.case15_ods_phone_active_df_v3\n# 2) internal_platform_db.t_app_regul_user_comm_security_cloud_active_status_phone_uid_df_copilot\n# -> internal_platform_db.case15_dwv_phone_regul_unionid_df_v3\n# 3) PARTITION(ds=...) 删除;output 表 ds 改为普通列,SELECT 头部补 ds 列\n# WHERE ds = {ds} 保留(普通列过滤)\n# INSERT 用显式列名避免列序错位\n# 4) sys.argv[1] -> 硬编码 '20260513'\n# (datawd PySpark TaskType=63 不直传命令行参数)\n# 5) OpenidCrypt UDF -> sha2(phone_enc, 256)\n# (原 jar hdfs://cluster-alpha/... 在沙箱不可用,实测 exit code 1;\n# sha2 同样是确定性单向加密,业务语义等价)\n# 6) 移除 jar_addr addJar + registerJavaFunction(不再需要)\n# ---\nimport sys\nfrom pyspark.sql import SparkSession\n\n\"\"\"\n\n脚本说明:API-SDK云查(sha2 加密版)\n\n\"\"\"\n\n\n# 生成和配置spark实例\ndef get_spark_cli():\n spark = SparkSession.builder \\\n .enableHiveSupport() \\\n .config(\"spark.sql.storeAssignmentPolicy\", \"LEGACY\") \\\n .getOrCreate()\n return spark\n\n\n# 生成spark sql语句\ndef get_sql_str():\n ds = '20260513' # was: sys.argv[1]\n sql = f\"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.case15_dwv_phone_regul_unionid_df_v3\n(phone, phone_type, not_active_days, is_sleep_flag, his_call_date_total, first_call_date_total, last_call_date_total, ds)\nSELECT\nsha2(phone_enc, 256) as phone,\nphone_type,\nnot_active_days,\nis_sleep_flag,\nhis_call_date_cloud as his_call_date_total,\nfirst_call_date_cloud as first_call_date_total,\nlast_call_date_cloud as last_call_date_total,\nds\nFROM internal_platform_db.case15_ods_phone_active_df_v3\nwhere ds = {ds}\n\"\"\"\n print(f\"sql: {sql}\")\n return sql\n\n\n# 执行\nif __name__ == \"__main__\":\n spark = get_spark_cli()\n # 确保输出表以正确 schema 存在\n spark.sql(\"DROP TABLE IF EXISTS internal_platform_db.case15_dwv_phone_regul_unionid_df_v3\")\n spark.sql('''\nCREATE TABLE internal_platform_db.case15_dwv_phone_regul_unionid_df_v3 (\n `phone` STRING COMMENT '加密后的 unionid',\n `phone_type` STRING COMMENT '号码类型',\n `not_active_days` INT COMMENT '最近连续不活跃天数',\n `is_sleep_flag` STRING COMMENT '当前是否处于休眠状态',\n `his_call_date_total` STRING COMMENT '历史首次查询日期',\n `first_call_date_total` STRING COMMENT '最近首次查询日期',\n `last_call_date_total` STRING COMMENT '最后查询日期',\n `ds` BIGINT COMMENT 'partition fields(原为分区列)'\n) STORED AS ORCFILE\n''')\n SQL = get_sql_str()\n spark.sql(SQL)", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_007_en"} {"task_id": "pyspark_008_en", "id": "offline-compute_PySpark_pyspark_008", "name": "Cleanse API Cloud-Check Logs", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that cleanses the \"API cloud-check log\" hourly table from ODS and synchronizes it to the DWD layer.\n\n**Business Background and Objective**: API-SDK cloud-check writes a raw log to ODS every hour (containing the caller's phone number `phonenum`/`phonenum_reg`, device IMEI/GUID/IMSI, calling IP (integer), query type, etc.). The downstream DWD layer wants: (1) filter out dirty data (empty phone number or IP, out-of-range IP); (2) use an IP library UDF to reverse-lookup country/province/city/district; (3) rename several fields and CAST them to the downstream schema.\n\n**Input Table**:\n- `internal_platform_db.case16_ods_comm_security_user_api_query_mgr_hi_v3`\n\n**Data Range and Filter Conditions (business description)**:\n - `ds` = current day partition; for this run, `ds` is fixed as `'20260513'` (original `sys.argv[1]` sandboxed and hardcoded).\n - `phonenum_reg IS NOT NULL`\n - `phonenum IS NOT NULL`\n - `ip IS NOT NULL`\n - `ip BETWEEN 0 AND 4294967295` (valid uint32 range, to avoid dirty data)\n\n**Table Join Relationships**: (No joins, single-table cleansing.)\n\n**Aggregation and Computation Rules (must be reflected in the SQL)**:\n 1. Column renaming / CAST:\n - `phonenum_reg` → `phone_num`\n - `phonenum` → `phone_num_original`\n - `imei` → `imei_reg` (retain the original `imei` as well)\n - `time` → `log_time`\n - `query_type` / `calltype` / `phonetype` / `src` all CAST AS STRING\n 2. Derived IP reverse-lookup columns `ip_country` / `ip_province` / `ip_city` / `ip_district`:\n - The original task reverse-looks up via the `get_ip_info(ip)[0..3]` UDF; this UDF's jar (`hdfs://cluster-alpha/...`) is unavailable in the sandbox, so the sandbox version replaces it with constants `lit('CN')` / `lit('default_province')` / `lit('default_city')` / `lit('default_district')`.\n - The original task also has a pure Python `int_to_ip_string` UDF (using only socket+struct, available in the sandbox), but since the output columns have been replaced with `lit`, it is no longer referenced and is removed to keep the GT clean.\n\n**Output Requirements**:\n - Target table: `internal_platform_db.case16_dwd_comm_security_user_api_query_mgr_hi_v3`\n - Output table schema (17 columns, in this order, with the following semantics):\n 1. `phone_num` STRING: normalized phone number\n 2. `phone_num_original` STRING: original phone number\n 3. `imei_reg` STRING: normalized IMEI (i.e., `imei`)\n 4. `imei` STRING: original IMEI\n 5. `guid` STRING, 6. `imsi` STRING: device identifiers\n 7. `log_time` STRING: log time (i.e., `time`)\n 8. `ip` BIGINT: query IP (integer)\n 9. `query_type` STRING, 10. `calltype` STRING, 11. `phonetype` STRING, 12. `src` STRING: query categories\n 13. `ip_country` STRING: country (sandbox constant `'CN'`)\n 14. `ip_province` STRING: province (sandbox constant `'default_province'`)\n 15. `ip_city` STRING: city (sandbox constant `'default_city'`)\n 16. `ip_district` STRING: district (sandbox constant `'default_district'`)\n 17. `ds` BIGINT: business date (originally a partition column, sandboxed as a regular column)\n - Write strategy: `INSERT OVERWRITE TABLE`, using an explicit column name list (17 columns).\n - Sandbox note: `PARTITION(ds={ds})` is changed to a regular column + `WHERE` filter; the `get_ip_info` UDF is sandboxed as `lit` constants; `addJar` + `registerJavaFunction(\"get_ip_info\", ...)` are removed; `ArrayType` / `StringType` imports are removed (no longer needed).\n - If the target table does not exist, first create it using standard Hive format (ORC storage), then write the data.", "ground_truth": "# data-mocker rewrite-gt\n# source: v7 xlsx row 17 (case16)\n# task_name: t_dwd_comm_security_user_api_query_mgr_hi_copilot\n# rewrite rules:\n# 1) internal_platform_db.t_ods_comm_security_user_api_query_mgr_hi_copilot\n# -> internal_platform_db.case16_ods_comm_security_user_api_query_mgr_hi_v3\n# 2) internal_platform_db.t_dwd_comm_security_user_api_query_mgr_hi_copilot\n# -> internal_platform_db.case16_dwd_comm_security_user_api_query_mgr_hi_v3\n# 3) PARTITION(ds={ds}) 删除;output 表 ds 改为普通列,SELECT 末尾补 ds\n# WHERE ds = {ds} 保留(普通列过滤)\n# INSERT 用显式列名避免列序错位\n# 4) sys.argv[1] -> 硬编码 '20260513'\n# 5) get_ip_info(...)[0..3] UDF -> lit('CN'/'default'/'default'/'default')\n# (原 jar hdfs://cluster-alpha/... 在沙箱不可用,同 case15 OpenidCrypt 处理)\n# 6) 移除 addJar + registerJavaFunction(\"get_ip_info\", ...)\n# 7) int_to_ip_string Python UDF 保留(纯 socket+struct 沙箱可用),\n# 但因为输出列已 lit 替换,实际不再被引用 → 一并删除以保持 GT 干净\n# 8) 删除 ArrayType/StringType import(已不再需要)\n# ---\nimport sys\nfrom pyspark.sql import SparkSession\n\n\"\"\"\n\n脚本说明:API-SDK云查(lit 替换 IP 反查 UDF 版)\n\n\"\"\"\n\n\n# 生成和配置spark实例\ndef get_spark_cli():\n spark = SparkSession.builder \\\n .enableHiveSupport() \\\n .config(\"spark.sql.storeAssignmentPolicy\", \"LEGACY\") \\\n .getOrCreate()\n return spark\n\n\n# 生成spark sql语句\ndef get_sql_str():\n ds = '20260513' # was: sys.argv[1]\n sql = f\"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.case16_dwd_comm_security_user_api_query_mgr_hi_v3\n(phone_num, phone_num_original, imei_reg, imei, guid, imsi, log_time, ip, query_type, calltype, phonetype, src, ip_country, ip_province, ip_city, ip_district, ds)\nSELECT\n phonenum_reg AS phone_num,\n phonenum AS phone_num_original,\n imei AS imei_reg,\n imei,\n guid,\n imsi,\n time AS log_time,\n ip,\n CAST(query_type AS STRING) AS query_type,\n CAST(calltype AS STRING) AS calltype,\n CAST(phonetype AS STRING) AS phonetype,\n CAST(src AS STRING) AS src,\n 'CN' AS ip_country,\n 'default_province' AS ip_province,\n 'default_city' AS ip_city,\n 'default_district' AS ip_district,\n ds\nFROM internal_platform_db.case16_ods_comm_security_user_api_query_mgr_hi_v3\nWHERE ds = {ds}\n AND phonenum_reg IS NOT NULL\n AND phonenum IS NOT NULL\n AND ip IS NOT NULL\n AND ip BETWEEN 0 AND 4294967295\n\"\"\"\n print(f\"sql: {sql}\")\n return sql\n\n\n# 执行\nif __name__ == \"__main__\":\n spark = get_spark_cli()\n\n # 确保输出表以正确 schema 存在\n spark.sql(\"DROP TABLE IF EXISTS internal_platform_db.case16_dwd_comm_security_user_api_query_mgr_hi_v3\")\n spark.sql('''\nCREATE TABLE internal_platform_db.case16_dwd_comm_security_user_api_query_mgr_hi_v3 (\n `phone_num` STRING,\n `phone_num_original` STRING,\n `imei_reg` STRING,\n `imei` STRING,\n `guid` STRING,\n `imsi` STRING,\n `log_time` STRING,\n `ip` BIGINT,\n `query_type` STRING,\n `calltype` STRING,\n `phonetype` STRING,\n `src` STRING,\n `ip_country` STRING,\n `ip_province` STRING,\n `ip_city` STRING,\n `ip_district` STRING,\n `ds` BIGINT\n) STORED AS ORCFILE\n''')\n\n SQL = get_sql_str()\n spark.sql(SQL)", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_008_en"} {"task_id": "pyspark_009_en", "id": "offline-compute_PySpark_pyspark_009", "name": "Anti-Spam H5 Work Order Log Daily Detail Sync", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that synchronizes the \"Anti-Spam H5 Work Order Log\" from ODS to the DWD detail table with full-field passthrough, and adds a run date column.\n\n**Business Background and Objective**: The anti-spam H5 work order service writes each appeal/report operation log to the raw `log_80001099` table (48 business fields + `databus_imp_date` partition). The downstream DWD wants to transport the full-field detail of the current day's partition every day, and additionally add a column `imp_date` (run date, YYYYMMDD) for convenient subsequent filtering by run date. The task has no aggregation and no joins — pure detail transport + one derived column.\n\n**Input Table**:\n- `internal_platform_db.caseR18_ods_log_80001099_v3`\n\n**Data Range and Filter Conditions (business description)**:\n - The original task in production reads from the full table (without `imp_date` filter); the sandbox v3 table is loaded by `ds` for the corresponding date, so the SELECT has no WHERE clause and reads the full table.\n - The run date `ds` is fixed as `'20260513'` and will be written as the new column `imp_date`.\n\n**Table Join Relationships**: (No joins, single-table passthrough.)\n\n**Aggregation and Computation Rules (must be reflected in the SQL)**:\n - Derived column `imp_date = '20260513'` (run date constant), placed as the first column in the SELECT.\n - The following 49 columns are passed through as-is: `databus_imp_date` + 48 business fields, in the same order as the DDL.\n - Use `INSERT OVERWRITE TABLE` + explicit column name list (50 columns) to avoid column order misalignment.\n\n**Output Requirements**:\n - Target table: `internal_platform_db.caseR18_dwd_log_80001099_daily_v3`\n - Output table schema (50 columns, in this order, with the following semantics; the first 2 columns are run/original partition date, the remaining 48 are business fields):\n 1. `imp_date` STRING: run date YYYYMMDD = `'20260513'`\n 2. `databus_imp_date` STRING: original partition date (passed through from input)\n 3. `logid` BIGINT, 4. `svrtime` STRING, 5. `svrip` STRING, 6. `module` STRING\n 7. `form_id` STRING, 8. `form_type` BIGINT, 9. `action` BIGINT, 10. `retcode` BIGINT\n 11. `vid` BIGINT, 12. `corpid` BIGINT, 13. `gid` BIGINT\n 14. `appeal_kind` BIGINT (appeal problem type), 15. `report_kind` BIGINT (report problem type), 16. `fraud_kind` BIGINT (fraud type), 17. `loss_amount` BIGINT (loss amount)\n 18. `suspect_vid` BIGINT, 19. `suspect_corpid` BIGINT\n 20. `order_id` STRING (work order number), 21. `order_result` BIGINT, 22. `order_source` BIGINT, 23. `order_action` BIGINT\n 24. `match_rule` STRING, 25. `roomid` BIGINT (problematic group number), 26. `create_vid` BIGINT, 27. `openid` STRING\n 28. `isfromwx` BIGINT (interception party ww/wx), 29. `spamtype` STRING, 30. `auto_finish_order_rule` STRING\n 31. `action_time` BIGINT (action occurrence time), 32. `industry_name` STRING, 33. `second_industry_name` STRING, 34. `is_ka` BIGINT\n 35. `create_time` STRING, 36. `urgent_time` STRING, 37. `result_time` STRING, 38. `reopen_time` BIGINT\n 39. `block_uin` BIGINT, 40. `block_user_id_type` BIGINT, 41. `version` STRING (v1/v2 differentiation)\n 42. `h5_source` BIGINT (0: frontline customer service, 1: user self-service), 43. `h5_platform` BIGINT (1: BizComm, 2: PlatformW), 44. `template_type` BIGINT\n 45. `current_owner` STRING, 46. `oid` BIGINT (appeal work order numeric ID), 47. `reason` STRING (QA closing evidence reason, base64)\n 48. `order_finish_type` STRING, 49. `reply_content` STRING (scripted reply, base64), 50. `match_rule_scene_id` BIGINT\n - Write strategy: `INSERT OVERWRITE TABLE` + explicit 50-column name list.\n - Sandbox note: The original task is encapsulated in SparkBase (SparkJob class), using the `self.load_dw_data().createOrReplaceTempView()` + `self.save_dw_data()` chain; the sandbox version is rewritten as a top-level SparkSession + a single `INSERT OVERWRITE TABLE ... SELECT`.\n - If the target table does not exist, first create it using standard Hive format (ORC storage), then write the data.", "ground_truth": "# caseR18 rewrite-gt\n# source: data/v7_gt_codes/case_row19_case_0011.py (v7 row 18, manifest_row 19)\n# task_name: t_dwd_ww_log_80001099_daily_copilot\n# rewrite rules:\n# 1) internal_platform_db.log_80001099_copilot\n# -> internal_platform_db.caseR18_ods_log_80001099_v3\n# 2) internal_platform_db.dwd_ww_log_80001099_daily_copilot\n# -> internal_platform_db.caseR18_dwd_log_80001099_daily_v3\n# 3) 删除 dw_spark_base_python3.SparkBase 框架封装:\n# - SparkJob(SparkBase) class -> 直接顶层 SparkSession\n# - self.load_dw_data(db, tbl).createOrReplaceTempView() -> 直接在 sql 里写全名\n# - self.save_dw_data(df, db_name, tbl_name) -> spark.sql('INSERT OVERWRITE TABLE ...')\n# - self.statdate -> 硬编码 '20260513'\n# - self.spark -> 顶层 spark 变量\n# 4) INSERT 用显式列名避免列序错位(50 列:imp_date + databus_imp_date + 48 业务列)\n# 5) 沙箱 v3 表无分区,databus_imp_date 在输入表中已沙箱化为普通列\n# ---\nfrom __future__ import print_function\n\nimport sys\nfrom pyspark.sql import SparkSession\n\n\nif __name__ == \"__main__\":\n ds = '20260513'\n\n spark = (\n SparkSession.builder\n .appName(\"caseR18_dwd_log_80001099_daily\")\n .enableHiveSupport()\n .getOrCreate()\n )\n\n # 确保输出表以正确 schema 存在\n spark.sql(\"DROP TABLE IF EXISTS internal_platform_db.caseR18_dwd_log_80001099_daily_v3\")\n spark.sql('''\nCREATE TABLE internal_platform_db.caseR18_dwd_log_80001099_daily_v3 (\n `imp_date` STRING COMMENT '运行日期(YYYYMMDD)',\n `databus_imp_date` STRING COMMENT '原分区日期(从输入透传)',\n `logid` BIGINT COMMENT 'logid',\n `svrtime` STRING COMMENT 'svrtime',\n `svrip` STRING COMMENT 'svrip',\n `module` STRING COMMENT 'module',\n `form_id` STRING COMMENT '表单唯一码',\n `form_type` BIGINT COMMENT '表单类型',\n `action` BIGINT COMMENT '动作类型',\n `retcode` BIGINT COMMENT '返回值',\n `vid` BIGINT COMMENT '用户帐号',\n `corpid` BIGINT COMMENT '用户公司账号',\n `gid` BIGINT COMMENT '用户gid',\n `appeal_kind` BIGINT COMMENT '申诉问题类型',\n `report_kind` BIGINT COMMENT '举报问题类型',\n `fraud_kind` BIGINT COMMENT '诈骗类型',\n `loss_amount` BIGINT COMMENT '损失金额',\n `suspect_vid` BIGINT COMMENT '举报嫌疑vid',\n `suspect_corpid` BIGINT COMMENT '举报嫌疑corpid',\n `order_id` STRING COMMENT '工单编号',\n `order_result` BIGINT COMMENT '工单结果',\n `order_source` BIGINT COMMENT '工单来源类型',\n `order_action` BIGINT COMMENT '工单动作',\n `match_rule` STRING COMMENT '工单相关的拦截规则',\n `roomid` BIGINT COMMENT '出问题的群号',\n `create_vid` BIGINT COMMENT '工单创建者vid',\n `openid` STRING COMMENT 'openid',\n `isfromwx` BIGINT COMMENT '拦截方:ww or wx',\n `spamtype` STRING COMMENT '审核定性',\n `auto_finish_order_rule` STRING COMMENT '自动结单策略',\n `action_time` BIGINT COMMENT '行为发生时间',\n `industry_name` STRING COMMENT '一级行业名称',\n `second_industry_name` STRING COMMENT '二级行业名称',\n `is_ka` BIGINT COMMENT 'corpid 是否为 ka',\n `create_time` STRING COMMENT '建单时间',\n `urgent_time` STRING COMMENT '催单时间',\n `result_time` STRING COMMENT '结单时间',\n `reopen_time` BIGINT COMMENT '重开时间(时间戳秒)',\n `block_uin` BIGINT COMMENT '实际拦截UIN',\n `block_user_id_type` BIGINT COMMENT '拦截UIN类型',\n `version` STRING COMMENT 'v1/v2 区分',\n `h5_source` BIGINT COMMENT '0:一线客服 1:用户自助',\n `h5_platform` BIGINT COMMENT '1:企业通讯平台B 2:平台W',\n `template_type` BIGINT COMMENT '在线申诉模板类型',\n `current_owner` STRING COMMENT '当前工单操作人',\n `oid` BIGINT COMMENT '申诉工单数字ID',\n `reason` STRING COMMENT 'QA结单证据原因(base64)',\n `order_finish_type` STRING COMMENT '工单结单类型',\n `reply_content` STRING COMMENT '话术回复(base64)',\n `match_rule_scene_id` BIGINT COMMENT '策略打击场景ID'\n) STORED AS ORCFILE\n''')\n\n # 反垃圾H5工单日志的每日明细同步\n sql = \"\"\"\n INSERT OVERWRITE TABLE internal_platform_db.caseR18_dwd_log_80001099_daily_v3 (\n imp_date, databus_imp_date, logid, svrtime, svrip, module, form_id, form_type, action, retcode,\n vid, corpid, gid, appeal_kind, report_kind, fraud_kind, loss_amount, suspect_vid, suspect_corpid, order_id,\n order_result, order_source, order_action, match_rule, roomid, create_vid, openid, isfromwx, spamtype, auto_finish_order_rule,\n action_time, industry_name, second_industry_name, is_ka, create_time, urgent_time, result_time, reopen_time, block_uin, block_user_id_type,\n version, h5_source, h5_platform, template_type, current_owner, oid, reason, order_finish_type, reply_content, match_rule_scene_id\n )\n select '{0}' as imp_date,\n databus_imp_date,\n logid,\n svrtime,\n svrip,\n module,\n form_id,\n form_type,\n action,\n retcode,\n vid,\n corpid,\n gid,\n appeal_kind,\n report_kind,\n fraud_kind,\n loss_amount,\n suspect_vid,\n suspect_corpid,\n order_id,\n order_result,\n order_source,\n order_action,\n match_rule,\n roomid,\n create_vid,\n openid,\n isfromwx,\n spamtype,\n auto_finish_order_rule,\n action_time,\n industry_name,\n second_industry_name,\n is_ka,\n create_time,\n urgent_time,\n result_time,\n reopen_time,\n block_uin,\n block_user_id_type,\n version,\n h5_source,\n h5_platform,\n template_type,\n current_owner,\n oid,\n reason,\n order_finish_type,\n reply_content,\n match_rule_scene_id\n from internal_platform_db.caseR18_ods_log_80001099_v3\n \"\"\".format(ds)\n print(\"sql:\")\n print(sql)\n spark.sql(sql)\n print(\"saved\")\n\n spark.stop()\n sys.exit(0)", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_009_en"} {"task_id": "pyspark_010", "id": "offline-compute_PySpark_pyspark_010", "name": "项目管理工具PM工单变更去重", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,将 项目管理工具PM 工单变更明细表做去重处理后写入 DWV 层。\n\n**业务背景**:上游 ODS 表 ods_pmtool_v_workitem_changes_df 按 databus_imp_date 分区存储 项目管理工具PM 工单的每次变更记录。同一个工单变更 ID 可能存在多条变更记录(如同一条 id 在不同时间点被多次修改),需要按 id 分组去重,保留最新的 workspace_id/workitem_id/workitem_type_id 等数值字段,以及最早的 creator/created/change_summary 等字符串字段,最终写入 DWV 汇总层供下游使用。\n\n**输入表**:\n- `internal_platform_db.ods_pmtool_v_workitem_changes_df_pyspark_245`\n\n**数据范围**:只取 databus_imp_date = '20260513' 分区的数据。\n\n**计算规则**:\n1. 按 id 分组 GROUP BY\n2. workspace_id、workitem_id、workitem_type_id 取 max(最新值)\n3. creator、created、change_summary、comment、changes、entity_type、change_type 取 first(最早值)\n4. _srcinstanceid、_srcdatabasename 输出空字符串\n\n**输出要求**:\n- 目标表:`internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245`\n- 分区:year='2026', month='05', day='13'\n- 写入策略:INSERT OVERWRITE TABLE ... PARTITION(year='2026', month='05', day='13')\n- 如果目标表不存在,请先按 Hive 标准建表(ORC 存储 + 分区),再写入数据。", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"pyspark_010: 项目管理工具PM workitem changes DWV - GROUP BY dedup + partition write\"\"\"\n\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName('dwv_pmtool_workitem_changes_df') \\\n .enableHiveSupport() \\\n .getOrCreate()\n\nds = '20260513'\nds_year = '2026'\nds_month = '05'\nds_day = '13'\n\n# 输出表 DDL\nspark.sql(\"DROP TABLE IF EXISTS internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245\")\nspark.sql('''\nCREATE TABLE internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245 (\n `id` STRING,\n `workspace_id` BIGINT,\n `workitem_id` BIGINT,\n `workitem_type_id` BIGINT,\n `creator` STRING,\n `created` STRING,\n `change_summary` STRING,\n `comment` STRING,\n `changes` STRING,\n `entity_type` STRING,\n `change_type` STRING,\n `_srcinstanceid` STRING,\n `_srcdatabasename` STRING\n)\nPARTITIONED BY (`year` STRING, `month` STRING, `day` STRING)\nSTORED AS ORC\n''')\n\nsql = '''\n WITH workitem_changes AS (\n SELECT * FROM internal_platform_db.ods_pmtool_v_workitem_changes_df_pyspark_245\n WHERE databus_imp_date = '20260513'\n )\n INSERT OVERWRITE TABLE internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245\n PARTITION(year='2026', month='05', day='13')\n SELECT\n `id`, max(`workspace_id`) AS workspace_id,\n max(`workitem_id`) AS workitem_id,\n max(`workitem_type_id`) AS workitem_type_id,\n first(`creator`) AS creator,\n first(`created`) AS created,\n first(`change_summary`) AS change_summary,\n first(`comment`) AS comment,\n first(`changes`) AS changes,\n first(`entity_type`) AS entity_type,\n first(`change_type`) AS change_type,\n '' AS _srcinstanceid,\n '' AS _srcdatabasename\n FROM workitem_changes\n GROUP BY id\n'''\n\nprint(sql)\nresult = spark.sql(sql)\nprint(result.show())\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_010"} {"task_id": "pyspark_011_en", "id": "offline-compute_PySpark_pyspark_011", "name": "Phone Number Encrypted Prefix Quality Score Statistics", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that computes a phone number encrypted prefix quality score statistics table.\n\n**Business Background and Objective**: The phone number quality score table stores the quality score (`maochi` field) for each phone number encrypted string. Operations needs to perform aggregation analysis on the first 7 characters of the encrypted prefix for each phone number, computing the average quality score, malicious ratio, and whitelist ratio under that prefix. The aggregation results are then backfilled onto each detail record to produce a wide table with prefix-level statistical dimensions.\n\n**Input Table**:\n- `internal_platform_db.t_dwd_phone_enc_quality_score_df_pyspark_216`\n\n**Data Range and Filter Conditions**:\n- Run date `ds` is fixed as `'20260513'`\n- Filter out invalid records where `maochi = -9`\n\n**Computation Rules**:\n1. Use `substr(phone_enc, 1, 7)` to extract the phone number encrypted prefix `phone_enc_p7`\n2. Group by `phone_enc_p7` and aggregate:\n - `prefix_1_7_score = floor(avg(maochi) * 10000)`: prefix average quality score (scaled by 10000)\n - `prefix_1_7_evil_score = floor(count(if(maochi >= -4 and maochi <= -2, 1, NULL)) * 10000 / count(1))`: prefix malicious ratio (in parts per ten thousand)\n - `prefix_1_7_white_score = floor(count(if(maochi >= 2 and maochi <= 4, 1, NULL)) * 10000 / count(1))`: prefix whitelist ratio (in parts per ten thousand)\n3. LEFT JOIN to associate the prefix aggregation results back to the original detail records\n\n**Output Requirements**:\n- Target table: `internal_platform_db.t_dwd_phone_enc_prefix_quality_score_df_pyspark_216`\n- Partition field: `p_date='20260513'`\n- Output columns: `ds`, `phone_enc`, `quality_score`, `prefix_1_7_score`, `prefix_1_7_evil_score`, `prefix_1_7_white_score`\n- Write strategy: First create the table (ORC storage), then use `INSERT OVERWRITE TABLE PARTITION(p_date=...)` to write", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\npyspark_011: Phone enc prefix quality score\n- Read t_dwd_phone_enc_quality_score_df, filter maochi != -9\n- Use substr() to extract phone_enc prefix (first 7 chars) instead of Java UDF IdSubstr\n- CTE aggregation per prefix: avg quality_score, evil ratio, white ratio\n- LEFT JOIN back to original, output with ds='20260513'\n\"\"\"\n\nfrom pyspark.sql import SparkSession\n\nspark = (\n SparkSession.builder\n .appName('pyspark_011_phone_enc_prefix_score')\n .enableHiveSupport()\n .getOrCreate()\n)\n\nTODAY = '20260513'\n\nquery = \"\"\"\n with t_phone_enc_score as (\n select\n phone_enc,\n maochi,\n substr(phone_enc, 1, 7) as phone_enc_p7\n from internal_platform_db.t_dwd_phone_enc_quality_score_df_pyspark_216\n where ds = {today} and maochi != -9\n ), t_phone_enc_p7_score as (\n select\n phone_enc_p7,\n floor(avg(maochi) * 10000) as prefix_1_7_score,\n floor(count(if(maochi >= -4 and maochi <= -2, 1, NULL)) * 10000 / count(1)) as prefix_1_7_evil_score,\n floor(count(if(maochi >= 2 and maochi <= 4, 1, NULL)) * 10000 / count(1)) as prefix_1_7_white_score\n from\n t_phone_enc_score\n group by\n phone_enc_p7\n ), t_merge as (\n select\n phone_enc,\n maochi as quality_score,\n prefix_1_7_score,\n prefix_1_7_evil_score,\n prefix_1_7_white_score\n from\n t_phone_enc_score t1\n left join\n t_phone_enc_p7_score t2\n on\n t1.phone_enc_p7 = t2.phone_enc_p7\n )\n select {today} as ds, phone_enc, quality_score, prefix_1_7_score, prefix_1_7_evil_score, prefix_1_7_white_score from t_merge\n\"\"\".format(today=TODAY)\nprint(f\"query_sql: {query}\")\ndf = spark.sql(query)\ndf.createOrReplaceTempView(\"tmp_result\")\n\n# Output table DDL\nspark.sql('DROP TABLE IF EXISTS internal_platform_db.t_dwd_phone_enc_prefix_quality_score_df_pyspark_216')\nspark.sql('''\nCREATE TABLE internal_platform_db.t_dwd_phone_enc_prefix_quality_score_df_pyspark_216 (\n `ds` STRING,\n `phone_enc` STRING,\n `quality_score` INT,\n `prefix_1_7_score` BIGINT,\n `prefix_1_7_evil_score` BIGINT,\n `prefix_1_7_white_score` BIGINT\n) PARTITIONED BY (`p_date` STRING)\nSTORED AS ORC\n''')\n\n# Write output via INSERT OVERWRITE with explicit partition\nspark.sql(\"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.t_dwd_phone_enc_prefix_quality_score_df_pyspark_216\nPARTITION (p_date='{0}')\nSELECT ds, phone_enc, quality_score, prefix_1_7_score, prefix_1_7_evil_score, prefix_1_7_white_score\nFROM tmp_result\n\"\"\".format(TODAY))\n\nprint(\"pyspark_011 done\")\n\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_011_en"} {"task_id": "pyspark_012", "id": "offline-compute_PySpark_pyspark_012", "name": "网页解析结果Top500详情统计", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,对网页解析结果进行质量统计,产出 Top500 站点的详情日报表。\n\n**业务背景与目标**:每天都会对大量网页进行解析,解析结果记录在 `ai_engine_classify_parse_result_daily` 表中。安全部门需要按站点维度统计解析质量,包括成功/失败解析数、索引页占比、短内容占比、各错误步骤分布等,并与站点优先级信息关联,生成一张按日期和站点粒度的解析质量详情表。\n\n**输入表**:\n- `internal_platform_db.sec_app_hy_top_500_sites_tag_v1_pyspark_100`\n- `internal_platform_db.ai_engine_classify_parse_result_daily_pyspark_100`\n\n**数据范围与过滤条件**:\n- 运行日期 today_str 固定为 '20260513'\n- 数据范围:date_key 从 '20260508' 到 '20260513'(最近 5 天)\n\n**计算规则**:\n1. 从 parse_html JSON 字段中提取 content 字段(使用 from_json + schema_of_json)\n2. 计算 content_length = length(content)\n3. 按 (date_key, host, fld) 分组聚合:\n - 成功解析数 successful_parses、失败解析数 failed_parses、总解析数 total_parses\n - 索引页数 index_page_count(web_type='索引页')、索引页比例 index_page_count_rate = index_page_count/total_parses\n - 短内容数 short_content_count(content_length < 50)、短内容比例 short_content_count_rate = short_content_count/successful_parses\n - 各错误步骤计数:error_step_1_count、error_step_2_count、error_step_3_count\n4. LEFT JOIN 关联 priority_info:匹配条件为 source_fld = priority_info.fld OR source_host = priority_info.host\n5. 去重:dropDuplicates([\"date_key\", \"host\", \"fld\", \"priority\", \"successful_parses\", \"total_parses\", \"index_page_count\"])\n\n**输出要求**:\n- 目标表:`internal_platform_db.ai_engine_classify_parse_result_daily_detail_pyspark_100`\n- 写入策略:先建表(ORC 存储,16 列),再使用 df.write.mode(\"overwrite\").insertInto() 写入\n- 输出列:date_key, host, fld, is_host, priority, successful_parses, failed_parses, total_parses, index_page_count, index_page_count_rate, short_content_count, short_content_count_rate, error_step_1_count, error_step_2_count, error_step_3_count, error_info_list", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\npyspark_012: AI search parse results top500 detail\n- 3 input tables: priority_info, daily parse results\n- Date range: hardcode today_str='20260513', five_days_ago='20260508'\n- Parse content JSON from parse_html field using from_json\n- Compute summary stats, index_page_ratio, content_length_ratio, error_reasons\n- Join with priority_info on fld or host match\n- Output via df.write.mode(\"overwrite\").insertInto()\n\"\"\"\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col, count, when, length, sum as _sum, from_json, schema_of_json, lit\nfrom pyspark.sql import functions as F\n\nspark = (\n SparkSession.builder\n .appName('pyspark_012_ai_engine_parse_detail')\n .enableHiveSupport()\n .getOrCreate()\n)\n\ntoday_str = '20260513'\nfive_days_ago = '20260508'\nprint(today_str, five_days_ago)\n\n# Read priority info\npriority_info = spark.table(\"internal_platform_db.sec_app_hy_top_500_sites_tag_v1_pyspark_100\").select(\n \"host\", \"fld\", \"priority\"\n)\n\n# Read data from past 5 days\ndf = spark.table(\"internal_platform_db.ai_engine_classify_parse_result_daily_pyspark_100\").filter(\n (col(\"date_key\") >= five_days_ago) & (col(\"date_key\") <= today_str)\n)\n\n# Parse data\nparsed_data = df.select(\n \"date_key\",\n col(\"host\").alias(\"source_host\"),\n when(col(\"is_error\") == 0, 1).otherwise(0).alias(\"success\"),\n when(col(\"is_error\") == 1, 1).otherwise(0).alias(\"failure\"),\n \"web_type\",\n from_json(col(\"parse_html\"), schema_of_json('{\"content\": \"string\"}')).getField(\"content\").alias(\"content\"),\n \"error_step\",\n col(\"fld\").alias(\"source_fld\")\n)\n\n# Compute content length\nparsed_data = parsed_data.withColumn(\"content_length\", length(col(\"content\")))\n\n# Summary stats\nsummary = parsed_data.groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(\"success\").alias(\"successful_parses\"),\n _sum(\"failure\").alias(\"failed_parses\"),\n count(\"*\").alias(\"total_parses\")\n)\n\n# Index page ratio\nindex_page_ratio = parsed_data.groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(when(col(\"web_type\") == \"索引页\", 1).otherwise(0)).alias(\"index_page_count\")\n)\n\n# Content length ratio\ncontent_length_ratio = parsed_data.filter(col(\"success\") == 1).groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(when(col(\"content_length\") < 50, 1).otherwise(0)).alias(\"short_content_count\")\n)\n\n# Error reasons\nerror_reasons = parsed_data.filter(col(\"failure\") == 1).groupBy(\"date_key\", \"source_host\", \"source_fld\").agg(\n _sum(when(col(\"error_step\") == 1, 1).otherwise(0)).alias(\"error_step_1_count\"),\n _sum(when(col(\"error_step\") == 2, 1).otherwise(0)).alias(\"error_step_2_count\"),\n _sum(when(col(\"error_step\") == 3, 1).otherwise(0)).alias(\"error_step_3_count\"),\n _sum(when(col(\"error_step\").isNotNull(), 1).otherwise(0)).alias(\"total_error_steps\")\n)\n\n# Merge all aggregations\nfinal_result = summary.join(index_page_ratio, [\"date_key\", \"source_host\", \"source_fld\"], \"left\") \\\n .join(content_length_ratio, [\"date_key\", \"source_host\", \"source_fld\"], \"left\") \\\n .join(error_reasons, [\"date_key\", \"source_host\", \"source_fld\"], \"left\")\n\n# Calculate ratios\nfinal_result = final_result.withColumn(\n \"index_page_count_rate\",\n col(\"index_page_count\") / col(\"total_parses\")\n).withColumn(\n \"short_content_count_rate\",\n col(\"short_content_count\") / col(\"successful_parses\")\n)\n\n# Add placeholder columns\nfinal_result = final_result.withColumn(\"error_info_list\", lit(\"default_value\"))\nfinal_result = final_result.withColumn(\"is_host\", lit(\"default_value\"))\n\n# Join with priority info\nfinal_result = final_result.join(\n priority_info,\n (final_result.source_fld == priority_info.fld) |\n (final_result.source_host == priority_info.host),\n \"left\"\n)\n\n# Select final columns\nfinal_result = final_result.select(\n \"date_key\",\n F.col(\"source_host\").alias(\"host\"),\n F.col(\"source_fld\").alias(\"fld\"),\n \"is_host\",\n \"priority\",\n \"successful_parses\",\n \"failed_parses\",\n \"total_parses\",\n \"index_page_count\",\n \"index_page_count_rate\",\n \"short_content_count\",\n \"short_content_count_rate\",\n \"error_step_1_count\",\n \"error_step_2_count\",\n \"error_step_3_count\",\n \"error_info_list\"\n)\n\nfinal_result = final_result.dropDuplicates([\"date_key\", \"host\", \"fld\", \"priority\", \"successful_parses\", \"total_parses\", \"index_page_count\"])\n\n# Output table DDL\nspark.sql('DROP TABLE IF EXISTS internal_platform_db.ai_engine_classify_parse_result_daily_detail_pyspark_100')\nspark.sql('''\nCREATE TABLE internal_platform_db.ai_engine_classify_parse_result_daily_detail_pyspark_100 (\n `date_key` STRING,\n `host` STRING,\n `fld` STRING,\n `is_host` STRING,\n `priority` STRING,\n `successful_parses` STRING,\n `failed_parses` STRING,\n `total_parses` STRING,\n `index_page_count` STRING,\n `index_page_count_rate` STRING,\n `short_content_count` STRING,\n `short_content_count_rate` STRING,\n `error_step_1_count` STRING,\n `error_step_2_count` STRING,\n `error_step_3_count` STRING,\n `error_info_list` STRING\n)\nSTORED AS ORC\n''')\n\n# Write output\nfinal_result.write.mode(\"overwrite\").insertInto(\"internal_platform_db.ai_engine_classify_parse_result_daily_detail_pyspark_100\")\n\nprint(\"pyspark_012 done\")\n\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_012"} {"task_id": "pyspark_013", "id": "offline-compute_PySpark_pyspark_013", "name": "银行XURL安全关系关联", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,从平台 URL 安全关系中提取银行X相关的贷中和意愿用户样本。\n\n**业务背景与目标**:安全部门维护了一份平台 guid 与 URL 的关系表,记录了用户访问过的 URL 及其 cgi 信息。风控业务需要从这份关系表中筛选出访问过银行X(bankx.com.cn)特定页面的用户,按贷款阶段分为\"贷中用户\"和\"意愿用户\"两类,输出到贷款用户样本表中,供下游风控模型使用。\n\n**输入表**:\n- `internal_platform_db.t_dwd_urlsafe_rela_guid_url_di_pyspark_101`\n\n**数据范围与过滤条件**:\n- 运行日期 ds 固定为 20260513(BIGINT 类型)\n- 域名过滤:domain = 'bankx.com.cn'\n- 站点过滤:site = 'm1.bankx.com.cn'\n\n**计算规则**:\n1. **贷中用户识别**:cgi 包含 `http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/WXMAIN/LOAN-REPAY-PLAN`,loan_stage 标记为 'in-loan'\n2. **意愿用户识别**:cgi 包含以下任一 URL 模式(18 个 will_cgis),loan_stage 标记为 'will':\n - LOANS/MAIN/XWMINI, LOANS/AUTHORIZATION, LOANS/DATA-SELF-ATTESTATION-CHECK, LOANS/DATA-SELF-ATTESTATION-EDIT, LOANS/MAIN/XWMINI-RESULT\n - FEIMA 系列路径\n3. 两类用户分别选取字段:uid(来自 guid), loan_type='unknown', city='unknown', industry='unknown', entity_name='unknown', legal_person='unknown', loan_stage, details(来自 url)\n4. 各用户组内按 uid 去重\n5. Union 合并后,整体按 uid 去重\n6. 写入时同时指定分区值:ds=20260513, data_source='social', id_type='guid'\n\n**输出要求**:\n- 目标表:`internal_platform_db.t_rta_loan_url_samples_pyspark_101`\n- 分区字段:ds BIGINT, data_source STRING, id_type STRING\n- 写入策略:先建表(ORC 存储,8 个非分区列 + 3 个分区列),再 INSERT OVERWRITE TABLE PARTITION(ds=..., data_source=..., id_type=...) SELECT * FROM tmp_view", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\npyspark_013: URL safety relation join (银行X)\n- 2 input tables: t_dwd_urlsafe_rela_guid_url_di, t_rta_loan_url_samples\n- Hardcode: ds='20260513', target_domain='bankx.com.cn', data_source='social'\n- Define in_loan_cgi and will_cgis URL patterns for BankX bank\n- Build in-loan users: match on in_loan_cgi, select uid + unknown placeholders\n- Build will users: match on will_cgis, select uid + unknown placeholders\n- Union, dropDuplicates, insert overwrite into output table partitioned by (ds, data_source, id_type)\n\"\"\"\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\n\nspark = SparkSession.builder.appName(\"pyspark_013_bankx\").enableHiveSupport().getOrCreate()\n\nds = '20260513'\ntarget_domain = 'bankx.com.cn'\ndata_source = 'social'\ndst_tb = \"internal_platform_db.t_rta_loan_url_samples_pyspark_101\"\ntarget_dfs = []\n\ndf = spark.sql(\n f\"select guid as uid, url, site, cgi from internal_platform_db.t_dwd_urlsafe_rela_guid_url_di_pyspark_101 where ds={ds} and domain='{target_domain}'\"\n).cache()\n\nwill_cgis = [\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/MAIN/XWMINI\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/786_3ZC6V00SCTS/KVP64MGHE6\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-NG/LOAN/OPEN-MINI-PROGRAM\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/786_3ZC6V00SCTS/EH29NY7VX6O\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/AUTHORIZATION\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/404/5297_ID8OJSK0CA/GO6WAHCH1Q8\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/2030_X896J30LP0M/32Z34ISSCYM\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/404/4995_PQD15LFBWHK/J4AUCBG4T9Q\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/DATA-SELF-ATTESTATION-CHECK\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/782_GCZRA2IPYHI/M5L9X3HI1YD\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/1488_AIX7S10A5D/YXES5G44DDI\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/DATA-SELF-ATTESTATION-EDIT\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/672_C1HLFOASYSA/3RVSG4RH23C\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/MAIN/XWMINI-RESULT\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/1488_AIX7S10A5D/2NS3G56ZR4P\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/2030_X896J30LP0M/2NS3G56ZR4P\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/404/4995_PQD15LFBWHK/2NS3G56ZR4P\",\n \"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/FEIMA/4/1792_ZHAWK9C9K1/LXTCEQ1UIO\"\n]\n\nin_loan_cgi = [\"http://m1.bankx.com.cn/BankX_MBSERVER/NEW/APP/MOBILE-BANK-H5/LOANS/WXMAIN/LOAN-REPAY-PLAN\"]\n\n# Build in-loan users\ninloan_condition = None\nfor url in in_loan_cgi:\n if inloan_condition is None:\n inloan_condition = F.col(\"cgi\").contains(url)\n else:\n inloan_condition = inloan_condition | F.col(\"cgi\").contains(url)\n\ntarget_dfs.append(\n df.filter(F.col(\"site\") == \"m1.bankx.com.cn\")\n .filter(inloan_condition)\n .withColumn(\"loan_stage\", F.lit('in-loan'))\n .selectExpr(\n \"uid\",\n \"'unknown' as loan_type\",\n \"'unknown' as city\",\n \"'unknown' as industry\",\n \"'unknown' as entity_name\",\n \"'unknown' as legal_person\",\n \"loan_stage\",\n \"url as details\",\n ).dropDuplicates([\"uid\"])\n)\n\n# Build will users\nwill_condition = None\nfor url in will_cgis:\n if will_condition is None:\n will_condition = F.col(\"cgi\").contains(url)\n else:\n will_condition = will_condition | F.col(\"cgi\").contains(url)\n\ntarget_dfs.append(\n df.filter(F.col(\"site\") == \"m1.bankx.com.cn\")\n .filter(will_condition)\n .withColumn(\"loan_stage\", F.lit('will'))\n .selectExpr(\n \"uid\",\n \"'unknown' as loan_type\",\n \"'unknown' as city\",\n \"'unknown' as industry\",\n \"'unknown' as entity_name\",\n \"'unknown' as legal_person\",\n \"loan_stage\",\n \"url as details\",\n ).dropDuplicates([\"uid\"])\n)\n\n# Union all\nresult_df = target_dfs[0]\nfor df_item in target_dfs[1:]:\n result_df = result_df.union(df_item)\n\nresult_df = result_df.cache()\nresult_df = result_df.dropDuplicates([\"uid\"])\nprint(f\"len of result_df: {result_df.count()}\")\n\nresult_df.createOrReplaceTempView(\"tmp_df\")\n\n# Output table DDL\nspark.sql('DROP TABLE IF EXISTS internal_platform_db.t_rta_loan_url_samples_pyspark_101')\nspark.sql('''\nCREATE TABLE internal_platform_db.t_rta_loan_url_samples_pyspark_101 (\n `uid` STRING,\n `loan_type` STRING,\n `city` STRING,\n `industry` STRING,\n `entity_name` STRING,\n `legal_person` STRING,\n `loan_stage` STRING,\n `details` STRING\n) PARTITIONED BY (`ds` BIGINT, `data_source` STRING, `id_type` STRING)\nSTORED AS ORC\n''')\n\nsql = f\"insert overwrite table {dst_tb} partition(ds={ds}, data_source='{data_source}', id_type='guid') select * from tmp_df\"\nprint(sql)\nspark.sql(sql)\nprint(\"pyspark_013 done\")\n\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_013"} {"task_id": "pyspark_014", "id": "offline-compute_PySpark_pyspark_014", "name": "过去半年在线过的实验计划信息查询", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,查询过去半年内上线过的实验计划信息,取每个实验分组的最新一条记录。\n\n**业务背景与目标**:实验平台按小时维度存储了实验计划的上线记录(fdate, exp_group_id, trigger_list)。运营需要从过去 180 天(半年)的历史数据中,按实验分组 exp_group_id 维度取最新的一条记录,输出到结果表中,用于后续的实验分析。\n\n**输入表**:\n- `internal_platform_db.exp_hours_input_pyspark_102`\n\n**数据范围与过滤条件**:\n- 运行日期 cur_date 固定为 '20260513'\n- 历史天数 history_days 固定为 180\n- 读取的分区范围:从 p_2026051300 往前推 180 * 24 = 4320 个小时的所有分区\n- 分区格式:p_YYYYMMDDHH\n\n**计算规则**:\n1. 生成历史分区列表:使用 Python time 模块,从 cur_date 当天 00:00:00 开始,依次减去 1 小时,共生成 history_days * 24 个分区名(如 p_2026051300, p_2026051223, p_2026051222, ...)\n2. 使用 WHERE p_hour IN (...) 过滤读取所有历史分区数据\n3. 使用窗口函数 row_number() OVER (PARTITION BY exp_group_id ORDER BY fdate DESC) 计算 date_rank_no\n4. 过滤 date_rank_no = 1,取每个实验分组的最新记录\n5. 添加 fdate = lit(cur_date) 列\n\n**输出要求**:\n- 目标表:`internal_platform_db.exp_hours_output_pyspark_102`\n- 写入策略:先建表(ORC 存储,5 列),再 INSERT OVERWRITE TABLE 写入\n- 输出列:exp_date, exp_group_id, trigger_list, date_rank_no, fdate", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\npyspark_014: Experiment plans past half year query\n- 1 input table: exp_hours_input_pyspark_102 (fdate, exp_group_id, trigger_list, partitioned by p_hour)\n- Read all partitions from p_2026051300 back to p_2026051300 - 24*180 hours (half year)\n- Hardcode: cur_date='20260513', history_days=180\n- Generate list of hour partitions to read\n- Window function: rank() over (partition by exp_group_id order by fdate desc), keep rank=1\n- Add fdate = lit(cur_date)\n- Output table: exp_hours_output_pyspark_102 via INSERT OVERWRITE TABLE\n\"\"\"\n\nimport time\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.window import Window\n\ncur_date = '20260513'\nhistory_days = 180\n\ndef get_history_hours(cur_date, history_days):\n cur_hour = cur_date + \" 00:00:00\"\n cur_ts = int(time.mktime(time.strptime(cur_hour, \"%Y%m%d %H:%M:%S\")))\n history_hours = []\n history_hour_num = history_days * 24\n for i in range(history_hour_num):\n history_hour = time.strftime(\"%Y%m%d%H\", time.localtime(cur_ts - i * 3600))\n history_hours.append(\"p_\" + history_hour)\n return history_hours\n\npartition_list = get_history_hours(cur_date, history_days)\nprint(\"cur_date: \" + cur_date)\nprint(\"history_days: \" + str(history_days))\nprint(\"partition_list length: \" + str(len(partition_list)))\n\nspark = SparkSession.builder \\\n .appName('pyspark_014_exp_plans') \\\n .enableHiveSupport() \\\n .getOrCreate()\n\n# Read all history partitions using a single SQL with OR conditions on partition values\n# Build partition filter string\npartition_filters = \", \".join([\"'%s'\" % p for p in partition_list])\nspark.sql(\"\"\"\n SELECT fdate, exp_group_id, trigger_list\n FROM internal_platform_db.exp_hours_input_pyspark_102\n WHERE p_hour IN ({0})\n\"\"\".format(partition_filters)).createOrReplaceTempView(\"t_exp_hours\")\n\nsql = '''\n select\n fdate as exp_date,\n exp_group_id,\n trigger_list\n from\n t_exp_hours\n'''\nprint(\"sql: \" + sql)\nexp_hours_df = spark.sql(sql)\nexp_hours_df.printSchema()\n\n# Window function: rank by exp_date desc per exp_group_id\nexp_partition_window = Window.partitionBy([\"exp_group_id\"]).orderBy(exp_hours_df[\"exp_date\"].desc())\nexp_hours_df = exp_hours_df.withColumn(\"date_rank_no\", F.row_number().over(exp_partition_window))\nexp_hours_df = exp_hours_df.filter(exp_hours_df.date_rank_no == 1)\nexp_hours_df = exp_hours_df.withColumn(\"fdate\", F.lit(cur_date))\n\n# Output table DDL\nspark.sql('DROP TABLE IF EXISTS internal_platform_db.exp_hours_output_pyspark_102')\nspark.sql('''\nCREATE TABLE internal_platform_db.exp_hours_output_pyspark_102 (\n `exp_date` STRING,\n `exp_group_id` STRING,\n `trigger_list` STRING,\n `date_rank_no` INT,\n `fdate` STRING\n)\nSTORED AS ORC\n''')\n\n# Write output via INSERT OVERWRITE TABLE\nexp_hours_df.createOrReplaceTempView(\"tmp_result\")\nspark.sql(\"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.exp_hours_output_pyspark_102\nSELECT exp_date, exp_group_id, trigger_list, date_rank_no, fdate\nFROM tmp_result\n\"\"\")\n\nprint(\"pyspark_014 done\")\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_014"} {"task_id": "pyspark_015", "id": "offline-compute_PySpark_pyspark_015", "name": "用户标签同步ETL", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,完成\"用户标签同步ETL\"的数据加工任务。\n\n**业务背景与目标**:安全平台每天从 event_log 日志中采集用户设备与标签数据(t_sh_event_log_v2_xab00014231),数据中包含手机号、IMEI、IMSI、AndroidID 等敏感信息,这些字段在原始日志中已经过在线加密(OnlineCrypt)存储为加密字段。本任务需要将加密字段解密后,使用加密算法重新加密,同时对数据类型字段做 INT 转换,最终写入下游用户标签同步表(t_ods_comm_security_user_tag_sync_hi)供安全分析使用。\n\n**输入表**:\n- `internal_platform_db.t_sh_event_log_v2_xab00014231_pyspark_254`\n\n**数据范围与过滤条件(业务说法)**:\n- 运行日期 ds 固定为 '20260513'(沙箱化日期,原任务由调度框架传入)。\n- 从输入表中读取 ds = '20260513' 分区的全量数据,不做额外过滤。\n\n**计算规则(需体现在 SQL/PySpark 中)**:\n1. **字段映射与类型转换**:\n - server_ip、tag_name、ip、ip_md5、ip_c_segment、manufacture、model、language、region、sdk_version、ip_country、ip_province、ip_city、ip_district → 原样透传\n - `time` → log_time(字段重命名)\n - src → CAST(src AS INT)\n - phonetype → CAST(phonetype AS INT)\n - apn → CAST(apn AS INT)\n - auth_type → CAST(auth_type AS INT)\n - call_type → CAST(call_type AS INT)\n - duration → CAST(duration AS INT)\n\n2. **敏感字段加密**(原逻辑:OnlineCrypt 解密 → IdCrypt 重新加密;沙箱改写为 sha2 哈希):\n - phonenum → sha2(phonenum, 256) AS phonenum_enc\n - self_phone → sha2(self_phone, 256) AS self_phone_enc\n - imei → sha2(imei, 256) AS imei_enc\n - imsi → sha2(imsi, 256) AS imsi_enc\n - phonenum_reg → sha2(phonenum_reg, 256) AS phonenum_reg_enc\n - android_id → sha2(android_id, 256) AS android_id_enc\n\n**输出要求**:\n- 目标表:`internal_platform_db.t_ods_comm_security_user_tag_sync_hi_pyspark_254`\n- 写入策略:INSERT OVERWRITE TABLE,使用显式分区写入 partition(ds='20260513')\n- 如果目标表不存在,请先按 Hive 标准建表(ORC 存储,分区列 ds),再写入数据。", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\npyspark_015: 用户标签同步ETL (Java UDF -> sha2 改写)\n- 原 pytoolkit/IdCrypt/OnlineCrypt 替换为内置 sha2() 函数\n- 原 self.statdate 硬编码为 '20260513'(沙箱化日期)\n- 原 self.save_dw_data 改为 spark.sql INSERT OVERWRITE TABLE\n\"\"\"\n\nfrom pyspark.sql import SparkSession\n\nspark = (\n SparkSession.builder\n .appName('pyspark_015_user_tag_sync')\n .enableHiveSupport()\n .getOrCreate()\n)\n\nds = '20260513'\n\n# Create output table DDL\nspark.sql('DROP TABLE IF EXISTS internal_platform_db.t_ods_comm_security_user_tag_sync_hi_pyspark_254')\nspark.sql('''\nCREATE TABLE internal_platform_db.t_ods_comm_security_user_tag_sync_hi_pyspark_254 (\n server_ip STRING,\n log_time STRING,\n src INT,\n phonenum_enc STRING,\n tag_name STRING,\n self_phone_enc STRING,\n ip STRING,\n imei_enc STRING,\n imsi_enc STRING,\n phonenum_reg_enc STRING,\n phonetype INT,\n apn INT,\n ip_md5 STRING,\n ip_c_segment STRING,\n auth_type INT,\n android_id_enc STRING,\n manufacture STRING,\n model STRING,\n language STRING,\n region STRING,\n sdk_version STRING,\n call_type INT,\n duration INT,\n ip_country STRING,\n ip_province STRING,\n ip_city STRING,\n ip_district STRING\n) PARTITIONED BY (ds STRING)\nSTORED AS ORC\n''')\n\n# Business logic: read from source, apply transformations, write to target\n# Original: OnlineCrypt decrypt encrypted fields -> IdCrypt re-encrypt\n# Rewrite: sha2() on plaintext fields to produce encrypted output\nspark.sql(\"\"\"\nINSERT OVERWRITE TABLE internal_platform_db.t_ods_comm_security_user_tag_sync_hi_pyspark_254 partition(ds='{ds}')\nSELECT server_ip\n ,`time` AS log_time\n ,CAST(src AS INT) AS src\n ,sha2(phonenum, 256) AS phonenum_enc\n ,tag_name\n ,sha2(self_phone, 256) AS self_phone_enc\n ,ip\n ,sha2(imei, 256) AS imei_enc\n ,sha2(imsi, 256) AS imsi_enc\n ,sha2(phonenum_reg, 256) AS phonenum_reg_enc\n ,CAST(phonetype AS INT) AS phonetype\n ,CAST(apn AS INT) AS apn\n ,ip_md5\n ,ip_c_segment\n ,CAST(auth_type AS INT) AS auth_type\n ,sha2(android_id, 256) AS android_id_enc\n ,manufacture\n ,model\n ,language\n ,region\n ,sdk_version\n ,CAST(call_type AS INT) AS call_type\n ,CAST(duration AS INT) AS duration\n ,ip_country\n ,ip_province\n ,ip_city\n ,ip_district\nFROM internal_platform_db.t_sh_event_log_v2_xab00014231_pyspark_254\nWHERE ds = '{ds}'\n\"\"\".format(ds=ds))\n\nprint(\"pyspark_015 done\")\n\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_015"} {"task_id": "pyspark_016", "id": "offline-compute_PySpark_pyspark_016", "name": "代码评审组织排行", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,产出代码协作平台代码评审(CR)按组织维度的排名表。\n\n**业务背景与目标**:代码协作平台每天都会产生代码评审数据,包括评审注释(line_note)和评审耗时(used_time)。运营希望按公司/部门/中心/小组四级组织维度,对成员进行两个维度的 Top10 排名:(1) 按评审注释数降序排名(notes_create_desc);(2) 按评审投入时间降序排名(cr_used_time_desc)。通过 rank_space 交叉连接生成完整的排名空间,左连接实际数据,产出组织排名明细表。\n\n**输入表**:\n- `internal_platform_db.dim_org_framework_org_d_f_pyspark_220`\n- `internal_platform_db.dim_code_employee_user_org_relation_bare_d_f_pyspark_220`\n- `internal_platform_db.dual_pyspark_220`\n- `internal_platform_db.dwm_code_review_note_user_stat_d_f_pyspark_220`\n- `internal_platform_db.dwd_code_review_used_time_d_i_pyspark_220`\n\n**数据范围与过滤条件**:\n- 运行日期 ds 固定为 '20260513'\n- 月份范围:month_start='2026-05-01', month_end='2026-06-01'\n- org 数据过滤 CONCAT(year,month,day) = ds\n- note 数据过滤 concat(year,month,day) = ds,且 note_crt_date 在 [month_start, month_end) 区间\n- used_time 数据过滤 dt 在 [month_start, month_end) 区间,且 (is_reviewer=1 OR is_fileowner=1)\n\n**处理逻辑**:\n1. 从 dim_org_framework_org 构建四级组织 CTE(cp 公司, dp 部门, ct 中心, gp 小组),每级提取对应的层级 ID\n2. 将员工关联到各层级组织(cp_user, dp_user, ct_user, gp_user)\n3. 计算 line_note_list(按 author_id 汇总 line_human_note_cnt)和 used_time_list(按 reviewer_id 汇总 duration_today)\n4. 对每级组织的用户按两个 ranktype 分别做 rank() 窗口排序\n5. 生成 rank_space(ranktype × rank 1-10 的笛卡尔积)\n6. 各组织级别 cross join rank_space,left join 对应的排名结果\n7. 四级结果 union all 后写入目标表\n\n**输出要求**:\n- 目标表:`internal_platform_db.ads_code_code_platform_mon_cr_org_rank_d_i_pyspark_220`\n- 写入策略:INSERT OVERWRITE TABLE\n- 输出列:month_name, month_start, month_end, org_id, org_type, ranktype, rank, user_id, user_name, value_string, value_int, value_float, value_datetime, created_at", "ground_truth": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\npyspark_220: 代码协作平台CR组织排名 - Code Review Org Ranking (L3)\n- 沙箱化改写:硬编码日期 '20260513',移除 pytoolkit/dateutil 依赖\n- 使用 spark.sql() 执行全部 CTE 逻辑\n\"\"\"\n\nimport datetime\nfrom pyspark.sql import SparkSession\n\nspark = (\n SparkSession.builder\n .appName('pyspark_016_cr_org_rank')\n .enableHiveSupport()\n .getOrCreate()\n)\n\n# Hardcoded dates\nds = '20260513'\nyear = '2026'\nmonth = '05'\nday = '13'\nmonth_start = '2026-05-01'\nmonth_end = '2026-06-01'\n\ndb = 'internal_platform_db'\ntbl = 'ads_code_code_platform_mon_cr_org_rank_d_i_pyspark_220'\n\n# Drop and create output table\nspark.sql('''\nDROP TABLE IF EXISTS {db}.{tbl}\n'''.format(db=db, tbl=tbl))\n\nspark.sql('''\nCREATE TABLE {db}.{tbl} (\n `month_name` STRING COMMENT 'cr创建时间转7位月份,yyyy-mm',\n `month_start` STRING COMMENT '月份开始时点',\n `month_end` STRING COMMENT '月份结束时点',\n `org_id` BIGINT COMMENT '组织id',\n `org_type` STRING COMMENT '组织类型',\n `ranktype` STRING COMMENT '排名类型',\n `rank` BIGINT COMMENT '排名',\n `user_id` BIGINT COMMENT '代码协作平台user_id',\n `user_name` STRING COMMENT 'user_name',\n `value_string` STRING COMMENT '排名所用文本',\n `value_int` BIGINT COMMENT '排名所用整数',\n `value_float` DOUBLE COMMENT '排名所用浮点数',\n `value_datetime` STRING COMMENT '排名所用时间',\n `created_at` STRING COMMENT '数据生成时间'\n)\nPARTITIONED BY (\n `year` STRING,\n `month` STRING,\n `day` STRING\n)\nSTORED AS ORC\n'''.format(db=db, tbl=tbl))\n\n# Main ETL query\nquery_sql = \"\"\"\n WITH org_list AS (\n SELECT org_id AS id, org_name AS name, company_id, company_name,\n org_bg_01_id, org_bg_02_id,\n business_line_01_id, business_line_02_id,\n department_01_id, department_02_id, department_03_id, department_04_id,\n center_01_id, center_02_id, center_03_id,\n group_01_id, group_02_id, group_03_id, group_04_id,\n group_05_id, group_06_id, group_07_id, group_08_id\n FROM internal_platform_db.dim_org_framework_org_d_f_pyspark_220\n WHERE CONCAT(year,month,day) = '{ds}'\n ),\n cp AS (\n SELECT o.id org_id,'company' org_type\n ,company_id\n ,-10000 org_bg_id\n ,-10000 business_line_id\n ,-10000 department_id\n ,-10000 center_id\n ,-10000 group_id\n FROM org_list AS o\n WHERE id = company_id\n ),\n dp AS (\n SELECT o.id org_id,'department' org_type\n ,company_id\n ,org_bg_01_id org_bg_id\n ,business_line_01_id business_line_id\n ,department_01_id department_id\n ,-10000 center_id\n ,-10000 group_id\n FROM org_list as o\n WHERE id = department_01_id\n ),\n ct AS (\n SELECT o.id org_id,'center' org_type\n ,company_id\n ,org_bg_01_id org_bg_id\n ,business_line_01_id business_line_id\n ,department_01_id department_id\n ,center_01_id center_id\n ,-10000 group_id\n FROM org_list as o\n WHERE id = center_01_id\n ),\n gp AS (\n SELECT o.id org_id,'group' org_type\n ,company_id\n ,org_bg_01_id org_bg_id\n ,business_line_01_id business_line_id\n ,department_01_id department_id\n ,center_01_id center_id\n ,group_01_id group_id\n FROM org_list as o\n WHERE id = group_01_id\n ),\n user_org as (\n select user_id,\n user_name,\n org_id,\n company_id,\n org_bg_id,\n business_line_id,\n department_id,\n center_id,\n group_id\n from internal_platform_db.dim_code_employee_user_org_relation_bare_d_f_pyspark_220\n where concat(year, month, day) = '{ds}'\n ),\n rank_space as (\n select t1.ranktype,t2.rank\n from (\n select 'notes_create_desc' as ranktype from internal_platform_db.dual_pyspark_220 union all\n select 'cr_used_time_desc' as ranktype from internal_platform_db.dual_pyspark_220\n ) as t1\n cross join (\n select 1 as rank from internal_platform_db.dual_pyspark_220 union all\n select 2 as rank from internal_platform_db.dual_pyspark_220 union all\n select 3 as rank from internal_platform_db.dual_pyspark_220 union all\n select 4 as rank from internal_platform_db.dual_pyspark_220 union all\n select 5 as rank from internal_platform_db.dual_pyspark_220 union all\n select 6 as rank from internal_platform_db.dual_pyspark_220 union all\n select 7 as rank from internal_platform_db.dual_pyspark_220 union all\n select 8 as rank from internal_platform_db.dual_pyspark_220 union all\n select 9 as rank from internal_platform_db.dual_pyspark_220 union all\n select 10 as rank from internal_platform_db.dual_pyspark_220\n ) as t2 on 1 = 1\n ),\n line_note_list as (\n select author_id user_id\n ,sum(line_human_note_cnt) line_human_note_cnt\n from internal_platform_db.dwm_code_review_note_user_stat_d_f_pyspark_220\n where concat(year,month,day) = '{ds}'\n and note_crt_date >= '{month_start}'\n and note_crt_date < '{month_end}'\n group by author_id\n ),\n used_time_list as (\n select reviewer_id user_id\n , sum(duration_today) duration_today\n from internal_platform_db.dwd_code_review_used_time_d_i_pyspark_220\n where concat(year,'-', month,'-', day) >= '{month_start}'\n and concat(year,'-', month,'-', day) < '{month_end}'\n and (is_reviewer = 1 or is_fileowner = 1)\n group by reviewer_id\n ),\n cp_user as (\n select t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n from cp as t1 left join user_org as t2 on t1.org_id = t2.company_id\n group by t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n ),\n dp_user as (\n select t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n from dp as t1 left join user_org as t2 on t1.org_id = t2.department_id\n group by t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n ),\n ct_user as (\n select t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n from ct as t1 left join user_org as t2 on t1.org_id = t2.center_id\n group by t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n ),\n gp_user as (\n select t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n from gp as t1 left join user_org as t2 on t1.org_id = t2.group_id\n group by t1.org_id,t1.org_type,t1.company_id,t1.org_bg_id,t1.business_line_id,t1.department_id,t1.center_id,t1.group_id,t2.user_id,t2.user_name\n ),\n cp_rank as (\n select t1.*\n ,'notes_create_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.line_human_note_cnt desc) rank\n ,null value_string\n ,t2.line_human_note_cnt value_int\n ,null value_float\n ,null value_datetime\n from cp_user as t1\n inner join line_note_list as t2 on t1.user_id = t2.user_id and t2.line_human_note_cnt > 0\n\n union all\n select t1.*\n ,'cr_used_time_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.duration_today desc) rank\n ,null value_string\n ,t2.duration_today value_int\n ,null value_float\n ,null value_datetime\n from cp_user as t1\n inner join used_time_list as t2 on t1.user_id = t2.user_id and t2.duration_today > 0\n ),\n dp_rank as (\n select t1.*\n ,'notes_create_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.line_human_note_cnt desc) rank\n ,null value_string\n ,t2.line_human_note_cnt value_int\n ,null value_float\n ,null value_datetime\n from dp_user as t1\n inner join line_note_list as t2 on t1.user_id = t2.user_id and t2.line_human_note_cnt > 0\n\n union all\n select t1.*\n ,'cr_used_time_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.duration_today desc) rank\n ,null value_string\n ,t2.duration_today value_int\n ,null value_float\n ,null value_datetime\n from dp_user as t1\n inner join used_time_list as t2 on t1.user_id = t2.user_id and t2.duration_today > 0\n ),\n ct_rank as (\n select t1.*\n ,'notes_create_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.line_human_note_cnt desc) rank\n ,null value_string\n ,t2.line_human_note_cnt value_int\n ,null value_float\n ,null value_datetime\n from ct_user as t1\n inner join line_note_list as t2 on t1.user_id = t2.user_id and t2.line_human_note_cnt > 0\n\n union all\n select t1.*\n ,'cr_used_time_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.duration_today desc) rank\n ,null value_string\n ,t2.duration_today value_int\n ,null value_float\n ,null value_datetime\n from ct_user as t1\n inner join used_time_list as t2 on t1.user_id = t2.user_id and t2.duration_today > 0\n ),\n gp_rank as (\n select t1.*\n ,'notes_create_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.line_human_note_cnt desc) rank\n ,null value_string\n ,t2.line_human_note_cnt value_int\n ,null value_float\n ,null value_datetime\n from gp_user as t1\n inner join line_note_list as t2 on t1.user_id = t2.user_id and t2.line_human_note_cnt > 0\n\n union all\n select t1.*\n ,'cr_used_time_desc' ranktype\n ,rank() over(partition by t1.org_id order by t2.duration_today desc) rank\n ,null value_string\n ,t2.duration_today value_int\n ,null value_float\n ,null value_datetime\n from gp_user as t1\n inner join used_time_list as t2 on t1.user_id = t2.user_id and t2.duration_today > 0\n )\n INSERT overwrite TABLE {db}.{tbl} partition(YEAR='{year}',MONTH='{month}',DAY='{day}')\n SELECT /*+ REPARTITION(64) */\n *\n from (\n select '{year}-{month}' month_name\n ,'{month_start} 00:00:00' month_start\n ,'{month_end} 00:00:00' month_end\n ,t1.org_id\n ,t1.org_type\n ,t2.ranktype\n ,t2.rank\n ,t3.user_id\n ,t3.user_name\n ,t3.value_string\n ,t3.value_int\n ,t3.value_float\n ,t3.value_datetime\n ,CAST('2026-05-13 00:00:00' AS STRING) AS created_at\n from cp as t1\n cross join rank_space as t2 on 1 = 1\n left join cp_rank as t3 on t1.org_id = t3.org_id and t2.rank = t3.rank and t2.ranktype = t3.ranktype\n\n union all\n select '{year}-{month}' month_name\n ,'{month_start} 00:00:00' month_start\n ,'{month_end} 00:00:00' month_end\n ,t1.org_id\n ,t1.org_type\n ,t2.ranktype\n ,t2.rank\n ,t3.user_id\n ,t3.user_name\n ,t3.value_string\n ,t3.value_int\n ,t3.value_float\n ,t3.value_datetime\n ,CAST('2026-05-13 00:00:00' AS STRING) AS created_at\n from dp as t1\n cross join rank_space as t2 on 1 = 1\n left join dp_rank as t3 on t1.org_id = t3.org_id and t2.rank = t3.rank and t2.ranktype = t3.ranktype\n\n union all\n select '{year}-{month}' month_name\n ,'{month_start} 00:00:00' month_start\n ,'{month_end} 00:00:00' month_end\n ,t1.org_id\n ,t1.org_type\n ,t2.ranktype\n ,t2.rank\n ,t3.user_id\n ,t3.user_name\n ,t3.value_string\n ,t3.value_int\n ,t3.value_float\n ,t3.value_datetime\n ,CAST('2026-05-13 00:00:00' AS STRING) AS created_at\n from ct as t1\n cross join rank_space as t2 on 1 = 1\n left join ct_rank as t3 on t1.org_id = t3.org_id and t2.rank = t3.rank and t2.ranktype = t3.ranktype\n\n union all\n select '{year}-{month}' month_name\n ,'{month_start} 00:00:00' month_start\n ,'{month_end} 00:00:00' month_end\n ,t1.org_id\n ,t1.org_type\n ,t2.ranktype\n ,t2.rank\n ,t3.user_id\n ,t3.user_name\n ,t3.value_string\n ,t3.value_int\n ,t3.value_float\n ,t3.value_datetime\n ,CAST('2026-05-13 00:00:00' AS STRING) AS created_at\n from gp as t1\n cross join rank_space as t2 on 1 = 1\n left join gp_rank as t3 on t1.org_id = t3.org_id and t2.rank = t3.rank and t2.ranktype = t3.ranktype\n )\n\"\"\".format(\n db=db, tbl=tbl,\n year=year, month=month, day=day, ds=ds,\n month_start=month_start, month_end=month_end,\n)\n\nspark.sql(query_sql)\n\nprint(\"pyspark_016 done\")\n\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_016"} {"task_id": "pyspark_017_en", "id": "offline-compute_PySpark_pyspark_017", "name": "Anomaly Detection Analysis", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that implements anomaly detection analysis based on business data.\n\n**Business Background and Objective**: In the advertising delivery business, operations needs to monitor changes in key metrics (such as `real_cost`) across different industry (`industry_for_business`) dimensions. By comparing and analyzing metric data between the pre-period and post-period, the metrics are summarized by industry dimension, labeling whether the data belongs to the pre-analysis period (`is_post=0`) or the post-analysis period (`is_post=1`). The anomaly detection analysis result table is produced for downstream analysis modules to use.\n\n**Input Table**:\n- `internal_platform_db.f_account_manage_analysis_d_pyspark_208`\n\n**Data Range and Filter Conditions**:\n- Run date `ds` is fixed as `'20260513'`\n- Pre-period: `process_time BETWEEN '20260510' AND '20260512'`\n- Post-period: `process_time BETWEEN '20260513' AND '20260513'`\n- Filter `partition_time = '20260513'`\n\n**Processing Logic**:\n1. Read data from the input table where `partition_time='20260513'`\n2. Divide into pre-period (pre, `is_post=0`) and post-period (post, `is_post=1`) by `process_time`\n3. Aggregate by the `industry_for_business` dimension, computing `SUM(real_cost)` as the metric value\n4. Union the pre and post results and write to the target table\n\n**Output Requirements**:\n- Target table: `internal_platform_db.abnormal_analysis_result_pyspark_208`\n- Write strategy: `INSERT OVERWRITE TABLE`\n- Output columns: `is_post` (INT, 0=pre-period, 1=post-period), `industry_for_business` (STRING, industry), `real_cost` (DOUBLE, sum of `real_cost`)", "ground_truth": "#!/usr/bin/env python3\n\"\"\"pyspark_017 ground truth: anomaly detection analysis (simplified)\"\"\"\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName('dataclaw_eval_gt_pyspark_017') \\\n .enableHiveSupport() \\\n .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \\\n .getOrCreate()\n\n# Hardcoded task configuration (originally from MySQL t_abnormal_detection_and_analysis_task_conf)\n# task_type=8 means use f_account_manage_analysis_d as source table\ntask_conf = {\n 'id': 1,\n 'pre_start_date': '20260510',\n 'pre_end_date': '20260512',\n 'post_start_date': '20260513',\n 'post_end_date': '20260513',\n 'metrics': 'real_cost',\n 'dimensions': 'industry_for_business',\n 'conditions': '[]',\n 'partition_time': '20260513',\n 'task_type': 8\n}\n\npartition = task_conf['partition_time']\npre_start = task_conf['pre_start_date']\npre_end = task_conf['pre_end_date']\npost_start = task_conf['post_start_date']\npost_end = task_conf['post_end_date']\nmetrics = task_conf['metrics']\ndimension_col = task_conf['dimensions']\n\n# Create output table DDL\nspark.sql('''\nDROP TABLE IF EXISTS internal_platform_db.abnormal_analysis_result_pyspark_208\n''')\nspark.sql('''\nCREATE TABLE IF NOT EXISTS internal_platform_db.abnormal_analysis_result_pyspark_208 (\n is_post INT COMMENT '0=pre period, 1=post period',\n industry_for_business STRING COMMENT '行业',\n real_cost DOUBLE COMMENT 'real_cost日均'\n)\nSTORED AS ORC\n''')\n\n# Read data from input table filtered by partition_time\ninput_df = spark.sql(f'''\nSELECT\n process_time,\n industry_for_business,\n real_cost\nFROM internal_platform_db.f_account_manage_analysis_d_pyspark_208\nWHERE partition_time = '{partition}'\n AND process_time BETWEEN '{pre_start}' AND '{post_end}'\n''')\n\n# Compute pre-period metrics (simple aggregation: sum real_cost per industry_for_business)\npre_df = spark.sql(f'''\nSELECT\n 0 AS is_post,\n industry_for_business,\n SUM(real_cost) AS real_cost\nFROM internal_platform_db.f_account_manage_analysis_d_pyspark_208\nWHERE partition_time = '{partition}'\n AND process_time BETWEEN '{pre_start}' AND '{pre_end}'\nGROUP BY industry_for_business\n''')\n\n# Compute post-period metrics\npost_df = spark.sql(f'''\nSELECT\n 1 AS is_post,\n industry_for_business,\n SUM(real_cost) AS real_cost\nFROM internal_platform_db.f_account_manage_analysis_d_pyspark_208\nWHERE partition_time = '{partition}'\n AND process_time BETWEEN '{post_start}' AND '{post_end}'\nGROUP BY industry_for_business\n''')\n\n# Union pre and post results\nresult_df = pre_df.union(post_df)\nresult_df.show()\n\n# Write result to output table\nresult_df.write.format(\"orc\").mode('overwrite').saveAsTable(\n 'internal_platform_db.abnormal_analysis_result_pyspark_208'\n)\n\nprint('Ground truth computation complete')\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_017_en"} {"task_id": "pyspark_018_en", "id": "offline-compute_PySpark_pyspark_018", "name": "SOA Dependency Analysis", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that implements strong dependency relationship analysis for high-impact modules of use cases, based on the Payment Platform W SOA architecture (SOA Dependency Analysis).\n\n**Business Background and Objective**: In the Payment Platform W SOA architecture, it is necessary to analyze the call relationships of high-quality network use cases (`qualitynetwork_case=1` or `importance=1`). Through upstream and downstream traversal of strong dependency (`dependent_intensity=\"strong\"`) call chains, identify modules directly and indirectly affected by use cases, record impact chain evidence, and output a strong dependency module relationship table for high-impact use cases, for use in premium network evaluation and architecture governance.\n\n**Input Tables**:\n- `internal_platform_db.t_dm_callrelation_extended_info_hour_pyspark_209`\n- `internal_platform_db.t_dm_usecase_and_asset_callrelation_hour_pyspark_209`\n- `internal_platform_db.t_dwd_module_info_hour_pyspark_209`\n- `internal_platform_db.t_app_callrelation_for_quality_analyse_hour_pyspark_209`\n\n**Data Range and Filter Conditions**:\n- Run date `ds` is fixed as `'p_2026051300'` (hourly partition)\n- From `t_dm_usecase_and_asset_callrelation_hour`, filter use cases where `qualitynetwork_case=1` or `importance=1`\n- Exclude modules not entering the premium network where `no_entry_premium_network_flag=1`\n- From `t_dm_callrelation_extended_info_hour`, filter strong dependency call relationships where `is_involved_to_high_usecase=1` and `dependent_intensity=\"strong\"`\n- Filter out invalid call relationships `ossid:0` and `0:0`\n\n**Processing Logic**:\n1. From the use case and call relationship table, obtain directly associated modules (mapping of `enter_module_name` to `case_id`), mark `is_dir=1`, with evidence \"direct association\"\n2. Build `case_id_relation_dict`: using `\"callee_module_name***callee_interface_name\"` as key, and the associated `case_id` set as value\n3. Build `relation_dict` from the call relationship table: using `\"callee_module_name***callee_interface_name\"` as key, and the `\"called_module_name***called_interface_name\"` set as value\n4. Use a DFS algorithm to traverse downstream call chains, add traversed modules to the results, mark `is_dir=0`, with evidence as the downstream analysis chain\n5. For use case entries where `analyse_type=\"cgi\"`, build a reverse call relationship dictionary `reverse_relation_dict`\n6. Use a DFS algorithm to traverse upstream call chains, add traversed modules to the results, mark `is_dir=0`, with evidence as the upstream analysis chain\n7. Merge the results of direct association, downstream analysis, and upstream analysis, and write to the target table\n\n**Output Requirements**:\n- Target table: `internal_platform_db.t_dwd_architecture_module_high_case_relation_strong_hour_pyspark_209`\n- Write strategy: `INSERT OVERWRITE TABLE`\n- Output columns: `databus_imp_date` (STRING, date), `case_id` (STRING, use case ID), `module_name` (STRING, module name), `is_dir` (BIGINT, 1=direct association, 0=indirect association), `evidence` (STRING, impact evidence chain)", "ground_truth": "#!/usr/bin/env python3\n\"\"\"pyspark_018 ground truth: SOA dependency analysis\"\"\"\nimport json\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName('dataclaw_eval_gt_pyspark_018') \\\n .enableHiveSupport() \\\n .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \\\n .getOrCreate()\n\nds = 'p_2026051300'\ntoday = '2026051300'\n\n# Output table DDL\nspark.sql('''\nDROP TABLE IF EXISTS internal_platform_db.t_dwd_architecture_module_high_case_relation_strong_hour_pyspark_209\n''')\nspark.sql('''\nCREATE TABLE IF NOT EXISTS internal_platform_db.t_dwd_architecture_module_high_case_relation_strong_hour_pyspark_209 (\n databus_imp_date STRING,\n case_id STRING,\n module_name STRING,\n is_dir BIGINT,\n evidence STRING\n)\nSTORED AS ORC\n''')\n\n# Create temp views from input tables\nspark.sql(f'''\nCREATE OR REPLACE TEMP VIEW t_dm_callrelation_extended_info_hour AS\nSELECT * FROM internal_platform_db.t_dm_callrelation_extended_info_hour_pyspark_209\nWHERE ds = '{ds}'\n''')\n\nspark.sql(f'''\nCREATE OR REPLACE TEMP VIEW t_dm_usecase_and_asset_callrelation_hour AS\nSELECT * FROM internal_platform_db.t_dm_usecase_and_asset_callrelation_hour_pyspark_209\nWHERE ds = '{ds}'\n''')\n\nspark.sql(f'''\nCREATE OR REPLACE TEMP VIEW t_dwd_module_info_hour AS\nSELECT * FROM internal_platform_db.t_dwd_module_info_hour_pyspark_209\nWHERE ds = '{ds}'\n''')\n\nspark.sql(f'''\nCREATE OR REPLACE TEMP VIEW t_app_callrelation_for_quality_analyse_hour AS\nSELECT * FROM internal_platform_db.t_app_callrelation_for_quality_analyse_hour_pyspark_209\nWHERE ds = '{ds}'\n''')\n\nprint(\"step 1\")\nprint(\"获取直接相关的模块\")\n\nT_SCHEMA = ('databus_imp_date', 'case_id', 'module_name', 'is_dir', 'evidence')\n\n# Get direct relations - modules directly associated with cases\ndir_sql = \"\"\"\nselect distinct\n relation.enter_module_name,\n relation.case_id\nfrom t_dm_usecase_and_asset_callrelation_hour relation\nleft join (\n select module_name\n from t_dwd_module_info_hour\n where no_entry_premium_network_flag = 1\n) modules_info on relation.enter_module_name = modules_info.module_name\nwhere (qualitynetwork_case = 1 or importance = 1)\n and (enter_module_name is not null and enter_module_name <> '')\n and modules_info.module_name is null\n\"\"\"\n\nservice_datas = spark.sql(dir_sql).toPandas()\n\nmodule_evidence = dict()\n\nclass Evidence:\n def __init__(self, module_name):\n self.module_name = module_name\n\n def set_case(self, case_id):\n self.case_id = case_id\n return self\n\n def set_evidence(self, evidence):\n self.evidence = evidence\n return self\n\n def to_string(self, comment):\n return \"[用例ID:{}--{}--证据链路:{}]\".format(self.case_id, comment, self.evidence)\n\nresult_list = []\nfor data in service_datas.values:\n enter_module_name = data[0]\n case_id = data[1]\n is_dir = 1\n\n if enter_module_name not in module_evidence:\n module_evidence[enter_module_name] = Evidence(enter_module_name).set_case(case_id).set_evidence(\"直接关联\")\n result_list.append((today, case_id, enter_module_name, is_dir, module_evidence[enter_module_name].to_string(\"直接关联\")))\n\nprint(\"直接影响的个数\")\norigin_length = len(result_list)\nprint(origin_length)\n\nprint(\"step 2\")\nprint(\"获取用例和调用关系入口模块-接口映射\")\n\ncase_id_relation_dict_sql = \"\"\"\nselect\n enter_module_name, case_id, callee_module_name, callee_interface_name\nfrom t_dm_usecase_and_asset_callrelation_hour\nwhere (qualitynetwork_case = 1 or importance = 1)\n and (enter_module_name is not null and enter_module_name <> '')\n and (callee_module_name is not null and callee_module_name <> '')\n and (callee_interface_name is not null and callee_interface_name <> '')\n and (called_module_name is not null and called_module_name <> '')\n and (called_interface_name is not null and called_interface_name <> '')\n and enter_module_name = callee_module_name\n\"\"\"\n\ncase_id_relation_dict = dict()\nservice_datas = spark.sql(case_id_relation_dict_sql).toPandas()\nfor data in service_datas.values:\n enter_module_name = data[0]\n case_id = data[1]\n callee_module_name = data[2]\n callee_interface_name = data[3]\n\n relation = \"{}***{}\".format(callee_module_name, callee_interface_name)\n if relation in case_id_relation_dict:\n case_id_relation_dict[relation].add(case_id)\n else:\n case_id_relation_dict[relation] = set()\n case_id_relation_dict[relation].add(case_id)\n\nprint(\"step 3\")\nprint(\"获取剔除了不进入精品网模块的强依赖调用关系\")\n\nrelation_dict_sql = \"\"\"\nselect\n relation.callee_module_name,\n relation.callee_interface_name,\n relation.called_module_name,\n relation.called_interface_name\nfrom\n (select\n callee_module_name, callee_interface_name, called_module_name, called_interface_name\n from t_dm_callrelation_extended_info_hour\n where is_involved_to_high_usecase = 1\n and dependent_intensity = 'strong'\n ) relation\nleft join (\n select module_name\n from t_dwd_module_info_hour\n where no_entry_premium_network_flag = 1\n) modules_callee on relation.callee_module_name = modules_callee.module_name\nleft join (\n select module_name\n from t_dwd_module_info_hour\n where no_entry_premium_network_flag = 1\n) modules_called on relation.called_module_name = modules_called.module_name\nwhere modules_callee.module_name is null\n and modules_called.module_name is null\n\"\"\"\n\nrelation_dict = dict()\nservice_datas = spark.sql(relation_dict_sql).toPandas()\nfor data in service_datas.values:\n callee_module_name = data[0]\n callee_interface_name = data[1]\n called_module_name = data[2]\n called_interface_name = data[3]\n\n relation_callee = \"{}***{}\".format(callee_module_name, callee_interface_name)\n relation_called = \"{}***{}\".format(called_module_name, called_interface_name)\n if relation_callee in relation_dict:\n relation_dict[relation_callee].add(relation_called)\n else:\n relation_dict[relation_callee] = set()\n relation_dict[relation_callee].add(relation_called)\n\n\ndef dfs(relation_dict, called_info, record_list, chain_list, space, case_id_now):\n if called_info not in relation_dict:\n return\n called_infos = relation_dict[called_info]\n for called_info_item in called_infos:\n if called_info_item in record_list:\n continue\n record_list.add(called_info_item)\n\n chain_list.append(called_info_item)\n\n module_name_now = called_info_item.split(\"***\")[0]\n if module_name_now != \"\" and module_name_now not in module_evidence:\n module_evidence[module_name_now] = Evidence(module_name_now).set_evidence(space.join(chain_list)).set_case(case_id_now)\n\n dfs(relation_dict, called_info_item, record_list, chain_list, space, case_id_now)\n\n chain_list.pop()\n\n\ndef dfs_fist(relation_dict, key, reverse, case_id_now):\n space = \"<-\" if reverse else \"->\"\n record_list = set()\n chain_list = list()\n\n if key not in relation_dict:\n return None\n\n chain_list.append(key)\n\n module_name_now = key.split(\"***\")[0]\n if module_name_now != \"\" and module_name_now not in module_evidence:\n module_evidence[module_name_now] = Evidence(module_name_now).set_evidence(space.join(chain_list)).set_case(case_id_now)\n\n called_infos = relation_dict[key]\n for called_info in called_infos:\n if called_info in record_list:\n continue\n record_list.add(called_info)\n\n module_name_now = called_info.split(\"***\")[0]\n chain_list.append(called_info)\n if module_name_now != \"\" and module_name_now not in module_evidence:\n module_evidence[module_name_now] = Evidence(module_name_now).set_evidence(space.join(chain_list)).set_case(case_id_now)\n\n dfs(relation_dict, called_info, record_list, chain_list, space, case_id_now)\n chain_list.pop()\n return record_list\n\n\n# Downstream analysis\nprint(\"step 4\")\nprint(\"开始下游分析\")\n\nis_dir = 0\nmodule_evidence = dict()\nfor key in case_id_relation_dict:\n case_id_now = list(case_id_relation_dict[key])[0]\n modules_list = dfs_fist(relation_dict, key, 0, case_id_now)\n if modules_list is None:\n continue\n cases = case_id_relation_dict[key]\n for case_id in cases:\n for module in modules_list:\n module_name = module.split(\"***\")[0]\n if module_name == \"\":\n continue\n result_list.append((today, case_id, module_name, is_dir, module_evidence[module_name].to_string(\"下游分析\")))\n\nprint(\"间接影响的个数\")\nprint(len(result_list) - origin_length)\n\n# Upstream analysis (CGI)\nprint(\"step 5\")\nprint(\"获取cgi用例和调用关系入口模块-接口映射\")\n\ncase_id_relation_dict_sql = \"\"\"\nselect\n enter_module_name, case_id, callee_module_name, callee_interface_name\nfrom t_dm_usecase_and_asset_callrelation_hour\nwhere (qualitynetwork_case = 1 or importance = 1)\n and (enter_module_name is not null and enter_module_name <> '')\n and (callee_module_name is not null and callee_module_name <> '')\n and (callee_interface_name is not null and callee_interface_name <> '')\n and (called_module_name is not null and called_module_name <> '')\n and (called_interface_name is not null and called_interface_name <> '')\n and enter_module_name = callee_module_name\n and analyse_type = 'cgi'\n\"\"\"\n\ncase_id_relation_dict = dict()\nservice_datas = spark.sql(case_id_relation_dict_sql).toPandas()\nfor data in service_datas.values:\n enter_module_name = data[0]\n case_id = data[1]\n callee_module_name = data[2]\n callee_interface_name = data[3]\n\n relation = \"{}***{}\".format(callee_module_name, callee_interface_name)\n if relation in case_id_relation_dict:\n case_id_relation_dict[relation].add(case_id)\n else:\n case_id_relation_dict[relation] = set()\n case_id_relation_dict[relation].add(case_id)\n\n# Build reverse relation dict\nall_relation_dict_sql = \"\"\"\nselect distinct\n callee_module_name,\n callee_interface_name,\n called_module_name,\n called_interface_name\nfrom t_app_callrelation_for_quality_analyse_hour\nwhere callee_module_name <> 'ossid:0'\n and called_module_name <> 'ossid:0'\n and callee_module_name <> '0:0'\n and called_module_name <> '0:0'\n\"\"\"\n\nreverse_relation_dict = dict()\nservice_datas = spark.sql(all_relation_dict_sql).toPandas()\nfor data in service_datas.values:\n callee_module_name = data[0]\n callee_interface_name = data[1]\n called_module_name = data[2]\n called_interface_name = data[3]\n\n relation_callee = \"{}***{}\".format(callee_module_name, callee_interface_name)\n relation_called = \"{}***{}\".format(called_module_name, called_interface_name)\n if relation_called in reverse_relation_dict:\n reverse_relation_dict[relation_called].add(relation_callee)\n else:\n reverse_relation_dict[relation_called] = set()\n reverse_relation_dict[relation_called].add(relation_callee)\n\nmodule_evidence = dict()\nis_dir = 0\nreverse_result_list = list()\nfor key in case_id_relation_dict:\n case_id_now = list(case_id_relation_dict[key])[0]\n modules_list = dfs_fist(reverse_relation_dict, key, 1, case_id_now)\n if modules_list is None:\n continue\n cases = case_id_relation_dict[key]\n for case_id in cases:\n for module in modules_list:\n module_name = module.split(\"***\")[0]\n if module_name == \"\":\n continue\n reverse_result_list.append((today, case_id, module_name, is_dir, module_evidence[module_name].to_string(\"上游分析\")))\n\nprint(\"反向影响的个数\")\nprint(len(reverse_result_list))\nresult_list = result_list + reverse_result_list\n\n# Write output\nt_df = spark.createDataFrame(result_list, T_SCHEMA)\nt_df.write.mode('overwrite').format('orc').saveAsTable(\n 'internal_platform_db.t_dwd_architecture_module_high_case_relation_strong_hour_pyspark_209'\n)\n\nprint('Ground truth computation complete')\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_018_en"} {"task_id": "pyspark_019_en", "id": "offline-compute_PySpark_pyspark_019", "name": "Campaign User Label Computation", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "en", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\nI need you to generate a PySpark script that implements campaign user targeting label computation based on brand campaign activities (Campaign User Label Computation).\n\n**Business Background and Objective**: In the Payment Platform W brand management platform, the targeting labels for campaign configurations are stored in JSON format (containing `label_groups` and `exclude_label_groups`). These need to be parsed into a structured label detail table, and transaction frequency labels (`label_type=7`) need to be automatically backfilled, for downstream user filtering and campaign delivery.\n\n**Input Tables**:\n- `internal_platform_db.t_dwd_brand_mgmt_activity_all_hour_pyspark_206`\n- `internal_platform_db.t_dwd_gift_mgmt_targeted_act_hour_pyspark_206`\n\n**Data Range and Filter Conditions**:\n- Run date `ds` is fixed as `'p_2026051300'` (hourly partition)\n- From `t_dwd_brand_mgmt_activity_all_hour`, filter campaigns where `factid>10 AND factstatus IN (2,6,7)`\n- Union with the `factid` and `factivitylabel` from `t_dwd_gift_mgmt_targeted_act_hour`\n\n**Processing Logic**:\n1. Obtain the campaign `factivitylabel` JSON data by unioning the brand management campaign table and the pay-gift table\n2. Use `flatMap` to parse the `label_groups.target_labels` and `exclude_label_groups.target_labels` from each row's JSON into independent rows\n3. Extract `label_type`, `label_value`, `effective_range_type`, `effective_range_value`, and `is_exclude` fields from `raw_json`\n4. Filter out invalid labels (records where `label_type`, `label_value`, or `effective_range_type` is empty or 0), and deduplicate\n5. For all brands (`fbrandid`) with valid campaigns, backfill the four values (1, 2, 3, 4) for `label_type=7` (transaction frequency), with `effective_range_type=2` and `is_exclude=0`\n6. Use a left_anti join to exclude already existing records, avoiding duplication\n\n**Output Requirements**:\n- Target table: `internal_platform_db.brand_mgmt_act_label_pyspark_206`\n- Write strategy: `INSERT OVERWRITE TABLE`\n- Output columns: `ds` (STRING, date), `label_type` (STRING, label type), `label_value` (STRING, label value), `effective_range_type` (STRING, effective range type), `effective_range_value` (STRING, effective range value), `raw_json` (STRING, original JSON), `is_exclude` (INT, 0=include, 1=exclude)", "ground_truth": "#!/usr/bin/env python3\n\"\"\"pyspark_019 ground truth: campaign user label computation\"\"\"\nimport json\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import lit, get_json_object, when, to_json, struct\n\nspark = SparkSession.builder \\\n .appName('dataclaw_eval_gt_pyspark_019') \\\n .enableHiveSupport() \\\n .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \\\n .getOrCreate()\n\nhour = '2026051300'\nHOUR_PARTITION = 'p_' + str(hour)\n\n# Output table DDL\nspark.sql('''\nDROP TABLE IF EXISTS internal_platform_db.brand_mgmt_act_label_pyspark_206\n''')\nspark.sql('''\nCREATE TABLE IF NOT EXISTS internal_platform_db.brand_mgmt_act_label_pyspark_206 (\n ds STRING,\n label_type STRING,\n label_value STRING,\n effective_range_type STRING,\n effective_range_value STRING,\n raw_json STRING,\n is_exclude INT\n)\nSTORED AS ORC\n''')\n\n# Step 1: Read activity data from brand manager + paygift, filter and union\nactivity_label = (\n spark.sql(f'''\n SELECT factid, factivitylabel\n FROM internal_platform_db.t_dwd_brand_mgmt_activity_all_hour_pyspark_206\n WHERE ds = '{HOUR_PARTITION}'\n AND factid > 10\n AND factstatus IN (2, 6, 7)\n ''')\n).union(\n spark.sql(f'''\n SELECT factid, factivitylabel\n FROM internal_platform_db.t_dwd_gift_mgmt_targeted_act_hour_pyspark_206\n WHERE ds = '{HOUR_PARTITION}'\n ''')\n)\n\nactivity_label.show(truncate=False)\n\n\ndef parse_labels(row):\n result = []\n if row[\"factivitylabel\"] is None:\n return result\n labels = json.loads(row[\"factivitylabel\"])\n if labels is None:\n return result\n if \"label_groups\" in labels.keys():\n for group in labels[\"label_groups\"]:\n if \"target_labels\" in group.keys():\n for l in group[\"target_labels\"]:\n json_str = json.dumps(l)\n result.append((json_str,))\n if \"exclude_label_groups\" in labels.keys():\n for group in labels[\"exclude_label_groups\"]:\n if \"target_labels\" in group.keys():\n for l in group[\"target_labels\"]:\n json_str = json.dumps(l)\n result.append((json_str,))\n return result\n\n\n# Step 2: flatMap to parse JSON labels into individual rows\nsingle_labels = activity_label.rdd.flatMap(lambda row: parse_labels(row))\nprint(1)\nif single_labels.isEmpty():\n single_labels_df = spark.createDataFrame([], \"raw_json: string\")\nelse:\n single_labels_df = spark.createDataFrame(single_labels, [\"raw_json\"])\n\nsingle_labels_df = (\n single_labels_df.withColumn(\"ds\", lit(hour))\n .withColumn(\"label_type\", get_json_object(single_labels_df.raw_json, \"$.label_type\"))\n .withColumn(\"label_value\", get_json_object(single_labels_df.raw_json, \"$.label_value\"))\n .withColumn(\"effective_range_type\", get_json_object(single_labels_df.raw_json, \"$.effective_range_type\"))\n .withColumn(\"effective_range_value\", get_json_object(single_labels_df.raw_json, \"$.effective_range_value\"))\n .withColumn(\"is_exclude\", when(get_json_object(single_labels_df.raw_json, \"$.is_exclude\") == \"true\", 1).otherwise(0))\n)\n\nsingle_labels_df.show(truncate=False)\n\n# Step 3: Dedup and filter valid labels\nfiltered_labels = (\n single_labels_df.select(\n \"ds\", \"label_type\", \"label_value\",\n \"effective_range_type\", \"effective_range_value\", \"raw_json\", \"is_exclude\",\n )\n .filter(\"nvl(label_type, 0) != 0 AND nvl(label_value, '0') != '0' AND nvl(effective_range_type, 0) != 0\")\n .distinct()\n)\n\n# Step 4: Supplement label_type=7 (transaction frequency labels)\nall_act_brands = (\n spark.sql(f'''\n SELECT DISTINCT fbrandid\n FROM internal_platform_db.t_dwd_brand_mgmt_activity_all_hour_pyspark_206\n WHERE ds = '{HOUR_PARTITION}'\n AND factid > 10\n AND factstatus IN (2, 6, 7)\n ''')\n .withColumnRenamed(\"fbrandid\", \"effective_range_value\")\n)\n\nfreq_label_values = spark.createDataFrame(\n [(\"1\",), (\"2\",), (\"3\",), (\"4\",)], [\"label_value\"]\n)\n\nextra_freq_labels = (\n all_act_brands.crossJoin(freq_label_values)\n .withColumn(\"ds\", lit(hour))\n .withColumn(\"label_type\", lit(\"7\"))\n .withColumn(\"effective_range_type\", lit(\"2\"))\n .withColumn(\"is_exclude\", lit(0))\n)\n\nextra_freq_labels = extra_freq_labels.withColumn(\n \"raw_json\",\n to_json(\n struct(\n extra_freq_labels.label_type,\n extra_freq_labels.label_value,\n extra_freq_labels.effective_range_type,\n extra_freq_labels.effective_range_value,\n )\n ),\n).select(\n \"ds\", \"label_type\", \"label_value\",\n \"effective_range_type\", \"effective_range_value\", \"raw_json\", \"is_exclude\",\n)\n\n# Use left_anti join to keep only records not already in filtered_labels\nnew_freq_labels = extra_freq_labels.join(\n filtered_labels,\n on=[\"label_type\", \"label_value\", \"effective_range_type\", \"effective_range_value\", \"is_exclude\"],\n how=\"left_anti\",\n)\n\nresult_labels = filtered_labels.unionByName(new_freq_labels)\n\n# Write output\nresult_labels.write.mode('overwrite').format('orc').saveAsTable(\n 'internal_platform_db.brand_mgmt_act_label_pyspark_206'\n)\n\nprint('Ground truth computation complete')\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_019_en"} {"task_id": "pyspark_020", "id": "offline-compute_PySpark_pyspark_020", "name": "小程序H5监控", "workload": "offline-compute", "engine": "PySpark", "category": "offline-compute/PySpark", "language": "zh", "modality": "pure-text", "timeout_seconds": 900, "prompt": "## Prompt\n我需要你生成一段 PySpark 代码,实现小程序打开第三方 H5 页面的大盘监控指标计算(Mini-Program H5 Monitoring)。\n\n**业务背景与目标**:小程序开放平台需要监控小程序内打开第三方 H5 页面的整体情况,包括 PV、UV、域名数、链接数等核心指标,按整体大盘和 Top100 小程序两个维度分别统计,同时按域名归属关系(同主体/关联主体/第三方)进行细分,产出结构化监控指标表。\n\n**输入表**:\n- `internal_platform_db.ods_daily_miniapp_h5_expand_raw_pyspark_212`\n- `internal_platform_db.ods_daily_miniapp_h5_top100_pv_raw_pyspark_212`\n\n**数据范围与过滤条件**:\n- 运行日期 ds 固定为 '20260513'(日分区)\n- ods_daily_miniapp_h5_expand_raw 提供全量 H5 访问明细\n- ods_daily_miniapp_h5_top100_pv_raw 提供 Top100 PV 小程序的 H5 访问明细\n- url 列重命名为 url_wop(无参数 URL)\n\n**处理逻辑**:\n1. 从 expand_raw 表计算整体大盘指标:total PV=总行数, total UV=去重 useruin, total domain=去重 domain, total url_wop=去重 url_wop,stat_type='total'\n2. 从 top100_raw 表按 appid 分组计算:PV=count, UV=去重 useruin, domain=去重 domain, url_wop=去重 url_wop,stat_type='total_top'\n3. 从 expand_raw 表按 related(域名归属关系)分组计算:PV=count, UV=去重 useruin, domain=去重 domain, url_wop=去重 url_wop,stat_type='contactor_{related}'\n4. 从 top100_raw 表按 appid+related 分组计算同样指标,stat_type='contactor_{related}_top'\n5. 使用 pandas merge 将各维度指标合并为统一格式\n6. 添加 ds 列(BIGINT 类型),生成最终结果\n\n**输出要求**:\n- 目标表:`internal_platform_db.ods_daily_miniapp_webview_total_pyspark_212`\n- 写入策略:INSERT OVERWRITE TABLE\n- 输出列:ds(BIGINT,日期), appid(STRING,小程序appid,大盘级为空字符串), pv(BIGINT,页面浏览量), uv(BIGINT,独立访客数), domain(BIGINT,域名数), url_wop(BIGINT,去参链接数), stat_type(STRING,统计类型:total/total_top/contactor_{related}/contactor_{related}_top)", "ground_truth": "#!/usr/bin/env python3\n\"\"\"pyspark_020 ground truth: mini-program H5 monitoring metrics\"\"\"\nimport pandas as pd\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\n\nspark = SparkSession.builder \\\n .appName('dataclaw_eval_gt_pyspark_020') \\\n .enableHiveSupport() \\\n .config('spark.sql.warehouse.dir', '/tmp/hive_warehouse') \\\n .getOrCreate()\n\nds = '20260513'\n\n# Output table DDL\nspark.sql('''\nDROP TABLE IF EXISTS internal_platform_db.ods_daily_miniapp_webview_total_pyspark_212\n''')\nspark.sql('''\nCREATE TABLE IF NOT EXISTS internal_platform_db.ods_daily_miniapp_webview_total_pyspark_212 (\n ds BIGINT COMMENT 'date',\n appid STRING COMMENT 'appid',\n pv BIGINT COMMENT 'page views',\n uv BIGINT COMMENT 'unique visitors',\n domain BIGINT COMMENT 'domain count',\n url_wop BIGINT COMMENT 'url without param count',\n stat_type STRING COMMENT 'statistic type'\n)\nSTORED AS ORC\n''')\n\ncols = ['appid', 'pv', 'uv', 'domain', 'url_wop', 'stat_type']\n\n# Read input data\nweb_stats_raw = spark.sql(f'''\n SELECT useruin, appid, url_, domain, url, contactor_domain, related\n FROM internal_platform_db.ods_daily_miniapp_h5_expand_raw_pyspark_212\n WHERE ds = '{ds}'\n''')\nweb_stats = web_stats_raw.withColumnRenamed('url', 'url_wop')\nweb_stats.persist()\nweb_stats_cnt = web_stats.count()\nprint(f\"Fetch total web_stats info: {web_stats_cnt}\")\n\nweb_stats_topuser_id_raw = spark.sql(f'''\n SELECT useruin, appid, url_, domain, url, contactor_domain, related\n FROM internal_platform_db.ods_daily_miniapp_h5_top100_pv_raw_pyspark_212\n WHERE ds = '{ds}'\n''')\nweb_stats_topuin = web_stats_topuser_id_raw.withColumnRenamed('url', 'url_wop')\nweb_stats_topuin.persist()\nweb_stats_topuser_id_cnt = web_stats_topuin.count()\nprint(f\"Fetch total web_stats_topuin info: {web_stats_topuser_id_cnt}\")\n\n# 1. Overall metrics: total PV/UV/domain/URL counts\ncate = 'total'\ntotal_pv = web_stats_cnt\ntotal_uv = web_stats[['useruin']].drop_duplicates().count()\ntotal_domain_cnt = web_stats[['domain']].drop_duplicates().count()\ntotal_url_cnt = web_stats[['url_wop']].drop_duplicates().count()\ndf_total = pd.DataFrame(data=[('', total_pv, total_uv, total_domain_cnt, total_url_cnt, cate)], columns=cols)\n\n# Per-app metrics for top100\ncate = 'total_top'\ntotal_top_pv = web_stats_topuin.groupby('appid').count().withColumnRenamed('count', 'pv').toPandas()\ntotal_top_uv = web_stats_topuin[['appid', 'useruin']].drop_duplicates().groupby('appid').count().withColumnRenamed('count', 'uv').toPandas()\ntotal_top_domain_cnt = web_stats_topuin[['appid', 'domain']].drop_duplicates().groupby('appid').count().withColumnRenamed('count', 'domain').toPandas()\ntotal_top_url_cnt = web_stats_topuin[['appid', 'url_wop']].drop_duplicates().groupby('appid').count().withColumnRenamed('count', 'url_wop').toPandas()\ntotal_top_metrics = total_top_pv.merge(total_top_uv, how='left', on='appid') \\\n .merge(total_top_domain_cnt, how='left', on='appid') \\\n .merge(total_top_url_cnt, how='left', on='appid')\ntotal_top_metrics['stat_type'] = cate\n\npdf_total = pd.concat([df_total[cols], total_top_metrics[cols]], ignore_index=True, axis=0)\n\n# 2. Contactor distribution metrics\ncate = 'contactor'\ncontactor_pv_dist = web_stats.groupby('related').count().withColumnRenamed('count', 'pv').toPandas()\ncontactor_pv_dist['stat_type'] = cate + '_' + contactor_pv_dist.related\ncontactor_uv_dist = web_stats[['related', 'useruin']].drop_duplicates().groupby('related').count().withColumnRenamed('count', 'uv').toPandas()\ncontactor_uv_dist['stat_type'] = cate + '_' + contactor_uv_dist.related\ncontactor_domain_dist = web_stats[['related', 'domain']].drop_duplicates().groupby('related').count().withColumnRenamed('count', 'domain').toPandas()\ncontactor_domain_dist['stat_type'] = cate + '_' + contactor_domain_dist.related\ncontactor_url_dist = web_stats[['related', 'url_wop']].drop_duplicates().groupby('related').count().withColumnRenamed('count', 'url_wop').toPandas()\ncontactor_url_dist['stat_type'] = cate + '_' + contactor_url_dist.related\ndf_contactor = contactor_pv_dist[['stat_type', 'pv']].merge(contactor_uv_dist[['stat_type', 'uv']]) \\\n .merge(contactor_domain_dist[['stat_type', 'domain']]) \\\n .merge(contactor_url_dist[['stat_type', 'url_wop']])\ndf_contactor['appid'] = ''\n\n# Per-app contactor metrics for top100\ncontactor_top_pv = web_stats_topuin.groupby(['appid', 'related']).count().withColumnRenamed('count', 'pv').toPandas()\ncontactor_top_uv = web_stats_topuin[['appid', 'related', 'useruin']].drop_duplicates().groupby(['appid', 'related']).count().withColumnRenamed('count', 'uv').toPandas()\ncontactor_top_domain = web_stats_topuin[['appid', 'related', 'domain']].drop_duplicates().groupby(['appid', 'related']).count().withColumnRenamed('count', 'domain').toPandas()\ncontactor_top_url = web_stats_topuin[['appid', 'related', 'url_wop']].drop_duplicates().groupby(['appid', 'related']).count().withColumnRenamed('count', 'url_wop').toPandas()\ncontactor_top_metrics = contactor_top_pv.merge(contactor_top_uv, how='left', on=['appid', 'related']) \\\n .merge(contactor_top_domain, how='left', on=['appid', 'related']) \\\n .merge(contactor_top_url, how='left', on=['appid', 'related'])\ncontactor_top_metrics['stat_type'] = cate + '_' + contactor_top_metrics.related + '_top'\n\npdf_contactor = pd.concat([df_contactor[cols], contactor_top_metrics[cols]], ignore_index=True, axis=0)\n\n# Combine all metrics\npdf_metrics = pd.concat([pdf_total, pdf_contactor], ignore_index=True, axis=0)\nsdf_metrics = spark.createDataFrame(pdf_metrics)\nres = sdf_metrics.withColumn('ds', F.lit(int(ds))).select('ds', 'appid', 'pv', 'uv', 'domain', 'url_wop', 'stat_type').repartition(1)\nres.persist()\nres_cnt = res.count()\nprint(f\"Fetch statistic metrics: {res_cnt}\")\n\n# Write output\nres.write.mode('overwrite').format('orc').saveAsTable(\n 'internal_platform_db.ods_daily_miniapp_webview_total_pyspark_212'\n)\n\nprint('Ground truth computation complete')\nspark.stop()", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/offline-compute/PySpark/pyspark_020"} {"task_id": "flinksql_001_en", "id": "online-compute_FlinkSQL_flinksql_001", "name": "Order Stream and Payment Stream Interval Join", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses the built-in datagen connector to simulate an order stream and a payment stream, performing an Interval Join on `order_id`, and writing matched records directly to the console.\n\n**Business Background and Objective**: Simulate an order stream and a payment stream using two datagen built-in tables, each generating 100 million records. The `order_id` and `user_id` in the order stream range from 1 to 1,000,000, and the `order_id` in the payment stream also ranges from 1 to 1,000,000. Both tables use `LOCALTIMESTAMP` as the event time and set a 5-second watermark delay.\n\nPerform an Interval Join on the two tables using `order_id`, matching only records where the payment time falls within 5 minutes after the order time. Upon a successful match, output the original fields directly to the console table, including `order_id`, `user_id`, `pay_amount`, the order time, and the payment time.\n\n**Source Table Definitions**:\n- `orders_source` (order stream, datagen connector):\n - `order_id INT`: Order ID, randomly generated in the range 1–1,000,000\n - `user_id INT`: User ID, randomly generated in the range 1–1,000,000\n - `order_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 1000`\n\n- `payments_source` (payment stream, datagen connector):\n - `order_id INT`: Order ID, randomly generated in the range 1–1,000,000\n - `pay_amount DOUBLE`: Payment amount, randomly generated in the range 1–100,000\n - `pay_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 1000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `order_id INT`\n - `user_id INT`\n - `pay_amount DOUBLE`\n - `order_time TIMESTAMP(3)`\n - `pay_time TIMESTAMP(3)`\n\n**Join Logic**:\n- Join condition: `orders_source.order_id = payments_source.order_id`\n- Time window: `payments_source.pay_time BETWEEN orders_source.order_time AND orders_source.order_time + INTERVAL '5' MINUTE`\n- Note: When writing to the sink, you must handle the dual rowtime attribute conflict by applying `CAST(pay_time AS TIMESTAMP(3))` to downgrade `pay_time` to a plain timestamp.\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the matched results.\n- Output field order: `order_id`, `user_id`, `pay_amount`, `order_time`, `pay_time`", "ground_truth": "-- online_001: 订单流 + 支付流 Interval Join\n-- 每个源生成 1 亿条数据 @ 1000 rows/sec\n\n-- 1. 订单流 datagen 源表\nCREATE TABLE orders_source (\n order_id INT,\n user_id INT,\n order_time AS LOCALTIMESTAMP,\n WATERMARK FOR order_time AS order_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '1000000'\n);\n\n-- 2. 支付流 datagen 源表\nCREATE TABLE payments_source (\n order_id INT,\n pay_amount DOUBLE,\n pay_time AS LOCALTIMESTAMP,\n WATERMARK FOR pay_time AS pay_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.pay_amount.kind' = 'random',\n 'fields.pay_amount.min' = '1',\n 'fields.pay_amount.max' = '100000'\n);\n\n-- 3. Console 输出表\nCREATE TABLE console_output (\n order_id INT,\n user_id INT,\n pay_amount DOUBLE,\n order_time TIMESTAMP(3),\n pay_time TIMESTAMP(3)\n) WITH (\n 'connector' = 'print'\n);\n\n-- 4. Interval Join: 匹配支付时间在订单时间后 5 分钟内的记录\nINSERT INTO console_output\nSELECT\n o.order_id,\n o.user_id,\n p.pay_amount,\n o.order_time,\n CAST(p.pay_time AS TIMESTAMP(3)) AS pay_time\nFROM orders_source o\nJOIN payments_source p\n ON o.order_id = p.order_id\nWHERE\n p.pay_time BETWEEN o.order_time AND o.order_time + INTERVAL '5' MINUTE;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_001_en"} {"task_id": "flinksql_002_en", "id": "online-compute_FlinkSQL_flinksql_002", "name": "Order-Payment Interval Join + Windowed Aggregation", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses two datagen built-in tables to simulate an order stream and a payment stream, performs an Interval Join on `order_id`, and then aggregates the order count and total payment amount over a 10-minute tumbling window, outputting the results to the console.\n\n**Business Background and Objective**: Simulate an order stream and a payment stream using two datagen built-in tables, each generating 100 million records. The `order_id` and `user_id` in the order stream range from 1 to 1,000,000, and the `order_id` in the payment stream also ranges from 1 to 1,000,000. Both tables use `LOCALTIMESTAMP` as the event time and set a 5-second watermark delay.\n\nPerform an Interval Join on the two tables using `order_id`, matching only records where the payment time falls within 10 minutes before or after the order time. Then, aggregate the successfully matched records over a 10-minute tumbling window to compute the order count and total payment amount per window, and finally output the results to the console table.\n\n**Source Table Definitions**:\n- `orders_source` (order stream, datagen connector):\n - `order_id INT`: Order ID, randomly generated in the range 1–1,000,000\n - `user_id INT`: User ID, randomly generated in the range 1–1,000,000\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 1000`\n\n- `payments_source` (payment stream, datagen connector):\n - `order_id INT`: Order ID, randomly generated in the range 1–1,000,000\n - `pay_amount DOUBLE`: Payment amount, randomly generated in the range 1–100,000\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 1000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `window_start VARCHAR`: Window start time\n - `window_end VARCHAR`: Window end time\n - `order_count BIGINT`: Order count within the window\n - `total_pay_amount DOUBLE`: Total payment amount within the window\n\n**Join + Aggregation Logic**:\n- Interval Join condition: `orders_source.order_id = payments_source.order_id`\n- Time window: `payments_source.event_time BETWEEN orders_source.event_time - INTERVAL '10' MINUTE AND orders_source.event_time + INTERVAL '10' MINUTE`\n- Tumbling window: `TUMBLE` 10 minutes\n- Aggregation metrics: `COUNT(*) AS order_count`, `SUM(pay_amount) AS total_pay_amount`\n- Convert window times to `VARCHAR` for output\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `window_start`, `window_end`, `order_count`, `total_pay_amount`", "ground_truth": "-- online_002: 订单支付 Interval Join + Tumble 窗口聚合\n-- 每个源生成 1 亿条数据 @ 1000 rows/sec\n\n-- 1. 订单流 datagen 源表\nCREATE TABLE orders_source (\n order_id INT,\n user_id INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '1000000'\n);\n\n-- 2. 支付流 datagen 源表\nCREATE TABLE payments_source (\n order_id INT,\n pay_amount DOUBLE,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.pay_amount.kind' = 'random',\n 'fields.pay_amount.min' = '1',\n 'fields.pay_amount.max' = '100000'\n);\n\n-- 3. Console 输出表\nCREATE TABLE console_output (\n window_start VARCHAR,\n window_end VARCHAR,\n order_count BIGINT,\n total_pay_amount DOUBLE\n) WITH (\n 'connector' = 'print'\n);\n\n-- 4. Interval Join + Tumble 10min 窗口聚合\nINSERT INTO console_output\nSELECT\n CAST(TUMBLE_START(o.event_time, INTERVAL '10' MINUTE) AS VARCHAR) AS window_start,\n CAST(TUMBLE_END(o.event_time, INTERVAL '10' MINUTE) AS VARCHAR) AS window_end,\n COUNT(*) AS order_count,\n SUM(p.pay_amount) AS total_pay_amount\nFROM orders_source o\nJOIN payments_source p\n ON o.order_id = p.order_id\n AND p.event_time BETWEEN o.event_time - INTERVAL '10' MINUTE\n AND o.event_time + INTERVAL '10' MINUTE\nGROUP BY TUMBLE(o.event_time, INTERVAL '10' MINUTE);", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_002_en"} {"task_id": "flinksql_003_en", "id": "online-compute_FlinkSQL_flinksql_003", "name": "Word Frequency Tumbling Window Statistics", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses a datagen built-in table to simulate a word frequency data stream, groups by `word` and opens a 1-minute tumbling window to count the occurrences of each word, and outputs the results to the console.\n\n**Business Background and Objective**: Simulate a word frequency data stream using a datagen built-in table, generating 1 billion records in the `word` field. Use `LOCALTIMESTAMP` as the event time and set a 5-second watermark delay. Group by `word` and count the occurrences of each word over a 1-minute tumbling window, then output `word` and `cnt` to the console table.\n\n**Source Table Definition**:\n- `word_source` (word frequency stream, datagen connector):\n - `word VARCHAR`: Word, randomly generated (value range 1–1000 to simulate distinct words)\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 1000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `word VARCHAR`: Word\n - `cnt BIGINT`: Number of occurrences of the word within the current window\n\n**Aggregation Logic**:\n- Group by `word`, using a 1-minute tumbling window\n- Aggregation metric: `COUNT(*) AS cnt`\n- The window is defined by the `TUMBLE` function\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `word`, `cnt`", "ground_truth": "-- online_003: 词频滚动窗口统计\n-- 单源生成 10 亿条数据 @ 1000 rows/sec\n\n-- 1. 词频流 datagen 源表\nCREATE TABLE word_source (\n word VARCHAR,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.word.kind' = 'random',\n 'fields.word.length' = '5'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n word VARCHAR,\n cnt BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. Tumble 1min 窗口词频统计\nINSERT INTO console_output\nSELECT\n word,\n COUNT(*) AS cnt\nFROM word_source\nGROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), word;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_003_en"} {"task_id": "flinksql_004_en", "id": "online-compute_FlinkSQL_flinksql_004", "name": "Dual Window Aggregation (Tumble + Hop)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses a datagen built-in table to generate order events, and computes the sales volume and order count per product using both a tumbling window and a sliding window, outputting the results to two separate console tables.\n\n**Business Background and Objective**: Generate order events (`order_id BIGINT`, `product_id INT`, `quantity INT`) using a datagen built-in table. Use `LOCALTIMESTAMP` as the event time and set a 5-second watermark delay.\n\nCompute statistics using two window types:\n1. **1-minute tumbling window**: Compute the sales volume `SUM(quantity) AS sales` and order count `COUNT(*) AS order_cnt` per product.\n2. **Sliding window** (slides every 30 seconds, covering the past 1 minute): Compute the sales volume `SUM(quantity) AS sales` and order count `COUNT(*) AS order_cnt` per product.\n\nPrint the results of both window types to two separate console tables, with each record carrying a window type identifier `window_type`.\n\n**Source Table Definition**:\n- `orders_source` (order event stream, datagen connector):\n - `order_id BIGINT`: Order ID, randomly generated in the range 1–1,000,000\n - `product_id INT`: Product ID, randomly generated in the range 1–10,000\n - `quantity INT`: Quantity, randomly generated in the range 1–10\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 50`\n\n**Output Table Definitions**:\n- `console_tumble` (print connector, tumbling window results):\n - `window_type STRING`: Window type identifier, fixed as `'TUMBLE'`\n - `window_start TIMESTAMP(3)`: Window start time\n - `window_end TIMESTAMP(3)`: Window end time\n - `product_id INT`: Product ID\n - `sales INT`: Sales volume of the product within the window\n - `order_cnt BIGINT`: Order count of the product within the window\n\n- `console_hop` (print connector, sliding window results):\n - `window_type STRING`: Window type identifier, fixed as `'HOP'`\n - `window_start TIMESTAMP(3)`: Window start time\n - `window_end TIMESTAMP(3)`: Window end time\n - `product_id INT`: Product ID\n - `sales INT`: Sales volume of the product within the window\n - `order_cnt BIGINT`: Order count of the product within the window\n\n**Aggregation Logic**:\n- Tumbling window: `GROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), product_id`\n- Sliding window: `GROUP BY HOP(event_time, INTERVAL '30' SECOND, INTERVAL '1' MINUTE), product_id`\n- Aggregation metrics: `SUM(quantity) AS sales`, `COUNT(*) AS order_cnt`\n- Both window times and the window type must be explicitly output\n\n**Output Requirements**:\n- Use two `INSERT INTO` statements to output to `console_tumble` and `console_hop` respectively.\n- Output field order: `window_type`, `window_start`, `window_end`, `product_id`, `sales`, `order_cnt`", "ground_truth": "-- online_004: 双窗口聚合 (Tumble + Hop)\n-- 单源生成 @ 50 rows/sec\n\n-- 1. 订单事件 datagen 源表\nCREATE TABLE orders_source (\n order_id BIGINT,\n product_id INT,\n quantity INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '50',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.product_id.kind' = 'random',\n 'fields.product_id.min' = '1',\n 'fields.product_id.max' = '10000',\n 'fields.quantity.kind' = 'random',\n 'fields.quantity.min' = '1',\n 'fields.quantity.max' = '10'\n);\n\n-- 2. Console 输出表 (Tumble 滚动窗口)\nCREATE TABLE console_tumble (\n window_type STRING,\n window_start TIMESTAMP(3),\n window_end TIMESTAMP(3),\n product_id INT,\n sales INT,\n order_cnt BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. Console 输出表 (Hop 滑动窗口)\nCREATE TABLE console_hop (\n window_type STRING,\n window_start TIMESTAMP(3),\n window_end TIMESTAMP(3),\n product_id INT,\n sales INT,\n order_cnt BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 4a. Tumble 1min 滚动窗口:SUM 销量 + COUNT 订单数\nINSERT INTO console_tumble\nSELECT\n 'TUMBLE' AS window_type,\n TUMBLE_START(event_time, INTERVAL '1' MINUTE) AS window_start,\n TUMBLE_END(event_time, INTERVAL '1' MINUTE) AS window_end,\n product_id,\n CAST(SUM(quantity) AS INT) AS sales,\n COUNT(*) AS order_cnt\nFROM orders_source\nGROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), product_id;\n\n-- 4b. Hop 滑动窗口 (30s slide, 1min size):SUM 销量 + COUNT 订单数\nINSERT INTO console_hop\nSELECT\n 'HOP' AS window_type,\n HOP_START(event_time, INTERVAL '30' SECOND, INTERVAL '1' MINUTE) AS window_start,\n HOP_END(event_time, INTERVAL '30' SECOND, INTERVAL '1' MINUTE) AS window_end,\n product_id,\n CAST(SUM(quantity) AS INT) AS sales,\n COUNT(*) AS order_cnt\nFROM orders_source\nGROUP BY HOP(event_time, INTERVAL '30' SECOND, INTERVAL '1' MINUTE), product_id;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_004_en"} {"task_id": "flinksql_005", "id": "online-compute_FlinkSQL_flinksql_005", "name": "滚动窗口 TopN 商品排行", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置表模拟电商订单,按 10 秒滚动窗口做 Top-N 商品排行,输出销售额最高的前 3 个商品到 console。\n\n**业务背景与目标**:用 datagen 内置表生成电商订单(字段 order_id / product_id / amount),每秒生成约 10 条。以 LOCALTIMESTAMP 作为事件时间,设置 5 秒的 Watermark 延迟。\n\n按 10 秒滚动窗口做 Top-N 排行:每个窗口内统计每个商品的销售额 SUM(amount) 和订单数 COUNT(*),按销售额降序取前三名,打印到 console。\n\n**源表定义**:\n- `orders_source`(订单流,datagen 连接器):\n - order_id BIGINT:订单 ID,随机取值 1~1000000\n - product_id INT:商品 ID,随机取值 1~1000\n - amount DOUBLE:订单金额,随机取值 1~10000\n - event_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 5 秒\n - 生成速率:rows-per-second = 10\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start TIMESTAMP(3):窗口起始时间\n - product_id INT:商品 ID\n - sales DOUBLE:该窗口内销售额\n - order_cnt BIGINT:该窗口内订单数\n - rn BIGINT:排名序号\n\n**TopN 逻辑**:\n- 使用 10 秒滚动窗口聚合:SUM(amount) AS sales, COUNT(*) AS order_cnt\n- 在窗口内使用 ROW_NUMBER() 按销售额降序排名\n- 只输出排名前 3 的记录(rn <= 3)\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将 Top 3 结果输出\n- 输出字段顺序:window_start, product_id, sales, order_cnt, rn", "ground_truth": "-- online_005: 滚动窗口 TopN 商品排行\n-- 单源生成 @ 10 rows/sec, Tumble 10s + ROW_NUMBER Top3\n\n-- 1. 订单流 datagen 源表\nCREATE TABLE orders_source (\n order_id BIGINT,\n product_id INT,\n amount DOUBLE,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '10',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.product_id.kind' = 'random',\n 'fields.product_id.min' = '1',\n 'fields.product_id.max' = '1000',\n 'fields.amount.kind' = 'random',\n 'fields.amount.min' = '1',\n 'fields.amount.max' = '10000'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP(3),\n product_id INT,\n sales DOUBLE,\n order_cnt BIGINT,\n rn BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. Tumble 10s 窗口聚合 + ROW_NUMBER Top 3\nINSERT INTO console_output\nSELECT\n window_start,\n product_id,\n sales,\n order_cnt,\n rn\nFROM (\n SELECT\n TUMBLE_START(event_time, INTERVAL '10' SECOND) AS window_start,\n product_id,\n SUM(amount) AS sales,\n COUNT(*) AS order_cnt,\n ROW_NUMBER() OVER (\n PARTITION BY TUMBLE_START(event_time, INTERVAL '10' SECOND)\n ORDER BY SUM(amount) DESC\n ) AS rn\n FROM orders_source\n GROUP BY TUMBLE(event_time, INTERVAL '10' SECOND), product_id\n)\nWHERE rn <= 3;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_005"} {"task_id": "flinksql_006", "id": "online-compute_FlinkSQL_flinksql_006", "name": "异常事件过滤 + 窗口 TopN", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置表造设备事件流,过滤出异常事件后按省份做窗口 TopN 排名,输出到 console。\n\n**业务背景与目标**:用内置 datagen 表生成设备事件数据,字段包括 device_id(int)、event_type(int)、province(string)、ts(timestamp),每秒 80 条,event_type 取值 1-10,province 长度 4 字符,用 ts 字段作为事件时间开 1 分钟滚动窗口(watermark 延迟 5 秒),先过滤 event_type=3 的异常事件,然后按省份分组统计每分钟的异常事件数,按异常数降序排名取 Top-5,输出字段包括窗口开始时间、省份、异常事件数、排名,打印到 console。\n\n**源表定义**:\n- `device_source`(设备事件流,datagen 连接器):\n - device_id INT:设备 ID,随机生成\n - event_type INT:事件类型,随机取值 1~10\n - province VARCHAR:省份,随机生成,长度 4 字符\n - event_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 5 秒\n - 生成速率:rows-per-second = 80\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start TIMESTAMP:窗口开始时间\n - province VARCHAR:省份\n - abnormal_cnt BIGINT:异常事件数\n - `rank` BIGINT:排名(注意 rank 是关键字,需要用反引号包裹)\n\n**查询逻辑**:\n- 过滤:WHERE event_type = 3(异常事件)\n- 窗口:TUMBLE(event_time, INTERVAL '1' MINUTE) 滚动窗口\n- 聚合:按 province 和窗口分组,COUNT(*) 统计异常事件数\n- 排名:ROW_NUMBER() OVER (PARTITION BY window_start ORDER BY abnormal_cnt DESC) AS `rank`\n- Top-N:WHERE `rank` <= 5\n\n**输出要求**:\n- 使用 INSERT INTO console_output 输出结果\n- 输出字段顺序:window_start, province, abnormal_cnt, `rank`", "ground_truth": "-- flinksql_006: 异常事件过滤 + 窗口 TopN\n-- datagen 生成设备事件流 @ 80 rows/sec, event_type=3 过滤后 Tumble 1min Top-5\n\n-- 1. 设备事件流 datagen 源表\nCREATE TABLE device_source (\n device_id INT,\n event_type INT,\n province VARCHAR,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '80',\n 'fields.event_type.kind' = 'random',\n 'fields.event_type.min' = '1',\n 'fields.event_type.max' = '10',\n 'fields.province.kind' = 'random',\n 'fields.province.length' = '4'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP,\n province VARCHAR,\n abnormal_cnt BIGINT,\n `rank` BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. 过滤异常事件(event_type=3) → Tumble 窗口 → Top-5\nINSERT INTO console_output\nSELECT\n window_start,\n province,\n abnormal_cnt,\n `rank`\nFROM (\n SELECT\n TUMBLE_START(event_time, INTERVAL '1' MINUTE) AS window_start,\n province,\n COUNT(*) AS abnormal_cnt,\n ROW_NUMBER() OVER (PARTITION BY TUMBLE_START(event_time, INTERVAL '1' MINUTE) ORDER BY COUNT(*) DESC) AS `rank`\n FROM device_source\n WHERE event_type = 3\n GROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), province\n)\nWHERE `rank` <= 5;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_006"} {"task_id": "flinksql_007", "id": "online-compute_FlinkSQL_flinksql_007", "name": "用户行为滚动窗口统计", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置表造用户行为流,开滚动窗口统计每个用户的 action 数,结果写到 console。\n\n**业务背景与目标**:用 datagen 内置数据源表模拟用户行为数据流,每秒生成 50 条记录,包含三个字段:userId(用户ID,字符串,长度6)、action(动作类型,字符串,长度8)、ftime(事件时间,timestamp 类型)。请基于这个 datagen 表,按事件时间做 1 分钟滚动窗口聚合,统计每个用户在每个 1 分钟窗口内的 action 总次数,并把结果(用户ID、动作次数、窗口起始时间)写入到内置控制台表中输出。事件时间字段 ftime 使用 LOCALTIMESTAMP 作为 computed column 并设置 watermark 延迟 5 秒。\n\n**源表定义**:\n- `user_source`(用户行为流,datagen 连接器):\n - userId VARCHAR:用户 ID,随机生成,长度 6 字符\n - action VARCHAR:动作类型,随机生成,长度 8 字符\n - ftime:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 5 秒\n - 生成速率:rows-per-second = 50\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - user_id VARCHAR:用户 ID\n - action_count BIGINT:动作次数\n - window_start TIMESTAMP:窗口起始时间\n\n**查询逻辑**:\n- 窗口:TUMBLE(ftime, INTERVAL '1' MINUTE) 滚动窗口\n- 聚合:按 userId 分组,COUNT(*) 统计 action 总次数\n- 输出:窗口起始时间 + 用户 ID + 动作次数\n\n**输出要求**:\n- 使用 INSERT INTO console_output 输出结果\n- 输出字段顺序:user_id, action_count, window_start", "ground_truth": "-- flinksql_007: 用户行为滚动窗口统计\n-- datagen 生成用户行为流 @ 50 rows/sec, Tumble 1min 窗口聚合\n\n-- 1. 用户行为流 datagen 源表\nCREATE TABLE user_source (\n userId VARCHAR,\n action VARCHAR,\n ftime AS LOCALTIMESTAMP,\n WATERMARK FOR ftime AS ftime - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '50',\n 'fields.userId.length' = '6',\n 'fields.action.length' = '8'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n user_id VARCHAR,\n action_count BIGINT,\n window_start TIMESTAMP\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. Tumble 1min 窗口聚合: 统计每个用户每分钟的 action 次数\nINSERT INTO console_output\nSELECT\n userId AS user_id,\n COUNT(*) AS action_count,\n TUMBLE_START(ftime, INTERVAL '1' MINUTE) AS window_start\nFROM user_source\nGROUP BY TUMBLE(ftime, INTERVAL '1' MINUTE), userId;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_007"} {"task_id": "flinksql_008_en", "id": "online-compute_FlinkSQL_flinksql_008", "name": "Session Window User Behavior Aggregation", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses a datagen built-in table to simulate a user behavior stream, performs session window aggregation to compute behavioral metrics per user within each session, and outputs the results to the console.\n\n**Business Background and Objective**: Simulate a user behavior data stream using a datagen built-in table that generates 50 records per second, containing four fields: `userId` (user ID, string of length 6), `action` (action type, string of length 8), `action_time` (action occurrence time, timestamp), and `ftime` (event time, timestamp). Based on this datagen table, using `ftime` as the event time (with a 5-second watermark delay), perform a 30-minute session window (`SESSION`) aggregation grouped by `userId`. Compute the following metrics for each user within each session window: session start time, session end time, total action count, number of distinct action types, and the last action time (the maximum value of `action_time`). Output the results to a built-in console table.\n\n**Source Table Definition**:\n- `user_source` (user behavior stream, datagen connector):\n - `userId VARCHAR`: User ID, randomly generated, 6 characters in length\n - `action VARCHAR`: Action type, randomly generated, 8 characters in length\n - `action_time TIMESTAMP(3)`: Action occurrence time\n - `ftime`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 50`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `user_id VARCHAR`: User ID\n - `session_start TIMESTAMP`: Session start time\n - `session_end TIMESTAMP`: Session end time\n - `action_count BIGINT`: Total action count\n - `unique_actions BIGINT`: Number of distinct action types\n - `last_action_time TIMESTAMP`: Last action time\n\n**Query Logic**:\n- Window: `SESSION(ftime, INTERVAL '30' MINUTE)` session window\n- Grouping: Group by `userId` and the session window\n- Aggregation: `COUNT(*)` for total action count, `COUNT(DISTINCT action)` for distinct action type count, `MAX(action_time)` for last action time\n- Window functions: Use `SESSION_START` / `SESSION_END` to obtain the window start and end times\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `user_id`, `session_start`, `session_end`, `action_count`, `unique_actions`, `last_action_time`", "ground_truth": "-- flinksql_008: 会话窗口用户行为聚合\n-- datagen 生成用户行为流 @ 50 rows/sec, SESSION 30min 窗口聚合\n\n-- 1. 用户行为流 datagen 源表\nCREATE TABLE user_source (\n userId VARCHAR,\n action VARCHAR,\n action_time TIMESTAMP(3),\n ftime AS LOCALTIMESTAMP,\n WATERMARK FOR ftime AS ftime - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '50',\n 'fields.userId.length' = '6',\n 'fields.action.length' = '8'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n user_id VARCHAR,\n session_start TIMESTAMP,\n session_end TIMESTAMP,\n action_count BIGINT,\n unique_actions BIGINT,\n last_action_time TIMESTAMP\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. SESSION 30min 窗口聚合: 统计每个用户每段会话的行为指标\nINSERT INTO console_output\nSELECT\n userId AS user_id,\n SESSION_START(ftime, INTERVAL '30' MINUTE) AS session_start,\n SESSION_END(ftime, INTERVAL '30' MINUTE) AS session_end,\n COUNT(*) AS action_count,\n COUNT(DISTINCT action) AS unique_actions,\n MAX(action_time) AS last_action_time\nFROM user_source\nGROUP BY SESSION(ftime, INTERVAL '30' MINUTE), userId;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_008_en"} {"task_id": "flinksql_009_en", "id": "online-compute_FlinkSQL_flinksql_009", "name": "Tumbling Window PV/UV Statistics", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses a datagen built-in table to simulate a user click stream, computes PV and UV per page over a window, and writes the results to the console.\n\n**Business Background and Objective**: Simulate a user click stream using a datagen built-in table (`user_id` ranging from 1–1000, `page_id` ranging from 1–50, 10,000 records per second). Compute the PV (`COUNT(*)`) and UV (`COUNT(DISTINCT user_id)`) per page over a 1-minute tumbling window. Output the results (window start, window end, `page_id`, `pv`, `uv`) to the console.\n\n**Source Table Definition**:\n- `click_source` (user click stream, datagen connector):\n - `user_id INT`: User ID, randomly generated in the range 1–1000\n - `page_id INT`: Page ID, randomly generated in the range 1–50\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 10000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `window_start TIMESTAMP`: Window start time\n - `window_end TIMESTAMP`: Window end time\n - `page_id INT`: Page ID\n - `pv BIGINT`: Page views (PV)\n - `uv BIGINT`: Unique visitors (UV)\n\n**Query Logic**:\n- Window: `TUMBLE(event_time, INTERVAL '1' MINUTE)` tumbling window\n- Grouping: Group by `page_id` and the window\n- PV: `COUNT(*)` to compute page views\n- UV: `COUNT(DISTINCT user_id)` to compute unique visitors\n- Window functions: Use `TUMBLE_START` / `TUMBLE_END` to obtain the window start and end times\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `window_start`, `window_end`, `page_id`, `pv`, `uv`", "ground_truth": "-- flinksql_009: 滚动窗口 PV/UV 统计\n-- datagen 生成用户点击流 @ 10000 rows/sec, Tumble 1min PV/UV\n\n-- 1. 用户点击流 datagen 源表\nCREATE TABLE click_source (\n user_id INT,\n page_id INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '10000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '1000',\n 'fields.page_id.kind' = 'random',\n 'fields.page_id.min' = '1',\n 'fields.page_id.max' = '50'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP,\n window_end TIMESTAMP,\n page_id INT,\n pv BIGINT,\n uv BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. Tumble 1min 窗口聚合: 按页面统计 PV 和 UV\nINSERT INTO console_output\nSELECT\n TUMBLE_START(event_time, INTERVAL '1' MINUTE) AS window_start,\n TUMBLE_END(event_time, INTERVAL '1' MINUTE) AS window_end,\n page_id,\n COUNT(*) AS pv,\n COUNT(DISTINCT user_id) AS uv\nFROM click_source\nGROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), page_id;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_009_en"} {"task_id": "flinksql_010", "id": "online-compute_FlinkSQL_flinksql_010", "name": "滑动窗口(HOP)店铺统计", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 模拟订单流,按店铺做滑动窗口统计订单金额和数量,写入 console。\n\n**业务背景与目标**:用 datagen 模拟订单流(order_id 取值 1~1000000、shop_id 取值 1~100、amount 取值 0~1000,每秒 5000 条),按 1 分钟步长、5 分钟窗口大小做 HOP 滑动窗口统计每个店铺的订单总额(SUM)、订单数(COUNT)和平均金额(AVG),写入 console。\n\n**源表定义**:\n- `order_source`(订单流,datagen 连接器):\n - order_id BIGINT:订单 ID,随机取值 1~1000000\n - shop_id INT:店铺 ID,随机取值 1~100\n - amount DOUBLE:订单金额,随机取值 0~1000\n - event_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 10 秒\n - 生成速率:rows-per-second = 5000\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start TIMESTAMP:窗口开始时间\n - window_end TIMESTAMP:窗口结束时间\n - shop_id INT:店铺 ID\n - total_amount DOUBLE:订单总额\n - order_cnt BIGINT:订单数量\n - avg_amount DOUBLE:平均订单金额\n\n**查询逻辑**:\n- 窗口:HOP(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE) 滑动窗口\n - 步长(slide):1 分钟\n - 窗口大小(size):5 分钟\n- 分组:按 shop_id 和窗口分组\n- 聚合:SUM(amount) 订单总额,COUNT(*) 订单数,AVG(amount) 平均金额\n- 窗口函数:HOP_START / HOP_END 获取窗口起止时间\n\n**输出要求**:\n- 使用 INSERT INTO console_output 输出结果\n- 输出字段顺序:window_start, window_end, shop_id, total_amount, order_cnt, avg_amount", "ground_truth": "-- flinksql_010: 滑动窗口(HOP)店铺统计\n-- datagen 生成订单流 @ 5000 rows/sec, HOP 1min slide 5min window\n\n-- 1. 订单流 datagen 源表\nCREATE TABLE order_source (\n order_id BIGINT,\n shop_id INT,\n amount DOUBLE,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '10' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '5000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.shop_id.kind' = 'random',\n 'fields.shop_id.min' = '1',\n 'fields.shop_id.max' = '100',\n 'fields.amount.kind' = 'random',\n 'fields.amount.min' = '0',\n 'fields.amount.max' = '1000'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP,\n window_end TIMESTAMP,\n shop_id INT,\n total_amount DOUBLE,\n order_cnt BIGINT,\n avg_amount DOUBLE\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. HOP 滑动窗口聚合: 按店铺统计订单总额、数量和平均金额\nINSERT INTO console_output\nSELECT\n HOP_START(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE) AS window_start,\n HOP_END(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE) AS window_end,\n shop_id,\n SUM(amount) AS total_amount,\n COUNT(*) AS order_cnt,\n AVG(amount) AS avg_amount\nFROM order_source\nGROUP BY HOP(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE), shop_id;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_010"} {"task_id": "flinksql_011_en", "id": "online-compute_FlinkSQL_flinksql_011", "name": "Tumbling Window Product TopN Ranking", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses the built-in datagen connector to simulate an order data source, aggregates product sales over a 10-minute tumbling window, and then uses the `ROW_NUMBER` window function to retrieve the top 5 products by sales within each window, outputting the results to the console.\n\n**Business Background and Objective**: Simulate an order stream using a datagen built-in table, generating massive order data. Group by a 10-minute tumbling window to compute the total sales amount and order count per product within each window, and finally use `ROW_NUMBER` ranking to retrieve the top 5 products by sales amount within each window.\n\n**Source Table Definition**:\n- `order_source` (order stream, datagen connector):\n - `order_id BIGINT`: Order ID, randomly generated in the range 1–10,000,000\n - `product_id INT`: Product ID, randomly generated in the range 1–200\n - `amount DOUBLE`: Order amount, randomly generated in the range 0–500\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 8000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `window_start TIMESTAMP(3)`: Tumbling window start time\n - `product_id INT`: Product ID\n - `sales DOUBLE`: Total sales amount of the product within the window\n - `order_cnt BIGINT`: Number of orders for the product within the window\n - `rn BIGINT`: Sales ranking within the window\n\n**SQL Logic**:\n- Apply `TUMBLE(event_time, INTERVAL '10' MINUTE)` tumbling window on `order_source`\n- Group by `window_start`, `window_end`, `product_id`\n- Aggregate `SUM(amount) AS sales` and `COUNT(*) AS order_cnt`\n- Use `ROW_NUMBER() OVER (PARTITION BY window_start, window_end ORDER BY sales DESC) AS rn`\n- Outer query filter: `WHERE rn <= 5`\n- Final SELECT: `window_start`, `product_id`, `sales`, `order_cnt`, `rn`\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `window_start`, `product_id`, `sales`, `order_cnt`, `rn`", "ground_truth": "-- flinksql_011: 滚动窗口商品 TopN 排行\n-- 10-min TUMBLE + SUM(amount) + COUNT(*) + ROW_NUMBER Top-5\n\n-- 1. 订单源 datagen 表\nCREATE TABLE order_source (\n order_id BIGINT,\n product_id INT,\n amount DOUBLE,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '8000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '10000000',\n 'fields.product_id.kind' = 'random',\n 'fields.product_id.min' = '1',\n 'fields.product_id.max' = '200',\n 'fields.amount.kind' = 'random',\n 'fields.amount.min' = '0',\n 'fields.amount.max' = '500'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP(3),\n product_id INT,\n sales DOUBLE,\n order_cnt BIGINT,\n rn BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. TUMBLE 窗口聚合 + ROW_NUMBER Top-5\nINSERT INTO console_output\nSELECT\n window_start,\n product_id,\n sales,\n order_cnt,\n rn\nFROM (\n SELECT\n window_start,\n window_end,\n product_id,\n sales,\n order_cnt,\n ROW_NUMBER() OVER (\n PARTITION BY window_start, window_end\n ORDER BY sales DESC\n ) AS rn\n FROM (\n SELECT\n TUMBLE_START(event_time, INTERVAL '10' MINUTE) AS window_start,\n TUMBLE_END(event_time, INTERVAL '10' MINUTE) AS window_end,\n product_id,\n SUM(amount) AS sales,\n COUNT(*) AS order_cnt\n FROM order_source\n GROUP BY\n TUMBLE(event_time, INTERVAL '10' MINUTE),\n product_id\n )\n)\nWHERE rn <= 5;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_011_en"} {"task_id": "flinksql_012_en", "id": "online-compute_FlinkSQL_flinksql_012", "name": "Session Window User Behavior Statistics", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses the built-in datagen connector to simulate a user behavior data source, computes per-user behavioral statistics over a 30-minute session window (`SESSION`), and outputs the results to the console.\n\n**Business Background and Objective**: Simulate a user behavior stream using a datagen built-in table. Group by a 30-minute session window to compute the total action count (`COUNT`) and the number of distinct action types (`COUNT DISTINCT`) per user within each session window. Output the results to the console.\n\n**Source Table Definition**:\n- `user_actions` (user behavior stream, datagen connector):\n - `user_id INT`: User ID, randomly generated in the range 1–5000\n - `action_id INT`: Action type ID, randomly generated in the range 1–10\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 2000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `user_id INT`: User ID\n - `session_start TIMESTAMP(3)`: Session window start time\n - `session_end TIMESTAMP(3)`: Session window end time\n - `action_count BIGINT`: Total action count\n - `unique_actions BIGINT`: Number of distinct action types\n\n**SQL Logic**:\n- Apply `SESSION(event_time, INTERVAL '30' MINUTE)` session window on `user_actions`\n- Group by `SESSION(event_time, INTERVAL '30' MINUTE)` and `user_id`\n- Aggregate `COUNT(*) AS action_count` and `COUNT(DISTINCT action_id) AS unique_actions`\n- Use `SESSION_START` and `SESSION_END` functions to obtain the window start and end times\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `user_id`, `session_start`, `session_end`, `action_count`, `unique_actions`", "ground_truth": "-- flinksql_012: 会话窗口用户行为统计\n-- 30-min SESSION + COUNT + COUNT DISTINCT\n\n-- 1. 用户行为 datagen 源表\nCREATE TABLE user_actions (\n user_id INT,\n action_id INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '2000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '5000',\n 'fields.action_id.kind' = 'random',\n 'fields.action_id.min' = '1',\n 'fields.action_id.max' = '10'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n user_id INT,\n session_start TIMESTAMP(3),\n session_end TIMESTAMP(3),\n action_count BIGINT,\n unique_actions BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. SESSION 窗口聚合\nINSERT INTO console_output\nSELECT\n user_id,\n SESSION_START(event_time, INTERVAL '30' MINUTE) AS session_start,\n SESSION_END(event_time, INTERVAL '30' MINUTE) AS session_end,\n COUNT(*) AS action_count,\n COUNT(DISTINCT action_id) AS unique_actions\nFROM user_actions\nGROUP BY\n SESSION(event_time, INTERVAL '30' MINUTE),\n user_id;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_012_en"} {"task_id": "flinksql_013", "id": "online-compute_FlinkSQL_flinksql_013", "name": "累积窗口日活统计 (Cumulate UV)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置连接器模拟用户登录数据源,通过累积窗口(CUMULATE)统计日活 UV 和登录次数,输出到 console。\n\n**业务背景与目标**:用 datagen 内置表模拟用户登录流水。使用 CUMULATE TVF 累积窗口,窗口步长 1 分钟、最大窗口 1 天,统计每个累积窗口内的独立用户数(UV)和登录总次数,输出到 console。\n\n**源表定义**:\n- `user_source`(用户登录流,datagen 连接器):\n - user_id INT:用户 ID,随机取值 1~100000\n - device_id INT:设备 ID,随机取值 1~5\n - event_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 5 秒\n - 生成速率:rows-per-second = 3000\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start TIMESTAMP(3):累积窗口起始时间\n - window_end TIMESTAMP(3):累积窗口结束时间\n - uv BIGINT:独立用户数(去重 user_id)\n - login_cnt BIGINT:登录总次数\n\n**SQL 逻辑**:\n- 使用 CUMULATE TVF:TABLE(CUMULATE(TABLE user_source, DESCRIPTOR(event_time), INTERVAL '1' MINUTE, INTERVAL '1' DAY))\n- 按 window_start 和 window_end 分组\n- 聚合 COUNT(DISTINCT user_id) AS uv 和 COUNT(*) AS login_cnt\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将结果输出\n- 输出字段顺序:window_start, window_end, uv, login_cnt", "ground_truth": "-- flinksql_013: 累积窗口日活统计 (Cumulate UV)\n-- CUMULATE(1min step, 1day max) + COUNT DISTINCT + COUNT\n\n-- 1. 用户登录 datagen 源表\nCREATE TABLE user_source (\n user_id INT,\n device_id INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '3000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '100000',\n 'fields.device_id.kind' = 'random',\n 'fields.device_id.min' = '1',\n 'fields.device_id.max' = '5'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP(3),\n window_end TIMESTAMP(3),\n uv BIGINT,\n login_cnt BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. CUMULATE TVF 窗口聚合\nINSERT INTO console_output\nSELECT\n window_start,\n window_end,\n COUNT(DISTINCT user_id) AS uv,\n COUNT(*) AS login_cnt\nFROM TABLE(\n CUMULATE(\n TABLE user_source,\n DESCRIPTOR(event_time),\n INTERVAL '1' MINUTE,\n INTERVAL '1' DAY\n )\n)\nGROUP BY window_start, window_end;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_013"} {"task_id": "flinksql_014", "id": "online-compute_FlinkSQL_flinksql_014", "name": "Interval Join + 窗口聚合 (订单支付)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用两个 datagen 内置连接器模拟订单流和支付流,先按 order_id 做 Interval Join 匹配订单与支付,再对匹配结果做 10 分钟滚动窗口聚合统计,输出到 console。\n\n**业务背景与目标**:用两张 datagen 内置表分别模拟订单流和支付流。先按 order_id 做 Interval Join(支付时间在订单时间前后 10 分钟内),对匹配上的记录按 10 分钟滚动窗口聚合,统计每个窗口内的订单数和支付总额,输出到 console。\n\n**源表定义**:\n- `orders_source`(订单流,datagen 连接器):\n - order_id INT:订单 ID,随机取值 1~1000000\n - user_id INT:用户 ID,随机取值 1~100000\n - order_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 60 秒\n - 生成速率:rows-per-second = 10000\n\n- `payments_source`(支付流,datagen 连接器):\n - order_id INT:订单 ID,随机取值 1~1000000\n - pay_amount DOUBLE:支付金额,随机取值 0~5000\n - pay_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 60 秒\n - 生成速率:rows-per-second = 10000\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start VARCHAR:滚动窗口起始时间\n - window_end VARCHAR:滚动窗口结束时间\n - order_count BIGINT:窗口内匹配订单数\n - total_pay DOUBLE:窗口内支付总额\n\n**SQL 逻辑**:\n- 第一步:orders_source 与 payments_source 做 Interval Join\n - 关联条件:o.order_id = p.order_id\n - 时间窗口:p.pay_time BETWEEN o.order_time - INTERVAL '10' MINUTE AND o.order_time + INTERVAL '10' MINUTE\n - 注意:对 pay_time 做 CAST(pay_time AS TIMESTAMP(3)) 降为普通时间戳\n- 第二步:对 Join 结果做 10 分钟 TUMBLE 滚动窗口聚合\n - 使用 TUMBLE 按 o.order_time 作为事件时间\n - 聚合 COUNT(*) AS order_count 和 SUM(p.pay_amount) AS total_pay\n - 使用 TUMBLE_START 和 TUMBLE_END(CAST 为 VARCHAR)\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将结果输出\n- 输出字段顺序:window_start, window_end, order_count, total_pay", "ground_truth": "-- flinksql_014: Interval Join + 10-min TUMBLE 窗口聚合 (订单支付)\n-- 双源 Interval Join → TUMBLE 聚合 → COUNT + SUM\n\n-- 1. 订单流 datagen 源表\nCREATE TABLE orders_source (\n order_id INT,\n user_id INT,\n order_time AS LOCALTIMESTAMP,\n WATERMARK FOR order_time AS order_time - INTERVAL '60' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '10000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '100000'\n);\n\n-- 2. 支付流 datagen 源表\nCREATE TABLE payments_source (\n order_id INT,\n pay_amount DOUBLE,\n pay_time AS LOCALTIMESTAMP,\n WATERMARK FOR pay_time AS pay_time - INTERVAL '60' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '10000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000',\n 'fields.pay_amount.kind' = 'random',\n 'fields.pay_amount.min' = '0',\n 'fields.pay_amount.max' = '5000'\n);\n\n-- 3. Console 输出表\nCREATE TABLE console_output (\n window_start VARCHAR,\n window_end VARCHAR,\n order_count BIGINT,\n total_pay DOUBLE\n) WITH (\n 'connector' = 'print'\n);\n\n-- 4. Interval Join + TUMBLE 窗口聚合\nINSERT INTO console_output\nSELECT\n CAST(TUMBLE_START(o.order_time, INTERVAL '10' MINUTE) AS VARCHAR) AS window_start,\n CAST(TUMBLE_END(o.order_time, INTERVAL '10' MINUTE) AS VARCHAR) AS window_end,\n COUNT(*) AS order_count,\n SUM(p.pay_amount) AS total_pay\nFROM orders_source o\nJOIN payments_source p\n ON o.order_id = p.order_id\nWHERE\n p.pay_time BETWEEN o.order_time - INTERVAL '10' MINUTE\n AND o.order_time + INTERVAL '10' MINUTE\nGROUP BY\n TUMBLE(o.order_time, INTERVAL '10' MINUTE);", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_014"} {"task_id": "flinksql_015", "id": "online-compute_FlinkSQL_flinksql_015", "name": "Regular Join 曝光点击关联", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用两个 datagen 内置连接器分别模拟广告曝光流和广告点击流,通过 Regular Join(常规内连接)关联曝光与点击,输出到 console。\n\n**业务背景与目标**:用两张 datagen 内置表分别模拟广告曝光和广告点击数据。Regular Join 不需要事件时间或 Watermark,直接按 user_id 和 ad_id 做内连接,将同一用户对同一广告的曝光和点击关联起来输出。\n\n**源表定义**:\n- `impression_source`(曝光流,datagen 连接器):\n - imp_id BIGINT:曝光 ID,随机取值 1~10000000\n - user_id INT:用户 ID,随机取值 1~100000\n - ad_id INT:广告 ID,随机取值 1~500\n - 生成速率:rows-per-second = 5000\n - 注意:Regular Join 不需要定义 event_time 或 WATERMARK\n\n- `click_source`(点击流,datagen 连接器):\n - click_id BIGINT:点击 ID,随机取值 1~10000000\n - user_id INT:用户 ID,随机取值 1~100000\n - ad_id INT:广告 ID,随机取值 1~500\n - 生成速率:rows-per-second = 1000\n - 注意:Regular Join 不需要定义 event_time 或 WATERMARK\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - user_id INT:用户 ID\n - ad_id INT:广告 ID\n - imp_id BIGINT:曝光 ID\n - click_id BIGINT:点击 ID\n\n**Join 逻辑**:\n- 使用 INNER JOIN 关联曝光流和点击流\n- 关联条件:i.user_id = c.user_id AND i.ad_id = c.ad_id\n- 这是一个 Regular Join,不需要 Interval Join 的时间窗口条件\n- 注意:Regular Join 的 state 会持续增长,在生产环境需注意 TTL 配置\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将匹配结果输出\n- 输出字段顺序:user_id, ad_id, imp_id, click_id", "ground_truth": "-- flinksql_015: Regular Join (广告曝光 + 点击)\n-- 双源无 WATERMARK + INNER JOIN on user_id AND ad_id\n\n-- 1. 曝光流 datagen 源表 (无 event_time, 无 WATERMARK)\nCREATE TABLE impression_source (\n imp_id BIGINT,\n user_id INT,\n ad_id INT\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '5000',\n 'fields.imp_id.kind' = 'random',\n 'fields.imp_id.min' = '1',\n 'fields.imp_id.max' = '10000000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '100000',\n 'fields.ad_id.kind' = 'random',\n 'fields.ad_id.min' = '1',\n 'fields.ad_id.max' = '500'\n);\n\n-- 2. 点击流 datagen 源表 (无 event_time, 无 WATERMARK)\nCREATE TABLE click_source (\n click_id BIGINT,\n user_id INT,\n ad_id INT\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.click_id.kind' = 'random',\n 'fields.click_id.min' = '1',\n 'fields.click_id.max' = '10000000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '100000',\n 'fields.ad_id.kind' = 'random',\n 'fields.ad_id.min' = '1',\n 'fields.ad_id.max' = '500'\n);\n\n-- 3. Console 输出表\nCREATE TABLE console_output (\n user_id INT,\n ad_id INT,\n imp_id BIGINT,\n click_id BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 4. Regular Join: 按 user_id + ad_id 关联曝光和点击\nINSERT INTO console_output\nSELECT\n i.user_id,\n i.ad_id,\n i.imp_id,\n c.click_id\nFROM impression_source i\nINNER JOIN click_source c\n ON i.user_id = c.user_id\n AND i.ad_id = c.ad_id;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_015"} {"task_id": "flinksql_016", "id": "online-compute_FlinkSQL_flinksql_016", "name": "滚动窗口多维聚合 (GROUPING SETS)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置连接器模拟事件流,按 1 分钟滚动窗口做 GROUPING SETS 多维聚合,结果打到 console。\n\n**业务背景与目标**:用 datagen 内置表生成设备事件流,共 5000 行/秒。字段包括 os_id(操作系统 ID,1~3)、device_id(设备 ID,1~20)、city_id(城市 ID,1~100)。使用 LOCALTIMESTAMP 作为事件时间,设置 5 秒 Watermark 延迟。\n\n按 1 分钟 TUMBLE 滚动窗口,使用 GROUPING SETS 进行多维分组聚合,分组组合包括:(os_id, device_id)、(city_id)、以及全局汇总()。统计每个维度组合的事件数 COUNT(*),输出到 console 表。\n\n**源表定义**:\n- `event_source`(datagen 连接器):\n - os_id INT:操作系统 ID,随机取值 1~3\n - device_id INT:设备 ID,随机取值 1~20\n - city_id INT:城市 ID,随机取值 1~100\n - event_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 5 秒\n - 生成速率:rows-per-second = 5000\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start TIMESTAMP(3):窗口起始时间\n - os_id INT:操作系统 ID(聚合维度可为 NULL)\n - device_id INT:设备 ID(聚合维度可为 NULL)\n - city_id INT:城市 ID(聚合维度可为 NULL)\n - event_cnt BIGINT:事件计数\n\n**聚合逻辑**:\n- 滚动窗口:TUMBLE 1 分钟\n- 分组方式:GROUPING SETS ((os_id, device_id), (city_id), ())\n- 聚合指标:COUNT(*) AS event_cnt\n- 窗口起始时间用 TUMBLE_START 计算\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将结果输出\n- 输出字段顺序:window_start, os_id, device_id, city_id, event_cnt", "ground_truth": "-- flinksql_016: 滚动窗口多维聚合 (GROUPING SETS) — TVF syntax\n-- 生成 5000 行/秒的设备事件流\n\n-- 1. 设备事件流 datagen 源表\nCREATE TABLE event_source (\n os_id INT,\n device_id INT,\n city_id INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '5000',\n 'fields.os_id.kind' = 'random',\n 'fields.os_id.min' = '1',\n 'fields.os_id.max' = '3',\n 'fields.device_id.kind' = 'random',\n 'fields.device_id.min' = '1',\n 'fields.device_id.max' = '20',\n 'fields.city_id.kind' = 'random',\n 'fields.city_id.min' = '1',\n 'fields.city_id.max' = '100'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP(3),\n os_id INT,\n device_id INT,\n city_id INT,\n event_cnt BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. TUMBLE TVF 1min + GROUPING SETS 多维聚合\nINSERT INTO console_output\nSELECT\n window_start,\n os_id,\n device_id,\n city_id,\n COUNT(*) AS event_cnt\nFROM TABLE(\n TUMBLE(TABLE event_source, DESCRIPTOR(event_time), INTERVAL '1' MINUTE)\n)\nGROUP BY window_start, window_end,\n GROUPING SETS ((os_id, device_id), (city_id), ());", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_016"} {"task_id": "flinksql_017_en", "id": "online-compute_FlinkSQL_flinksql_017", "name": "Row-Level TopN (Windowless)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses the built-in datagen connector to simulate a spending stream, retrieves the top 3 records by spending amount grouped by `country_id` without any window, and outputs the results directly to the console.\n\n**Business Background and Objective**: Generate user spending records using a datagen built-in table at a rate of 1000 rows per second. Fields include `country_id` (country ID, 1–30), `user_id` (user ID, 1–100,000), and `cost_money` (spending amount, 0–10,000). No event time or watermark is required, since no window operations are involved.\n\nUse the `ROW_NUMBER()` window function, partitioned by `country_id` and sorted by `cost_money` in descending order, keeping only the top 3 records per partition (`row_num <= 3`), and output the results directly to the console table. This is a continuous TopN query where each country's top 3 dynamically updates as new data flows in.\n\n**Source Table Definition**:\n- `spend_source` (datagen connector):\n - `country_id INT`: Country ID, randomly generated in the range 1–30\n - `user_id INT`: User ID, randomly generated in the range 1–100,000\n - `cost_money DOUBLE`: Spending amount, randomly generated in the range 0–10,000\n - Generation rate: `rows-per-second = 1000`\n\n**Output Table Definition**:\n- `console_output` (print connector):\n - `country_id INT`: Country ID\n - `user_id INT`: User ID\n - `cost_money DOUBLE`: Spending amount\n - `row_num BIGINT`: Row number\n\n**TopN Logic**:\n- Use `ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY cost_money DESC)` to generate row numbers\n- Apply `WHERE row_num <= 3` to keep the top 3 per country\n- No window operation is required; no event time or watermark needs to be defined\n\n**Output Requirements**:\n- Use `INSERT INTO console_output` to output the results.\n- Output field order: `country_id`, `user_id`, `cost_money`, `row_num`", "ground_truth": "-- flinksql_017: 行级 TopN (无窗口)\n-- 生成 1000 行/秒的用户消费流\n\n-- 1. 用户消费流 datagen 源表(无事件时间/Watermark)\nCREATE TABLE spend_source (\n country_id INT,\n user_id INT,\n cost_money DOUBLE\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '1000',\n 'fields.country_id.kind' = 'random',\n 'fields.country_id.min' = '1',\n 'fields.country_id.max' = '30',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '100000',\n 'fields.cost_money.kind' = 'random',\n 'fields.cost_money.min' = '0',\n 'fields.cost_money.max' = '10000'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n country_id INT,\n user_id INT,\n cost_money DOUBLE,\n row_num BIGINT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. 行级 TopN: 每个 country_id 取 cost_money 最高的前 3 条\nINSERT INTO console_output\nSELECT\n country_id,\n user_id,\n cost_money,\n row_num\nFROM (\n SELECT\n country_id,\n user_id,\n cost_money,\n ROW_NUMBER() OVER (\n PARTITION BY country_id\n ORDER BY cost_money DESC\n ) AS row_num\n FROM spend_source\n) t\nWHERE row_num <= 3;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_017_en"} {"task_id": "flinksql_018_en", "id": "online-compute_FlinkSQL_flinksql_018", "name": "Dual Output (Detail + Windowed Aggregation)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "en", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\nI need you to write a Flink SQL that uses the built-in datagen connector to simulate an order stream, simultaneously outputting detail records to `console1` and windowed aggregation results over a 1-minute tumbling window to `console2`.\n\n**Business Background and Objective**: Generate an order event stream using a datagen built-in table at a rate of 2000 rows per second. Fields include `order_id` (order ID), `user_id` (user ID, 1–10,000), and `amount` (order amount, 0–1000). Use `LOCALTIMESTAMP` as the event time and set a 5-second watermark delay.\n\nThe same source data must be simultaneously output to two sinks:\n- `console1`: Detail passthrough, directly outputting the original fields\n- `console2`: Aggregation over a 1-minute `TUMBLE` tumbling window, grouped by `user_id` to compute the order count and total amount\n\n**Source Table Definition**:\n- `order_source` (datagen connector):\n - `order_id BIGINT`: Order ID, randomly generated\n - `user_id INT`: User ID, randomly generated in the range 1–10,000\n - `amount DOUBLE`: Order amount, randomly generated in the range 0–1000\n - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds\n - Generation rate: `rows-per-second = 2000`\n\n**Output Table 1 Definition**:\n- `console1` (print connector, detail output):\n - `order_id BIGINT`\n - `user_id INT`\n - `amount DOUBLE`\n\n**Output Table 2 Definition**:\n- `console2` (print connector, aggregation output):\n - `window_start TIMESTAMP(3)`: Window start time\n - `user_id INT`: User ID\n - `order_cnt BIGINT`: Order count within the window\n - `total_amount DOUBLE`: Total order amount within the window\n\n**Aggregation Logic**:\n- Detail output: Direct passthrough from `order_source`\n- Aggregation output: `TUMBLE` 1-minute tumbling window, `GROUP BY user_id`\n- Aggregation metrics: `COUNT(*) AS order_cnt`, `SUM(amount) AS total_amount`\n\n**Output Requirements**:\n- Use two `INSERT INTO` statements to write to `console1` and `console2` respectively.\n- `console1` output field order: `order_id`, `user_id`, `amount`\n- `console2` output field order: `window_start`, `user_id`, `order_cnt`, `total_amount`", "ground_truth": "-- flinksql_018: 双输出 (明细 + 窗口聚合)\n-- 生成 2000 行/秒的订单事件流\n\n-- 1. 订单事件流 datagen 源表\nCREATE TABLE order_source (\n order_id BIGINT,\n user_id INT,\n amount DOUBLE,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '2000',\n 'fields.order_id.kind' = 'random',\n 'fields.order_id.min' = '1',\n 'fields.order_id.max' = '1000000000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '10000',\n 'fields.amount.kind' = 'random',\n 'fields.amount.min' = '0',\n 'fields.amount.max' = '1000'\n);\n\n-- 2. Console1: 明细透传输出表\nCREATE TABLE console1 (\n order_id BIGINT,\n user_id INT,\n amount DOUBLE\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. Console2: 窗口聚合输出表\nCREATE TABLE console2 (\n window_start TIMESTAMP(3),\n user_id INT,\n order_cnt BIGINT,\n total_amount DOUBLE\n) WITH (\n 'connector' = 'print'\n);\n\n-- 4. 明细透传:直接输出原始字段\nINSERT INTO console1\nSELECT\n order_id,\n user_id,\n amount\nFROM order_source;\n\n-- 5. 窗口聚合:TUMBLE 1min 按 user_id 分组统计\nINSERT INTO console2\nSELECT\n TUMBLE_START(event_time, INTERVAL '1' MINUTE) AS window_start,\n user_id,\n COUNT(*) AS order_cnt,\n SUM(amount) AS total_amount\nFROM order_source\nGROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), user_id;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_018_en"} {"task_id": "flinksql_019", "id": "online-compute_FlinkSQL_flinksql_019", "name": "全局分组 + 过滤统计", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置连接器模拟交易流,按状态过滤后全局分组统计,结果打到 console。\n\n**业务背景与目标**:用 datagen 内置表生成交易事件流,共 3000 行/秒。字段包括 trade_id(交易 ID)、type(交易类型,1~5)、status(状态,0~2)、amount(交易金额,0~5000)。\n\n注意:`type` 和 `status` 是 SQL 保留字,需要使用反引号包裹(例如 `` `type` ``、`` `status` ``)。\n\n先按 status = 1 过滤,再按 type 分组统计交易笔数和交易金额总和,最后输出到 console 表。因为不涉及窗口操作,无需定义事件时间和 Watermark。\n\n**源表定义**:\n- `trade_source`(datagen 连接器):\n - trade_id BIGINT:交易 ID,随机取值\n - `` `type` `` INT:交易类型,随机取值 1~5\n - `` `status` `` INT:状态,随机取值 0~2\n - amount DOUBLE:交易金额,随机取值 0~5000\n - 生成速率:rows-per-second = 3000\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - `` `type` `` INT:交易类型\n - trade_cnt BIGINT:交易笔数\n - total_amount DOUBLE:交易金额总和\n\n**过滤与聚合逻辑**:\n- 过滤条件:`` `status` `` = 1(仅统计状态为 1 的交易)\n- 分组:按 `` `type` `` 分组\n- 聚合指标:COUNT(*) AS trade_cnt, SUM(amount) AS total_amount\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将结果输出\n- 输出字段顺序:`` `type` ``, trade_cnt, total_amount", "ground_truth": "-- flinksql_019: 全局分组 + 过滤统计\n-- 生成 3000 行/秒的交易事件流,使用反引号包裹保留字\n\n-- 1. 交易事件流 datagen 源表(无事件时间/Watermark)\nCREATE TABLE trade_source (\n trade_id BIGINT,\n `type` INT,\n `status` INT,\n amount DOUBLE\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '3000',\n 'fields.trade_id.kind' = 'random',\n 'fields.trade_id.min' = '1',\n 'fields.trade_id.max' = '1000000000',\n 'fields.type.kind' = 'random',\n 'fields.type.min' = '1',\n 'fields.type.max' = '5',\n 'fields.status.kind' = 'random',\n 'fields.status.min' = '0',\n 'fields.status.max' = '2',\n 'fields.amount.kind' = 'random',\n 'fields.amount.min' = '0',\n 'fields.amount.max' = '5000'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n `type` INT,\n trade_cnt BIGINT,\n total_amount DOUBLE\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. 过滤 status=1 + 按 type 分组统计\nINSERT INTO console_output\nSELECT\n `type`,\n COUNT(*) AS trade_cnt,\n SUM(amount) AS total_amount\nFROM trade_source\nWHERE `status` = 1\nGROUP BY `type`;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_019"} {"task_id": "flinksql_020", "id": "online-compute_FlinkSQL_flinksql_020", "name": "窗口去重 (TVF Dedup)", "workload": "online-compute", "engine": "FlinkSQL", "category": "online-compute/FlinkSQL", "language": "zh", "modality": "pure-text", "timeout_seconds": 600, "prompt": "## Prompt\n我需要你写一段 Flink SQL,用 datagen 内置连接器模拟事件流,使用 TUMBLE TVF 窗口表值函数 + ROW_NUMBER 做窗口去重,每个窗口内每个用户只保留最早的一条事件。\n\n**业务背景与目标**:用 datagen 内置表生成用户事件流,共 5000 行/秒。字段包括 user_id(用户 ID,1~10000)、event_id(事件 ID)、event_type(事件类型,1~8)。使用 LOCALTIMESTAMP 作为事件时间,设置 10 秒 Watermark 延迟。\n\n使用 TUMBLE 表值函数(TABLE(TUMBLE(...)))将事件分配到 5 分钟滚动窗口,然后在每个(window_start, user_id)分区内,按事件时间升序使用 ROW_NUMBER() 编号,只保留每个窗口每个用户的第一条事件(rn = 1),最后输出到 console。\n\n**源表定义**:\n- `event_source`(datagen 连接器):\n - user_id INT:用户 ID,随机取值 1~10000\n - event_id BIGINT:事件 ID,随机取值\n - event_type INT:事件类型,随机取值 1~8\n - event_time:使用 LOCALTIMESTAMP 生成事件时间,设置 WATERMARK 延迟 10 秒\n - 生成速率:rows-per-second = 5000\n\n**输出表定义**:\n- `console_output`(print 连接器):\n - window_start TIMESTAMP(3):窗口起始时间\n - window_end TIMESTAMP(3):窗口结束时间\n - user_id INT:用户 ID\n - event_id BIGINT:事件 ID\n - event_type INT:事件类型\n\n**去重逻辑**:\n- 窗口:TUMBLE TVF 5 分钟滚动窗口\n- 排序:ROW_NUMBER() OVER (PARTITION BY window_start, user_id ORDER BY event_time ASC)\n- 过滤:WHERE rn = 1 保留每个窗口每个用户的第一条事件\n- 窗口时间字段可从 TVF 的 window_start 和 window_end 获得\n\n**输出要求**:\n- 使用 INSERT INTO console_output 将结果输出\n- 输出字段顺序:window_start, window_end, user_id, event_id, event_type", "ground_truth": "-- flinksql_020: 窗口去重 (TVF Dedup)\n-- TUMBLE TVF + ROW_NUMBER 按窗口去重,保留每个窗口每个用户的第一条\n\n-- 1. 用户事件流 datagen 源表\nCREATE TABLE event_source (\n user_id INT,\n event_id BIGINT,\n event_type INT,\n event_time AS LOCALTIMESTAMP,\n WATERMARK FOR event_time AS event_time - INTERVAL '10' SECOND\n) WITH (\n 'connector' = 'datagen',\n 'rows-per-second' = '5000',\n 'fields.user_id.kind' = 'random',\n 'fields.user_id.min' = '1',\n 'fields.user_id.max' = '10000',\n 'fields.event_id.kind' = 'random',\n 'fields.event_id.min' = '1',\n 'fields.event_id.max' = '1000000000',\n 'fields.event_type.kind' = 'random',\n 'fields.event_type.min' = '1',\n 'fields.event_type.max' = '8'\n);\n\n-- 2. Console 输出表\nCREATE TABLE console_output (\n window_start TIMESTAMP(3),\n window_end TIMESTAMP(3),\n user_id INT,\n event_id BIGINT,\n event_type INT\n) WITH (\n 'connector' = 'print'\n);\n\n-- 3. TUMBLE TVF + ROW_NUMBER 窗口去重\nINSERT INTO console_output\nSELECT\n window_start,\n window_end,\n user_id,\n event_id,\n event_type\nFROM (\n SELECT\n window_start,\n window_end,\n user_id,\n event_id,\n event_type,\n ROW_NUMBER() OVER (\n PARTITION BY window_start, user_id\n ORDER BY event_time ASC\n ) AS rn\n FROM TABLE(\n TUMBLE(TABLE event_source, DESCRIPTOR(event_time), INTERVAL '5' MINUTE)\n )\n) t\nWHERE rn = 1;", "expected_csv": "", "grade_spec_csv": "", "path": "tasks/online-compute/FlinkSQL/flinksql_020"}