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): drop implicit-session getters on Conversation/Message inputs and model_config (#42335)

Keithbba566540d7b
diff --git a/api/core/memory/token_buffer_memory.py b/api/core/memory/token_buffer_memory.py
index b83f3b84274..8b050d92c1c 100644
--- a/api/core/memory/token_buffer_memory.py
+++ b/api/core/memory/token_buffer_memory.py
@@ -64,7 +64,9 @@ class TokenBufferMemory:
"""
match self.conversation.mode:
case AppMode.AGENT_CHAT | AppMode.COMPLETION | AppMode.CHAT:
- file_extra_config = FileUploadConfigManager.convert(self.conversation.model_config)
+ file_extra_config = FileUploadConfigManager.convert(
+ self.conversation.model_config_with_session(session=db.session())
+ )
case AppMode.ADVANCED_CHAT | AppMode.WORKFLOW:
app = self.conversation.app
if not app:
diff --git a/api/core/ops/ops_trace_manager.py b/api/core/ops/ops_trace_manager.py
index 34679afc139..c7a1fcfb512 100644
--- a/api/core/ops/ops_trace_manager.py
+++ b/api/core/ops/ops_trace_manager.py
@@ -1188,7 +1188,7 @@ class TraceTask:
dataset_retrieval_trace_info = DatasetRetrievalTraceInfo(
trace_id=self.trace_id,
message_id=message_id,
- inputs=message_data.query or message_data.inputs,
+ inputs=message_data.query or message_data.inputs_with_session(session=db.session()),
documents=doc_list,
start_time=timer.get("start"),
end_time=timer.get("end"),
diff --git a/api/models/model.py b/api/models/model.py
index 7b94b4e38c0..0cd3c2e16eb 100644
--- a/api/models/model.py
+++ b/api/models/model.py
@@ -1183,12 +1183,7 @@ class Conversation(Base):
is_deleted: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.false())
- @property
- def inputs(self) -> dict[str, Any]:
- return self.inputs_with_session(session=db.session())
-
- @inputs.setter
- def inputs(self, value: Mapping[str, Any]):
+ def _set_inputs(self, value: Mapping[str, Any]):
inputs = dict(value)
for k, v in inputs.items():
match v:
@@ -1199,6 +1194,9 @@ class Conversation(Base):
inputs[k] = [item.model_dump() for item in v if isinstance(item, File)]
self._inputs = inputs
+ # Write-only: reading requires a session, use inputs_with_session instead.
+ inputs = property(fset=_set_inputs)
+
def inputs_with_session(self, *, session: Session) -> dict[str, Any]:
inputs = self._inputs.copy()
# Compatibility bridge: stored input payloads may come from before or after the
@@ -1242,10 +1240,6 @@ class Conversation(Base):
return inputs
- @property
- def model_config(self) -> AppModelConfigDict:
- return self.model_config_with_session(session=db.session())
-
def model_config_with_session(self, *, session: Session) -> AppModelConfigDict:
model_config = cast(AppModelConfigDict, {})
app_model_config: AppModelConfig | None = None
@@ -1428,7 +1422,7 @@ class Conversation(Base):
"mode": self.mode,
"name": self.name,
"summary": self.summary,
- "inputs": self.inputs,
+ "inputs": self.inputs_with_session(session=db.session()),
"introduction": self.introduction,
"system_instruction": self.system_instruction,
"system_instruction_tokens": self.system_instruction_tokens,
@@ -1504,12 +1498,7 @@ class Message(Base):
workflow_run_id: Mapped[str | None] = mapped_column(StringUUID)
app_mode: Mapped[AppMode | None] = mapped_column(EnumText(AppMode, length=255), nullable=True)
- @property
- def inputs(self) -> dict[str, Any]:
- return self.inputs_with_session(session=db.session())
-
- @inputs.setter
- def inputs(self, value: Mapping[str, Any]):
+ def _set_inputs(self, value: Mapping[str, Any]):
inputs = dict(value)
for k, v in inputs.items():
match v:
@@ -1521,6 +1510,9 @@ class Message(Base):
inputs[k] = [item.model_dump() for item in v_list if isinstance(item, File)]
self._inputs = inputs
+ # Write-only: reading requires a session, use inputs_with_session instead.
+ inputs = property(fset=_set_inputs)
+
def inputs_with_session(self, *, session: Session) -> dict[str, Any]:
inputs = self._inputs.copy()
# Compatibility bridge: message inputs are persisted as JSON and must remain
@@ -1799,7 +1791,7 @@ class Message(Base):
"app_id": self.app_id,
"conversation_id": self.conversation_id,
"model_id": self.model_id,
- "inputs": self.inputs,
+ "inputs": self.inputs_with_session(session=db.session()),
"query": self.query,
"total_price": self.total_price,
"message": self.message,
diff --git a/api/tests/test_containers_integration_tests/models/test_conversation_message_inputs.py b/api/tests/test_containers_integration_tests/models/test_conversation_message_inputs.py
index f10f519e250..45cb28cd169 100644
--- a/api/tests/test_containers_integration_tests/models/test_conversation_message_inputs.py
+++ b/api/tests/test_containers_integration_tests/models/test_conversation_message_inputs.py
@@ -80,7 +80,7 @@ class TestConversationMessageInputsTenantResolution:
owner = owner_cls(app_id=app.id)
owner.inputs = {"file": _build_local_file_mapping("upload-1")}
- restored_inputs = owner.inputs
+ restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
# The tenant_id should come from the real App row in the DB
assert restored_inputs["file"] == {"tenant_id": app.tenant_id, "upload_file_id": "upload-1"}
@@ -108,7 +108,7 @@ class TestConversationMessageInputsTenantResolution:
owner = owner_cls(app_id=app.id)
owner.inputs = {"file": _build_local_file_mapping("upload-1", tenant_id=payload_tenant_id)}
- restored_inputs = owner.inputs
+ restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
assert restored_inputs["file"] == {"tenant_id": payload_tenant_id, "upload_file_id": "upload-1"}
assert len(build_calls) == 1
@@ -139,7 +139,7 @@ class TestConversationMessageInputsTenantResolution:
]
}
- restored_inputs = owner.inputs
+ restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
assert len(build_calls) == 2
assert all(call[1] == app.tenant_id for call in build_calls)
diff --git a/api/tests/unit_tests/models/test_app_models.py b/api/tests/unit_tests/models/test_app_models.py
index 3ae1824a2e9..50e439fb7d0 100644
--- a/api/tests/unit_tests/models/test_app_models.py
+++ b/api/tests/unit_tests/models/test_app_models.py
@@ -634,8 +634,8 @@ class TestConversationModel:
assert conversation.from_source == "api"
assert conversation.from_end_user_id == from_end_user_id
- def test_conversation_with_inputs(self):
- """Test conversation inputs property."""
+ def test_conversation_with_inputs(self, sqlite_session: Session):
+ """Test conversation inputs round-trip through the session-aware accessor."""
# Arrange
inputs = {"query": "Hello", "context": "test"}
conversation = Conversation(
@@ -649,11 +649,18 @@ class TestConversationModel:
conversation._inputs = inputs
# Act
- result = conversation.inputs
+ result = conversation.inputs_with_session(session=sqlite_session)
# Assert
assert result == inputs
+ def test_conversation_inputs_is_write_only(self):
+ """Reading conversation.inputs must fail loudly; reads go through inputs_with_session."""
+ conversation = Conversation(app_id=str(uuid4()), _inputs={})
+
+ with pytest.raises(AttributeError, match="no getter"):
+ _ = conversation.inputs
+
def test_conversation_inputs_setter(self):
"""Test conversation inputs setter."""
# Arrange
@@ -878,8 +885,8 @@ class TestMessageModel:
assert message.currency == "USD"
assert message.from_source == "api"
- def test_message_with_inputs(self):
- """Test message inputs property."""
+ def test_message_with_inputs(self, sqlite_session: Session):
+ """Test message inputs round-trip through the session-aware accessor."""
# Arrange
inputs = {"query": "Hello", "context": "test"}
message = Message(
@@ -896,11 +903,18 @@ class TestMessageModel:
)
# Act
- result = message.inputs
+ result = message.inputs_with_session(session=sqlite_session)
# Assert
assert result == inputs
+ def test_message_inputs_is_write_only(self):
+ """Reading message.inputs must fail loudly; reads go through inputs_with_session."""
+ message = Message(app_id=str(uuid4()), _inputs={})
+
+ with pytest.raises(AttributeError, match="no getter"):
+ _ = message.inputs
+
def test_message_inputs_setter(self):
"""Test message inputs setter."""
# Arrange
diff --git a/api/tests/unit_tests/models/test_model.py b/api/tests/unit_tests/models/test_model.py
index 39a84d64d7e..47b9aeb9074 100644
--- a/api/tests/unit_tests/models/test_model.py
+++ b/api/tests/unit_tests/models/test_model.py
@@ -104,7 +104,9 @@ def _build_local_file_mapping(record_id: str, *, tenant_id: str | None = None) -
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
-def test_inputs_restore_external_remote_url_file_mappings(owner_cls: type[Conversation] | type[Message]) -> None:
+def test_inputs_restore_external_remote_url_file_mappings(
+ owner_cls: type[Conversation] | type[Message], sqlite_session: Session
+) -> None:
owner = owner_cls(app_id="app-1")
owner.inputs = {
"file": {
@@ -119,7 +121,7 @@ def test_inputs_restore_external_remote_url_file_mappings(owner_cls: type[Conver
}
}
- restored_file = owner.inputs["file"]
+ restored_file = owner.inputs_with_session(session=sqlite_session)["file"]
assert restored_file.transfer_method == FileTransferMethod.REMOTE_URL
assert restored_file.remote_url == "https://example.com/report.pdf"