""" backend/app/services/schedule/test_run_service.py 用途:排程 test-run 同步小规模试跑编排。 依赖:models、scheduler_service、excel_service、srm_service、kb_sync。 逻辑:由 api/schedule/config.py test-run 路由调用。 """ from __future__ import annotations import time as _time import traceback from datetime import datetime from typing import Any from flask import current_app from app import db from app.core.errors import AppError, NotFoundError from app.models import ScheduleRun, ScheduleTask from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user from app.services.schedule.excel_service import export_schedule_result_excel from app.services.schedule.scheduler_service import _generate_test_run_no, _notify_schedule_run_wecom from app.services.schedule.serialization import safe_json_value from app.services.schedule.srm_service import ( _build_record_text, _execute_writeback, _fetch_records, _run_check_job_loop, ) from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id def _parse_kb_sync_flag(raw_value: Any) -> bool: if isinstance(raw_value, str): return raw_value.strip().lower() in ('1', 'true', 'yes', 'on') return bool(raw_value) def _build_test_run_callbacks(cfg, test_sql: str): """构建 test-run 用的 fetch/writeback/pre_dify/build_record 回调。""" def _test_fetch_fn(conn_str_arg): return _fetch_records(conn_str_arg, test_sql) def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message): _execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id))) test_pre_dify = None test_build_record = None if cfg.detail_sql: def _test_pre_dify(conn_str_arg, item, row_id_value): try: detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),)) except Exception as detail_exc: return { 'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc), } detail_lines = [] for dr in detail_rows: parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order] detail_lines.append(', '.join(parts)) item['detail_text'] = '; '.join(detail_lines) if detail_lines else '' item['_detail_rows'] = detail_rows return None test_pre_dify = _test_pre_dify def _test_build_with_detail(conn_str_arg, item, row_id_value): detail_rows = item.get('_detail_rows', []) text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order) return (text, item.get('attachment')) test_build_record = _test_build_with_detail else: def _test_build_simple(conn_str_arg, item, row_id_value): text = _build_record_text(item, cfg.alias_order, cfg.header_labels) return (text, item.get('attachment')) test_build_record = _test_build_simple return _test_fetch_fn, _test_writeback_fn, test_pre_dify, test_build_record def _finalize_run_status(total_count: int, success_count: int, failed_count: int, errors: list) -> str: if total_count == 0 and (not errors): return 'success' if failed_count == 0: return 'success' if success_count == 0: return 'failed' return 'partial_failed' def execute_test_run( task_id: int, data: dict[str, Any], *, triggered_by_user_id: int | None, ) -> dict[str, Any]: """ 同步执行排程 test-run。 Args: task_id: ScheduleTask 主键。 data: fetch_where/order、limit、kb_sync_enabled 等。 triggered_by_user_id: 触发用户 id。 Returns: test-run API 响应 dict。 Raises: NotFoundError: 任务或配置不存在。 AppError: 执行过程异常。 """ task = db.session.get(ScheduleTask, task_id) if not task: raise NotFoundError('Not found') cfg = get_schedule_sql_config_by_task_id(task_id) if not cfg: raise NotFoundError(f'Config for task {task_id} not found') custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip() custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip() limit = min(int(data.get('limit') or 3), 10) test_kb_sync_enabled = _parse_kb_sync_flag(data.get('kb_sync_enabled', False)) base = cfg.base_fetch_sql or cfg.fetch_sql test_sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base if cfg.data_source and (not cfg.data_source.is_empty()): conn_str = cfg.data_source.build_connection_string() else: conn_str = _build_srm_conn_str() agent = _resolve_dify_agent(task) if task else None user = _resolve_schedule_user(task) if task else 'test_user' wait_seconds = task.wait_seconds if task else 120 dify_agent_id = task.dify_agent_id if task else None run = ScheduleRun( run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=triggered_by_user_id, started_at=datetime.utcnow(), status='running', ) db.session.add(run) db.session.commit() from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot capture_dify_execution_snapshot(run, task) db.session.commit() if not cfg.fetch_sql: run.status = 'success' run.finished_at = datetime.utcnow() run.error_message = '无抓取SQL,跳过外部系统数据抓取' try: if task.notify_enabled: _notify_schedule_run_wecom(task, run) except Exception as wecom_exc: current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc) db.session.commit() return { 'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id, } fetch_fn, writeback_fn, pre_dify_fn, build_record_fn = _build_test_run_callbacks(cfg, test_sql) start_ts = _time.time() try: total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop( conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=fetch_fn, build_record_fn=build_record_fn, writeback_fn=writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=pre_dify_fn, dify_system_prompt=cfg.dify_system_prompt, ) duration_ms = int((_time.time() - start_ts) * 1000) status = _finalize_run_status(total_count, success_count, failed_count, errors) header_order = cfg.alias_order if cfg.alias_order else None header_labels = cfg.header_labels if cfg.header_labels else None detail_alias_order = cfg.detail_alias_order or [] try: file_data, file_name, file_size = export_schedule_result_excel( run_no=run.run_no, summary={ 'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms, }, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order, ) except Exception as excel_exc: current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True) file_data, file_name, file_size = (None, None, 0) run.finished_at = datetime.utcnow() run.duration_ms = duration_ms run.status = status run.total_count = total_count run.success_count = success_count run.failed_count = failed_count run.skipped_count = skipped_count run.step_logs = step_logs if step_logs else None run.error_message = '; '.join(errors[:3]) if errors else None run.excel_file_data = file_data run.excel_file_name = file_name run.excel_file_size = file_size or 0 db.session.commit() if test_kb_sync_enabled: try: from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb db.session.refresh(task) db.session.refresh(run) sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True) db.session.refresh(run) except Exception as kb_exc: db.session.rollback() db.session.refresh(run) current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True) run.kb_sync_status = 'failed' run.kb_group_id = getattr(task, 'kb_group_id', None) run.kb_sync_error = str(kb_exc) db.session.commit() try: if task.notify_enabled: _notify_schedule_run_wecom(task, run) except Exception as wecom_exc: current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc) safe_details = [{k: safe_json_value(v) for k, v in item.items()} for item in details] return { 'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id, } except Exception as exc: db.session.rollback() run = db.session.get(ScheduleRun, run.id) duration_ms = int((_time.time() - start_ts) * 1000) run.finished_at = datetime.utcnow() run.duration_ms = duration_ms run.status = 'failed' run.error_message = str(exc) db.session.commit() raise AppError( code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()}, )