PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix(billing): 修复钱包外键死锁与资产任务异常回滚
yi323b45499269
diff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.pyindex 7e172f7..fc6a055 100644--- a/backend/app/services/billing/settlement.py+++ b/backend/app/services/billing/settlement.py@@ -61,12 +61,14 @@ async def _ledger(async def _lock_user(db: AsyncSession, user_id: int) -> User | None:- """行锁用户钱包,避免并发预扣/结算透支;populate_existing 防止会话内过期余额。"""+ """串行化钱包写入,同时允许用量行对 users.id 的外键 KEY SHARE 校验。"""return (await db.execute(select(User).where(User.id == int(user_id))- .with_for_update()+ # 余额更新不修改用户主键;FOR UPDATE 会阻塞 usage_events 外键校验,+ # 与资产/任务锁形成死锁。NO KEY UPDATE 仍互斥其他钱包写入。+ .with_for_update(key_share=True).execution_options(populate_existing=True))).scalar_one_or_none()diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex 20d5c67..4d19717 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -1871,6 +1871,8 @@ async def run_asset_image_job(from app.services.exc_format import format_exception_messageerr_text = format_exception_message(exc, fallback="生图失败", limit=500)+ # flush 失败后 Session 不可继续查询;回滚未提交交付,再记录原始异常。+ await db.rollback()if asset_id:asset = await db.get(DramaAsset, asset_id)if asset:@@ -2025,6 +2027,8 @@ async def run_asset_video_job(from app.services.exc_format import format_exception_messagefrom app.services.storage import RetryableMediaDownloadError+ # 用量或交付 flush 可能已失败,必须先恢复事务再读取资产和保存状态。+ await db.rollback()if isinstance(exc, RetryableMediaDownloadError) and exc.provider_task_id:asset = await db.get(DramaAsset, asset_id)if asset:diff --git a/backend/tests/test_billing_wallet_lock_concurrency.py b/backend/tests/test_billing_wallet_lock_concurrency.pynew file mode 100644index 0000000..f96bb85--- /dev/null+++ b/backend/tests/test_billing_wallet_lock_concurrency.py@@ -0,0 +1,53 @@+"""PostgreSQL 钱包写锁应串行化扣款,同时允许用量外键校验。"""+import uuid++import pytest+from sqlalchemy import text+from sqlalchemy.exc import DBAPIError+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++import app.models_teams # noqa: F401+from app.config import get_settings+from app.models import User+from app.services.billing.settlement import _lock_user+from tests.conftest import _ensure_test_database, _resolve_test_database_url+++async def test_wallet_lock_allows_usage_fk_and_still_serializes_writers():+ """独立测试库和临时 schema,不接触业务表;复现线上 users 外键锁冲突。"""+ url, name = _resolve_test_database_url(get_settings().database_url)+ await _ensure_test_database(url, name)+ schema = "wallet_lock_" + uuid.uuid4().hex+ admin = create_async_engine(url)+ engine = create_async_engine(url, connect_args={"server_settings": {"search_path": schema}})+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ try:+ async with admin.begin() as conn:+ await conn.execute(text(f'CREATE SCHEMA "{schema}"'))+ async with engine.begin() as conn:+ await conn.run_sync(User.__table__.create)+ await conn.execute(text("CREATE TABLE usage_fk_probe (user_id integer REFERENCES users(id))"))+ async with sessions() as db:+ db.add(User(id=1, email="[email protected]", hashed_password="unused", balance_fen=1000))+ await db.commit()+ async with sessions() as wallet, sessions() as usage, sessions() as contender:+ owner = await _lock_user(wallet, 1)+ owner.balance_fen -= 100+ await wallet.flush()+ await usage.execute(text("SET LOCAL lock_timeout = '300ms'"))+ # usage_events INSERT 对 users.id 的外键检查需要 KEY SHARE。+ await usage.execute(text("INSERT INTO usage_fk_probe (user_id) VALUES (1)"))+ await usage.commit()+ await contender.execute(text("SET LOCAL lock_timeout = '300ms'"))+ with pytest.raises(DBAPIError) as error:+ await _lock_user(contender, 1)+ assert error.value.orig.sqlstate == "55P03"+ await contender.rollback()+ await wallet.commit()+ owner = await _lock_user(contender, 1)+ assert owner.balance_fen == 900+ finally:+ await engine.dispose()+ async with admin.begin() as conn:+ await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))+ await admin.dispose()diff --git a/backend/tests/test_drama_asset_transaction_failure.py b/backend/tests/test_drama_asset_transaction_failure.pynew file mode 100644index 0000000..eeea499--- /dev/null+++ b/backend/tests/test_drama_asset_transaction_failure.py@@ -0,0 +1,55 @@+"""资产用量 flush 失败后,必须回滚再保存失败状态,保留原始异常。"""+from pathlib import Path++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++import app.models_teams # noqa: F401+from app.models import User+from app.models_drama import DramaAsset, DramaProject, DramaScript+from app.services.drama import jobs++[email protected]("kind", ["image", "video"])+async def test_asset_job_recovers_failed_flush(tmp_path: Path, monkeypatch, kind: str):+ """真实数据库使 Session 进入 pending rollback;失败处理仍须可写库。"""+ engine = create_async_engine(f"sqlite+aiosqlite:///{(tmp_path / 'assets.db').as_posix()}")+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ try:+ async with engine.begin() as conn:+ for model in (User, DramaProject, DramaScript, DramaAsset):+ await conn.run_sync(model.__table__.create)+ async with sessions() as db:+ db.add(User(id=1, email="[email protected]", hashed_password="unused"))+ db.add(DramaProject(id=1, user_id=1, title="资产事务测试"))+ db.add(DramaAsset(id=1, project_id=1, type="none", name="镜头", asset_type=kind,+ url="/static/previous.mp4", params={"visualPrompt": "镜头"}))+ await db.commit()++ async def failed_generation(db, _user, _project, *args, **kwargs):+ """模拟交付过程中用量落库失败,留下未提交的资产修改。"""+ asset = await db.get(DramaAsset, 1)+ asset.url = "/static/uncommitted.mp4"+ db.add(User(email="[email protected]", hashed_password="duplicate"))+ await db.flush()++ async def resolve_prompt(*args, **kwargs):+ return "镜头"++ monkeypatch.setattr(jobs, "AsyncSessionLocal", sessions)+ monkeypatch.setattr(jobs, f"generate_asset_{kind}", failed_generation)+ monkeypatch.setattr(jobs, "resolve_visual_prompt_for_asset", resolve_prompt)+ if kind == "video":+ result = await jobs.run_asset_video_job(1, 1, "镜头", 1)+ else:+ result = await jobs.run_asset_image_job(1, 1, "镜头", asset_id=1, name="镜头", kind="none")+ assert result["ok"] is False+ assert "IntegrityError" in result["error"]+ assert "PendingRollbackError" not in result["error"]+ async with sessions() as db:+ asset = await db.get(DramaAsset, 1)+ assert asset.params["generation"]["status"] == "failed"+ assert "IntegrityError" in asset.params["generation"]["error"]+ assert asset.url == "/static/previous.mp4"+ finally:+ await engine.dispose()diff --git a/docs/BILLING.md b/docs/BILLING.mdindex 1dcd7ca..5691db1 100644--- a/docs/BILLING.md+++ b/docs/BILLING.md@@ -13,6 +13,7 @@- **所有 AI 调用**均关联 `task_run_id`(单次聊天/API/工具调用创建轻量 TaskRun)。- 本地按时长估算的视频 tokens 使用 `tokens_estimated` 标记,不能被识别为上游实测用量;实际费用仍优先取上游账单。- 画布视频下载中断时保留原上游任务号,按退避策略重试获取成片,不重新创建视频生成请求;超过重试上限后保留原任务号供排查。+- 钱包余额写入使用 PostgreSQL `FOR NO KEY UPDATE` 行锁,保持扣款互斥,同时允许 `usage_events` 对用户主键的外键校验,避免与画布资产、任务状态写入形成循环等待。资产生图/视频落库失败后先回滚,再记录原始异常和失败状态。## 公式