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.

refactor(models): pass session into WorkflowRun accessors and drop dead ones (#42034)

Keith21d5e4e020b7
diff --git a/api/controllers/console/app/workflow_run.py b/api/controllers/console/app/workflow_run.py
index 66873a9b523..08097d6d43e 100644
--- a/api/controllers/console/app/workflow_run.py
+++ b/api/controllers/console/app/workflow_run.py
@@ -3,11 +3,13 @@ from uuid import UUID
from flask_restx import Resource
from pydantic import BaseModel, Field, field_validator
+from sqlalchemy.orm import Session
from configs import dify_config
from controllers.common.errors import NotFoundError
from controllers.common.rbac import PlainApp, RBACCheck
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
+from controllers.common.session import with_session
from controllers.console import console_ns
from controllers.console.app.wraps import get_app_model
from controllers.console.flask_admission import console_account_admission
@@ -24,6 +26,8 @@ from fields.workflow_run_fields import (
WorkflowRunNodeExecutionListResponse,
WorkflowRunNodeExecutionResponse,
WorkflowRunPaginationResponse,
+ workflow_run_pagination_response_source,
+ workflow_run_response_source,
)
from libs.custom_inputs import time_duration
from libs.helper import dump_response, uuid_value
@@ -147,7 +151,8 @@ class AdvancedChatAppWorkflowRunListApi(Resource):
)
@get_app_model(mode=[AppMode.ADVANCED_CHAT])
@model_validate(WorkflowRunListQuery)
- def get(self, req_data: WorkflowRunListQuery, request_context: RequestContext, app_model: App):
+ @with_session(write=False)
+ def get(self, session: Session, req_data: WorkflowRunListQuery, request_context: RequestContext, app_model: App):
"""
Get advanced chat app workflow run list
"""
@@ -158,7 +163,10 @@ class AdvancedChatAppWorkflowRunListApi(Resource):
triggered_from=_triggered_from(req_data.triggered_from),
)
- return dump_response(AdvancedChatWorkflowRunPaginationResponse, result)
+ return dump_response(
+ AdvancedChatWorkflowRunPaginationResponse,
+ workflow_run_pagination_response_source(result, session=session),
+ )
@console_ns.route("/apps/<uuid:app_id>/advanced-chat/workflow-runs/count")
@@ -208,7 +216,8 @@ class WorkflowRunListApi(Resource):
)
@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
@model_validate(WorkflowRunListQuery)
- def get(self, req_data: WorkflowRunListQuery, request_context: RequestContext, app_model: App):
+ @with_session(write=False)
+ def get(self, session: Session, req_data: WorkflowRunListQuery, request_context: RequestContext, app_model: App):
"""
Get workflow run list
"""
@@ -219,7 +228,9 @@ class WorkflowRunListApi(Resource):
triggered_from=_triggered_from(req_data.triggered_from),
)
- return dump_response(WorkflowRunPaginationResponse, result)
+ return dump_response(
+ WorkflowRunPaginationResponse, workflow_run_pagination_response_source(result, session=session)
+ )
@console_ns.route("/apps/<uuid:app_id>/workflow-runs/count")
@@ -267,8 +278,9 @@ class WorkflowRunDetailApi(Resource):
@console_account_admission(
rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())],
)
+ @with_session(write=False)
@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
- def get(self, request_context: RequestContext, app_model: App, run_id: UUID):
+ def get(self, session: Session, request_context: RequestContext, app_model: App, run_id: UUID):
"""
Get workflow run detail
"""
@@ -280,7 +292,7 @@ class WorkflowRunDetailApi(Resource):
if workflow_run is None:
raise NotFoundError("Workflow run not found")
- return dump_response(WorkflowRunDetailResponse, workflow_run)
+ return dump_response(WorkflowRunDetailResponse, workflow_run_response_source(workflow_run, session=session))
@console_ns.route("/apps/<uuid:app_id>/workflow-runs/<uuid:run_id>/node-executions")
diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
index 230cc5a3cd5..4df2e49b5ec 100644
--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
@@ -54,6 +54,8 @@ from fields.workflow_run_fields import (
WorkflowRunNodeExecutionResponse,
WorkflowRunPaginationResponse,
node_execution_response_source,
+ workflow_run_pagination_response_source,
+ workflow_run_response_source,
)
from graphon.model_runtime.utils.encoders import jsonable_encoder
from libs import helper
@@ -199,12 +201,12 @@ class DraftRagPipelineApi(Resource):
@get_rag_pipeline
@edit_permission_required
@rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline()))
- def get(self, pipeline: Pipeline):
+ @with_session(write=False)
+ def get(self, session: Session, pipeline: Pipeline):
"""
Get draft rag pipeline's workflow
"""
# fetch draft workflow by app_model
- session = db.session()
rag_pipeline_service = RagPipelineService(session)
workflow = rag_pipeline_service.get_draft_workflow(pipeline=pipeline)
@@ -913,7 +915,8 @@ class RagPipelineWorkflowRunListApi(Resource):
@login_required
@account_initialization_required
@get_rag_pipeline
- def get(self, pipeline: Pipeline):
+ @with_session(write=False)
+ def get(self, session: Session, pipeline: Pipeline):
"""
Get workflow run list
"""
@@ -928,10 +931,12 @@ class RagPipelineWorkflowRunListApi(Resource):
"limit": query.limit,
}
- rag_pipeline_service = RagPipelineService(db.session())
+ rag_pipeline_service = RagPipelineService(session)
result = rag_pipeline_service.get_rag_pipeline_paginate_workflow_runs(pipeline=pipeline, args=args)
- return WorkflowRunPaginationResponse.model_validate(result, from_attributes=True).model_dump(mode="json")
+ return WorkflowRunPaginationResponse.model_validate(
+ workflow_run_pagination_response_source(result, session=session), from_attributes=True
+ ).model_dump(mode="json")
@console_ns.route("/rag/pipelines/<uuid:pipeline_id>/workflow-runs/<uuid:run_id>")
@@ -945,18 +950,21 @@ class RagPipelineWorkflowRunDetailApi(Resource):
@login_required
@account_initialization_required
@get_rag_pipeline
- def get(self, pipeline: Pipeline, run_id: UUID):
+ @with_session(write=False)
+ def get(self, session: Session, pipeline: Pipeline, run_id: UUID):
"""
Get workflow run detail
"""
run_id_str = str(run_id)
- rag_pipeline_service = RagPipelineService(db.session())
+ rag_pipeline_service = RagPipelineService(session)
workflow_run = rag_pipeline_service.get_rag_pipeline_workflow_run(pipeline=pipeline, run_id=run_id_str)
if workflow_run is None:
raise NotFound("Workflow run not found")
- return WorkflowRunDetailResponse.model_validate(workflow_run, from_attributes=True).model_dump(mode="json")
+ return WorkflowRunDetailResponse.model_validate(
+ workflow_run_response_source(workflow_run, session=session), from_attributes=True
+ ).model_dump(mode="json")
@console_ns.route("/rag/pipelines/<uuid:pipeline_id>/workflow-runs/<uuid:run_id>/node-executions")
diff --git a/api/controllers/console/snippets/snippet_workflow.py b/api/controllers/console/snippets/snippet_workflow.py
index 5cc8d42d5a6..d4a6497ad7a 100644
--- a/api/controllers/console/snippets/snippet_workflow.py
+++ b/api/controllers/console/snippets/snippet_workflow.py
@@ -12,6 +12,7 @@ from controllers.common.controller_schemas import WorkflowUpdatePayload
from controllers.common.fields import GeneratedAppResponse, SimpleResultResponse
from controllers.common.rbac import RBACCheck, Workspace
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
+from controllers.common.session import with_session
from controllers.console import console_ns
from controllers.console.app.error import DraftWorkflowNotExist, DraftWorkflowNotSync
from controllers.console.app.workflow import (
@@ -52,6 +53,8 @@ from fields.workflow_run_fields import (
WorkflowRunNodeExecutionResponse,
WorkflowRunPaginationResponse,
node_execution_response_source,
+ workflow_run_pagination_response_source,
+ workflow_run_response_source,
)
from graphon.graph_engine.manager import GraphEngineManager
from libs import helper
@@ -512,7 +515,8 @@ class SnippetWorkflowRunsApi(Resource):
@login_required
@account_initialization_required
@get_snippet
- def get(self, snippet: CustomizedSnippet):
+ @with_session(write=False)
+ def get(self, session: Session, snippet: CustomizedSnippet):
"""List workflow runs for snippet."""
query = WorkflowRunQuery.model_validate(
{
@@ -528,7 +532,9 @@ class SnippetWorkflowRunsApi(Resource):
snippet_service = _snippet_service()
result = snippet_service.get_snippet_workflow_runs(snippet=snippet, args=args)
- return WorkflowRunPaginationResponse.model_validate(result, from_attributes=True).model_dump(mode="json")
+ return WorkflowRunPaginationResponse.model_validate(
+ workflow_run_pagination_response_source(result, session=session), from_attributes=True
+ ).model_dump(mode="json")
@console_ns.route("/snippets/<uuid:snippet_id>/workflow-runs/<uuid:run_id>")
@@ -544,7 +550,8 @@ class SnippetWorkflowRunDetailApi(Resource):
@login_required
@account_initialization_required
@get_snippet
- def get(self, snippet: CustomizedSnippet, run_id):
+ @with_session(write=False)
+ def get(self, session: Session, snippet: CustomizedSnippet, run_id):
"""Get workflow run detail for snippet."""
run_id = str(run_id)
@@ -554,7 +561,9 @@ class SnippetWorkflowRunDetailApi(Resource):
if not workflow_run:
raise NotFound("Workflow run not found")
- return WorkflowRunDetailResponse.model_validate(workflow_run, from_attributes=True).model_dump(mode="json")
+ return WorkflowRunDetailResponse.model_validate(
+ workflow_run_response_source(workflow_run, session=session), from_attributes=True
+ ).model_dump(mode="json")
@console_ns.route("/snippets/<uuid:snippet_id>/workflow-runs/<uuid:run_id>/node-executions")
diff --git a/api/fields/base.py b/api/fields/base.py
index 826a07d00ea..c8c1b8c8d56 100644
--- a/api/fields/base.py
+++ b/api/fields/base.py
@@ -1,7 +1,27 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
from pydantic import BaseModel, ConfigDict
+if TYPE_CHECKING:
+ from sqlalchemy.orm import Session
+
+
+class SessionResponseSource[SourceT]:
+ """Wrap a model so session-backed accessors resolve during response validation.
+
+ Subclasses override the accessors that need the session as properties;
+ every other attribute is delegated to the wrapped model unchanged.
+ """
+
+ def __init__(self, source: SourceT, *, session: Session) -> None:
+ self._source = source
+ self._session = session
+
+ def __getattr__(self, name: str) -> object:
+ return getattr(self._source, name) # guard-ignore: no-new-getattr -- delegates model fields
+
class ResponseModel(BaseModel):
model_config = ConfigDict(
diff --git a/api/fields/conversation_fields.py b/api/fields/conversation_fields.py
index 37cd8cd6214..bb016b9ca53 100644
--- a/api/fields/conversation_fields.py
+++ b/api/fields/conversation_fields.py
@@ -5,9 +5,8 @@ from datetime import datetime
from typing import Annotated, Any
from pydantic import Field, WithJsonSchema, field_validator, model_validator
-from sqlalchemy.orm import Session
-from fields.base import ResponseModel
+from fields.base import ResponseModel, SessionResponseSource
from graphon.file import File
from libs.helper import to_timestamp
from models.account import Account
@@ -31,22 +30,13 @@ Int64 = Annotated[int, WithJsonSchema({"format": "int64", "type": "integer"})]
URLString = Annotated[str, WithJsonSchema({"format": "url", "type": "string"})]
-class _SessionResponseSource[SourceT]:
- def __init__(self, source: SourceT, *, session: Session) -> None:
- self._source = source
- self._session = session
-
- def __getattr__(self, name: str) -> object:
- return getattr(self._source, name) # guard-ignore: no-new-getattr -- delegates model fields
-
-
-class _FeedbackResponseSource(_SessionResponseSource[MessageFeedback]):
+class _FeedbackResponseSource(SessionResponseSource[MessageFeedback]):
@property
def from_account(self) -> Account | None:
return self._source.from_account_with_session(session=self._session)
-class _AnnotationResponseSource(_SessionResponseSource[MessageAnnotation]):
+class _AnnotationResponseSource(SessionResponseSource[MessageAnnotation]):
@property
def account(self) -> Account | None:
return self._source.account_with_session(session=self._session)
@@ -56,7 +46,7 @@ class _AnnotationResponseSource(_SessionResponseSource[MessageAnnotation]):
return self._source.annotation_create_account_with_session(session=self._session)
-class MessageResponseSource(_SessionResponseSource[MessageModel]):
+class MessageResponseSource(SessionResponseSource[MessageModel]):
@property
def inputs(self) -> dict[str, Any]:
return self._source.inputs_with_session(session=self._session)
@@ -91,7 +81,7 @@ class MessageResponseSource(_SessionResponseSource[MessageModel]):
return self._source.message_files_with_session(session=self._session)
-class ConversationResponseSource(_SessionResponseSource[ConversationModel]):
+class ConversationResponseSource(SessionResponseSource[ConversationModel]):
@property
def inputs(self) -> dict[str, Any]:
return self._source.inputs_with_session(session=self._session)
diff --git a/api/fields/workflow_run_fields.py b/api/fields/workflow_run_fields.py
index 55caa4893f9..4b69c1a107a 100644
--- a/api/fields/workflow_run_fields.py
+++ b/api/fields/workflow_run_fields.py
@@ -6,7 +6,6 @@ Pydantic models in this module.
from __future__ import annotations
-from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Any
@@ -14,7 +13,7 @@ from typing import Any
from pydantic import AliasChoices, Field, field_validator
from sqlalchemy.orm import Session
-from fields.base import ResponseModel
+from fields.base import ResponseModel, SessionResponseSource
from fields.end_user_fields import SimpleEndUser
from fields.member_fields import SimpleAccount
from libs.helper import to_timestamp
@@ -185,27 +184,45 @@ class WorkflowRunNodeExecutionResponse(ResponseModel):
return to_timestamp(value)
-@dataclass(frozen=True)
-class WorkflowNodeExecutionResponseSource:
- """Expose session-backed node-execution accessors during response validation."""
-
- node_execution: Any
- session: Session
+class WorkflowRunResponseSource(SessionResponseSource[Any]):
+ """Expose session-backed workflow-run accessors during response validation."""
@property
def created_by_account(self) -> Any:
- return self.node_execution.created_by_account(self.session)
+ return self._source.created_by_account(self._session)
@property
def created_by_end_user(self) -> Any:
- return self.node_execution.created_by_end_user(self.session)
+ return self._source.created_by_end_user(self._session)
+
+
+def workflow_run_response_source(workflow_run: Any, *, session: Session) -> WorkflowRunResponseSource:
+ return WorkflowRunResponseSource(workflow_run, session=session)
+
+
+def workflow_run_pagination_response_source(pagination: Any, *, session: Session) -> dict[str, Any]:
+ """Wrap each run in a pagination payload so list responses resolve accessors via the session."""
+ return {
+ "limit": pagination.limit,
+ "has_more": pagination.has_more,
+ "data": [workflow_run_response_source(run, session=session) for run in pagination.data],
+ }
+
- def __getattr__(self, name: str) -> Any:
- return getattr(self.node_execution, name) # guard-ignore: no-new-getattr -- delegates model fields
+class WorkflowNodeExecutionResponseSource(SessionResponseSource[Any]):
+ """Expose session-backed node-execution accessors during response validation."""
+
+ @property
+ def created_by_account(self) -> Any:
+ return self._source.created_by_account(self._session)
+
+ @property
+ def created_by_end_user(self) -> Any:
+ return self._source.created_by_end_user(self._session)
def node_execution_response_source(node_execution: Any, *, session: Session) -> WorkflowNodeExecutionResponseSource:
- return WorkflowNodeExecutionResponseSource(node_execution=node_execution, session=session)
+ return WorkflowNodeExecutionResponseSource(node_execution, session=session)
class WorkflowRunNodeExecutionListResponse(ResponseModel):
diff --git a/api/models/workflow.py b/api/models/workflow.py
index dbc248e5a11..a53cd4248c8 100644
--- a/api/models/workflow.py
+++ b/api/models/workflow.py
@@ -866,19 +866,15 @@ class WorkflowRun(Base):
back_populates="workflow_run",
)
- @property
- @deprecated("This method is retained for historical reasons; avoid using it if possible.")
- def created_by_account(self):
+ def created_by_account(self, session: orm.Session) -> Account | None:
created_by_role = CreatorUserRole(self.created_by_role)
- return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
+ return session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
- @property
- @deprecated("This method is retained for historical reasons; avoid using it if possible.")
- def created_by_end_user(self):
+ def created_by_end_user(self, session: orm.Session):
from .model import EndUser
created_by_role = CreatorUserRole(self.created_by_role)
- return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
+ return session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
@property
def graph_dict(self) -> Mapping[str, Any]:
@@ -892,20 +888,6 @@ class WorkflowRun(Base):
def outputs_dict(self) -> Mapping[str, Any]:
return json.loads(self.outputs) if self.outputs else {}
- @property
- @deprecated("This method is retained for historical reasons; avoid using it if possible.")
- def message(self):
- from .model import Message
-
- return db.session.scalar(
- select(Message).where(Message.app_id == self.app_id, Message.workflow_run_id == self.id)
- )
-
- @property
- @deprecated("This method is retained for historical reasons; avoid using it if possible.")
- def workflow(self):
- return db.session.scalar(select(Workflow).where(Workflow.id == self.workflow_id))
-
def to_dict(self) -> WorkflowRunDict:
return WorkflowRunDict(
id=self.id,
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py
index 2f9e597bcc1..16c85e24f62 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py
@@ -153,13 +153,12 @@ def test_workflow_run_list_returns_frontend_history_contract(
_account(sqlite_session)
workflow_run = _workflow_run_summary(sqlite_session)
workflow_runs = Mock()
- workflow_runs.get_paginate_workflow_runs.return_value = {
- "limit": 10,
- "has_more": False,
- "data": [workflow_run],
- }
+ workflow_runs.get_paginate_workflow_runs.return_value = SimpleNamespace(
+ limit=10,
+ has_more=False,
+ data=[workflow_run],
+ )
_mock_application_services(monkeypatch, workflow_runs)
- monkeypatch.setattr(db, "session", sqlite_session)
request_context = _request_context()
api = workflow_run_module.WorkflowRunListApi()
@@ -168,6 +167,7 @@ def test_workflow_run_list_returns_frontend_history_contract(
with app.test_request_context("/apps/app-1/workflow-runs?limit=10", method="GET"):
payload = handler(
api,
+ sqlite_session,
workflow_run_module.WorkflowRunListQuery(limit=10),
request_context,
app_model=_app(),
@@ -208,13 +208,12 @@ def test_advanced_chat_workflow_run_list_keeps_message_fields(
message_id="message-1",
)
workflow_runs = Mock()
- workflow_runs.get_paginate_advanced_chat_workflow_runs.return_value = {
- "limit": 1,
- "has_more": True,
- "data": [workflow_run],
- }
+ workflow_runs.get_paginate_advanced_chat_workflow_runs.return_value = SimpleNamespace(
+ limit=1,
+ has_more=True,
+ data=[workflow_run],
+ )
_mock_application_services(monkeypatch, workflow_runs)
- monkeypatch.setattr(db, "session", sqlite_session)
request_context = _request_context()
api = workflow_run_module.AdvancedChatAppWorkflowRunListApi()
@@ -223,6 +222,7 @@ def test_advanced_chat_workflow_run_list_keeps_message_fields(
with app.test_request_context("/apps/app-1/advanced-chat/workflow-runs?limit=1", method="GET"):
payload = handler(
api,
+ sqlite_session,
workflow_run_module.WorkflowRunListQuery(limit=1),
request_context,
app_model=_app(),
@@ -288,14 +288,13 @@ def test_workflow_run_detail_returns_frontend_detail_contract(
workflow_runs = Mock()
workflow_runs.get_workflow_run.return_value = workflow_run
_mock_application_services(monkeypatch, workflow_runs)
- monkeypatch.setattr(db, "session", sqlite_session)
request_context = _request_context()
api = workflow_run_module.WorkflowRunDetailApi()
handler = unwrap(api.get)
with app.test_request_context("/apps/app-1/workflow-runs/run-1", method="GET"):
- payload = handler(api, request_context, app_model=_app(), run_id="run-1")
+ payload = handler(api, sqlite_session, request_context, app_model=_app(), run_id="run-1")
response = _serialize_200_response(api.get, payload)
@@ -324,7 +323,9 @@ def test_workflow_run_detail_returns_frontend_detail_contract(
)
-def test_workflow_run_detail_maps_missing_run_to_not_found(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_workflow_run_detail_maps_missing_run_to_not_found(
+ app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+) -> None:
workflow_runs = Mock()
workflow_runs.get_workflow_run.return_value = None
_mock_application_services(monkeypatch, workflow_runs)
@@ -334,7 +335,7 @@ def test_workflow_run_detail_maps_missing_run_to_not_found(app: Flask, monkeypat
with app.test_request_context("/apps/app-1/workflow-runs/run-1", method="GET"):
with pytest.raises(NotFoundError, match="Workflow run not found"):
- handler(api, request_context, app_model=_app(), run_id="run-1")
+ handler(api, sqlite_session, request_context, app_model=_app(), run_id="run-1")
workflow_runs.get_workflow_run.assert_called_once_with(
request_context,
@@ -353,7 +354,7 @@ def test_workflow_run_node_executions_return_frontend_trace_contract(
node_execution_response_source(execution, session=sqlite_session)
]
_mock_application_services(monkeypatch, workflow_runs)
- monkeypatch.setattr(db, "session", sqlite_session)
+ monkeypatch.setattr(db, "session", lambda: sqlite_session)
request_context = _request_context()
api = workflow_run_module.WorkflowRunNodeExecutionListApi()
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
index f4a2e2c948f..f6ab01e9cce 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
@@ -129,7 +129,7 @@ def test_draft_rag_pipeline_workflow_get_serializes_response_model() -> None:
api = module.DraftRagPipelineApi()
handler = unwrap_all(api.get)
- response = handler(api, _pipeline())
+ response = handler(api, db.session(), _pipeline())
assert response["id"] == DEFAULT_WORKFLOW_ID
assert response["graph"] == {"nodes": [], "edges": []}
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py
index 46009877a09..fd26d0ec33f 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py
@@ -255,7 +255,7 @@ def workflow_author(sqlite_database: scoped_session[Session]) -> Account:
class TestDraftWorkflowApi:
- def test_get_draft_success(self, app: Flask, workflow_author: Account) -> None:
+ def test_get_draft_success(self, app: Flask, workflow_author: Account, sqlite_session: Session) -> None:
api = DraftRagPipelineApi()
method = unwrap(api.get)
@@ -272,7 +272,7 @@ class TestDraftWorkflowApi:
return_value=service,
),
):
- result = method(api, pipeline)
+ result = method(api, sqlite_session, pipeline)
assert result["id"] == "workflow-1"
assert result["graph"] == {"nodes": [], "edges": []}
@@ -285,7 +285,7 @@ class TestDraftWorkflowApi:
}
assert result["updated_by"] is None
- def test_get_draft_not_exist(self, app: Flask) -> None:
+ def test_get_draft_not_exist(self, app: Flask, sqlite_session: Session) -> None:
api = DraftRagPipelineApi()
method = unwrap(api.get)
@@ -301,7 +301,7 @@ class TestDraftWorkflowApi:
),
):
with pytest.raises(DraftWorkflowNotExist):
- method(api, pipeline)
+ method(api, sqlite_session, pipeline)
def test_sync_hash_not_match(self, app: Flask) -> None:
api = DraftRagPipelineApi()
diff --git a/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py b/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py
index 8af0e633620..733ab1fb048 100644
--- a/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py
+++ b/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py
@@ -641,7 +641,9 @@ def test_delete_published_snippet_workflow_raises_bad_request_when_in_use(
assert exc_info.value.code == 400
-def test_workflow_run_detail_raises_not_found_when_run_missing(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_workflow_run_detail_raises_not_found_when_run_missing(
+ app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+) -> None:
snippet = _snippet()
monkeypatch.setattr(
snippet_workflow_module,
@@ -654,7 +656,7 @@ def test_workflow_run_detail_raises_not_found_when_run_missing(app: Flask, monke
with app.test_request_context("/snippets/snippet-1/workflow-runs/run-1"):
with pytest.raises(NotFound, match="Workflow run not found"):
- handler(api, snippet=snippet, run_id="run-1")
+ handler(api, sqlite_session, snippet=snippet, run_id="run-1")
def test_draft_node_last_run_raises_not_found_when_execution_missing(
diff --git a/api/tests/unit_tests/models/test_workflow_run_accessors.py b/api/tests/unit_tests/models/test_workflow_run_accessors.py
new file mode 100644
index 00000000000..62c94d004ee
--- /dev/null
+++ b/api/tests/unit_tests/models/test_workflow_run_accessors.py
@@ -0,0 +1,114 @@
+"""Regression coverage for ``WorkflowRun`` account accessors.
+
+Ensures the ``@property``→session-parameter refactor preserves the role-based dispatch:
+``created_by_account`` looks up an Account only when role is ACCOUNT; ``created_by_end_user``
+looks up an EndUser only when role is END_USER. Also covers the session-carrying response
+sources used by the console endpoints that validate the run detail / pagination responses
+with ``from_attributes=True``.
+"""
+
+from types import SimpleNamespace
+from uuid import uuid4
+
+from sqlalchemy.orm import Session
+
+from fields.workflow_run_fields import workflow_run_pagination_response_source, workflow_run_response_source
+from models.account import Account
+from models.enums import CreatorUserRole, EndUserType, WorkflowRunTriggeredFrom
+from models.model import EndUser
+from models.workflow import WorkflowRun
+
+
+def _run(role: CreatorUserRole, created_by: str) -> WorkflowRun:
+ """Construct a WorkflowRun without touching the database."""
+ return WorkflowRun(
+ id=str(uuid4()),
+ tenant_id="00000000-0000-0000-0000-000000000001",
+ app_id="00000000-0000-0000-0000-000000000002",
+ workflow_id=str(uuid4()),
+ type="workflow",
+ triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
+ version="1.0",
+ status="succeeded",
+ created_by_role=role,
+ created_by=created_by,
+ )
+
+
+class TestCreatedByAccount:
+ def test_returns_account_lookup_when_role_is_account(self, sqlite_session: Session) -> None:
+ account = Account(name="Test Account", email="[email protected]")
+ sqlite_session.add(account)
+ sqlite_session.flush()
+ run = _run(CreatorUserRole.ACCOUNT, created_by=account.id)
+
+ result = run.created_by_account(session=sqlite_session)
+
+ assert result is not None
+ assert result.id == account.id
+
+ def test_returns_none_when_role_is_end_user(self, sqlite_session: Session) -> None:
+ account = Account(name="Test Account", email="[email protected]")
+ sqlite_session.add(account)
+ sqlite_session.flush()
+ run = _run(CreatorUserRole.END_USER, created_by=account.id)
+
+ assert run.created_by_account(session=sqlite_session) is None
+
+
+class TestCreatedByEndUser:
+ def test_returns_end_user_lookup_when_role_is_end_user(self, sqlite_session: Session) -> None:
+ end_user = EndUser(
+ tenant_id="00000000-0000-0000-0000-000000000001",
+ type=EndUserType.BROWSER,
+ session_id="session-1",
+ )
+ sqlite_session.add(end_user)
+ sqlite_session.flush()
+ run = _run(CreatorUserRole.END_USER, created_by=end_user.id)
+
+ result = run.created_by_end_user(session=sqlite_session)
+
+ assert result is not None
+ assert result.id == end_user.id
+
+ def test_returns_none_when_role_is_account(self, sqlite_session: Session) -> None:
+ end_user = EndUser(
+ tenant_id="00000000-0000-0000-0000-000000000001",
+ type=EndUserType.BROWSER,
+ session_id="session-1",
+ )
+ sqlite_session.add(end_user)
+ sqlite_session.flush()
+ run = _run(CreatorUserRole.ACCOUNT, created_by=end_user.id)
+
+ assert run.created_by_end_user(session=sqlite_session) is None
+
+
+class TestWorkflowRunResponseSources:
+ def test_detail_source_resolves_accessors_and_proxies_other_attributes(self, sqlite_session: Session) -> None:
+ account = Account(name="Test Account", email="[email protected]")
+ sqlite_session.add(account)
+ sqlite_session.flush()
+ run = _run(CreatorUserRole.ACCOUNT, created_by=account.id)
+
+ source = workflow_run_response_source(run, session=sqlite_session)
+
+ resolved = source.created_by_account
+ assert resolved is not None
+ assert resolved.id == account.id
+ assert source.created_by_end_user is None
+ assert source.version == "1.0"
+
+ def test_pagination_source_wraps_each_run(self, sqlite_session: Session) -> None:
+ account = Account(name="Test Account", email="[email protected]")
+ sqlite_session.add(account)
+ sqlite_session.flush()
+ runs = [_run(CreatorUserRole.ACCOUNT, created_by=account.id) for _ in range(2)]
+ pagination = SimpleNamespace(data=runs, limit=20, has_more=False)
+
+ payload = workflow_run_pagination_response_source(pagination, session=sqlite_session)
+
+ assert payload["limit"] == 20
+ assert payload["has_more"] is False
+ assert [item.created_by_account.id for item in payload["data"]] == [account.id, account.id]