diff --git a/app/infrastructure/repositories.py b/app/infrastructure/repositories.py index 9ffbbf9..352f5c6 100644 --- a/app/infrastructure/repositories.py +++ b/app/infrastructure/repositories.py @@ -1864,7 +1864,14 @@ class Database: if self._engine is not None: async with self._engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) - await seed_data(self.session) + # 种子容错:个别幂等保护不严的地方(如 demo 用户固定 agent id)可能触发唯一冲突, + # 不能让种子失败拖垮 lifespan 建库,否则 app.state.db 未设置→全部 500。 + try: + await seed_data(self.session) + except Exception as e: # noqa: BLE001 + import logging + logging.getLogger("servercore").warning("种子数据写入失败(忽略,应用仍可用): %s", e) + await self.session.rollback() async def close(self) -> None: if self._owns_session: diff --git a/app/infrastructure/seed.py b/app/infrastructure/seed.py index 9ad2935..19608c1 100644 --- a/app/infrastructure/seed.py +++ b/app/infrastructure/seed.py @@ -1045,12 +1045,12 @@ async def _ensure_port_agents(session: AsyncSession, now: str) -> None: if (user_id, port) in seen: continue seen.add((user_id, port)) - existing = await session.scalar( - select(Agent.id).where(Agent.user_id == user_id, Agent.port == port).limit(1) + existing_ids = set( + (await session.execute(select(Agent.id).where(Agent.user_id == user_id, Agent.port == port))).scalars() ) - if existing is not None: - continue for seed in AGENT_SEED: + if seed["id"] in existing_ids: + continue # 已存在,跳过(幂等,避免 (id,user_id,port) 唯一冲突) session.add( Agent( id=seed["id"], user_id=user_id, port=port, name=seed["name"],