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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(api): drop global db.session from workflow run trace assembly (#45679)
Paul Y Hui5507d4630bb7
diff --git a/api/services/workflow_run_service.py b/api/services/workflow_run_service.pyindex 399fd6647cd..4b8fd6367ff 100644--- a/api/services/workflow_run_service.py+++ b/api/services/workflow_run_service.py@@ -11,7 +11,6 @@ from core.workflow.node_execution_process_data import (WORKFLOW_TOOL_ROOT_APP_ID_KEY,)from core.workflow.nodes.human_input.pause_reason import HumanInputRequired-from extensions.ext_database import dbfrom graphon.enums import WorkflowExecutionStatusfrom libs.infinite_scroll_pagination import InfiniteScrollPaginationfrom machinery.context import RequestContext@@ -199,6 +198,10 @@ class WorkflowRunService:) -> list[WorkflowNodeExecutionTrace]:"""Get workflow run node execution list++ Returns an empty list when the run is not visible to the admitted workspace.+ Creator accounts and end users are resolved in a short read-only session that+ closes before returning, so the traces carry detached, already-loaded rows."""workflow_run = self.get_workflow_run(context, app_id=app_id, run_id=run_id)@@ -213,7 +216,8 @@ class WorkflowRunService:app_id=app_id,workflow_run_id=run_id,)- return assemble_workflow_node_execution_traces(node_executions, self._node_executions, session=db.session())+ with self._session_factory() as session:+ return assemble_workflow_node_execution_traces(node_executions, self._node_executions, session=session)def get_workflow_tool_node_executions(self,@@ -223,7 +227,12 @@ class WorkflowRunService:run_id: str,node_execution_id: str,) -> list[WorkflowNodeExecutionTrace] | None:- """Read nested Tool traces through the admitted root app and workflow run."""+ """Read nested Tool traces through the admitted root app and workflow run.++ Returns None when the root run is not visible to the admitted workspace.+ Creator lookups use a short read-only session that closes before the internal+ correlation keys are stripped from ``process_data``.+ """if self.get_workflow_run(context, app_id=app_id, run_id=run_id) is None:return Nonecontexts.plugin_tool_providers.set({})@@ -233,7 +242,8 @@ class WorkflowRunService:workflow_run_id=run_id,parent_node_execution_id=node_execution_id,)- traces = assemble_workflow_node_execution_traces(executions, self._node_executions, session=db.session())+ with self._session_factory() as session:+ traces = assemble_workflow_node_execution_traces(executions, self._node_executions, session=session)for trace in traces:if trace.process_data is not None:trace.process_data = {diff --git a/api/tests/unit_tests/services/test_workflow_node_execution_trace_service.py b/api/tests/unit_tests/services/test_workflow_node_execution_trace_service.pyindex b26abc34d7c..42778758e02 100644--- a/api/tests/unit_tests/services/test_workflow_node_execution_trace_service.py+++ b/api/tests/unit_tests/services/test_workflow_node_execution_trace_service.py@@ -7,7 +7,7 @@ from typing import castfrom unittest.mock import MagicMockimport pytest-from sqlalchemy.orm import Session+from sqlalchemy.orm import Session, sessionmakerfrom domain.workflow.retry_history import RETRY_HISTORY_PROCESS_DATA_KEY, WorkflowNodeRetryAttemptfrom fields.workflow_run_fields import WorkflowRunNodeExecutionListResponse@@ -166,3 +166,25 @@ def test_virtual_trace_validates_through_node_execution_response(sqlite_session:assert response.data[0].retry_index == 1assert response.model_dump(mode="json")["data"][0]["retry_index"] == 1+++def test_traces_serialize_creator_after_the_assembly_session_closes(+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ account = Account(name="Alice", email="[email protected]")+ account.id = "account-1"+ with sqlite_session_factory.begin() as session:+ session.add(account)+ process_data = {RETRY_HISTORY_PROCESS_DATA_KEY: [_retry_attempt(1)]}++ with sqlite_session_factory() as session:+ traces = assemble_workflow_node_execution_traces(+ [_execution(process_data)], _repository(process_data), session=session+ )++ response = WorkflowRunNodeExecutionListResponse.model_validate({"data": traces}, from_attributes=True)++ assert [item["created_by_account"] for item in response.model_dump(mode="json")["data"]] == [+ {"id": "account-1", "name": "Alice", "email": "[email protected]"},+ {"id": "account-1", "name": "Alice", "email": "[email protected]"},+ ]diff --git a/api/tests/unit_tests/services/test_workflow_run_service.py b/api/tests/unit_tests/services/test_workflow_run_service.pyindex 011a1a743f8..fd7f5b96c25 100644--- a/api/tests/unit_tests/services/test_workflow_run_service.py+++ b/api/tests/unit_tests/services/test_workflow_run_service.py@@ -1,5 +1,6 @@from datetime import datetimefrom types import SimpleNamespace+from typing import overridefrom unittest.mock import ANY, MagicMock, create_autospecimport pytest@@ -50,6 +51,17 @@ def _workflow_run_service_service(dependencies: tuple[MagicMock, MagicMock]) ->)+class _CloseTrackingSession(Session):+ """Real Session that records whether its owner closed it."""++ closed = False++ @override+ def close(self) -> None:+ super().close()+ self.closed = True++def _workflow_run_service_request_context(*, workspace_id: str = "tenant-1") -> RequestContext:return RequestContext(request_id="request-1",@@ -281,6 +293,49 @@ class TestWorkflowRunServiceCases:)mock_assemble.assert_called_once_with(expected_executions, node_executions, session=ANY)+ @pytest.mark.parametrize("tool_traces", [False, True])+ def test_trace_assembly_uses_a_session_from_the_injected_factory(+ self,+ service_dependencies: tuple[MagicMock, MagicMock],+ monkeypatch: pytest.MonkeyPatch,+ tool_traces: bool,+ ) -> None:+ node_executions, workflow_runs = service_dependencies+ workflow_runs.get_workflow_run_by_id.return_value = _workflow_run()+ service = WorkflowRunService(+ workflow_runs=workflow_runs,+ node_executions=node_executions,+ session_factory=sessionmaker(class_=_CloseTrackingSession),+ )+ expected_executions = (+ node_executions.get_workflow_tool_executions.return_value+ if tool_traces+ else node_executions.get_executions_by_workflow_run.return_value+ )+ assembly_sessions: list[Session] = []++ def assemble(+ executions: object, repository: object, *, session: Session+ ) -> list[WorkflowNodeExecutionTrace]:+ assert executions is expected_executions+ assert repository is node_executions+ assembly_sessions.append(session)+ return []++ monkeypatch.setattr(service_module, "assemble_workflow_node_execution_traces", assemble)+ context = _workflow_run_service_request_context()++ if tool_traces:+ service.get_workflow_tool_node_executions(+ context, app_id="app-1", run_id="run-1", node_execution_id="parent-1"+ )+ else:+ service.get_workflow_run_node_executions(context, app_id="app-1", run_id="run-1")++ [assembly_session] = assembly_sessions+ assert isinstance(assembly_session, _CloseTrackingSession)+ assert assembly_session.closed+"""Tests for Console workflow pause details."""