feat: 岗位会商命令幂等与圆桌后台作业租约调度

岗位会商写操作引入 command_id 幂等与版本锁,前端支持同键重试;圆桌后台作业改为 DB 租约 dispatcher、去重与草稿 outbox 补偿,并持久化 intent turns。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-14 11:08:12 +08:00
1 parent 4f536d9b39
commit 75963c9ad9
51 files changed
+4449 -670

No files matched your search

@@ -130,7 +130,7 @@ async def _run_alembic_upgrade(url: str) -> None:
try:
await asyncio.wait_for(asyncio.to_thread(_do_upgrade), timeout=timeout_s)
logger.info("Alembic migrations applied (or already up-to-date)")
except asyncio.TimeoutError:
except TimeoutError:
logger.error(
"Alembic upgrade did not finish within %.0fs; continuing startup on create_all schema. "
"Likely cause: MySQL metadata-lock wait — check SHOW FULL PROCESSLIST for a blocking transaction.",
@@ -213,12 +213,18 @@ def _ensure_orm_columns_sync(sync_conn) -> None:
This sweep compares each existing table against the ORM metadata and issues
``ALTER TABLE … ADD COLUMN`` for every missing column that can be added
safely (nullable, or carrying a server_default). Indexes covering a newly
added column are created as well. Works on sqlite/mysql/postgres — the
column DDL is compiled through the active dialect, so portable types
(``PortableJSON``/``PortableLongText``/``BeijingDateTime``) resolve to the
right backend type. Everything is per-column best-effort: a failure is
logged and startup continues.
added column are created as well. Table-level ``UniqueConstraint`` objects
that are declared on the model but missing from the table are also created
(as a ``CREATE UNIQUE INDEX`` of the same name, which is what the migrations
emit too, and works on SQLite/MySQL/PostgreSQL alike) — without this a newly
declared uniqueness rule (e.g. ``active_dedupe_key``) would silently be absent
on an existing database, weakening dedupe.
Works on sqlite/mysql/postgres — the column DDL is compiled through the
active dialect, so portable types (``PortableJSON``/``PortableLongText``/
``BeijingDateTime``) resolve to the right backend type. Everything is
per-column best-effort: a failure is logged and startup continues.
"""
from sqlalchemy import UniqueConstraint
from sqlalchemy import inspect as sa_inspect
from sqlalchemy.schema import CreateColumn
@@ -273,6 +279,48 @@ def _ensure_orm_columns_sync(sync_conn) -> None:
except Exception:
logger.exception("Failed to auto-create index %s on %s", idx.name, table.name)
# ── 表级 UNIQUE 约束补齐 ──────────────────────────────────────────────────
# create_all 只为全新表建 UniqueConstraint;既有表上新增声明的唯一约束(如
# roundtable_jobs.active_dedupe_key)会静默缺失,去重/幂等的正确性就靠它,故
# 这里显式补建。迁移可能用 CREATE UNIQUE INDEX(同名)实现唯一性,故同时查
# get_unique_constraints 与 get_indexes 的名字集合,避免重复建。
for table in Base.metadata.sorted_tables:
if table.name not in existing_tables:
continue
named_uqs = [
c for c in table.constraints
if isinstance(c, UniqueConstraint) and c.name is not None
]
if not named_uqs:
continue
try:
existing_uq_names = {
uq["name"] for uq in inspector.get_unique_constraints(table.name) if uq.get("name")
}
except Exception:
existing_uq_names = set()
try:
existing_idx_names = {
ix["name"] for ix in inspector.get_indexes(table.name) if ix.get("name")
}
except Exception:
existing_idx_names = set()
for uq in named_uqs:
if uq.name in existing_uq_names or uq.name in existing_idx_names:
continue
# 用 CREATE UNIQUE INDEX(而非 ALTER TABLE ADD CONSTRAINT):迁移本身也用
# CREATE UNIQUE INDEX,且它在 SQLite/MySQL/PostgreSQL 都受支持(SQLite 不
# 支持 ALTER TABLE ADD CONSTRAINT),功能等价地强制唯一性。
cols = ", ".join(preparer.quote(c.name) for c in uq.columns)
try:
sync_conn.exec_driver_sql(
f"CREATE UNIQUE INDEX {preparer.quote(uq.name)} "
f"ON {preparer.quote(table.name)} ({cols})"
)
logger.info("Auto-added unique index %s on %s", uq.name, table.name)
except Exception:
logger.exception("Failed to add unique index %s on %s", uq.name, table.name)
def _is_mysql_unknown_database_error(exc: Exception) -> bool:
message = str(exc).lower()
@@ -287,6 +335,7 @@ async def init_engine(
pool_size: int = 5,
max_overflow: int = 10,
pool_timeout: int = 30,
pool_recycle: int = 1800,
sqlite_dir: str = "",
) -> None:
"""Create the async engine and session factory, then auto-create tables.
@@ -298,6 +347,8 @@ async def init_engine(
pool_size: Base connection pool size (postgres/mysql).
max_overflow: Extra connections allowed beyond pool_size under load (postgres/mysql).
pool_timeout: Seconds to wait for a free pooled connection before erroring (postgres/mysql).
pool_recycle: Recycle connections after N seconds (postgres/mysql). Prevents stale
connections dropped by firewalls / MySQL wait_timeout / pgbouncer.
sqlite_dir: Directory to create for SQLite (ensured to exist).
"""
global _engine, _session_factory, _engine_loop
@@ -366,6 +417,7 @@ async def init_engine(
max_overflow=max_overflow,
pool_timeout=pool_timeout,
pool_pre_ping=True,
pool_recycle=pool_recycle,
json_serializer=_json_serializer,
)
elif backend == "mysql":
@@ -376,7 +428,7 @@ async def init_engine(
max_overflow=max_overflow,
pool_timeout=pool_timeout,
pool_pre_ping=True,
pool_recycle=1800,
pool_recycle=pool_recycle,
json_serializer=_json_serializer,
)
else:
@@ -407,7 +459,7 @@ async def init_engine(
await _auto_create_postgres_db(url)
# Rebuild engine against the now-existing database
await _engine.dispose()
_engine = create_async_engine(url, echo=echo, pool_size=pool_size, max_overflow=max_overflow, pool_timeout=pool_timeout, pool_pre_ping=True, json_serializer=_json_serializer)
_engine = create_async_engine(url, echo=echo, pool_size=pool_size, max_overflow=max_overflow, pool_timeout=pool_timeout, pool_pre_ping=True, pool_recycle=pool_recycle, json_serializer=_json_serializer)
_session_factory = async_sessionmaker(_engine, expire_on_commit=False)
async with _engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
@@ -423,7 +475,7 @@ async def init_engine(
max_overflow=max_overflow,
pool_timeout=pool_timeout,
pool_pre_ping=True,
pool_recycle=1800,
pool_recycle=pool_recycle,
json_serializer=_json_serializer,
)
_session_factory = async_sessionmaker(_engine, expire_on_commit=False)
@@ -460,6 +512,7 @@ async def init_engine_from_config(config) -> None:
pool_size=config.pool_size,
max_overflow=getattr(config, "max_overflow", 10),
pool_timeout=getattr(config, "pool_timeout", 30),
pool_recycle=getattr(config, "pool_recycle", 1800),
sqlite_dir=config.sqlite_dir if config.backend == "sqlite" else "",
)