421 lines
14 KiB
Python
421 lines
14 KiB
Python
"""
|
|
tests/test_dify_workflow_reliability.py
|
|
|
|
用途:覆盖 Dify Workflow streaming 断连补偿、重试与可靠性元信息。
|
|
依赖:requests、DifyService、FileCheckService 与 pytest Flask fixture。
|
|
逻辑:模拟 Dify SSE、HTTP 错误及超时,验证 Workflow 轮询补偿和 Chatflow 终态事件不会丢失。
|
|
"""
|
|
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]:
|
|
"""把事件字典编码为 Dify requests.iter_lines 返回的字节行。"""
|
|
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_observer_normalizes_node_events_and_isolates_failure(monkeypatch):
|
|
"""节点事件应脱敏传给观察器;观察器抛错不能阻断 Workflow 结果。"""
|
|
lines = _sse_lines(
|
|
{"event": "workflow_started", "data": {"workflow_run_id": "wf-observe"}},
|
|
{
|
|
"event": "node_started",
|
|
"data": {
|
|
"workflow_run_id": "wf-observe",
|
|
"node_execution_id": "node-exec-1",
|
|
"node_data": {"type": "llm", "title": "Extract orders"},
|
|
"inputs": {"secret": "must not be forwarded"},
|
|
},
|
|
},
|
|
{"event": "workflow_finished", "data": {"status": "succeeded", "workflow_run_id": "wf-observe"}},
|
|
)
|
|
_mock_stream_response(monkeypatch, lines=lines)
|
|
observed = []
|
|
|
|
def _observer(event):
|
|
observed.append(event)
|
|
if event["event_type"] == "node_started":
|
|
raise RuntimeError("diagnostics unavailable")
|
|
|
|
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"}, event_observer=_observer)
|
|
|
|
assert result["status"] == "succeeded"
|
|
node_event = next(event for event in observed if event["event_type"] == "node_started")
|
|
assert node_event == {
|
|
"event_type": "node_started",
|
|
"workflow_run_id": "wf-observe",
|
|
"node_execution_id": "node-exec-1",
|
|
"node_type": "llm",
|
|
"node_title": "Extract orders",
|
|
"event_status": None,
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
|
def test_merge_stream_answer_text_replaces_when_terminal_contains_streamed():
|
|
streamed = "检核完成,共处理 3 个文件,全部成功。"
|
|
terminal = streamed
|
|
merged = DifyService._merge_stream_answer_text(streamed, terminal)
|
|
assert merged == streamed
|
|
assert merged != streamed + terminal
|
|
|
|
|
|
def test_merge_stream_answer_text_honors_replace_answer_flag():
|
|
streamed = "partial"
|
|
terminal = "final answer"
|
|
merged = DifyService._merge_stream_answer_text(streamed, terminal, replace_answer=True)
|
|
assert merged == "final answer"
|
|
|
|
|
|
def test_merge_stream_answer_text_appends_non_overlapping_suffix():
|
|
merged = DifyService._merge_stream_answer_text("Hello", " world")
|
|
assert merged == "Hello world"
|
|
|
|
|
|
def test_build_final_answer_text_dedupes_message_end_payload():
|
|
streamed_parts = ["检核", "完成。"]
|
|
data = {"answer": "检核完成。"}
|
|
result = DifyService._build_final_answer_text(
|
|
streamed_parts=streamed_parts,
|
|
data=data,
|
|
event_name="message_end",
|
|
)
|
|
assert result == "检核完成。"
|
|
|
|
|
|
def test_dedupe_exact_doubled_text_fixes_historical_records():
|
|
doubled = "检核完成,共处理 3 个文件。" * 2
|
|
assert DifyService._dedupe_exact_doubled_text(doubled) == "检核完成,共处理 3 个文件。"
|
|
assert DifyService._dedupe_exact_doubled_text("unique answer") == "unique answer"
|
|
|
|
|
|
def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
|
|
"""连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。"""
|
|
monkeypatch.setattr(
|
|
"app.services.dify.requests.post",
|
|
lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")),
|
|
)
|
|
monkeypatch.setattr(
|
|
DifyService,
|
|
"_persist_stream_chat_record",
|
|
staticmethod(lambda **kwargs: {"chat_log_id": 42, "run_id": None}),
|
|
)
|
|
|
|
with app.app_context():
|
|
lines = list(DifyService.stream_chat(
|
|
"extract orders",
|
|
1,
|
|
_Agent(),
|
|
request_id="req-connect-timeout",
|
|
session_id="session-connect-timeout",
|
|
))
|
|
|
|
events = [json.loads(line.removeprefix("data: ").strip()) for line in lines]
|
|
error_event = next(event for event in events if event.get("event") == "error")
|
|
# 关键断言:持久化返回的主键必须沿原 error 事件继续向 relay 传播。
|
|
assert error_event["chat_log_id"] == 42
|
|
assert error_event["message"]
|
|
|
|
|
|
def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeypatch):
|
|
"""已有正文后 ReadTimeout 应合成 message_end,避免领域状态永久停留在 extracting。"""
|
|
class _ChatResponse:
|
|
ok = True
|
|
status_code = 200
|
|
reason = "OK"
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *args):
|
|
return False
|
|
|
|
def raise_for_status(self):
|
|
return None
|
|
|
|
def iter_lines(self):
|
|
yield _sse_lines({"event": "message", "answer": "partial answer"})[0]
|
|
raise requests.exceptions.ReadTimeout("read timed out")
|
|
|
|
monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
|
monkeypatch.setattr(
|
|
DifyService,
|
|
"_persist_stream_chat_record",
|
|
staticmethod(lambda **kwargs: {"chat_log_id": 43, "run_id": None}),
|
|
)
|
|
|
|
with app.app_context():
|
|
lines = list(DifyService.stream_chat(
|
|
"extract orders",
|
|
1,
|
|
_Agent(),
|
|
request_id="req-read-timeout",
|
|
session_id="session-read-timeout",
|
|
))
|
|
|
|
events = [json.loads(line.removeprefix("data: ").strip()) for line in lines]
|
|
terminal = next(event for event in events if event.get("event") == "message_end")
|
|
assert terminal["answer"] == "partial answer"
|
|
assert terminal["chat_log_id"] == 43
|