Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(app): validate channel updates instead of copying nulls into storage (#2744)
lihongyuan99d26173c9d1d8
diff --git a/src/agentscope/app/_service/_channel.py b/src/agentscope/app/_service/_channel.pyindex d6ef2ad80..be4272a35 100644--- a/src/agentscope/app/_service/_channel.py+++ b/src/agentscope/app/_service/_channel.py@@ -8,6 +8,8 @@ instances against storage. Holds no channel instances.import timefrom datetime import datetime+from pydantic import ValidationError+from ..._utils._common import _generate_idfrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import (@@ -110,9 +112,21 @@ class ChannelService:record = await self._require(channel_id)updates.pop("credentials", None)updates.pop("channel_type", None)- updated = record.model_copy(- update={**updates, "updated_at": datetime.now()},- )+ # model_copy(update=...) skips validation; reject invalid updates+ # before they reach storage.+ try:+ updated = ChannelRecord.model_validate(+ {+ **record.model_dump(),+ **updates,+ "updated_at": datetime.now(),+ },+ )+ except ValidationError as exc:+ raise ChannelError(+ f"Invalid channel update: {exc.errors()}",+ 422,+ ) from excbot_id = self._types.extract_platform_bot_id(updated.channel_type,updated.credentials,diff --git a/tests/channel_clients_test.py b/tests/channel_clients_test.pyindex d28f006aa..89c6bd525 100644--- a/tests/channel_clients_test.py+++ b/tests/channel_clients_test.py@@ -12,13 +12,18 @@ import timefrom datetime import datetimefrom typing import Any, AsyncIteratorfrom unittest import IsolatedAsyncioTestCase+from unittest.mock import patch+from fastapi import HTTPExceptionfrom pydantic import BaseModel+from agentscope.app._router._channel import update_channel+from agentscope.app._router._schema import UpdateChannelRequestfrom agentscope.app._service import ChannelServicefrom agentscope.app.channel import (ChannelBase,ChannelClients,+ ChannelError,ChannelEvent,ChannelHeartbeat,ChannelStatus,@@ -107,6 +112,17 @@ class _Storage:self.calls += 1return self.record+ async def upsert_channel(+ self,+ record: ChannelRecord,+ platform_bot_id: str, # pylint: disable=unused-argument+ ) -> str:+ """Round-trip the record through the storage serialization format."""+ self.record = ChannelRecord.model_validate_json(+ record.model_dump_json(),+ )+ return record.id+def _record(bot_id: str = "bot-1", enabled: bool = True) -> ChannelRecord:"""Build a minimal enabled channel record for the fake platform."""@@ -275,6 +291,79 @@ class ChannelDeliveryTest(IsolatedAsyncioTestCase):await self._deliver(clients)+class ChannelUpdateTest(IsolatedAsyncioTestCase):+ """Channel updates validate before writing or notifying listeners."""++ def setUp(self) -> None:+ """Reuse the fake channel and storage without starting an app."""+ self.record = _record()+ self.record.name = "my bot"+ self.storage = _Storage(self.record)+ bus = InMemoryMessageBus()+ self.registry = ChannelTypeRegistry([_FakeChannel])+ self.service = ChannelService(self.storage, bus, self.registry)+ self.write = self.enterContext(+ patch.object(+ self.storage,+ "upsert_channel",+ wraps=self.storage.upsert_channel,+ ),+ )+ self.publish = self.enterContext(patch.object(bus, "publish"))++ async def test_null_required_fields_leave_storage_unchanged(self) -> None:+ """Reject the whole patch, including otherwise valid changes."""+ before = self.record.model_dump()+ for field in ("routing", "session", "platform_config", "enabled"):+ with self.subTest(field=field):+ with self.assertRaises(ChannelError) as caught:+ await self.service.update(+ self.record.id,+ {field: None, "name": "changed"},+ )+ self.assertEqual(caught.exception.status_code, 422)+ self.write.assert_not_awaited()+ self.publish.assert_not_awaited()+ stored = await self.storage.get_channel(self.record.id)+ self.assertEqual(stored.model_dump(), before)++ async def test_valid_updates_round_trip(self) -> None:+ """Clearing a name and changing enabled preserve all other fields."""+ patches: list[dict] = [{"name": None}, {"enabled": False}]+ for updates in patches:+ with self.subTest(updates=updates):+ before = self.storage.record.model_dump()+ updated = await self.service.update(self.record.id, updates)+ expected = {+ **before,+ **updates,+ "updated_at": updated.updated_at,+ }+ self.assertEqual(updated.model_dump(), expected)+ stored = await self.storage.get_channel(self.record.id)+ self.assertEqual(stored.model_dump(), expected)+ self.write.assert_awaited_with(updated, "bot-1")+ self.publish.assert_awaited_with(+ MessageBusKeys.channel_lifecycle(),+ {"channel_id": self.record.id},+ )++ async def test_router_maps_invalid_update_to_422(self) -> None:+ """The route translates service validation errors to HTTP errors."""+ with self.assertRaises(HTTPException) as caught:+ await update_channel(+ self.record.id,+ UpdateChannelRequest(routing=None),+ storage=self.storage,+ service=self.service,+ registry=self.registry,+ user_id=self.record.user_id,+ )+ self.assertEqual(caught.exception.status_code, 422)+ self.write.assert_not_awaited()+ self.publish.assert_not_awaited()++class ChannelStatusTest(IsolatedAsyncioTestCase):"""Status is read from the heartbeat, not from local instances."""