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 error handling in A2A migration to provide more informative exceptions. Updated the exception handling in the ensure_dispatch_user_column function to raise the original DBAPIError for better debugging. Additionally, improved unit tests for A2A migration to ensure proper isolation and dependency management.

NickFuryXXX8552c439b84f
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py
index e54e0f2d17..3b37a0a313 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py
@@ -59,9 +59,9 @@ async def ensure_dispatch_user_column(engine: AsyncEngine) -> None:
try:
async with engine.begin() as connection:
await connection.run_sync(upgrade)
- except DBAPIError:
+ except DBAPIError as exc:
# 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(owner_ready):
- raise
+ raise exc
diff --git a/tests/unit_tests/gateway/test_a2a_history_migration.py b/tests/unit_tests/gateway/test_a2a_history_migration.py
index ca3e79ff52..016afb1d15 100644
--- a/tests/unit_tests/gateway/test_a2a_history_migration.py
+++ b/tests/unit_tests/gateway/test_a2a_history_migration.py
@@ -1,128 +1,118 @@
-"""Exercise real SQLite schema upgrades without assigning legacy ownership."""
+"""A2A migration unit tests using stdlib SQLite and isolated dependency doubles."""
-from dataclasses import replace
-from datetime import datetime
+import builtins
+import importlib.util
+import re
+import sqlite3
+from contextlib import asynccontextmanager, closing
+from pathlib import Path
+from types import SimpleNamespace
import pytest
-from sqlalchemy import inspect, text
-from openjiuwen_runtime.foundation.db.sqlite_handler import SQLiteHandler
-
-from jiuwenswarm.gateway.config.enterprise.tables.a2a_models import (
- A2A_OUTBOUND_DISPATCH_TABLE_DEF,
-)
-from jiuwenswarm.gateway.config.enterprise.tables.table_init import init_all_tables
-from jiuwenswarm.gateway.config.enterprise.tables import table_init
-from jiuwenswarm.gateway.a2a_manager.outbound.registry import A2AOutboundRegistry
-from jiuwenswarm.gateway.storage.backends.db.persistent_store import DbPersistentBackend
-from jiuwenswarm.gateway.storage_assembly import (
- build_gateway_store_registry,
- create_a2a_outbound_repository,
-)
+
+
+class DBAPIError(Exception):
+ pass
+
+
+def _dialect(name):
+ return SimpleNamespace(name=name, identifier_preparer=SimpleNamespace(quote=lambda value: value))
+
+
+class _Definition:
+ def __init__(self, *args, **kwargs):
+ self.args = args
+ self.__dict__.update(kwargs)
+ if args:
+ self.name = args[0]
+
+
+def migration():
+ # Execute the real source with per-module imports. No global sys.modules stubs
+ # and no optional runtime/SQLAlchemy imports leak into other tests.
+ root = Path(__file__).resolve().parents[3] / "jiuwenswarm/gateway/config/enterprise/tables"
+ dependencies = {
+ "openjiuwen_runtime.foundation.db.table_def": SimpleNamespace(
+ ColumnDefinition=_Definition, IndexDefinition=_Definition, TableDefinition=_Definition,
+ ),
+ "sqlalchemy": SimpleNamespace(inspect=lambda connection: connection, text=lambda sql: sql),
+ "sqlalchemy.exc": SimpleNamespace(DBAPIError=DBAPIError),
+ "sqlalchemy.ext.asyncio": SimpleNamespace(AsyncEngine=object),
+ }
+
+ def import_dependency(name, globals=None, locals=None, fromlist=(), level=0):
+ if name in dependencies:
+ return dependencies[name]
+ if name.startswith(("sqlalchemy", "openjiuwen_runtime")):
+ raise AssertionError(f"Unexpected optional dependency: {name}")
+ return builtins.__import__(name, globals, locals, fromlist, level)
+
+ def load(name):
+ spec = importlib.util.spec_from_file_location(name, root / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ module.__dict__["__builtins__"] = {**vars(builtins), "__import__": import_dependency}
+ spec.loader.exec_module(module)
+ return module
+
+ dependencies["a2a_models"] = load("a2a_models")
+ return load("a2a_migration")
+
+
+class _SQLiteConnection:
+ dialect = _dialect("sqlite")
+
+ def __init__(self, db):
+ self.db = db
+
+ async def run_sync(self, callback):
+ return callback(self)
+
+ def has_table(self, name):
+ return self.db.execute(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,),
+ ).fetchone() is not None
+
+ def get_columns(self, name):
+ return [
+ {"name": row[1], "type": SimpleNamespace(
+ length=int(re.search(r"\d+", row[2]).group()) if re.search(r"\d+", row[2]) else None,
+ )}
+ for row in self.db.execute(f"PRAGMA table_info({name})")
+ ]
+
+ def execute(self, statement):
+ return self.db.execute(statement)
@pytest.mark.asyncio
- "ignore:This declarative base already contains a class:sqlalchemy.exc.SAWarning"
-)
[email protected]("legacy", [True, False])
-async def test_a2a_schema_upgrade_is_idempotent_and_does_not_claim_history(
- tmp_path, monkeypatch, legacy
-):
- handler = SQLiteHandler(str(tmp_path / "gateway.db"))
- await handler.connect()
- table = A2A_OUTBOUND_DISPATCH_TABLE_DEF
- monkeypatch.setattr(table_init, "ALL_TABLE_DEFINITIONS", (table,))
- monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
- try:
- if legacy:
- old = replace(
- table,
- columns=[col for col in table.columns if col.name != "source_user_id"],
- indexes=[
- idx for idx in table.indexes if "source_user_id" not in idx.columns
- ],
- )
- await handler.init_table(old)
- await handler.create(
- table.table_name,
- {
- "dispatch_id": "legacy",
- "agent_id": "agent",
- "agent_revision": 1,
- "mode": "async",
- "status": "completed",
- "request_message_id": "request",
- "source_session_id": "session",
- "created_at": datetime(2026, 9, 1),
- "updated_at": datetime(2026, 9, 1),
- },
- )
- await init_all_tables(handler)
- await init_all_tables(handler)
- async with handler.get_engine().connect() as connection:
- columns = await connection.run_sync(
- lambda c: inspect(c).get_columns(table.table_name)
- )
- owner = next(col for col in columns if col["name"] == "source_user_id")
- assert owner["nullable"] is True
- indexes = await connection.run_sync(
- lambda c: inspect(c).get_indexes(table.table_name)
- )
- assert (
- sum(
- idx["column_names"] == ["source_user_id", "created_at"]
- for idx in indexes
- )
- == 1
- )
- if legacy:
- result = await connection.execute(
- text(
- "SELECT source_user_id FROM a2a_outbound_dispatch WHERE dispatch_id='legacy'"
- )
- )
- assert result.one() == (None,)
-
- # Verify the actual database filter, not just the in-memory backend.
- class Connection:
- async def ensure_ready(self):
- return handler
-
- store = DbPersistentBackend(Connection(), build_gateway_store_registry())
- repository = create_a2a_outbound_repository(store)
- for name, user, day in [
- ("a1", "alice", 1),
- ("a2", "alice", 2),
- ("b1", "bob", 3),
- ("long", "u" * 256, 4),
- ]:
- await handler.create(
- table.table_name,
- {
- "dispatch_id": name,
- "agent_id": "agent",
- "agent_revision": 1,
- "mode": "async",
- "status": "completed",
- "request_message_id": name,
- "source_session_id": "session",
- "source_user_id": user,
- "created_at": datetime(2026, 9, day),
- "updated_at": datetime(2026, 9, day),
- },
- )
- 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
[email protected]("owner_length", [None, 64, 256])
+async def test_sqlite_migration_preserves_history_and_long_ids(migration, owner_length):
+ with closing(sqlite3.connect(":memory:")) as db:
+ owner_sql = "" if owner_length is None else f", source_user_id VARCHAR({owner_length}) NULL"
+ db.execute(f"CREATE TABLE a2a_outbound_dispatch (dispatch_id TEXT{owner_sql})")
+ db.execute("INSERT INTO a2a_outbound_dispatch (dispatch_id) VALUES ('legacy')")
+ connection = _SQLiteConnection(db)
+
+ @asynccontextmanager
+ async def begin():
+ with db:
+ yield connection
+
+ engine = SimpleNamespace(begin=begin, connect=begin)
+ await migration.ensure_dispatch_user_column(engine)
+ await migration.ensure_dispatch_user_column(engine)
+ assert db.execute("SELECT source_user_id FROM a2a_outbound_dispatch").fetchall() == [(None,)]
+ assert next(
+ col for col in migration.A2A_OUTBOUND_DISPATCH_TABLE_DEF.columns
+ if col.name == "source_user_id"
+ ).length == 256
+ db.execute(
+ "INSERT INTO a2a_outbound_dispatch VALUES (?, ?)", ("long-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()
+ assert db.execute(
+ "SELECT dispatch_id FROM a2a_outbound_dispatch WHERE source_user_id=?", ("u" * 256,),
+ ).fetchall() == [("long-id",)]
@pytest.mark.asyncio
@@ -131,15 +121,13 @@ async def test_a2a_schema_upgrade_is_idempotent_and_does_not_claim_history(
("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):
+async def test_existing_owner_column_widening(monkeypatch, migration, 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
+ a2a_migration = migration
- dialect = {"mysql": mysql, "postgresql": postgresql, "sqlite": sqlite}[dialect_name].dialect()
- owner = {"name": "source_user_id", "type": String(length)}
+ dialect = _dialect(dialect_name)
+ owner = {"name": "source_user_id", "type": SimpleNamespace(length=length)}
statements = []
inspector = SimpleNamespace(has_table=lambda name: True, get_columns=lambda name: [owner])
monkeypatch.setattr(a2a_migration, "inspect", lambda connection: inspector)
@@ -150,7 +138,7 @@ async def test_existing_owner_column_widening(monkeypatch, dialect_name, length,
def execute(self, statement):
statements.append(str(statement))
- owner["type"] = String(256)
+ owner["type"] = SimpleNamespace(length=256)
connection = Connection()
connection.dialect = dialect
@@ -167,22 +155,19 @@ async def test_existing_owner_column_widening(monkeypatch, dialect_name, length,
@pytest.mark.asyncio
@pytest.mark.parametrize("final_length", [64, 256])
-async def test_failed_widening_requires_verified_final_length(monkeypatch, final_length):
+async def test_failed_widening_requires_verified_final_length(monkeypatch, migration, 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
+ a2a_migration = migration
- owner = {"name": "source_user_id", "type": String(64)}
+ owner = {"name": "source_user_id", "type": SimpleNamespace(length=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()
+ dialect = _dialect("postgresql")
async def run_sync(self, callback):
return callback(self)
@@ -196,7 +181,7 @@ async def test_failed_widening_requires_verified_final_length(monkeypatch, final
yield Connection()
finally:
events.append("rollback")
- owner["type"] = String(final_length)
+ owner["type"] = SimpleNamespace(length=final_length)
@asynccontextmanager
async def connect():