Skip to content

Build and run agents you can see, understand and trust.

feat(storage): support channel records on SQL storage (#2388)

DavdGao24bdf4ae43f7
diff --git a/src/agentscope/app/_router/_schema/_channel.py b/src/agentscope/app/_router/_schema/_channel.py
index c2720fe41..4c17dad81 100644
--- a/src/agentscope/app/_router/_schema/_channel.py
+++ b/src/agentscope/app/_router/_schema/_channel.py
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
"""Request / response schemas for the channel router."""
+from datetime import datetime
+
from pydantic import BaseModel, Field
from ...storage import (
@@ -49,8 +51,8 @@ class ChannelResponse(BaseModel):
platform_config: dict
routing: RoutingConfig
session: SessionSettings
- created_at: str
- updated_at: str
+ created_at: datetime
+ updated_at: datetime
class ChannelActionResponse(BaseModel):
diff --git a/src/agentscope/app/_service/_channel.py b/src/agentscope/app/_service/_channel.py
index bb583fae1..dd2c57c69 100644
--- a/src/agentscope/app/_service/_channel.py
+++ b/src/agentscope/app/_service/_channel.py
@@ -81,7 +81,7 @@ class ChannelService:
)
channel_id = _generate_id()
- now = datetime.now().isoformat()
+ now = datetime.now()
record = ChannelRecord(
id=channel_id,
channel_type=channel_type,
@@ -111,7 +111,7 @@ class ChannelService:
updates.pop("credentials", None)
updates.pop("channel_type", None)
updated = record.model_copy(
- update={**updates, "updated_at": datetime.now().isoformat()},
+ update={**updates, "updated_at": datetime.now()},
)
bot_id = self._types.extract_platform_bot_id(
updated.channel_type,
diff --git a/src/agentscope/app/channel/_dispatcher.py b/src/agentscope/app/channel/_dispatcher.py
index 8503761d7..31dd01ff6 100644
--- a/src/agentscope/app/channel/_dispatcher.py
+++ b/src/agentscope/app/channel/_dispatcher.py
@@ -19,6 +19,7 @@ import socket
import time
from contextlib import asynccontextmanager
from dataclasses import dataclass
+from datetime import datetime
from typing import AsyncIterator
from ..._logging import logger
@@ -47,7 +48,7 @@ class ChannelInstance:
channel: ChannelBase
task: asyncio.Task
- version: str
+ version: datetime
class ChannelLifecycleDispatcher:
diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.py
index 229d6fd1e..3bc13af76 100644
--- a/src/agentscope/app/storage/_base.py
+++ b/src/agentscope/app/storage/_base.py
@@ -611,10 +611,11 @@ class StorageBase(ABC):
# ------------------------------------------------------------------
# Channel persistence
#
- # Optional capability: channels require the distributed message bus
- # (locks / pub-sub / queues), so only bus-backed stores (Redis)
- # implement these. Other backends inherit the NotImplementedError
- # default.
+ # Optional capability. Note it is orthogonal to the message bus:
+ # running channels across several nodes needs a *distributed bus*,
+ # but the storage backend is a separate injection — SQL storage
+ # with a Redis bus is the normal production shape. A backend that
+ # does not implement these inherits the NotImplementedError default.
# ------------------------------------------------------------------
async def upsert_channel(
diff --git a/src/agentscope/app/storage/_model/_channel.py b/src/agentscope/app/storage/_model/_channel.py
index 3e3493aa4..9f5414d32 100644
--- a/src/agentscope/app/storage/_model/_channel.py
+++ b/src/agentscope/app/storage/_model/_channel.py
@@ -15,6 +15,7 @@ from typing import Any
from pydantic import BaseModel, Field, field_validator
+from ._base import _RecordBase
from ....permission import PermissionMode
@@ -130,16 +131,19 @@ class SessionSettings(BaseModel):
return v
-class ChannelRecord(BaseModel):
+class ChannelRecord(_RecordBase):
"""Persistent record for a channel instance — the single source of
truth. Running adapter instances are a projection of this record.
+
+ ``id`` / ``created_at`` / ``updated_at`` come from
+ :class:`_RecordBase`, so this record round-trips through the generic
+ SQL row mapper like every other one. ``updated_at`` doubles as the
+ reconcile version: the lifecycle dispatcher compares it to detect
+ that a running instance's config has changed.
"""
# -- Identity & ownership --
- id: str
- """Server-generated UUID."""
-
channel_type: str
"""Platform adapter type: feishu / dingtalk / discord / wecom."""
@@ -172,10 +176,3 @@ class ChannelRecord(BaseModel):
routing: RoutingConfig
session: SessionSettings
-
- # -- Versioning (reconcile basis for the lifecycle dispatcher) --
-
- created_at: str
- updated_at: str
- """Refreshed on every write; the dispatcher compares it to detect
- that a running instance's config has changed."""
diff --git a/src/agentscope/app/storage/_sql/_alembic/versions/0003_channels.py b/src/agentscope/app/storage/_sql/_alembic/versions/0003_channels.py
new file mode 100644
index 000000000..6861fb41f
--- /dev/null
+++ b/src/agentscope/app/storage/_sql/_alembic/versions/0003_channels.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+"""Channel table.
+
+Revision ID: 0003_channels
+Revises: 0002_mcps_skills
+Create Date: 2026-08-21 00:00:00.000000
+
+The table is new — channels have only ever been stored on Redis — so
+there is nothing to backfill. ``platform_bot_id`` is unique because no
+two channels may drive the same platform bot; it replaces the separate
+bot-id index key the Redis backend maintains.
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import mysql
+
+
+# revision identifiers, used by Alembic.
+revision: str = "0003_channels"
+down_revision: Union[str, None] = "0002_mcps_skills"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+VERSION_TIMESTAMP = sa.DateTime().with_variant(
+ mysql.DATETIME(fsp=6),
+ "mysql",
+ "mariadb",
+)
+
+
+def upgrade() -> None:
+ """Create the ``channels`` table."""
+ op.create_table(
+ "channels",
+ sa.Column("user_id", sa.String(length=255), nullable=False),
+ sa.Column("platform_bot_id", sa.String(length=255), nullable=False),
+ sa.Column("id", sa.String(length=255), nullable=False),
+ # Microseconds, because ``updated_at`` is the channel's
+ # configuration version and MySQL's DATETIME would round
+ # two edits in one second to the same value.
+ sa.Column("created_at", VERSION_TIMESTAMP, nullable=False),
+ sa.Column("updated_at", VERSION_TIMESTAMP, nullable=False),
+ sa.Column("payload", sa.JSON(), nullable=False),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("platform_bot_id", name="uq_channels_bot"),
+ )
+ with op.batch_alter_table("channels", schema=None) as batch_op:
+ for column in ("created_at", "updated_at", "user_id"):
+ batch_op.create_index(
+ batch_op.f(f"ix_channels_{column}"),
+ [column],
+ unique=False,
+ )
+
+
+def downgrade() -> None:
+ """Drop the ``channels`` table."""
+ with op.batch_alter_table("channels", schema=None) as batch_op:
+ for column in ("user_id", "updated_at", "created_at"):
+ batch_op.drop_index(batch_op.f(f"ix_channels_{column}"))
+ op.drop_table("channels")
diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.py
index c3746c0ce..e3e2cf276 100644
--- a/src/agentscope/app/storage/_sql/_storage.py
+++ b/src/agentscope/app/storage/_sql/_storage.py
@@ -22,6 +22,7 @@ from typing import TYPE_CHECKING, Any, Self
from .._base import StorageBase
from .._model import (
AgentRecord,
+ ChannelRecord,
CredentialRecord,
KnowledgeBaseRecord,
KnowledgeDocumentRecord,
@@ -39,6 +40,7 @@ from ._mappers import _from_record, _to_record
from ._tables import (
_Base,
AgentRow,
+ ChannelRow,
CredentialRow,
KnowledgeBaseRow,
KnowledgeDocumentRow,
@@ -332,6 +334,7 @@ class AsyncSQLAlchemyStorage(StorageBase):
record: Any,
*,
preserve_created_at: bool = True,
+ extra: dict[str, Any] | None = None,
) -> Any:
"""Atomically insert-or-update *record* via *row_cls*.
@@ -355,6 +358,11 @@ class AsyncSQLAlchemyStorage(StorageBase):
original one on an update) is read back into the
returned record. Set `False` on pure-create paths
where no prior row can exist, to skip that read.
+ extra (`dict[str, Any] | None`, optional):
+ Column values that are not record fields, so the
+ generic mapper cannot produce them (e.g. a channel's
+ ``platform_bot_id``). Written and refreshed on
+ conflict alongside the promoted columns.
Returns:
`Any`:
@@ -373,7 +381,9 @@ class AsyncSQLAlchemyStorage(StorageBase):
col: getattr(new_row, col)
for col in ("id", "created_at", "updated_at", "payload") + indexed
}
+ values.update(extra or {})
update_cols = ("updated_at", "payload") + indexed
+ update_cols += tuple(extra or ())
async with self._session() as sess:
await sess.execute(
@@ -1314,6 +1324,177 @@ class AsyncSQLAlchemyStorage(StorageBase):
rows = (await sess.execute(select(ScheduleRow))).scalars().all()
return [_to_record(r, ScheduleRecord) for r in rows]
+ # ------------------------------------------------------------------
+ # Channels
+ #
+ # ``platform_bot_id`` is a promoted column rather than a record
+ # field, so the bot-uniqueness index the Redis backend keeps as a
+ # separate key is just a UNIQUE constraint here.
+ # ------------------------------------------------------------------
+
+ async def upsert_channel(
+ self,
+ record: ChannelRecord,
+ platform_bot_id: str,
+ ) -> str:
+ """Persist a channel record and its bot-uniqueness column.
+
+ Args:
+ record (`ChannelRecord`):
+ The channel record to store.
+ platform_bot_id (`str`):
+ The platform-side bot identifier, extracted from the
+ credentials by the caller. Globally unique: a bot drives
+ at most one channel.
+
+ Returns:
+ `str`:
+ The id of the stored record.
+
+ Raises:
+ `ValueError`:
+ If another channel already drives this bot. Checked here
+ rather than left to the UNIQUE constraint, because
+ MySQL's ``ON DUPLICATE KEY UPDATE`` fires on *any*
+ unique-key conflict — the write would silently overwrite
+ the holder instead of failing, and the same call would
+ behave differently per dialect.
+
+ Neither this check nor `ChannelService.create`'s is
+ atomic with the write, so two creates racing for one bot
+ can both pass. The constraint then decides, and how it
+ surfaces depends on the dialect: Postgres and SQLite
+ raise `IntegrityError`, while on MySQL the duplicate-key
+ update lands on the holder's row and the read-back of
+ the new id then raises `NoResultFound`, rolling the
+ transaction back. Either way nothing is committed.
+ """
+ holder = await self.get_channel_id_by_platform_bot_id(
+ platform_bot_id,
+ )
+ if holder is not None and holder != record.id:
+ raise ValueError(
+ f"Bot {platform_bot_id!r} already drives channel "
+ f"{holder!r}.",
+ )
+ await self._write_row(
+ ChannelRow,
+ record,
+ extra={"platform_bot_id": platform_bot_id},
+ )
+ return record.id
+
+ async def get_channel(self, channel_id: str) -> ChannelRecord | None:
+ """Fetch a channel record by its global id.
+
+ Args:
+ channel_id (`str`):
+ The channel id.
+
+ Returns:
+ `ChannelRecord | None`:
+ The record, or ``None`` if not found.
+ """
+ async with self._session() as sess:
+ row = await sess.get(ChannelRow, channel_id)
+ return None if row is None else _to_record(row, ChannelRecord)
+
+ async def list_channels(self, user_id: str) -> list[ChannelRecord]:
+ """Return all channel records owned by *user_id*.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+
+ Returns:
+ `list[ChannelRecord]`:
+ Every channel record for that user.
+ """
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ rows = (
+ (
+ await sess.execute(
+ select(ChannelRow).where(
+ ChannelRow.user_id == user_id,
+ ),
+ )
+ )
+ .scalars()
+ .all()
+ )
+ return [_to_record(r, ChannelRecord) for r in rows]
+
+ async def list_all_channels(self) -> list[ChannelRecord]:
+ """Every channel across every user.
+
+ Returns:
+ `list[ChannelRecord]`:
+ All channel records in the store, which reconcile reads
+ to decide what this node should be running.
+ """
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ rows = (await sess.execute(select(ChannelRow))).scalars().all()
+ return [_to_record(r, ChannelRecord) for r in rows]
+
+ async def delete_channel(
+ self,
+ channel_id: str,
+ platform_bot_id: str,
+ ) -> bool:
+ """Delete a channel record.
+
+ Args:
+ channel_id (`str`):
+ The id of the channel to delete.
+ platform_bot_id (`str`):
+ Unused, and accepted only for parity with the Redis
+ backend, which keeps the bot index in a separate key.
+ Here the UNIQUE column goes with the row.
+
+ Returns:
+ `bool`:
+ ``True`` if a record was deleted, ``False`` if none
+ matched.
+ """
+ from sqlalchemy import delete
+
+ _ = platform_bot_id
+ async with self._session() as sess:
+ result = await sess.execute(
+ delete(ChannelRow).where(ChannelRow.id == channel_id),
+ )
+ await sess.commit()
+ return result.rowcount > 0
+
+ async def get_channel_id_by_platform_bot_id(
+ self,
+ platform_bot_id: str,
+ ) -> str | None:
+ """Return the channel bound to a platform bot, if any.
+
+ Args:
+ platform_bot_id (`str`):
+ The platform-side bot identifier.
+
+ Returns:
+ `str | None`:
+ The bound channel id, or ``None``.
+ """
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ return (
+ await sess.execute(
+ select(ChannelRow.id).where(
+ ChannelRow.platform_bot_id == platform_bot_id,
+ ),
+ )
+ ).scalar_one_or_none()
+
# ------------------------------------------------------------------
# Messages
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/storage/_sql/_tables.py b/src/agentscope/app/storage/_sql/_tables.py
index 9a37f0b4f..d7b4e09b3 100644
--- a/src/agentscope/app/storage/_sql/_tables.py
+++ b/src/agentscope/app/storage/_sql/_tables.py
@@ -36,6 +36,7 @@ from sqlalchemy import (
String,
UniqueConstraint,
)
+from sqlalchemy.dialects.mysql import DATETIME as _MySQLDateTime
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -335,6 +336,54 @@ class SkillRow(_JsonRecordMixin):
_indexed_fields = ("user_id", "name")
+class ChannelRow(_JsonRecordMixin):
+ """One row per :class:`~agentscope.app.storage.ChannelRecord`.
+
+ ``platform_bot_id`` is globally unique — no two channels may drive
+ the same platform bot — but it is deliberately NOT a record field
+ (it is extracted from ``credentials`` on write and passed alongside
+ the record), so it is not listed in ``_indexed_fields``; the write
+ path sets this column explicitly.
+
+ ``updated_at`` is this record's configuration version: the client
+ cache and the lifecycle dispatcher both compare it for equality to
+ decide whether a running instance still matches its record. MySQL's
+ ``DATETIME`` keeps whole seconds unless a precision is asked for, so
+ two edits within one second would persist the same version and the
+ second one would never be picked up. Both timestamps therefore
+ override the mixin's to carry microseconds.
+ """
+
+ __tablename__ = "channels"
+
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime().with_variant(_MySQLDateTime(fsp=6), "mysql", "mariadb"),
+ index=True,
+ nullable=False,
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime().with_variant(_MySQLDateTime(fsp=6), "mysql", "mariadb"),
+ index=True,
+ nullable=False,
+ )
+
+ user_id: Mapped[str] = mapped_column(
+ String(_ID_LEN),
+ nullable=False,
+ index=True,
+ )
+ platform_bot_id: Mapped[str] = mapped_column(
+ String(_ID_LEN),
+ nullable=False,
+ )
+
+ __table_args__ = (
+ UniqueConstraint("platform_bot_id", name="uq_channels_bot"),
+ )
+
+ _indexed_fields = ("user_id",)
+
+
class MessageRow(_Base):
"""One row per persisted :class:`~agentscope.message.Msg`.
diff --git a/tests/channel_gateway_test.py b/tests/channel_gateway_test.py
index 75f142c07..29a4430ae 100644
--- a/tests/channel_gateway_test.py
+++ b/tests/channel_gateway_test.py
@@ -335,8 +335,6 @@ def _channel_record(user_id: str) -> ChannelRecord:
"parameters": {},
},
),
- created_at="t",
- updated_at="t",
)
diff --git a/tests/channel_routing_test.py b/tests/channel_routing_test.py
index 362980e24..6a01055c9 100644
--- a/tests/channel_routing_test.py
+++ b/tests/channel_routing_test.py
@@ -26,8 +26,6 @@ def _record(bindings: list[ChannelBinding]) -> ChannelRecord:
user_id="owner-1",
routing=RoutingConfig(bindings=bindings),
session=SessionSettings(chat_model_config={"type": "x"}),
- created_at="t",
- updated_at="t",
)
diff --git a/tests/service_chat_channel_delivery_test.py b/tests/service_chat_channel_delivery_test.py
index 9754f4657..73f6d48be 100644
--- a/tests/service_chat_channel_delivery_test.py
+++ b/tests/service_chat_channel_delivery_test.py
@@ -186,8 +186,6 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
bindings=[ChannelBinding(match_value="*", agent_id=agent.id)],
),
session=SessionSettings(chat_model_config={"type": "test"}),
- created_at="t",
- updated_at="t",
)
return user_id, agent, session, channel
diff --git a/tests/storage_sql_test.py b/tests/storage_sql_test.py
index 2e20c95f4..624ce1c81 100644
--- a/tests/storage_sql_test.py
+++ b/tests/storage_sql_test.py
@@ -11,13 +11,20 @@ stay behavioural equivalents.
"""
from contextlib import AsyncExitStack
from datetime import datetime, timedelta
+from importlib import import_module
+from unittest import TestCase
from unittest.async_case import IsolatedAsyncioTestCase
from pydantic import SecretStr
+from sqlalchemy.dialects import mysql
+
+from utils import AnyString
from agentscope.app.storage import (
AgentData,
AgentRecord,
+ ChannelBinding,
+ ChannelRecord,
ChatModelConfig,
EmbeddingModelConfig,
KnowledgeBaseData,
@@ -25,9 +32,11 @@ from agentscope.app.storage import (
KnowledgeDocumentData,
KnowledgeDocumentRecord,
MCPRecord,
+ RoutingConfig,
ScheduleData,
ScheduleRecord,
SessionConfig,
+ SessionSettings,
SessionSource,
SkillRecord,
AsyncSQLAlchemyStorage,
@@ -35,12 +44,37 @@ from agentscope.app.storage import (
TeamMember,
TeamRecord,
)
+from agentscope.app.storage._sql._tables import ChannelRow
from agentscope.agent import ContextConfig, ReActConfig
from agentscope.credential import DashScopeCredential
from agentscope.mcp import HttpMCPConfig, MCPClient
from agentscope.message import AssistantMsg, UserMsg
+def _channel_record(
+ channel_id: str,
+ user_id: str = "user-1",
+) -> ChannelRecord:
+ """Build a minimal but complete :class:`ChannelRecord`."""
+ return ChannelRecord(
+ id=channel_id,
+ channel_type="feishu",
+ user_id=user_id,
+ credentials={"app_id": channel_id},
+ routing=RoutingConfig(
+ bindings=[ChannelBinding(match_value="*", agent_id="agent-x")],
+ ),
+ session=SessionSettings(
+ chat_model_config={
+ "type": "openai",
+ "credential_id": "cred-1",
+ "model": "gpt-4o",
+ "parameters": {},
+ },
+ ),
+ )
+
+
def _agent_record(user_id: str, name: str = "agent-x") -> AgentRecord:
"""Build a minimal but complete :class:`AgentRecord`."""
return AgentRecord(
@@ -887,6 +921,131 @@ class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):
await self.storage.get_mcp_by_name("user-1", "shared"),
)
+ # ------------------------------------------------------------------
+ # Channels
+ # ------------------------------------------------------------------
+
+ async def test_channels_round_trip(self) -> None:
+ """Upsert / get / list / list-all / delete + the bot-id lookup."""
+ record = ChannelRecord(
+ id="chan-1",
+ channel_type="feishu",
+ name="产品群机器人",
+ user_id="user-1",
+ credentials={"app_id": "cli-1", "app_secret": "s3cret"},
+ platform_config={"only_at_reply": True},
+ routing=RoutingConfig(
+ bindings=[
+ ChannelBinding(match_value="*", agent_id="agent-x"),
+ ],
+ ),
+ session=SessionSettings(
+ chat_model_config={
+ "type": "openai",
+ "credential_id": "cred-1",
+ "model": "gpt-4o",
+ "parameters": {},
+ },
+ ),
+ )
+ await self.storage.upsert_channel(record, "cli-1")
+
+ fetched = await self.storage.get_channel("chan-1")
+ self.assertDictEqual(
+ fetched.model_dump(mode="json"),
+ {
+ "id": "chan-1",
+ "channel_type": "feishu",
+ "name": "产品群机器人",
+ "user_id": "user-1",
+ "enabled": True,
+ "credentials": {"app_id": "cli-1", "app_secret": "s3cret"},
+ "platform_config": {"only_at_reply": True},
+ "routing": {
+ "bindings": [
+ {
+ "match_key": "chat_id",
+ "match_value": "*",
+ "agent_id": "agent-x",
+ "session_scope": "per_chat",
+ },
+ ],
+ },
+ "session": {
+ "chat_model_config": {
+ "type": "openai",
+ "credential_id": "cred-1",
+ "model": "gpt-4o",
+ "parameters": {},
+ },
+ "fallback_chat_model_config": None,
+ "permission_mode": "default",
+ },
+ "created_at": AnyString(),
+ "updated_at": AnyString(),
+ },
+ )
+
+ self.assertListEqual(
+ [c.id for c in await self.storage.list_channels("user-1")],
+ ["chan-1"],
+ )
+ self.assertListEqual(await self.storage.list_channels("user-2"), [])
+ self.assertListEqual(
+ [c.id for c in await self.storage.list_all_channels()],
+ ["chan-1"],
+ )
+
+ self.assertEqual(
+ await self.storage.get_channel_id_by_platform_bot_id("cli-1"),
+ "chan-1",
+ )
+ self.assertIsNone(
+ await self.storage.get_channel_id_by_platform_bot_id("nope"),
+ )
+
+ self.assertTrue(await self.storage.delete_channel("chan-1", "cli-1"))
+ self.assertFalse(await self.storage.delete_channel("chan-1", "cli-1"))
+ self.assertIsNone(await self.storage.get_channel("chan-1"))
+ self.assertIsNone(
+ await self.storage.get_channel_id_by_platform_bot_id("cli-1"),
+ )
+
+ async def test_platform_bot_id_is_globally_unique(self) -> None:
+ """A second channel may not claim a bot already bound elsewhere,
+ even under a different owner.
+
+ Rejected before the write rather than by the UNIQUE constraint:
+ MySQL's ``ON DUPLICATE KEY UPDATE`` fires on any unique-key
+ conflict, so leaving it to the constraint would overwrite the
+ holder there while raising on SQLite and Postgres.
+ """
+ await self.storage.upsert_channel(_channel_record("chan-1"), "cli-1")
+ with self.assertRaises(ValueError):
+ await self.storage.upsert_channel(
+ _channel_record("chan-2", user_id="user-2"),
+ "cli-1",
+ )
+
+ held = await self.storage.get_channel("chan-1")
+ self.assertEqual(held.user_id, "user-1")
+ self.assertIsNone(await self.storage.get_channel("chan-2"))
+
+ async def test_rebinding_a_channel_frees_the_old_bot_id(self) -> None:
+ """Re-upserting the same channel under a new bot id moves the
+ uniqueness claim with it."""
+ record = _channel_record("chan-1")
+ await self.storage.upsert_channel(record, "cli-1")
+ await self.storage.upsert_channel(record, "cli-2")
+
+ self.assertIsNone(
+ await self.storage.get_channel_id_by_platform_bot_id("cli-1"),
+ )
+ self.assertEqual(
+ await self.storage.get_channel_id_by_platform_bot_id("cli-2"),
+ "chan-1",
+ )
+
class AsyncSQLAlchemyStorageAutoMigrateTest(IsolatedAsyncioTestCase):
"""Boot via ``auto_migrate=True`` and confirm the schema is live.
@@ -917,6 +1076,58 @@ class AsyncSQLAlchemyStorageAutoMigrateTest(IsolatedAsyncioTestCase):
fetched = await storage.get_agent("user-1", agent.id)
self.assertEqual(fetched.id, agent.id)
+ async def test_migrations_alone_create_the_channels_table(self) -> None:
+ """``create_tables=False`` isolates the Alembic path, so a broken
+ or missing 0003 fails here instead of being masked by
+ ``metadata.create_all``."""
+ import os
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as tmp:
+ url = f"sqlite+aiosqlite:///{os.path.join(tmp, 'as.db')}"
+
+ async with AsyncSQLAlchemyStorage(
+ url,
+ auto_migrate=True,
+ create_tables=False,
+ ) as storage:
+ await storage.upsert_channel(
+ _channel_record("chan-1"),
+ "cli-1",
+ )
+ self.assertEqual(
+ await storage.get_channel_id_by_platform_bot_id("cli-1"),
+ "chan-1",
+ )
+
+
+class ChannelTimestampPrecisionTest(TestCase):
+ """``channels.updated_at`` is the channel's configuration version.
+
+ The client cache and the dispatcher compare it for equality, so a
+ MySQL ``DATETIME`` rounded to whole seconds would let two edits one
+ second apart share a version and leave the second one unapplied.
+ """
+
+ def test_mysql_keeps_microseconds(self) -> None:
+ """Both timestamps carry ``fsp=6`` on MySQL, and the migration
+ that creates the table agrees with the ORM metadata."""
+ migration = import_module(
+ "agentscope.app.storage._sql._alembic.versions.0003_channels",
+ )
+ dialect = mysql.dialect()
+ self.assertListEqual(
+ [
+ type_.compile(dialect)
+ for type_ in (
+ ChannelRow.__table__.c.created_at.type,
+ ChannelRow.__table__.c.updated_at.type,
+ migration.VERSION_TIMESTAMP,
+ )
+ ],
+ ["DATETIME(6)", "DATETIME(6)", "DATETIME(6)"],
+ )
+
class LegacyRecordShapeTest(IsolatedAsyncioTestCase):
"""The ``mode='before'`` validators absorb pre-refactor payloads.