Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

Refactor A2A migration logic to enhance handling of the source_user_id column. Updated the column length from 64 to 256 characters to accommodate longer user IDs. Improved migration checks to ensure proper widening of the column type without data loss. Added unit tests to validate the new behavior and ensure idempotency of schema upgrades.

NickFuryXXX97f8e40828ec
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py
index f38e503ff7..e54e0f2d17 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py
@@ -8,7 +8,7 @@ from .a2a_models import A2A_OUTBOUND_DISPATCH_TABLE_DEF
async def ensure_dispatch_user_column(engine: AsyncEngine) -> None:
- """Add the nullable owner before init_table creates its declared index."""
+ """Add or widen the nullable owner without assigning legacy ownership."""
table_name = A2A_OUTBOUND_DISPATCH_TABLE_DEF.table_name
column = next(
col
@@ -16,29 +16,52 @@ async def ensure_dispatch_user_column(engine: AsyncEngine) -> None:
if col.name == "source_user_id"
)
- def has_owner(connection):
+ def owner_column(connection):
inspector = inspect(connection)
- return inspector.has_table(table_name) and any(
- col["name"] == column.name for col in inspector.get_columns(table_name)
+ if not inspector.has_table(table_name):
+ return None
+ return next(
+ (col for col in inspector.get_columns(table_name) if col["name"] == column.name),
+ None,
+ )
+
+ def needs_widening(connection, owner):
+ # SQLite does not enforce VARCHAR length; no table rebuild is needed.
+ length = getattr(owner["type"], "length", None)
+ return (
+ connection.dialect.name in {"mysql", "postgresql"}
+ and length is not None and length < column.length
)
def upgrade(connection):
- if not inspect(connection).has_table(table_name) or has_owner(connection):
+ if not inspect(connection).has_table(table_name):
return
+ owner = owner_column(connection)
quote = connection.dialect.identifier_preparer.quote
- connection.execute(
- text(
- f"ALTER TABLE {quote(table_name)} ADD COLUMN "
- f"{quote(column.name)} VARCHAR({column.length}) NULL"
+ prefix = f"ALTER TABLE {quote(table_name)}"
+ field = f"{quote(column.name)} VARCHAR({column.length})"
+ if owner is None:
+ statement = f"{prefix} ADD COLUMN {field} NULL"
+ elif not needs_widening(connection, owner):
+ return
+ elif connection.dialect.name == "mysql":
+ statement = f"{prefix} MODIFY COLUMN {field} NULL"
+ else:
+ statement = (
+ f"{prefix} ALTER COLUMN {quote(column.name)} TYPE VARCHAR({column.length})"
)
- )
+ connection.execute(text(statement))
+
+ def owner_ready(connection):
+ owner = owner_column(connection)
+ return owner is not None and not needs_widening(connection, owner)
try:
async with engine.begin() as connection:
await connection.run_sync(upgrade)
except DBAPIError:
- # Another Gateway may have added it concurrently. Verify after rollback;
+ # Another Gateway may have added or widened it concurrently. Verify after rollback;
# all other failures must prevent startup with a partially upgraded table.
async with engine.connect() as connection:
- if not await connection.run_sync(has_owner):
+ if not await connection.run_sync(owner_ready):
raise
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py
index 3d30565845..34c2f1f278 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py
@@ -56,7 +56,7 @@ A2A_OUTBOUND_DISPATCH_TABLE_DEF = TableDefinition(
ColumnDefinition("request_message_id", "string", length=100, nullable=False),
ColumnDefinition("source_session_id", "string", length=512, nullable=False),
ColumnDefinition("source_resource_id", "string", length=100, nullable=True),
- ColumnDefinition("source_user_id", "string", length=64, nullable=True),
+ ColumnDefinition("source_user_id", "string", length=256, nullable=True),
ColumnDefinition("remote_task_id", "string", length=256, nullable=True),
ColumnDefinition("remote_context_id", "string", length=256, nullable=True),
ColumnDefinition("accepted_at", "datetime", nullable=True),
diff --git a/tests/unit_tests/gateway/test_a2a_history_migration.py b/tests/unit_tests/gateway/test_a2a_history_migration.py
index e68e8c62fe..ca3e79ff52 100644
--- a/tests/unit_tests/gateway/test_a2a_history_migration.py
+++ b/tests/unit_tests/gateway/test_a2a_history_migration.py
@@ -94,6 +94,7 @@ async def test_a2a_schema_upgrade_is_idempotent_and_does_not_claim_history(
("a1", "alice", 1),
("a2", "alice", 2),
("b1", "bob", 3),
+ ("long", "u" * 256, 4),
]:
await handler.create(
table.table_name,
@@ -113,7 +114,100 @@ async def test_a2a_schema_upgrade_is_idempotent_and_does_not_claim_history(
result = await A2AOutboundRegistry(repository).list_dispatches(
limit=1, source_user_id="alice"
)
+ long_result = await A2AOutboundRegistry(repository).list_dispatches(
+ limit=1, source_user_id="u" * 256
+ )
+ assert long_result["total"] == 1
+ assert long_result["items"][0]["dispatch_id"] == "long"
assert result["total"] == 2
assert [item["dispatch_id"] for item in result["items"]] == ["a2"]
finally:
await handler.disconnect()
+
+
[email protected]("dialect_name,length,expected", [
+ ("postgresql", 64, "ALTER COLUMN source_user_id TYPE VARCHAR(256)"),
+ ("mysql", 64, "MODIFY COLUMN source_user_id VARCHAR(256) NULL"),
+ ("postgresql", 256, None), ("mysql", 512, None), ("sqlite", 64, None),
+])
+async def test_existing_owner_column_widening(monkeypatch, dialect_name, length, expected):
+ from contextlib import asynccontextmanager
+ from types import SimpleNamespace
+ from sqlalchemy import String
+ from sqlalchemy.dialects import mysql, postgresql, sqlite
+ from jiuwenswarm.gateway.config.enterprise.tables import a2a_migration
+
+ dialect = {"mysql": mysql, "postgresql": postgresql, "sqlite": sqlite}[dialect_name].dialect()
+ owner = {"name": "source_user_id", "type": String(length)}
+ statements = []
+ inspector = SimpleNamespace(has_table=lambda name: True, get_columns=lambda name: [owner])
+ monkeypatch.setattr(a2a_migration, "inspect", lambda connection: inspector)
+
+ class Connection:
+ async def run_sync(self, callback):
+ return callback(self)
+
+ def execute(self, statement):
+ statements.append(str(statement))
+ owner["type"] = String(256)
+
+ connection = Connection()
+ connection.dialect = dialect
+
+ @asynccontextmanager
+ async def begin():
+ yield connection
+
+ engine = SimpleNamespace(begin=begin)
+ await a2a_migration.ensure_dispatch_user_column(engine)
+ await a2a_migration.ensure_dispatch_user_column(engine)
+ assert statements == ([] if expected is None else [f"ALTER TABLE a2a_outbound_dispatch {expected}"])
+
+
[email protected]("final_length", [64, 256])
+async def test_failed_widening_requires_verified_final_length(monkeypatch, final_length):
+ from contextlib import asynccontextmanager
+ from types import SimpleNamespace
+ from sqlalchemy import String
+ from sqlalchemy.dialects import postgresql
+ from sqlalchemy.exc import DBAPIError
+ from jiuwenswarm.gateway.config.enterprise.tables import a2a_migration
+
+ owner = {"name": "source_user_id", "type": String(64)}
+ events = []
+ failure = DBAPIError("ALTER TABLE", {}, Exception("DDL failed"))
+ inspector = SimpleNamespace(has_table=lambda name: True, get_columns=lambda name: [owner])
+ monkeypatch.setattr(a2a_migration, "inspect", lambda connection: inspector)
+
+ class Connection:
+ dialect = postgresql.dialect()
+
+ async def run_sync(self, callback):
+ return callback(self)
+
+ def execute(self, statement):
+ raise failure
+
+ @asynccontextmanager
+ async def begin():
+ try:
+ yield Connection()
+ finally:
+ events.append("rollback")
+ owner["type"] = String(final_length)
+
+ @asynccontextmanager
+ async def connect():
+ events.append("verify")
+ yield Connection()
+
+ engine = SimpleNamespace(begin=begin, connect=connect)
+ if final_length == 256:
+ await a2a_migration.ensure_dispatch_user_column(engine)
+ else:
+ with pytest.raises(DBAPIError) as caught:
+ await a2a_migration.ensure_dispatch_user_column(engine)
+ assert caught.value is failure
+ assert events == ["rollback", "verify"]