refactor(file-check): 增强文件检核服务,新增可靠性元信息与错误分类
This commit is contained in:
1 parent
f72c1c9f0e
commit
090281835a
14 files changed
+1063
-121
No files matched your search
@@ -1,2 +0,0 @@
|
|||||||
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
|
|
||||||
DEBUG_SESSION_ID=retry-rpa-no-request
|
|
||||||
@@ -37,7 +37,18 @@ def serialize_file_judgement(payload: dict) -> dict:
|
|||||||
judgement = response_summary.get('file_judgement')
|
judgement = response_summary.get('file_judgement')
|
||||||
if not isinstance(judgement, dict):
|
if not isinstance(judgement, dict):
|
||||||
judgement = {}
|
judgement = {}
|
||||||
return {'qualified_count': int(judgement.get('qualified_count') or 0), 'unqualified_count': int(judgement.get('unqualified_count') or 0), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)}
|
return {
|
||||||
|
'qualified_count': int(judgement.get('qualified_count') or 0),
|
||||||
|
'unqualified_count': int(judgement.get('unqualified_count') or 0),
|
||||||
|
'manual_count': int(judgement.get('manual_count') or 0),
|
||||||
|
'dify_error_count': int(judgement.get('dify_error_count') or 0),
|
||||||
|
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
|
||||||
|
'business_manual_count': int(judgement.get('business_manual_count') or 0),
|
||||||
|
'system_error_count': int(judgement.get('system_error_count') or 0),
|
||||||
|
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
|
||||||
|
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
|
||||||
|
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
|
||||||
|
}
|
||||||
|
|
||||||
def serialize_current_step(payload: dict) -> dict | None:
|
def serialize_current_step(payload: dict) -> dict | None:
|
||||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||||
|
|||||||
+207
-38
@@ -325,38 +325,60 @@ class DifyService:
|
|||||||
return data
|
return data
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def run_workflow_streaming(
|
def _classify_workflow_request_exception(exc: Exception) -> tuple[str, bool]:
|
||||||
|
"""
|
||||||
|
将 Workflow HTTP/网络异常归类为 error_type,并判断是否可重试。
|
||||||
|
502/503/504 与连接/读超时视为可恢复;400/401/403 不重试。
|
||||||
|
"""
|
||||||
|
if isinstance(exc, requests.exceptions.ConnectTimeout):
|
||||||
|
return "connect_timeout", True
|
||||||
|
if isinstance(exc, requests.exceptions.ReadTimeout):
|
||||||
|
return "read_timeout", True
|
||||||
|
if isinstance(exc, requests.exceptions.ConnectionError):
|
||||||
|
return "connection_error", True
|
||||||
|
if isinstance(exc, requests.exceptions.HTTPError):
|
||||||
|
status = int(getattr(getattr(exc, "response", None), "status_code", 0) or 0)
|
||||||
|
if status in (502, 503, 504):
|
||||||
|
return f"http_{status}", True
|
||||||
|
if status in (400, 401, 403):
|
||||||
|
return f"http_{status}", False
|
||||||
|
return f"http_{status}", False
|
||||||
|
return "request_error", False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _attach_workflow_reliability_meta(
|
||||||
|
result: dict[str, Any],
|
||||||
*,
|
*,
|
||||||
agent,
|
poll_used: bool = False,
|
||||||
inputs: dict[str, Any] | None = None,
|
retry_count: int = 0,
|
||||||
user: str = "system",
|
error_type: str | None = None,
|
||||||
timeout: tuple[int, int] = (5, 300),
|
workflow_run_id: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
"""在 Dify Workflow 响应上附加网关侧可靠性元信息(poll/重试/错误类型)。"""
|
||||||
url = DifyService._build_workflow_url(base_url)
|
out = dict(result) if isinstance(result, dict) else {}
|
||||||
|
if workflow_run_id and not out.get("workflow_run_id"):
|
||||||
headers = {
|
out["workflow_run_id"] = workflow_run_id
|
||||||
"Authorization": f"Bearer {agent.dify_api_key}",
|
out["_workflow_poll_used"] = bool(poll_used)
|
||||||
"Content-Type": "application/json",
|
out["_workflow_retry_count"] = max(0, int(retry_count))
|
||||||
}
|
if error_type:
|
||||||
payload = {
|
out["_workflow_error_type"] = error_type
|
||||||
"inputs": DifyService._stringify_inputs(inputs),
|
return out
|
||||||
"response_mode": "streaming",
|
|
||||||
"user": str(user or "system"),
|
|
||||||
}
|
|
||||||
|
|
||||||
if current_app:
|
|
||||||
current_app.logger.info(
|
|
||||||
"[workflow-streaming] start user=%s agent_id=%s url=%s",
|
|
||||||
user,
|
|
||||||
getattr(agent, "id", None),
|
|
||||||
url,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _consume_workflow_stream(
|
||||||
|
*,
|
||||||
|
url: str,
|
||||||
|
headers: dict[str, str],
|
||||||
|
payload: dict[str, Any],
|
||||||
|
timeout: tuple[int, int],
|
||||||
|
state: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
|
||||||
|
state 在解析过程中写入 workflow_run_id / result,供断连后补偿使用。
|
||||||
|
"""
|
||||||
result: dict[str, Any] = {}
|
result: dict[str, Any] = {}
|
||||||
workflow_run_id: str | None = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
|
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
body = resp.text[:2000]
|
body = resp.text[:2000]
|
||||||
@@ -383,15 +405,17 @@ class DifyService:
|
|||||||
event_type = evt.get("event", "")
|
event_type = evt.get("event", "")
|
||||||
|
|
||||||
if event_type == "workflow_started":
|
if event_type == "workflow_started":
|
||||||
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
|
run_id = (evt.get("data") or {}).get("workflow_run_id")
|
||||||
|
state["workflow_run_id"] = run_id
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
"[workflow-streaming] started run_id=%s",
|
"[workflow-streaming] started run_id=%s",
|
||||||
workflow_run_id,
|
run_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
elif event_type == "workflow_finished":
|
elif event_type == "workflow_finished":
|
||||||
result = evt.get("data") or {}
|
result = evt.get("data") or {}
|
||||||
|
state["result"] = result
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
"[workflow-streaming] finished status=%s error=%s",
|
"[workflow-streaming] finished status=%s error=%s",
|
||||||
@@ -408,32 +432,177 @@ class DifyService:
|
|||||||
)
|
)
|
||||||
raise RuntimeError(f"Dify workflow error: {err_msg}")
|
raise RuntimeError(f"Dify workflow error: {err_msg}")
|
||||||
|
|
||||||
except requests.exceptions.RequestException as exc:
|
return result
|
||||||
if result:
|
|
||||||
|
@staticmethod
|
||||||
|
def run_workflow_streaming(
|
||||||
|
*,
|
||||||
|
agent,
|
||||||
|
inputs: dict[str, Any] | None = None,
|
||||||
|
user: str = "system",
|
||||||
|
timeout: tuple[int, int] = (5, 300),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
|
||||||
|
对可恢复网络错误最多重试 1 次;返回体附带 _workflow_* 可靠性元信息。
|
||||||
|
"""
|
||||||
|
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
||||||
|
url = DifyService._build_workflow_url(base_url)
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {agent.dify_api_key}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
payload = {
|
||||||
|
"inputs": DifyService._stringify_inputs(inputs),
|
||||||
|
"response_mode": "streaming",
|
||||||
|
"user": str(user or "system"),
|
||||||
|
}
|
||||||
|
max_wait = timeout[1] if isinstance(timeout, tuple) else 300
|
||||||
|
max_attempts = 2
|
||||||
|
retry_count = 0
|
||||||
|
poll_used = False
|
||||||
|
last_error_type: str | None = None
|
||||||
|
last_workflow_run_id: str | None = None
|
||||||
|
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
"[workflow-streaming] connection dropped but result already captured",
|
"[workflow-streaming] start user=%s agent_id=%s url=%s",
|
||||||
|
user,
|
||||||
|
getattr(agent, "id", None),
|
||||||
|
url,
|
||||||
)
|
)
|
||||||
elif workflow_run_id:
|
|
||||||
|
result: dict[str, Any] = {}
|
||||||
|
stream_state: dict[str, Any] = {"workflow_run_id": None, "result": {}}
|
||||||
|
|
||||||
|
for attempt in range(max_attempts):
|
||||||
|
try:
|
||||||
|
result = DifyService._consume_workflow_stream(
|
||||||
|
url=url,
|
||||||
|
headers=headers,
|
||||||
|
payload=payload,
|
||||||
|
timeout=timeout,
|
||||||
|
state=stream_state,
|
||||||
|
)
|
||||||
|
workflow_run_id = stream_state.get("workflow_run_id")
|
||||||
|
if workflow_run_id:
|
||||||
|
last_workflow_run_id = workflow_run_id
|
||||||
|
|
||||||
|
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
|
||||||
|
if not result and workflow_run_id:
|
||||||
|
poll_used = True
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.warning(
|
current_app.logger.warning(
|
||||||
"[workflow-streaming] connection dropped, polling result for run_id=%s",
|
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
|
||||||
workflow_run_id,
|
workflow_run_id,
|
||||||
)
|
)
|
||||||
result = DifyService._poll_workflow_result(
|
result = DifyService._poll_workflow_result(
|
||||||
agent=agent,
|
agent=agent,
|
||||||
workflow_run_id=workflow_run_id,
|
workflow_run_id=workflow_run_id,
|
||||||
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
|
max_wait=max_wait,
|
||||||
)
|
)
|
||||||
else:
|
poll_error_type = None if result else "poll_timeout"
|
||||||
|
return DifyService._attach_workflow_reliability_meta(
|
||||||
|
result,
|
||||||
|
poll_used=True,
|
||||||
|
retry_count=retry_count,
|
||||||
|
error_type=poll_error_type or "stream_closed_early",
|
||||||
|
workflow_run_id=workflow_run_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.info(
|
||||||
|
"[workflow-streaming] attempt=%s finished run_id=%s retry_count=%s",
|
||||||
|
attempt + 1,
|
||||||
|
workflow_run_id,
|
||||||
|
retry_count,
|
||||||
|
)
|
||||||
|
return DifyService._attach_workflow_reliability_meta(
|
||||||
|
result,
|
||||||
|
poll_used=False,
|
||||||
|
retry_count=retry_count,
|
||||||
|
workflow_run_id=workflow_run_id,
|
||||||
|
)
|
||||||
|
except requests.exceptions.RequestException as exc:
|
||||||
|
error_type, retryable = DifyService._classify_workflow_request_exception(exc)
|
||||||
|
last_error_type = error_type
|
||||||
|
workflow_run_id = stream_state.get("workflow_run_id")
|
||||||
|
partial_result = stream_state.get("result") or {}
|
||||||
|
if workflow_run_id:
|
||||||
|
last_workflow_run_id = workflow_run_id
|
||||||
|
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[workflow-streaming] attempt=%s error_type=%s retryable=%s run_id=%s err=%s",
|
||||||
|
attempt + 1,
|
||||||
|
error_type,
|
||||||
|
retryable,
|
||||||
|
workflow_run_id,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
|
if partial_result:
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.info(
|
||||||
|
"[workflow-streaming] connection dropped but result already captured run_id=%s",
|
||||||
|
workflow_run_id,
|
||||||
|
)
|
||||||
|
return DifyService._attach_workflow_reliability_meta(
|
||||||
|
partial_result,
|
||||||
|
poll_used=False,
|
||||||
|
retry_count=retry_count,
|
||||||
|
error_type=error_type,
|
||||||
|
workflow_run_id=workflow_run_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if workflow_run_id:
|
||||||
|
poll_used = True
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
|
||||||
|
workflow_run_id,
|
||||||
|
error_type,
|
||||||
|
)
|
||||||
|
result = DifyService._poll_workflow_result(
|
||||||
|
agent=agent,
|
||||||
|
workflow_run_id=workflow_run_id,
|
||||||
|
max_wait=max_wait,
|
||||||
|
)
|
||||||
|
poll_error_type = None if result else "poll_timeout"
|
||||||
|
return DifyService._attach_workflow_reliability_meta(
|
||||||
|
result,
|
||||||
|
poll_used=True,
|
||||||
|
retry_count=retry_count,
|
||||||
|
error_type=poll_error_type or error_type,
|
||||||
|
workflow_run_id=workflow_run_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if retryable and attempt < max_attempts - 1:
|
||||||
|
retry_count += 1
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.info(
|
||||||
|
"[workflow-streaming] retrying attempt=%s error_type=%s",
|
||||||
|
attempt + 2,
|
||||||
|
error_type,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.error(
|
current_app.logger.error(
|
||||||
"[workflow-streaming] request error (no run_id): %s",
|
"[workflow-streaming] request failed (no run_id) error_type=%s err=%s",
|
||||||
|
error_type,
|
||||||
exc,
|
exc,
|
||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
return result if isinstance(result, dict) else {}
|
return DifyService._attach_workflow_reliability_meta(
|
||||||
|
result if isinstance(result, dict) else {},
|
||||||
|
poll_used=poll_used,
|
||||||
|
retry_count=retry_count,
|
||||||
|
error_type=last_error_type,
|
||||||
|
workflow_run_id=last_workflow_run_id,
|
||||||
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _poll_workflow_result(
|
def _poll_workflow_result(
|
||||||
|
|||||||
@@ -7,12 +7,180 @@ backend/app/services/file_check.py
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
from app.services.dify import DifyService
|
from app.services.dify import DifyService
|
||||||
|
|
||||||
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
|
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
|
||||||
|
|
||||||
|
MANUAL_REASON_BUSINESS_UNCERTAIN = "business_uncertain"
|
||||||
|
MANUAL_REASON_DIFY_TIMEOUT = "dify_timeout"
|
||||||
|
MANUAL_REASON_POLL_TIMEOUT = "poll_timeout"
|
||||||
|
MANUAL_REASON_DIFY_FAILED = "dify_failed"
|
||||||
|
MANUAL_REASON_INVALID_OUTPUT = "invalid_workflow_output"
|
||||||
|
MANUAL_REASON_ATTACHMENT_FAILED = "attachment_read_failed"
|
||||||
|
MANUAL_REASON_NO_DIFY_AGENT = "no_dify_agent"
|
||||||
|
|
||||||
|
SYSTEM_MANUAL_REASON_TYPES = {
|
||||||
|
MANUAL_REASON_DIFY_TIMEOUT,
|
||||||
|
MANUAL_REASON_POLL_TIMEOUT,
|
||||||
|
MANUAL_REASON_DIFY_FAILED,
|
||||||
|
MANUAL_REASON_INVALID_OUTPUT,
|
||||||
|
MANUAL_REASON_ATTACHMENT_FAILED,
|
||||||
|
}
|
||||||
|
|
||||||
|
_GATEWAY_TIMEOUT_ERROR_TYPES = {
|
||||||
|
"read_timeout",
|
||||||
|
"connect_timeout",
|
||||||
|
"connection_error",
|
||||||
|
"stream_closed_early",
|
||||||
|
}
|
||||||
|
|
||||||
|
_ATTACHMENT_FAIL_PATTERN = re.compile(
|
||||||
|
r"附件.{0,8}读取失败|读取附件失败|无法读取附件|attachment.{0,12}read.{0,8}fail|attachment_read_failed",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_workflow_reliability_meta(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
"""从 Dify Workflow 原始响应提取网关侧可靠性元信息。"""
|
||||||
|
data = workflow_result if isinstance(workflow_result, dict) else {}
|
||||||
|
workflow_run_id = data.get("workflow_run_id") or data.get("id")
|
||||||
|
return {
|
||||||
|
"workflow_run_id": workflow_run_id,
|
||||||
|
"poll_used": bool(data.get("_workflow_poll_used")),
|
||||||
|
"retry_count": int(data.get("_workflow_retry_count") or 0),
|
||||||
|
"error_type": data.get("_workflow_error_type"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _classify_evaluate_exception(exc: Exception) -> tuple[str, bool]:
|
||||||
|
"""将 evaluate 层异常映射为 error_type 与是否可重试。"""
|
||||||
|
if isinstance(exc, requests.exceptions.RequestException):
|
||||||
|
return DifyService._classify_workflow_request_exception(exc)
|
||||||
|
return "evaluate_error", False
|
||||||
|
|
||||||
|
|
||||||
|
def _gateway_error_to_manual_reason(error_type: str | None) -> str:
|
||||||
|
"""将网关 error_type 映射为 manual_reason_type。"""
|
||||||
|
normalized = str(error_type or "").strip().lower()
|
||||||
|
if normalized == "poll_timeout":
|
||||||
|
return MANUAL_REASON_POLL_TIMEOUT
|
||||||
|
if normalized in _GATEWAY_TIMEOUT_ERROR_TYPES:
|
||||||
|
return MANUAL_REASON_DIFY_TIMEOUT
|
||||||
|
return MANUAL_REASON_DIFY_FAILED
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_attachment_read_failure(*texts: str | None) -> bool:
|
||||||
|
"""根据 Dify 返回文案判断是否附件读取失败。"""
|
||||||
|
combined = " ".join(str(t or "") for t in texts if t)
|
||||||
|
if not combined.strip():
|
||||||
|
return False
|
||||||
|
if _ATTACHMENT_FAIL_PATTERN.search(combined):
|
||||||
|
return True
|
||||||
|
lowered = combined.lower()
|
||||||
|
return "attachment_read_failed" in lowered or "附件读取失败" in combined
|
||||||
|
|
||||||
|
|
||||||
|
def user_action_hint_for_manual_reason(manual_reason_type: str | None) -> str | None:
|
||||||
|
"""按 manual_reason_type 返回给业务人员的操作建议。"""
|
||||||
|
hints = {
|
||||||
|
MANUAL_REASON_BUSINESS_UNCERTAIN: "AI 无法给出明确结论,请人工复核材料后至 SRM 审核或驳回",
|
||||||
|
MANUAL_REASON_DIFY_TIMEOUT: "系统调用 Dify 超时,请稍后重试或联系运维排查网络/代理",
|
||||||
|
MANUAL_REASON_POLL_TIMEOUT: "系统补偿查询 Dify 结果超时,请稍后重试或凭 workflow_run_id 对账",
|
||||||
|
MANUAL_REASON_DIFY_FAILED: "Dify Workflow 执行失败,请查看 dify_message 或联系运维",
|
||||||
|
MANUAL_REASON_INVALID_OUTPUT: "Dify 返回格式不符合约定,请检查 Workflow 输出节点",
|
||||||
|
MANUAL_REASON_ATTACHMENT_FAILED: "附件读取失败,请检查 SRM 附件链接或文件是否可访问",
|
||||||
|
MANUAL_REASON_NO_DIFY_AGENT: "未配置 Dify Agent,请在排程管理中绑定后重新检核",
|
||||||
|
}
|
||||||
|
if not manual_reason_type:
|
||||||
|
return None
|
||||||
|
return hints.get(manual_reason_type)
|
||||||
|
|
||||||
|
|
||||||
|
def build_manual_classification(
|
||||||
|
manual_reason_type: str | None,
|
||||||
|
*,
|
||||||
|
is_system_error: bool | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""构建 manual_reason_type / is_system_error / user_action_hint 三元组。"""
|
||||||
|
reason = str(manual_reason_type or "").strip() or None
|
||||||
|
system = (
|
||||||
|
bool(is_system_error)
|
||||||
|
if is_system_error is not None
|
||||||
|
else bool(reason and reason in SYSTEM_MANUAL_REASON_TYPES)
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"manual_reason_type": reason,
|
||||||
|
"is_system_error": system,
|
||||||
|
"user_action_hint": user_action_hint_for_manual_reason(reason),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_no_dify_agent_result() -> dict[str, Any]:
|
||||||
|
"""未配置 Dify Agent 时的标准判定结果。"""
|
||||||
|
classification = build_manual_classification(MANUAL_REASON_NO_DIFY_AGENT, is_system_error=False)
|
||||||
|
return {
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": "未配置 Agent ID,跳过 Dify",
|
||||||
|
**classification,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def increment_judgement_stats(
|
||||||
|
stats: dict[str, Any],
|
||||||
|
*,
|
||||||
|
dify_result: str,
|
||||||
|
manual_reason_type: str | None = None,
|
||||||
|
is_system_error: bool = False,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
按单条判定结果累加批次 judgement 统计。
|
||||||
|
manual_count 仍表示所有「人工判定」条数;新增字段区分业务与系统原因。
|
||||||
|
"""
|
||||||
|
result = str(dify_result or "").strip()
|
||||||
|
if result == "合格":
|
||||||
|
stats["qualified_count"] = int(stats.get("qualified_count") or 0) + 1
|
||||||
|
return
|
||||||
|
if result == "不合格":
|
||||||
|
stats["unqualified_count"] = int(stats.get("unqualified_count") or 0) + 1
|
||||||
|
return
|
||||||
|
|
||||||
|
stats["manual_count"] = int(stats.get("manual_count") or 0) + 1
|
||||||
|
reason = str(manual_reason_type or "").strip()
|
||||||
|
|
||||||
|
if reason == MANUAL_REASON_BUSINESS_UNCERTAIN:
|
||||||
|
stats["business_manual_count"] = int(stats.get("business_manual_count") or 0) + 1
|
||||||
|
if is_system_error:
|
||||||
|
stats["system_error_count"] = int(stats.get("system_error_count") or 0) + 1
|
||||||
|
stats["dify_error_count"] = int(stats.get("dify_error_count") or 0) + 1
|
||||||
|
if reason in (MANUAL_REASON_DIFY_TIMEOUT, MANUAL_REASON_POLL_TIMEOUT):
|
||||||
|
stats["dify_timeout_count"] = int(stats.get("dify_timeout_count") or 0) + 1
|
||||||
|
if reason == MANUAL_REASON_INVALID_OUTPUT:
|
||||||
|
stats["invalid_output_count"] = int(stats.get("invalid_output_count") or 0) + 1
|
||||||
|
stats["invalid_result_count"] = int(stats.get("invalid_result_count") or 0) + 1
|
||||||
|
if reason == MANUAL_REASON_ATTACHMENT_FAILED:
|
||||||
|
stats["attachment_error_count"] = int(stats.get("attachment_error_count") or 0) + 1
|
||||||
|
|
||||||
|
|
||||||
|
def empty_judgement_stats() -> dict[str, int]:
|
||||||
|
"""文件检核批次 judgement 统计初始值。"""
|
||||||
|
return {
|
||||||
|
"qualified_count": 0,
|
||||||
|
"unqualified_count": 0,
|
||||||
|
"manual_count": 0,
|
||||||
|
"dify_error_count": 0,
|
||||||
|
"invalid_result_count": 0,
|
||||||
|
"business_manual_count": 0,
|
||||||
|
"system_error_count": 0,
|
||||||
|
"dify_timeout_count": 0,
|
||||||
|
"invalid_output_count": 0,
|
||||||
|
"attachment_error_count": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class FileCheckService:
|
class FileCheckService:
|
||||||
"""文件检核 Dify Workflow 调用与结果规范化。"""
|
"""文件检核 Dify Workflow 调用与结果规范化。"""
|
||||||
@@ -44,7 +212,7 @@ class FileCheckService:
|
|||||||
timeout: HTTP 超时 (connect, read) 秒。
|
timeout: HTTP 超时 (connect, read) 秒。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
含 dify_result、dify_message、workflow_run_id 等字段的 dict。
|
含 dify_result、dify_message、workflow_run_id 及可靠性/分类元信息的 dict。
|
||||||
"""
|
"""
|
||||||
inputs: dict[str, Any] = {
|
inputs: dict[str, Any] = {
|
||||||
"run_no": run_no,
|
"run_no": run_no,
|
||||||
@@ -63,12 +231,20 @@ class FileCheckService:
|
|||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
error_type, retryable = _classify_evaluate_exception(exc)
|
||||||
|
manual_reason = _gateway_error_to_manual_reason(error_type)
|
||||||
|
classification = build_manual_classification(manual_reason, is_system_error=True)
|
||||||
return {
|
return {
|
||||||
"dify_result": "人工判定",
|
"dify_result": "人工判定",
|
||||||
"dify_message": f"Dify执行失败:{exc}",
|
"dify_message": f"Dify执行失败:{exc}",
|
||||||
"provider": cls.PROVIDER,
|
"provider": cls.PROVIDER,
|
||||||
"workflow_run_id": None,
|
"workflow_run_id": None,
|
||||||
"error": str(exc),
|
"error": str(exc),
|
||||||
|
"error_type": error_type,
|
||||||
|
"retryable": retryable,
|
||||||
|
"retry_count": 0,
|
||||||
|
"poll_used": False,
|
||||||
|
**classification,
|
||||||
}
|
}
|
||||||
|
|
||||||
normalized = cls.normalize_workflow_result(workflow_result)
|
normalized = cls.normalize_workflow_result(workflow_result)
|
||||||
@@ -77,40 +253,107 @@ class FileCheckService:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
|
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
"""将 Dify Workflow 输出规范为合格/不合格/人工判定。"""
|
"""将 Dify Workflow 输出规范为合格/不合格/人工判定,并附加分类与可靠性元信息。"""
|
||||||
data = workflow_result if isinstance(workflow_result, dict) else {}
|
data = workflow_result if isinstance(workflow_result, dict) else {}
|
||||||
outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data
|
reliability = _extract_workflow_reliability_meta(data)
|
||||||
output_data = outputs if isinstance(outputs, dict) else {}
|
outputs_container = data.get("outputs")
|
||||||
|
if isinstance(outputs_container, dict):
|
||||||
|
nested = outputs_container.get("output")
|
||||||
|
output_data = nested if isinstance(nested, dict) else outputs_container
|
||||||
|
else:
|
||||||
|
output_data = {}
|
||||||
dify_result = str(output_data.get("dify_result") or output_data.get("result") or "").strip()
|
dify_result = str(output_data.get("dify_result") or output_data.get("result") or "").strip()
|
||||||
dify_message = str(output_data.get("dify_message") or output_data.get("message") or "").strip()
|
dify_message = str(output_data.get("dify_message") or output_data.get("message") or "").strip()
|
||||||
workflow_run_id = data.get("workflow_run_id") if isinstance(data, dict) else None
|
workflow_run_id = reliability.get("workflow_run_id")
|
||||||
status = data.get("status") if isinstance(data, dict) else None
|
status = data.get("status") if isinstance(data, dict) else None
|
||||||
error = data.get("error") if isinstance(data, dict) else None
|
error = data.get("error") if isinstance(data, dict) else None
|
||||||
|
gateway_error_type = reliability.get("error_type")
|
||||||
|
reliability_fields = {
|
||||||
|
"workflow_run_id": workflow_run_id,
|
||||||
|
"poll_used": reliability.get("poll_used"),
|
||||||
|
"retry_count": reliability.get("retry_count"),
|
||||||
|
"error_type": gateway_error_type,
|
||||||
|
"retryable": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _with_classification(payload: dict[str, Any], manual_reason_type: str) -> dict[str, Any]:
|
||||||
|
classification = build_manual_classification(manual_reason_type)
|
||||||
|
return {**payload, **reliability_fields, **classification}
|
||||||
|
|
||||||
|
if _detect_attachment_read_failure(dify_message, str(error or ""), str(output_data.get("error") or "")):
|
||||||
|
return _with_classification(
|
||||||
|
{
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": dify_message or f"Dify执行失败:{error or '附件读取失败'}",
|
||||||
|
"error": str(error or "attachment_read_failed"),
|
||||||
|
"raw_outputs": output_data,
|
||||||
|
},
|
||||||
|
MANUAL_REASON_ATTACHMENT_FAILED,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not output_data and not dify_result and gateway_error_type == "poll_timeout":
|
||||||
|
return _with_classification(
|
||||||
|
{
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": "Dify执行失败:poll 超时未获取最终结果",
|
||||||
|
"error": "poll_timeout",
|
||||||
|
"raw_outputs": output_data,
|
||||||
|
},
|
||||||
|
MANUAL_REASON_POLL_TIMEOUT,
|
||||||
|
)
|
||||||
|
|
||||||
|
if gateway_error_type in _GATEWAY_TIMEOUT_ERROR_TYPES and not output_data and not dify_result:
|
||||||
|
return _with_classification(
|
||||||
|
{
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": f"Dify执行失败:{gateway_error_type}",
|
||||||
|
"error": str(gateway_error_type),
|
||||||
|
"raw_outputs": output_data,
|
||||||
|
},
|
||||||
|
MANUAL_REASON_DIFY_TIMEOUT,
|
||||||
|
)
|
||||||
|
|
||||||
if status == "failed" or (error and not output_data):
|
if status == "failed" or (error and not output_data):
|
||||||
return {
|
return _with_classification(
|
||||||
|
{
|
||||||
"dify_result": "人工判定",
|
"dify_result": "人工判定",
|
||||||
"dify_message": f"Dify执行失败:{error or f'status={status}'}",
|
"dify_message": f"Dify执行失败:{error or f'status={status}'}",
|
||||||
"workflow_run_id": workflow_run_id,
|
|
||||||
"error": str(error or ""),
|
"error": str(error or ""),
|
||||||
"raw_outputs": output_data,
|
"raw_outputs": output_data,
|
||||||
}
|
},
|
||||||
|
MANUAL_REASON_DIFY_FAILED,
|
||||||
|
)
|
||||||
|
|
||||||
if dify_result not in VALID_FILE_CHECK_RESULTS:
|
if dify_result not in VALID_FILE_CHECK_RESULTS:
|
||||||
bad_value = dify_result or "空"
|
bad_value = dify_result or "空"
|
||||||
extra = f" | {dify_message}" if dify_message else ""
|
extra = f" | {dify_message}" if dify_message else ""
|
||||||
return {
|
return _with_classification(
|
||||||
|
{
|
||||||
"dify_result": "人工判定",
|
"dify_result": "人工判定",
|
||||||
"dify_message": f"返回值异常:{bad_value}{extra}",
|
"dify_message": f"返回值异常:{bad_value}{extra}",
|
||||||
"workflow_run_id": workflow_run_id,
|
|
||||||
"error": None,
|
"error": None,
|
||||||
"raw_outputs": output_data,
|
"raw_outputs": output_data,
|
||||||
|
},
|
||||||
|
MANUAL_REASON_INVALID_OUTPUT,
|
||||||
|
)
|
||||||
|
|
||||||
|
if dify_result == "人工判定":
|
||||||
|
return {
|
||||||
|
"dify_result": dify_result,
|
||||||
|
"dify_message": dify_message,
|
||||||
|
"error": None,
|
||||||
|
"raw_outputs": output_data,
|
||||||
|
**reliability_fields,
|
||||||
|
**build_manual_classification(MANUAL_REASON_BUSINESS_UNCERTAIN, is_system_error=False),
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"dify_result": dify_result,
|
"dify_result": dify_result,
|
||||||
"dify_message": dify_message,
|
"dify_message": dify_message,
|
||||||
"workflow_run_id": workflow_run_id,
|
|
||||||
"error": None,
|
"error": None,
|
||||||
"raw_outputs": output_data,
|
"raw_outputs": output_data,
|
||||||
|
**reliability_fields,
|
||||||
|
"manual_reason_type": None,
|
||||||
|
"is_system_error": False,
|
||||||
|
"user_action_hint": None,
|
||||||
}
|
}
|
||||||
@@ -32,7 +32,19 @@ def export_schedule_result_excel(
|
|||||||
header_labels = header_labels or {}
|
header_labels = header_labels or {}
|
||||||
detail_alias_order = detail_alias_order or []
|
detail_alias_order = detail_alias_order or []
|
||||||
|
|
||||||
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
|
exec_result_order = [
|
||||||
|
"dify_result",
|
||||||
|
"dify_message",
|
||||||
|
"workflow_run_id",
|
||||||
|
"dify_error_type",
|
||||||
|
"dify_retry_count",
|
||||||
|
"dify_poll_used",
|
||||||
|
"manual_reason_type",
|
||||||
|
"is_system_error",
|
||||||
|
"user_action_hint",
|
||||||
|
"writeback_srm",
|
||||||
|
"writeback_err",
|
||||||
|
]
|
||||||
|
|
||||||
sql_headers: list[str] = []
|
sql_headers: list[str] = []
|
||||||
detail_headers: list[str] = []
|
detail_headers: list[str] = []
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from typing import Any, Callable
|
|||||||
|
|
||||||
from flask import current_app, has_app_context
|
from flask import current_app, has_app_context
|
||||||
|
|
||||||
from app.services.file_check import FileCheckService
|
from app.services.file_check import FileCheckService, build_no_dify_agent_result, empty_judgement_stats, increment_judgement_stats
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import pyodbc # type: ignore
|
import pyodbc # type: ignore
|
||||||
@@ -187,13 +187,7 @@ def _run_check_job_loop(
|
|||||||
success_count = 0
|
success_count = 0
|
||||||
failed_count = 0
|
failed_count = 0
|
||||||
skipped_count = 0
|
skipped_count = 0
|
||||||
judgement_stats = {
|
judgement_stats = empty_judgement_stats()
|
||||||
"qualified_count": 0,
|
|
||||||
"unqualified_count": 0,
|
|
||||||
"manual_count": 0,
|
|
||||||
"dify_error_count": 0,
|
|
||||||
"invalid_result_count": 0,
|
|
||||||
}
|
|
||||||
current_step: dict[str, Any] | None = None
|
current_step: dict[str, Any] | None = None
|
||||||
all_errors: list[str] = []
|
all_errors: list[str] = []
|
||||||
|
|
||||||
@@ -302,6 +296,13 @@ def _run_check_job_loop(
|
|||||||
dify_ok = False
|
dify_ok = False
|
||||||
dify_result = "人工判定"
|
dify_result = "人工判定"
|
||||||
dify_message = ""
|
dify_message = ""
|
||||||
|
workflow_run_id = None
|
||||||
|
dify_error_type = None
|
||||||
|
dify_retry_count = 0
|
||||||
|
dify_poll_used = False
|
||||||
|
manual_reason_type = None
|
||||||
|
is_system_error = False
|
||||||
|
user_action_hint = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if use_dify:
|
if use_dify:
|
||||||
@@ -337,21 +338,20 @@ def _run_check_job_loop(
|
|||||||
|
|
||||||
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
|
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
|
||||||
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
|
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
|
||||||
|
dify_error_type = dify_res.get("error_type") if isinstance(dify_res, dict) else None
|
||||||
|
dify_retry_count = dify_res.get("retry_count") if isinstance(dify_res, dict) else None
|
||||||
|
dify_poll_used = dify_res.get("poll_used") if isinstance(dify_res, dict) else None
|
||||||
|
manual_reason_type = dify_res.get("manual_reason_type") if isinstance(dify_res, dict) else None
|
||||||
|
is_system_error = bool(dify_res.get("is_system_error")) if isinstance(dify_res, dict) else False
|
||||||
|
user_action_hint = dify_res.get("user_action_hint") if isinstance(dify_res, dict) else None
|
||||||
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
|
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
|
||||||
dify_ok = True
|
dify_ok = True
|
||||||
if dify_result == "合格":
|
increment_judgement_stats(
|
||||||
judgement_stats["qualified_count"] += 1
|
judgement_stats,
|
||||||
elif dify_result == "不合格":
|
dify_result=dify_result,
|
||||||
judgement_stats["unqualified_count"] += 1
|
manual_reason_type=manual_reason_type,
|
||||||
else:
|
is_system_error=is_system_error,
|
||||||
judgement_stats["manual_count"] += 1
|
)
|
||||||
if dify_error:
|
|
||||||
judgement_stats["dify_error_count"] += 1
|
|
||||||
raw_outputs = dify_res.get("raw_outputs") if isinstance(dify_res, dict) else None
|
|
||||||
if dify_result == "人工判定" and isinstance(raw_outputs, dict) and not dify_error:
|
|
||||||
raw_result = str(raw_outputs.get("dify_result") or raw_outputs.get("result") or "").strip()
|
|
||||||
if raw_result and raw_result not in {"合格", "不合格", "人工判定"}:
|
|
||||||
judgement_stats["invalid_result_count"] += 1
|
|
||||||
|
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
@@ -370,13 +370,28 @@ def _run_check_job_loop(
|
|||||||
"dify_message": _truncate_str(dify_message),
|
"dify_message": _truncate_str(dify_message),
|
||||||
"workflow_run_id": workflow_run_id,
|
"workflow_run_id": workflow_run_id,
|
||||||
"error": dify_error,
|
"error": dify_error,
|
||||||
|
"error_type": dify_error_type,
|
||||||
|
"retry_count": dify_retry_count,
|
||||||
|
"poll_used": dify_poll_used,
|
||||||
|
"manual_reason_type": manual_reason_type,
|
||||||
|
"is_system_error": is_system_error,
|
||||||
|
"user_action_hint": user_action_hint,
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
else:
|
else:
|
||||||
dify_result = "人工判定"
|
no_agent = build_no_dify_agent_result()
|
||||||
dify_message = "未配置 Agent ID,跳过 Dify"
|
dify_result = no_agent["dify_result"]
|
||||||
|
dify_message = no_agent["dify_message"]
|
||||||
|
manual_reason_type = no_agent["manual_reason_type"]
|
||||||
|
is_system_error = no_agent["is_system_error"]
|
||||||
|
user_action_hint = no_agent["user_action_hint"]
|
||||||
dify_ok = True
|
dify_ok = True
|
||||||
judgement_stats["manual_count"] += 1
|
increment_judgement_stats(
|
||||||
|
judgement_stats,
|
||||||
|
dify_result=dify_result,
|
||||||
|
manual_reason_type=manual_reason_type,
|
||||||
|
is_system_error=is_system_error,
|
||||||
|
)
|
||||||
|
|
||||||
wb_sql = writeback_sql
|
wb_sql = writeback_sql
|
||||||
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
|
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
|
||||||
@@ -391,6 +406,13 @@ def _run_check_job_loop(
|
|||||||
item.update({
|
item.update({
|
||||||
"dify_result": dify_result,
|
"dify_result": dify_result,
|
||||||
"dify_message": dify_message,
|
"dify_message": dify_message,
|
||||||
|
"workflow_run_id": workflow_run_id,
|
||||||
|
"dify_error_type": dify_error_type,
|
||||||
|
"dify_retry_count": dify_retry_count,
|
||||||
|
"dify_poll_used": dify_poll_used,
|
||||||
|
"manual_reason_type": manual_reason_type,
|
||||||
|
"is_system_error": is_system_error,
|
||||||
|
"user_action_hint": user_action_hint,
|
||||||
"writeback_srm": True,
|
"writeback_srm": True,
|
||||||
"writeback_err": item.get("writeback_err"),
|
"writeback_err": item.get("writeback_err"),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ from app.services.shipping_notice.inventory_upload import (
|
|||||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
|
||||||
from app.services.shipping_notice.tool_common import (
|
from app.services.shipping_notice.tool_common import (
|
||||||
log_task_action_event,
|
log_task_action_event,
|
||||||
log_task_event,
|
log_task_event,
|
||||||
@@ -271,15 +271,18 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
|
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||||
return inventory_mapping_checkpoint_response(
|
warning = t("workflow.decision.mapping_missing_reservation_warning", lang=lang)
|
||||||
task,
|
ui = resolve_task_ui_state(task)
|
||||||
column_meta=meta,
|
return tool_response(
|
||||||
extra_data={
|
status="needs_human",
|
||||||
"warnings": [
|
task=task,
|
||||||
t("workflow.decision.mapping_missing_reservation_warning", lang=lang),
|
message=warning,
|
||||||
],
|
data=serialize_task_for_tool(task),
|
||||||
},
|
checkpoint=ui.checkpoint,
|
||||||
lang=lang or None,
|
human_options=ui.human_options,
|
||||||
|
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||||
|
forbidden_next_tools=["match_inventory"],
|
||||||
|
stop_agent_turn=True,
|
||||||
)
|
)
|
||||||
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
|
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
|
||||||
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
|
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
|
||||||
|
|||||||
@@ -462,4 +462,8 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str:
|
|||||||
def t(key: str, *, lang: str | None = None) -> str:
|
def t(key: str, *, lang: str | None = None) -> str:
|
||||||
"""按语言键查找 i18n 文案;未命中时回退 zh 或原 key。"""
|
"""按语言键查找 i18n 文案;未命中时回退 zh 或原 key。"""
|
||||||
resolved = normalize_lang(lang) if lang else "zh"
|
resolved = normalize_lang(lang) if lang else "zh"
|
||||||
return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key
|
if key in _MESSAGES.get(resolved, {}):
|
||||||
|
return _MESSAGES[resolved][key]
|
||||||
|
if key in _MESSAGES["zh"]:
|
||||||
|
return _MESSAGES["zh"][key]
|
||||||
|
return key
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
"""
|
||||||
|
tests/test_dify_workflow_reliability.py
|
||||||
|
|
||||||
|
用途:覆盖 Dify Workflow streaming 断连补偿、重试与可靠性元信息。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from app.services.dify import DifyService
|
||||||
|
from app.services.file_check import FileCheckService
|
||||||
|
|
||||||
|
|
||||||
|
class _Agent:
|
||||||
|
id = 1
|
||||||
|
dify_api_key = "secret"
|
||||||
|
api_base_url = "http://dify.example/v1"
|
||||||
|
|
||||||
|
|
||||||
|
def _sse_lines(*events: dict) -> list[bytes]:
|
||||||
|
return [f"data: {json.dumps(evt, ensure_ascii=False)}".encode("utf-8") for evt in events]
|
||||||
|
|
||||||
|
|
||||||
|
def _mock_stream_response(monkeypatch, *, status_code: int = 200, lines: list[bytes] | None = None, exc: Exception | None = None):
|
||||||
|
calls = {"count": 0}
|
||||||
|
|
||||||
|
class _Resp:
|
||||||
|
def __init__(self):
|
||||||
|
self.ok = status_code < 400
|
||||||
|
self.status_code = status_code
|
||||||
|
self.text = "upstream error"
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *args):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
if not self.ok:
|
||||||
|
resp = requests.Response()
|
||||||
|
resp.status_code = self.status_code
|
||||||
|
raise requests.HTTPError(response=resp)
|
||||||
|
|
||||||
|
def iter_lines(self, decode_unicode=True):
|
||||||
|
for line in lines or []:
|
||||||
|
yield line.decode("utf-8") if decode_unicode else line
|
||||||
|
if exc is not None:
|
||||||
|
raise exc
|
||||||
|
|
||||||
|
def _post(*args, **kwargs):
|
||||||
|
calls["count"] += 1
|
||||||
|
return _Resp()
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_streaming_normal_finished(monkeypatch):
|
||||||
|
lines = _sse_lines(
|
||||||
|
{"event": "workflow_started", "data": {"workflow_run_id": "wf-ok"}},
|
||||||
|
{
|
||||||
|
"event": "workflow_finished",
|
||||||
|
"data": {
|
||||||
|
"status": "succeeded",
|
||||||
|
"workflow_run_id": "wf-ok",
|
||||||
|
"outputs": {"output": {"dify_result": "合格", "dify_message": "ok"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
_mock_stream_response(monkeypatch, lines=lines)
|
||||||
|
|
||||||
|
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||||
|
|
||||||
|
assert result["status"] == "succeeded"
|
||||||
|
assert result["workflow_run_id"] == "wf-ok"
|
||||||
|
assert result["_workflow_poll_used"] is False
|
||||||
|
assert result["_workflow_retry_count"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_streaming_read_timeout_polls_success(monkeypatch):
|
||||||
|
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-poll"}})
|
||||||
|
_mock_stream_response(
|
||||||
|
monkeypatch,
|
||||||
|
lines=lines,
|
||||||
|
exc=requests.exceptions.ReadTimeout("read timed out"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _poll(**kwargs):
|
||||||
|
return {
|
||||||
|
"id": "wf-poll",
|
||||||
|
"status": "succeeded",
|
||||||
|
"outputs": {"output": {"dify_result": "不合格", "dify_message": "from poll"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
monkeypatch.setattr(DifyService, "_poll_workflow_result", staticmethod(lambda **kwargs: _poll(**kwargs)))
|
||||||
|
|
||||||
|
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"}, timeout=(5, 60))
|
||||||
|
|
||||||
|
assert result["status"] == "succeeded"
|
||||||
|
assert result["_workflow_poll_used"] is True
|
||||||
|
assert result["_workflow_retry_count"] == 0
|
||||||
|
assert result["_workflow_error_type"] == "read_timeout"
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_streaming_503_retries_then_success(monkeypatch):
|
||||||
|
calls = {"count": 0}
|
||||||
|
|
||||||
|
def _post(*args, **kwargs):
|
||||||
|
calls["count"] += 1
|
||||||
|
if calls["count"] == 1:
|
||||||
|
resp = requests.Response()
|
||||||
|
resp.status_code = 503
|
||||||
|
raise requests.HTTPError(response=resp)
|
||||||
|
lines = _sse_lines(
|
||||||
|
{"event": "workflow_started", "data": {"workflow_run_id": "wf-retry"}},
|
||||||
|
{"event": "workflow_finished", "data": {"status": "succeeded", "workflow_run_id": "wf-retry"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
class _Resp:
|
||||||
|
ok = True
|
||||||
|
status_code = 200
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *args):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def iter_lines(self, decode_unicode=True):
|
||||||
|
for line in lines:
|
||||||
|
yield line.decode("utf-8")
|
||||||
|
|
||||||
|
return _Resp()
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||||
|
|
||||||
|
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||||
|
|
||||||
|
assert calls["count"] == 2
|
||||||
|
assert result["status"] == "succeeded"
|
||||||
|
assert result["_workflow_retry_count"] == 1
|
||||||
|
assert result["_workflow_poll_used"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_streaming_401_does_not_retry(monkeypatch):
|
||||||
|
calls = {"count": 0}
|
||||||
|
|
||||||
|
def _post(*args, **kwargs):
|
||||||
|
calls["count"] += 1
|
||||||
|
resp = requests.Response()
|
||||||
|
resp.status_code = 401
|
||||||
|
raise requests.HTTPError(response=resp)
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||||
|
|
||||||
|
with pytest.raises(requests.HTTPError):
|
||||||
|
DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||||
|
|
||||||
|
assert calls["count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_streaming_poll_timeout_sets_error_type(monkeypatch):
|
||||||
|
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-timeout"}})
|
||||||
|
_mock_stream_response(
|
||||||
|
monkeypatch,
|
||||||
|
lines=lines,
|
||||||
|
exc=requests.exceptions.ReadTimeout("read timed out"),
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(DifyService, "_poll_workflow_result", staticmethod(lambda **kwargs: {}))
|
||||||
|
|
||||||
|
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||||
|
|
||||||
|
assert not result.get("status")
|
||||||
|
assert result["_workflow_poll_used"] is True
|
||||||
|
assert result["_workflow_error_type"] == "poll_timeout"
|
||||||
|
assert result.get("workflow_run_id") == "wf-timeout"
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_streaming_clean_close_without_finished_polls(monkeypatch):
|
||||||
|
"""仅收到 workflow_started、连接正常关闭且无异常时,应 poll 补偿。"""
|
||||||
|
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-clean-close"}})
|
||||||
|
_mock_stream_response(monkeypatch, lines=lines)
|
||||||
|
|
||||||
|
def _poll(**kwargs):
|
||||||
|
return {
|
||||||
|
"id": "wf-clean-close",
|
||||||
|
"status": "succeeded",
|
||||||
|
"outputs": {"output": {"dify_result": "合格", "dify_message": "from poll after clean close"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
monkeypatch.setattr(DifyService, "_poll_workflow_result", staticmethod(lambda **kwargs: _poll(**kwargs)))
|
||||||
|
|
||||||
|
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||||
|
|
||||||
|
assert result["status"] == "succeeded"
|
||||||
|
assert result["_workflow_poll_used"] is True
|
||||||
|
assert result.get("workflow_run_id") == "wf-clean-close"
|
||||||
|
|
||||||
|
|
||||||
|
def test_srm_loop_without_dify_agent_does_not_crash(app, monkeypatch):
|
||||||
|
from app.services.schedule.srm_service import _run_check_job_loop
|
||||||
|
|
||||||
|
writebacks = []
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
total, success, failed, skipped, details, errors, _step_logs = _run_check_job_loop(
|
||||||
|
conn_str="",
|
||||||
|
run_no="RUN-NO-AGENT",
|
||||||
|
agent=None,
|
||||||
|
user="tester",
|
||||||
|
wait_seconds=5,
|
||||||
|
run_id=None,
|
||||||
|
fetch_fn=lambda _conn: [{"id": "R1"}],
|
||||||
|
build_record_fn=lambda _conn, item, row_id: ("record text", None),
|
||||||
|
writeback_fn=lambda _conn, **kwargs: writebacks.append(kwargs),
|
||||||
|
row_id_key="id",
|
||||||
|
log_prefix="row",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert total == 1
|
||||||
|
assert success == 1
|
||||||
|
assert failed == 0
|
||||||
|
assert details[0]["dify_message"] == "未配置 Agent ID,跳过 Dify"
|
||||||
|
assert details[0]["workflow_run_id"] is None
|
||||||
|
assert details[0]["dify_retry_count"] == 0
|
||||||
|
assert details[0]["dify_poll_used"] is False
|
||||||
|
assert writebacks
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_check_evaluate_passes_reliability_meta(monkeypatch):
|
||||||
|
def _streaming(**kwargs):
|
||||||
|
return {
|
||||||
|
"status": "succeeded",
|
||||||
|
"workflow_run_id": "wf-meta",
|
||||||
|
"outputs": {"output": {"dify_result": "合格", "dify_message": "ok"}},
|
||||||
|
"_workflow_poll_used": True,
|
||||||
|
"_workflow_retry_count": 1,
|
||||||
|
"_workflow_error_type": "read_timeout",
|
||||||
|
}
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.file_check.DifyService.run_workflow_streaming", _streaming)
|
||||||
|
|
||||||
|
payload = FileCheckService.evaluate(agent=_Agent(), run_no="RUN-1", record="Pb: 100ppm")
|
||||||
|
|
||||||
|
assert payload["dify_result"] == "合格"
|
||||||
|
assert payload["workflow_run_id"] == "wf-meta"
|
||||||
|
assert payload["poll_used"] is True
|
||||||
|
assert payload["retry_count"] == 1
|
||||||
|
assert payload["error_type"] == "read_timeout"
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_check_evaluate_exception_includes_error_type(monkeypatch):
|
||||||
|
def _boom(**kwargs):
|
||||||
|
resp = requests.Response()
|
||||||
|
resp.status_code = 403
|
||||||
|
raise requests.HTTPError(response=resp)
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.file_check.DifyService.run_workflow_streaming", _boom)
|
||||||
|
|
||||||
|
payload = FileCheckService.evaluate(agent=_Agent(), run_no="RUN-1", record="Pb: 100ppm")
|
||||||
|
|
||||||
|
assert payload["dify_result"] == "人工判定"
|
||||||
|
assert payload["error_type"] == "http_403"
|
||||||
|
assert payload["retryable"] is False
|
||||||
|
assert payload["poll_used"] is False
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
"""
|
||||||
|
tests/test_file_check_error_classification.py
|
||||||
|
|
||||||
|
用途:覆盖文件检核「业务人工判定」与「系统异常」分类。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from app.services.file_check import (
|
||||||
|
MANUAL_REASON_ATTACHMENT_FAILED,
|
||||||
|
MANUAL_REASON_BUSINESS_UNCERTAIN,
|
||||||
|
MANUAL_REASON_DIFY_FAILED,
|
||||||
|
MANUAL_REASON_INVALID_OUTPUT,
|
||||||
|
MANUAL_REASON_NO_DIFY_AGENT,
|
||||||
|
MANUAL_REASON_POLL_TIMEOUT,
|
||||||
|
MANUAL_REASON_DIFY_TIMEOUT,
|
||||||
|
FileCheckService,
|
||||||
|
build_no_dify_agent_result,
|
||||||
|
increment_judgement_stats,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_business_uncertain_classification():
|
||||||
|
payload = FileCheckService.normalize_workflow_result({
|
||||||
|
"status": "succeeded",
|
||||||
|
"workflow_run_id": "wf-biz",
|
||||||
|
"outputs": {"output": {"dify_result": "人工判定", "dify_message": "报告签章不清晰"}},
|
||||||
|
})
|
||||||
|
assert payload["dify_result"] == "人工判定"
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_BUSINESS_UNCERTAIN
|
||||||
|
assert payload["is_system_error"] is False
|
||||||
|
assert payload["user_action_hint"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_poll_timeout_classification():
|
||||||
|
payload = FileCheckService.normalize_workflow_result({
|
||||||
|
"workflow_run_id": "wf-poll",
|
||||||
|
"_workflow_poll_used": True,
|
||||||
|
"_workflow_error_type": "poll_timeout",
|
||||||
|
})
|
||||||
|
assert payload["dify_result"] == "人工判定"
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_POLL_TIMEOUT
|
||||||
|
assert payload["is_system_error"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_dify_timeout_classification():
|
||||||
|
payload = FileCheckService.normalize_workflow_result({
|
||||||
|
"workflow_run_id": "wf-read",
|
||||||
|
"_workflow_error_type": "read_timeout",
|
||||||
|
})
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_DIFY_TIMEOUT
|
||||||
|
assert payload["is_system_error"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_failed_classification():
|
||||||
|
payload = FileCheckService.normalize_workflow_result({
|
||||||
|
"status": "failed",
|
||||||
|
"error": "workflow timeout",
|
||||||
|
"workflow_run_id": "wf-fail",
|
||||||
|
})
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_DIFY_FAILED
|
||||||
|
assert payload["is_system_error"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_output_classification():
|
||||||
|
payload = FileCheckService.normalize_workflow_result({
|
||||||
|
"status": "succeeded",
|
||||||
|
"outputs": {"dify_result": "OK", "dify_message": "bad enum"},
|
||||||
|
"workflow_run_id": "wf-invalid",
|
||||||
|
})
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_INVALID_OUTPUT
|
||||||
|
assert payload["is_system_error"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_attachment_read_failed_classification():
|
||||||
|
payload = FileCheckService.normalize_workflow_result({
|
||||||
|
"status": "succeeded",
|
||||||
|
"outputs": {
|
||||||
|
"output": {
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": "附件读取失败:无法下载供应商 PDF",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"workflow_run_id": "wf-att",
|
||||||
|
})
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_ATTACHMENT_FAILED
|
||||||
|
assert payload["is_system_error"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_dify_agent_classification():
|
||||||
|
payload = build_no_dify_agent_result()
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_NO_DIFY_AGENT
|
||||||
|
assert payload["is_system_error"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_http_error_classified_as_system(monkeypatch):
|
||||||
|
class _Agent:
|
||||||
|
id = 1
|
||||||
|
|
||||||
|
def _boom(**kwargs):
|
||||||
|
resp = requests.Response()
|
||||||
|
resp.status_code = 503
|
||||||
|
raise requests.HTTPError(response=resp)
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.file_check.DifyService.run_workflow_streaming", _boom)
|
||||||
|
payload = FileCheckService.evaluate(agent=_Agent(), run_no="RUN-1", record="Pb")
|
||||||
|
assert payload["manual_reason_type"] == MANUAL_REASON_DIFY_FAILED
|
||||||
|
assert payload["is_system_error"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_increment_judgement_stats_splits_business_and_system():
|
||||||
|
stats = {
|
||||||
|
"qualified_count": 0,
|
||||||
|
"unqualified_count": 0,
|
||||||
|
"manual_count": 0,
|
||||||
|
"dify_error_count": 0,
|
||||||
|
"invalid_result_count": 0,
|
||||||
|
"business_manual_count": 0,
|
||||||
|
"system_error_count": 0,
|
||||||
|
"dify_timeout_count": 0,
|
||||||
|
"invalid_output_count": 0,
|
||||||
|
"attachment_error_count": 0,
|
||||||
|
}
|
||||||
|
increment_judgement_stats(
|
||||||
|
stats,
|
||||||
|
dify_result="人工判定",
|
||||||
|
manual_reason_type=MANUAL_REASON_BUSINESS_UNCERTAIN,
|
||||||
|
is_system_error=False,
|
||||||
|
)
|
||||||
|
increment_judgement_stats(
|
||||||
|
stats,
|
||||||
|
dify_result="人工判定",
|
||||||
|
manual_reason_type=MANUAL_REASON_POLL_TIMEOUT,
|
||||||
|
is_system_error=True,
|
||||||
|
)
|
||||||
|
increment_judgement_stats(
|
||||||
|
stats,
|
||||||
|
dify_result="人工判定",
|
||||||
|
manual_reason_type=MANUAL_REASON_ATTACHMENT_FAILED,
|
||||||
|
is_system_error=True,
|
||||||
|
)
|
||||||
|
assert stats["manual_count"] == 3
|
||||||
|
assert stats["business_manual_count"] == 1
|
||||||
|
assert stats["system_error_count"] == 2
|
||||||
|
assert stats["dify_timeout_count"] == 1
|
||||||
|
assert stats["attachment_error_count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_srm_loop_records_manual_reason_on_system_error(app, monkeypatch):
|
||||||
|
from app.services.schedule.srm_service import _run_check_job_loop
|
||||||
|
|
||||||
|
class _Agent:
|
||||||
|
id = 1
|
||||||
|
dify_api_key = "secret"
|
||||||
|
|
||||||
|
def _evaluate(**kwargs):
|
||||||
|
return {
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": "Dify执行失败:poll 超时未获取最终结果",
|
||||||
|
"workflow_run_id": "wf-timeout",
|
||||||
|
"error": "poll_timeout",
|
||||||
|
"error_type": "poll_timeout",
|
||||||
|
"poll_used": True,
|
||||||
|
"retry_count": 0,
|
||||||
|
"manual_reason_type": MANUAL_REASON_POLL_TIMEOUT,
|
||||||
|
"is_system_error": True,
|
||||||
|
"user_action_hint": "系统补偿查询 Dify 结果超时,请稍后重试或凭 workflow_run_id 对账",
|
||||||
|
"provider": "dify_workflow",
|
||||||
|
}
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.services.schedule.srm_service.FileCheckService.evaluate", _evaluate)
|
||||||
|
with app.app_context():
|
||||||
|
total, success, failed, skipped, details, errors, _logs = _run_check_job_loop(
|
||||||
|
conn_str="",
|
||||||
|
run_no="RUN-CLS",
|
||||||
|
agent=_Agent(),
|
||||||
|
user="tester",
|
||||||
|
wait_seconds=5,
|
||||||
|
run_id=None,
|
||||||
|
fetch_fn=lambda _conn: [{"id": "R1"}],
|
||||||
|
build_record_fn=lambda _conn, item, row_id: ("record text", None),
|
||||||
|
writeback_fn=lambda _conn, **kwargs: None,
|
||||||
|
row_id_key="id",
|
||||||
|
log_prefix="row",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert total == 1
|
||||||
|
assert success == 1
|
||||||
|
assert details[0]["manual_reason_type"] == MANUAL_REASON_POLL_TIMEOUT
|
||||||
|
assert details[0]["is_system_error"] is True
|
||||||
|
assert details[0]["user_action_hint"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_serialize_file_judgement_includes_split_counts():
|
||||||
|
from app.api.workspace.file_check import serialize_file_judgement
|
||||||
|
|
||||||
|
payload = serialize_file_judgement({
|
||||||
|
"response_summary_json": {
|
||||||
|
"file_judgement": {
|
||||||
|
"qualified_count": 2,
|
||||||
|
"unqualified_count": 1,
|
||||||
|
"manual_count": 4,
|
||||||
|
"business_manual_count": 1,
|
||||||
|
"system_error_count": 3,
|
||||||
|
"dify_timeout_count": 2,
|
||||||
|
"invalid_output_count": 1,
|
||||||
|
"attachment_error_count": 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
assert payload["business_manual_count"] == 1
|
||||||
|
assert payload["system_error_count"] == 3
|
||||||
|
assert payload["dify_timeout_count"] == 2
|
||||||
|
assert payload["attachment_error_count"] == 1
|
||||||
@@ -86,6 +86,8 @@ def test_file_check_service_normalizes_failed_workflow():
|
|||||||
assert payload['dify_result'] == '人工判定'
|
assert payload['dify_result'] == '人工判定'
|
||||||
assert 'Dify执行失败' in payload['dify_message']
|
assert 'Dify执行失败' in payload['dify_message']
|
||||||
assert payload['workflow_run_id'] == 'wf-2'
|
assert payload['workflow_run_id'] == 'wf-2'
|
||||||
|
assert payload['manual_reason_type'] == 'dify_failed'
|
||||||
|
assert payload['is_system_error'] is True
|
||||||
|
|
||||||
|
|
||||||
def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch):
|
def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch):
|
||||||
@@ -130,6 +132,8 @@ def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch
|
|||||||
'dify_message': 'Dify执行失败:workflow timeout',
|
'dify_message': 'Dify执行失败:workflow timeout',
|
||||||
'workflow_run_id': 'wf-failed',
|
'workflow_run_id': 'wf-failed',
|
||||||
'error': 'workflow timeout',
|
'error': 'workflow timeout',
|
||||||
|
'manual_reason_type': 'dify_failed',
|
||||||
|
'is_system_error': True,
|
||||||
}
|
}
|
||||||
|
|
||||||
writebacks = []
|
writebacks = []
|
||||||
@@ -169,6 +173,7 @@ def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch
|
|||||||
assert errors == []
|
assert errors == []
|
||||||
assert judgement['manual_count'] == 1
|
assert judgement['manual_count'] == 1
|
||||||
assert judgement['dify_error_count'] == 1
|
assert judgement['dify_error_count'] == 1
|
||||||
|
assert judgement['system_error_count'] == 1
|
||||||
assert (run.response_summary_json or {}).get('current_step', {}).get('step') == 'completed'
|
assert (run.response_summary_json or {}).get('current_step', {}).get('step') == 'completed'
|
||||||
assert any(log['step'] == 'call_dify' and log['status'] == 'success' for log in step_logs)
|
assert any(log['step'] == 'call_dify' and log['status'] == 'success' for log in step_logs)
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
# Debug Session: retry-rpa-no-request
|
|
||||||
- **Status**: [OPEN]
|
|
||||||
- **Issue**: 点击“重试 RPA”后,界面出现已触发/已重新触发类文案,但怀疑本轮并未真正写出 RPA trigger。
|
|
||||||
- **Debug Server**: pending
|
|
||||||
- **Log File**: .dbg/trae-debug-log-retry-rpa-no-request.ndjson
|
|
||||||
|
|
||||||
## Reproduction Steps
|
|
||||||
1. 打开发货通知聊天页,定位任务 `SN-20260702-9D76D759`。
|
|
||||||
2. 在右侧工作台或聊天气泡中点击“重试 RPA”。
|
|
||||||
3. 观察是否出现新的聊天回复、任务卡刷新以及后端 trigger 写入。
|
|
||||||
|
|
||||||
## Hypotheses & Verification
|
|
||||||
| ID | Hypothesis | Likelihood | Effort | Evidence |
|
|
||||||
|----|------------|------------|--------|----------|
|
|
||||||
| A | 前端点击后没有真正触发 decision 请求 | High | Low | Pending |
|
|
||||||
| B | 前端提交了 decision,但 `taskId/decision` 参数错误 | High | Low | Pending |
|
|
||||||
| C | 后端收到了 `retry_rpa`,但没有成功写出 trigger 文件 | High | Medium | Pending |
|
|
||||||
| D | trigger 已写出,但前端显示的是旧消息/旧状态 | Medium | Medium | Pending |
|
|
||||||
| E | 当前可见文本并非本轮点击实时产物,而是聊天消息复用 | Medium | Medium | Pending |
|
|
||||||
|
|
||||||
## Log Evidence
|
|
||||||
- Pending
|
|
||||||
|
|
||||||
## Verification Conclusion
|
|
||||||
- Pending
|
|
||||||
@@ -9,17 +9,14 @@ import { describe, expect, it, vi } from 'vitest';
|
|||||||
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
|
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
|
||||||
|
|
||||||
const {
|
const {
|
||||||
autoProgressWorkspaceShippingTask,
|
|
||||||
markWorkspaceShippingManualUploaded,
|
markWorkspaceShippingManualUploaded,
|
||||||
submitWorkspaceShippingDecision,
|
submitWorkspaceShippingDecision,
|
||||||
} = vi.hoisted(() => ({
|
} = vi.hoisted(() => ({
|
||||||
autoProgressWorkspaceShippingTask: vi.fn(),
|
|
||||||
markWorkspaceShippingManualUploaded: vi.fn(),
|
markWorkspaceShippingManualUploaded: vi.fn(),
|
||||||
submitWorkspaceShippingDecision: vi.fn(),
|
submitWorkspaceShippingDecision: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||||
autoProgressWorkspaceShippingTask,
|
|
||||||
markWorkspaceShippingManualUploaded,
|
markWorkspaceShippingManualUploaded,
|
||||||
submitWorkspaceShippingDecision,
|
submitWorkspaceShippingDecision,
|
||||||
}));
|
}));
|
||||||
@@ -114,4 +111,20 @@ describe('useChatShippingDecision', () => {
|
|||||||
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-TARGET-009', 'retry_rpa');
|
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-TARGET-009', 'retry_rpa');
|
||||||
expect(ctx.msg.warning).not.toHaveBeenCalled();
|
expect(ctx.msg.warning).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('submits confirm_inventory_mapping via submit_decision instead of auto_progress', async () => {
|
||||||
|
submitWorkspaceShippingDecision.mockResolvedValue({
|
||||||
|
status: 'running',
|
||||||
|
message: '库存字段对齐已确认,后台继续处理匹配与后续步骤。',
|
||||||
|
data: {},
|
||||||
|
});
|
||||||
|
const ctx = createContext();
|
||||||
|
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||||
|
|
||||||
|
const ok = await executeShippingDecision('confirm_inventory_mapping', '确认');
|
||||||
|
|
||||||
|
expect(ok).toBe(true);
|
||||||
|
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'confirm_inventory_mapping');
|
||||||
|
expect(ctx.messages.value).toHaveLength(2);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -5,7 +5,6 @@
|
|||||||
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。
|
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
autoProgressWorkspaceShippingTask,
|
|
||||||
markWorkspaceShippingManualUploaded,
|
markWorkspaceShippingManualUploaded,
|
||||||
submitWorkspaceShippingDecision,
|
submitWorkspaceShippingDecision,
|
||||||
} from '@/features/chat/api/shipping.api';
|
} from '@/features/chat/api/shipping.api';
|
||||||
@@ -101,10 +100,9 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
|||||||
taskId,
|
taskId,
|
||||||
});
|
});
|
||||||
// #endregion
|
// #endregion
|
||||||
const result =
|
// 字段对齐确认必须走 submit_decision(confirm_inventory_mapping);
|
||||||
decision === 'confirm_inventory_mapping'
|
// auto_progress 在 align_review 只会再次返回同一检查点,造成点击确认后死循环。
|
||||||
? await autoProgressWorkspaceShippingTask(taskId)
|
const result = await submitWorkspaceShippingDecision(taskId, decision);
|
||||||
: await submitWorkspaceShippingDecision(taskId, decision);
|
|
||||||
// #region debug-point D:decision-after-submit
|
// #region debug-point D:decision-after-submit
|
||||||
void reportRetryRpaDebug('D', 'executeShippingDecision after submit', {
|
void reportRetryRpaDebug('D', 'executeShippingDecision after submit', {
|
||||||
decision,
|
decision,
|
||||||
|
|||||||
Reference in new issue
Block a user