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 App.app_model_config and App.workflow (#42190)

JessYan28e2682986de
diff --git a/api/controllers/mcp/mcp.py b/api/controllers/mcp/mcp.py
index 95aa2be8218..fb4912b0741 100644
--- a/api/controllers/mcp/mcp.py
+++ b/api/controllers/mcp/mcp.py
@@ -88,7 +88,7 @@ class MCPAppApi(Resource):
self._validate_server_status(mcp_server)
# Get user input form
- user_input_form = self._get_user_input_form(app)
+ user_input_form = self._get_user_input_form(app, session)
# Handle notification vs request differently
return self._process_mcp_message(
@@ -180,17 +180,19 @@ class MCPAppApi(Resource):
return helper.compact_generate_response(result.model_dump(by_alias=True, mode="json", exclude_none=True))
- def _get_user_input_form(self, app: App) -> list[VariableEntity]:
+ def _get_user_input_form(self, app: App, session: Session) -> list[VariableEntity]:
"""Get and convert user input form"""
# Get raw user input form based on app mode
if app.mode in {AppMode.ADVANCED_CHAT, AppMode.WORKFLOW}:
- if not app.workflow:
+ workflow = app.workflow_with_session(session=session)
+ if not workflow:
raise MCPRequestError(mcp_types.INVALID_REQUEST, "App is unavailable")
- raw_user_input_form = app.workflow.user_input_form(to_old_structure=True)
+ raw_user_input_form = workflow.user_input_form(to_old_structure=True)
else:
- if not app.app_model_config:
+ app_model_config = app.app_model_config_with_session(session=session)
+ if not app_model_config:
raise MCPRequestError(mcp_types.INVALID_REQUEST, "App is unavailable")
- features_dict = app.app_model_config.to_dict()
+ features_dict = app_model_config.to_dict()
raw_user_input_form = features_dict.get("user_input_form", [])
# Convert to VariableEntity objects
diff --git a/api/core/plugin/backwards_invocation/app.py b/api/core/plugin/backwards_invocation/app.py
index 2972e2be207..4165b585d1c 100644
--- a/api/core/plugin/backwards_invocation/app.py
+++ b/api/core/plugin/backwards_invocation/app.py
@@ -281,7 +281,10 @@ class PluginAppBackwardsInvocation(BaseBackwardsInvocation):
@classmethod
def _get_workflow(cls, app: App) -> Workflow | None:
"""
- get workflow without relying on App.workflow's request-scoped session property
+ get workflow with an owned session, additionally scoped by tenant and app
+
+ `App.workflow_with_session` resolves by `workflow_id` alone; a plugin
+ invocation must also confirm the workflow belongs to this tenant and app.
"""
if not app.workflow_id:
return None
diff --git a/api/models/model.py b/api/models/model.py
index 2bb8dfc35bc..7b94b4e38c0 100644
--- a/api/models/model.py
+++ b/api/models/model.py
@@ -466,20 +466,12 @@ class App(Base):
def site_with_session(self, *, session: Session) -> Site | None:
return session.scalar(select(Site).where(Site.app_id == self.id))
- @property
- def app_model_config(self) -> AppModelConfig | None:
- return self.app_model_config_with_session(session=db.session())
-
def app_model_config_with_session(self, *, session: Session) -> AppModelConfig | None:
if self.app_model_config_id:
return session.scalar(select(AppModelConfig).where(AppModelConfig.id == self.app_model_config_id))
return None
- @property
- def workflow(self) -> Workflow | None:
- return self.workflow_with_session(session=db.session())
-
def workflow_with_session(self, *, session: Session) -> Workflow | None:
if self.workflow_id:
from .workflow import Workflow
diff --git a/api/services/agent/dsl_service.py b/api/services/agent/dsl_service.py
index 3c13ee0112b..454c887f901 100644
--- a/api/services/agent/dsl_service.py
+++ b/api/services/agent/dsl_service.py
@@ -203,7 +203,7 @@ class AgentDslService:
package=package,
package_path="agent",
)
- if app.app_model_config is None:
+ if app.app_model_config_with_session(session=self.session) is None:
model_config = AppModelConfig(app_id=app.id, created_by=account.id, updated_by=account.id)
self.session.add(model_config)
self.session.flush()
diff --git a/api/services/app_service.py b/api/services/app_service.py
index e90e962cf2b..4fa63c76f76 100644
--- a/api/services/app_service.py
+++ b/api/services/app_service.py
@@ -809,9 +809,12 @@ class AppService:
def __init__(self, app):
self.__dict__.update(app.__dict__)
- @property
@override
- def app_model_config(self):
+ def app_model_config_with_session(self, *, session: Session) -> AppModelConfig | None:
+ # Hand back the in-memory config the masking pass above produced, and
+ # deliberately ignore `session`: re-reading the row here would undo the
+ # masking. Response paths resolve the config through this accessor
+ # (`AppResponseView.app_model_config`), so the override has to sit here.
return model_config
app = ModifiedApp(app)
diff --git a/api/services/tools/workflow_tools_manage_service.py b/api/services/tools/workflow_tools_manage_service.py
index b094d4231d1..99dda57dae8 100644
--- a/api/services/tools/workflow_tools_manage_service.py
+++ b/api/services/tools/workflow_tools_manage_service.py
@@ -61,18 +61,18 @@ class WorkflowToolManageService:
if existing_workflow_tool_provider is not None:
raise ValueError(f"Tool with name {name} or app_id {workflow_app_id} already exists")
- # query the app
+ # query the app and its published workflow in the same session
app: App | None = None
+ workflow: Workflow | None = None
with sessionmaker(db.engine, expire_on_commit=False).begin() as _session:
app = _session.scalar(select(App).where(App.id == workflow_app_id, App.tenant_id == tenant_id).limit(1))
+ if app is not None:
+ workflow = app.workflow_with_session(session=_session)
# if not found raise error
if app is None:
raise ValueError(f"App {workflow_app_id} not found")
- # query the workflow
- workflow: Workflow | None = app.workflow
-
# if not found raise error
if workflow is None:
raise ValueError(f"Workflow not found for app {workflow_app_id}")
@@ -172,20 +172,20 @@ class WorkflowToolManageService:
if workflow_tool_provider is None:
raise ValueError(f"Tool {workflow_tool_id} not found")
- # query the app
+ # query the app and its published workflow in the same session
app: App | None = None
+ workflow: Workflow | None = None
with sessionmaker(db.engine, expire_on_commit=False).begin() as _session:
app = _session.scalar(
select(App).where(App.id == workflow_tool_provider.app_id, App.tenant_id == tenant_id).limit(1)
)
+ if app is not None:
+ workflow = app.workflow_with_session(session=_session)
# if not found raise error
if app is None:
raise ValueError(f"App {workflow_tool_provider.app_id} not found")
- # query the workflow
- workflow: Workflow | None = app.workflow
-
# if not found raise error
if workflow is None:
raise ValueError(f"Workflow not found for app {workflow_tool_provider.app_id}")
@@ -342,15 +342,17 @@ class WorkflowToolManageService:
raise ValueError("Tool not found")
workflow_app: App | None = None
+ workflow: Workflow | None = None
with sessionmaker(db.engine, expire_on_commit=False).begin() as _session:
workflow_app = _session.scalar(
select(App).where(App.id == db_tool.app_id, App.tenant_id == db_tool.tenant_id).limit(1)
)
+ if workflow_app is not None:
+ workflow = workflow_app.workflow_with_session(session=_session)
if workflow_app is None:
raise ValueError(f"App {db_tool.app_id} not found")
- workflow = workflow_app.workflow
if not workflow:
raise ValueError("Workflow not found")
diff --git a/api/tests/test_containers_integration_tests/services/test_agent_service.py b/api/tests/test_containers_integration_tests/services/test_agent_service.py
index d6e0ff103c1..4217e573b5a 100644
--- a/api/tests/test_containers_integration_tests/services/test_agent_service.py
+++ b/api/tests/test_containers_integration_tests/services/test_agent_service.py
@@ -133,8 +133,9 @@ class TestAgentService:
app = app_service.create_app(tenant.id, app_args, account, session=db_session_with_containers)
# Update the app model config to set agent_mode for agent-chat mode
- if app.mode == AppMode.AGENT_CHAT and app.app_model_config:
- app.app_model_config.agent_mode = json.dumps({"enabled": True, "strategy": "react", "tools": []})
+ app_model_config = app.app_model_config_with_session(session=db_session_with_containers)
+ if app.mode == AppMode.AGENT_CHAT and app_model_config:
+ app_model_config.agent_mode = json.dumps({"enabled": True, "strategy": "react", "tools": []})
db_session_with_containers.commit()
diff --git a/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py b/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py
index c2c5fe838fb..f05a0fb28da 100644
--- a/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py
+++ b/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py
@@ -537,6 +537,9 @@ class TestWorkflowToolManageService:
]
}
)
+ # The service reads the published workflow in its own session, so the graph has
+ # to be committed — matching test_update_workflow_tool_human_input_node_error.
+ db_session_with_containers.commit()
tool_parameters = self._create_test_workflow_tool_parameters()
with pytest.raises(WorkflowToolHumanInputNotSupportedError) as exc_info:
@@ -877,6 +880,9 @@ class TestWorkflowToolManageService:
]
}
workflow.graph = json.dumps(workflow_graph)
+ # The service reads the published workflow in its own session, so the graph has
+ # to be committed for this setup to reach it.
+ db_session_with_containers.commit()
# Setup workflow tool parameters with FILE type
file_parameters = [
@@ -952,6 +958,9 @@ class TestWorkflowToolManageService:
]
}
workflow.graph = json.dumps(workflow_graph)
+ # The service reads the published workflow in its own session, so the graph has
+ # to be committed for this setup to reach it.
+ db_session_with_containers.commit()
# Setup workflow tool parameters with FILES type
files_parameters = [
diff --git a/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py b/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py
index 8cd9526f6a0..fa102683cdf 100644
--- a/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py
+++ b/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py
@@ -325,7 +325,7 @@ class TestWorkflowConverter:
workflow_converter = WorkflowConverter()
workflow = workflow_converter.convert_app_model_config_to_workflow(
app_model=app,
- app_model_config=app.app_model_config,
+ app_model_config=app.app_model_config_with_session(session=db_session_with_containers),
account_id=account.id,
session=db_session_with_containers,
)
diff --git a/api/tests/unit_tests/controllers/console/app/test_model_config_api.py b/api/tests/unit_tests/controllers/console/app/test_model_config_api.py
index 43d4925e165..d9d99221dff 100644
--- a/api/tests/unit_tests/controllers/console/app/test_model_config_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_model_config_api.py
@@ -4,7 +4,6 @@ import importlib
import json
import os
from inspect import unwrap
-from typing import Never
from unittest.mock import MagicMock
from uuid import uuid4
@@ -21,13 +20,13 @@ from models.model import App, AppMode, AppModelConfig
app_wraps_module = importlib.import_module("controllers.console.app.wraps")
-def _poison_implicit_app_config_properties(monkeypatch: pytest.MonkeyPatch) -> None:
- def fail(_app: App) -> Never:
- raise AssertionError("implicit App model-config property was accessed")
-
- # `App.is_agent` used to be poisoned here too. It no longer exists as an
- # implicit property, so its absence enforces the same thing outright.
- monkeypatch.setattr(App, "app_model_config", property(fail))
+def _assert_no_implicit_app_config_properties() -> None:
+ # `App.is_agent` and `App.app_model_config` used to be poisoned here with a
+ # raising property. Neither exists as an implicit accessor any more, so their
+ # absence enforces the same thing outright — assert it instead of
+ # monkeypatching an attribute that is gone.
+ assert not hasattr(App, "is_agent")
+ assert not hasattr(App, "app_model_config")
@pytest.mark.parametrize("app_mode", [AppMode.CHAT, AppMode.COMPLETION])
@@ -54,7 +53,7 @@ def test_post_updates_non_agent_model_config_without_implicit_properties(
original_config.agent_mode = None
sqlite_session.add(original_config)
sqlite_session.commit()
- _poison_implicit_app_config_properties(monkeypatch)
+ _assert_no_implicit_app_config_properties()
monkeypatch.setattr(
model_config_module.AppModelConfigService,
"validate_configuration",
@@ -184,7 +183,7 @@ def test_post_encrypts_agent_tool_parameters(
updated_by=None,
updated_at=None,
)
- _poison_implicit_app_config_properties(monkeypatch)
+ _assert_no_implicit_app_config_properties()
original_config = AppModelConfig(app_id="app-1", created_by="u1", updated_by="u1")
original_config.id = "config-0"
diff --git a/api/tests/unit_tests/models/test_app_models.py b/api/tests/unit_tests/models/test_app_models.py
index 7d0a42ebcb8..3ae1824a2e9 100644
--- a/api/tests/unit_tests/models/test_app_models.py
+++ b/api/tests/unit_tests/models/test_app_models.py
@@ -33,6 +33,7 @@ from models.model import (
Site,
load_annotation_reply_config,
)
+from models.workflow import Workflow, WorkflowType
class TestAppModelValidation:
@@ -268,6 +269,110 @@ class TestAppModelValidation:
# Assert
assert result == AppMode.AGENT_CHAT
+ @pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
+ def test_app_model_config_with_session_reads_through_the_caller_session(self, sqlite_session: Session):
+ """`app_model_config_with_session` resolves the linked config through the caller's session."""
+ # Arrange
+ app = App(
+ tenant_id=str(uuid4()),
+ name="Test App",
+ mode=AppMode.CHAT,
+ enable_site=True,
+ enable_api=False,
+ created_by=str(uuid4()),
+ )
+ sqlite_session.add(app)
+ sqlite_session.flush()
+ model_config = AppModelConfig(app_id=app.id, agent_mode=json.dumps({"enabled": False}))
+ sqlite_session.add(model_config)
+ sqlite_session.flush()
+ app.app_model_config_id = model_config.id
+ sqlite_session.commit()
+
+ # Act: a session the model never owns, proving the lookup does not reach for a global one
+ with Session(sqlite_session.get_bind(), expire_on_commit=False) as caller_session:
+ result = app.app_model_config_with_session(session=caller_session)
+
+ # Assert
+ assert result is not None
+ assert result.id == model_config.id
+ assert result in caller_session
+
+ @pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
+ def test_app_model_config_with_session_returns_none_when_unlinked(self, sqlite_session: Session):
+ """An app without `app_model_config_id` resolves to None without querying."""
+ # Arrange
+ app = App(
+ tenant_id=str(uuid4()),
+ name="Test App",
+ mode=AppMode.CHAT,
+ enable_site=True,
+ enable_api=False,
+ created_by=str(uuid4()),
+ )
+ sqlite_session.add(app)
+ sqlite_session.flush()
+
+ # Act / Assert: an unbound session would raise if the guard were dropped
+ with Session(expire_on_commit=False) as unbound_session:
+ assert app.app_model_config_with_session(session=unbound_session) is None
+
+ @pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
+ def test_workflow_with_session_reads_through_the_caller_session(self, sqlite_session: Session):
+ """`workflow_with_session` resolves the published workflow through the caller's session."""
+ # Arrange
+ app = App(
+ tenant_id=str(uuid4()),
+ name="Test App",
+ mode=AppMode.WORKFLOW,
+ enable_site=True,
+ enable_api=False,
+ created_by=str(uuid4()),
+ )
+ sqlite_session.add(app)
+ sqlite_session.flush()
+ workflow = Workflow(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ type=WorkflowType.WORKFLOW,
+ version="1",
+ graph=json.dumps({"nodes": [], "edges": []}),
+ created_by=app.created_by,
+ )
+ workflow._features = "{}"
+ sqlite_session.add(workflow)
+ sqlite_session.flush()
+ app.workflow_id = workflow.id
+ sqlite_session.commit()
+
+ # Act: a session the model never owns, proving the lookup does not reach for a global one
+ with Session(sqlite_session.get_bind(), expire_on_commit=False) as caller_session:
+ result = app.workflow_with_session(session=caller_session)
+
+ # Assert
+ assert result is not None
+ assert result.id == workflow.id
+ assert result in caller_session
+
+ @pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
+ def test_workflow_with_session_returns_none_when_unpublished(self, sqlite_session: Session):
+ """An app without `workflow_id` resolves to None without querying."""
+ # Arrange
+ app = App(
+ tenant_id=str(uuid4()),
+ name="Test App",
+ mode=AppMode.WORKFLOW,
+ enable_site=True,
+ enable_api=False,
+ created_by=str(uuid4()),
+ )
+ sqlite_session.add(app)
+ sqlite_session.flush()
+
+ # Act / Assert: an unbound session would raise if the guard were dropped
+ with Session(expire_on_commit=False) as unbound_session:
+ assert app.workflow_with_session(session=unbound_session) is None
+
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_deleted_tools_checks_plugin_builtin_providers_through_core_plugin_service(self, sqlite_session: Session):
"""Plugin-backed built-in tools are checked through core PluginService."""
diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.py
index 1e6f79261f3..d568fb6742c 100644
--- a/api/tests/unit_tests/services/test_app_service.py
+++ b/api/tests/unit_tests/services/test_app_service.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
from collections.abc import Callable
from datetime import datetime
from types import SimpleNamespace
@@ -544,6 +545,32 @@ class TestGetApp:
is_agent.assert_not_called()
get_model_config.assert_called_once_with(session=unbound_session)
+ def test_masked_agent_config_is_served_through_the_session_accessor(self, unbound_session: Session):
+ """The masked config must be reachable via `app_model_config_with_session`.
+
+ Every response path resolves an `App`'s model config through that accessor
+ (`AppResponseView.app_model_config`), never through a raw attribute, so the
+ masking `get_app` applies has to be observable there.
+ """
+ app = App(mode=AppMode.AGENT_CHAT)
+ app.id = str(uuid4())
+ masked_config = AppModelConfig(app_id=app.id, agent_mode=json.dumps({"enabled": True, "tools": []}))
+ # A second, unmasked instance: what a fresh lookup would hand back if the
+ # returned app ever fell through to the base accessor.
+ refetched_config = AppModelConfig(app_id=app.id, agent_mode=json.dumps({"enabled": True, "tools": []}))
+ account = Account(name="Test Account", email="[email protected]")
+ account._current_tenant = Tenant(name="Test Tenant")
+ account._current_tenant.id = "tenant-1"
+
+ with (
+ patch.object(App, "app_model_config_with_session", side_effect=[masked_config, refetched_config]),
+ patch("services.app_service.current_user", account),
+ ):
+ result = AppService().get_app(app, session=unbound_session)
+
+ assert result is not app
+ assert result.app_model_config_with_session(session=unbound_session) is masked_config
+
class TestAgentAppType:
"""S1: new ``AppMode.AGENT`` app type wiring."""