Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test(api): verify workflow publish transactions with SQLite (#45142)

周龙杰da24f6d13302
diff --git a/api/controllers/console/app/workflow.py b/api/controllers/console/app/workflow.py
index 407ad2a6dc0..91236611694 100644
--- a/api/controllers/console/app/workflow.py
+++ b/api/controllers/console/app/workflow.py
@@ -1344,7 +1344,7 @@ class PublishedWorkflowApi(Resource):
"""
workflow_service = WorkflowService()
- with sessionmaker(db.engine).begin() as session:
+ with session_factory.get_session_maker().begin() as session:
workflow = workflow_service.publish_workflow(
session=session,
app_model=app_model,
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow.py b/api/tests/unit_tests/controllers/console/app/test_workflow.py
index 746e9519696..bbeedacdab5 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow.py
@@ -12,7 +12,8 @@ from unittest.mock import ANY, MagicMock, Mock
import pytest
from flask import Flask
from pydantic import ValidationError
-from sqlalchemy.orm import Session
+from sqlalchemy import Engine
+from sqlalchemy.orm import Session, sessionmaker
from werkzeug.exceptions import HTTPException, NotFound, UnprocessableEntity
from controllers.common.errors import InvalidArgumentError
@@ -160,10 +161,13 @@ class TestWorkflowCases:
def test_publish_workflow_returns_success(
app: Flask,
monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
advisory: str,
) -> None:
current_user = SimpleNamespace(id="account-1")
- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")
+ app_model = _workflow_app(app_id="app-1", tenant_id="tenant-1")
+ sqlite_session.add(app_model)
+ sqlite_session.commit()
graph = {
"nodes": [
{"id": "start", "data": {"type": "start"}},
@@ -197,19 +201,11 @@ class TestWorkflowCases:
"format_variable_reference_errors",
Mock(side_effect=RuntimeError("format")),
)
- session = Mock()
- session.get.return_value = app_model
monkeypatch.setattr(
workflow_module,
"WorkflowService",
Mock(return_value=SimpleNamespace(publish_workflow=Mock(return_value=workflow))),
)
- monkeypatch.setattr(
- workflow_module,
- "sessionmaker",
- lambda _engine: SimpleNamespace(begin=lambda: nullcontext(session)),
- )
- monkeypatch.setattr(workflow_module, "db", SimpleNamespace(engine=object()))
with app.test_request_context("/apps/app-1/workflows/publish", method="POST", json={}):
response = inspect.unwrap(workflow_module.PublishedWorkflowApi.post)(
workflow_module.PublishedWorkflowApi(),
@@ -219,7 +215,11 @@ class TestWorkflowCases:
)
assert response["result"] == "success"
- assert app_model.workflow_id == workflow.id
+ sqlite_session.expire_all()
+ persisted_app = sqlite_session.get(_workflow_App, app_model.id)
+ assert persisted_app is not None
+ assert persisted_app.workflow_id == workflow.id
+ assert persisted_app.updated_by == current_user.id
assert isinstance(response["created_at"], int)
if advisory == "warning":
assert "Consumer" in response["warning"]
@@ -228,6 +228,41 @@ class TestWorkflowCases:
else:
assert "warning" not in response
+ @staticmethod
+ def test_publish_workflow_rolls_back_on_service_failure(
+ app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session, sqlite_engine: Engine
+ ) -> None:
+ app_model = _workflow_app(app_id="app-1", tenant_id="tenant-1")
+ sqlite_session.add(app_model)
+ sqlite_session.commit()
+
+ def fail_after_update(*, session: Session, **_kwargs: object) -> None:
+ persisted_app = session.get(_workflow_App, app_model.id)
+ assert persisted_app is not None
+ persisted_app.name = "changed"
+ session.flush()
+ raise RuntimeError("publish failed")
+
+ service = workflow_module.WorkflowService(session_maker=sessionmaker(bind=sqlite_engine))
+ monkeypatch.setattr(service, "publish_workflow", fail_after_update)
+ monkeypatch.setattr(workflow_module, "WorkflowService", lambda: service)
+ current_user = _workflow_Account(name="Test", email="[email protected]")
+ current_user.id = "account-1"
+ with app.test_request_context("/apps/app-1/workflows/publish", method="POST", json={}):
+ with pytest.raises(RuntimeError, match="publish failed"):
+ inspect.unwrap(workflow_module.PublishedWorkflowApi.post)(
+ workflow_module.PublishedWorkflowApi(),
+ workflow_module.PublishWorkflowPayload.model_validate({}),
+ current_user,
+ app_model,
+ )
+
+ sqlite_session.expire_all()
+ persisted_app = sqlite_session.get(_workflow_App, app_model.id)
+ assert persisted_app is not None
+ assert persisted_app.name == "Workflow App"
+ assert persisted_app.workflow_id is None
+
@staticmethod
@pytest.mark.parametrize("transaction_fails", [False, True], ids=["commit-succeeds", "commit-fails"])
def test_delete_workflow_retires_candidates_only_after_transaction_exit(