PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix(billing): prevent double settle on fragment video poll
yifcc263bbbc48
diff --git a/backend/app/services/admin/stats.py b/backend/app/services/admin/stats.pyindex 09c4c40..409c830 100644--- a/backend/app/services/admin/stats.py+++ b/backend/app/services/admin/stats.py@@ -324,6 +324,135 @@ def _row_to_usage_summary(row: Any) -> dict[str, int]:}+def _deduped_usage_event_ids_subq():+ """+ 同一 task_run + billing_key 只保留最早一条用量行,避免并发重复记费把项目汇总抬高。+ 无 task_run_id 的孤儿行全部保留。+ """+ ranked = (+ select(+ UsageEvent.id.label("id"),+ func.row_number()+ .over(+ partition_by=(UsageEvent.task_run_id, UsageEvent.billing_key),+ order_by=UsageEvent.id.asc(),+ )+ .label("rn"),+ )+ .where(UsageEvent.task_run_id.is_not(None))+ .subquery()+ )+ with_task = select(ranked.c.id).where(ranked.c.rn == 1)+ orphans = select(UsageEvent.id).where(UsageEvent.task_run_id.is_(None))+ return with_task.union_all(orphans).subquery()+++async def _sum_task_charged_fen(+ db: AsyncSession,+ *,+ project_ids: list[int] | None = None,+ drama_project_ids: list[int] | None = None,+) -> dict[int, int]:+ """按任务实扣汇总(钱包结算口径)。"""+ from app.models_tasks import TaskRun++ if project_ids is not None:+ if not project_ids:+ return {}+ rows = (+ await db.execute(+ select(+ TaskRun.project_id,+ func.coalesce(func.sum(TaskRun.billing_charged_fen), 0),+ )+ .where(TaskRun.project_id.in_(project_ids))+ .group_by(TaskRun.project_id)+ )+ ).all()+ return {int(r[0]): int(r[1] or 0) for r in rows if r[0] is not None}++ if drama_project_ids is not None:+ if not drama_project_ids:+ return {}+ rows = (+ await db.execute(+ select(+ TaskRun.drama_project_id,+ func.coalesce(func.sum(TaskRun.billing_charged_fen), 0),+ )+ .where(TaskRun.drama_project_id.in_(drama_project_ids))+ .group_by(TaskRun.drama_project_id)+ )+ ).all()+ return {int(r[0]): int(r[1] or 0) for r in rows if r[0] is not None}+ return {}+++async def _sum_orphan_usage_charge_fen(+ db: AsyncSession,+ *,+ scope_col,+ scope_ids: list[int],+) -> dict[int, int]:+ """无 task_run_id 的用量扣费(未走 TaskRun 结算的历史/旁路行)。"""+ if not scope_ids:+ return {}+ rows = (+ await db.execute(+ select(+ scope_col,+ func.coalesce(func.sum(UsageEvent.charge_fen), 0),+ )+ .where(scope_col.in_(scope_ids), UsageEvent.task_run_id.is_(None))+ .group_by(scope_col)+ )+ ).all()+ return {int(r[0]): int(r[1] or 0) for r in rows if r[0] is not None}+++async def _aggregate_usage_by_scope(+ db: AsyncSession,+ *,+ scope_col,+ scope_ids: list[int],+ project_ids: list[int] | None = None,+ drama_project_ids: list[int] | None = None,+) -> dict[int, dict[str, Any]]:+ """按项目/漫剧项目聚合去重后的用量行;扣费用任务实扣+孤儿用量。"""+ image_case, video_case, llm_case, tts_case = _usage_billing_cases()+ empty = _empty_usage_summary()+ if not scope_ids:+ return {}+ deduped = _deduped_usage_event_ids_subq()+ result = await db.execute(+ select(+ scope_col,+ func.coalesce(func.sum(UsageEvent.charge_fen), 0),+ func.coalesce(func.sum(UsageEvent.cost_fen), 0),+ func.coalesce(func.sum(UsageEvent.total_tokens), 0),+ func.count(UsageEvent.id),+ func.coalesce(func.sum(image_case), 0),+ func.coalesce(func.sum(video_case), 0),+ func.coalesce(func.sum(llm_case), 0),+ func.coalesce(func.sum(tts_case), 0),+ )+ .where(scope_col.in_(scope_ids), UsageEvent.id.in_(select(deduped.c.id)))+ .group_by(scope_col)+ )+ out: dict[int, dict[str, Any]] = {pid: dict(empty) for pid in scope_ids}+ for row in result.all():+ out[int(row[0])] = _row_to_usage_summary(row[1:])++ charged_map = await _sum_task_charged_fen(+ db, project_ids=project_ids, drama_project_ids=drama_project_ids+ )+ orphan_map = await _sum_orphan_usage_charge_fen(db, scope_col=scope_col, scope_ids=scope_ids)+ for pid in scope_ids:+ if pid in charged_map or pid in orphan_map:+ out[pid]["charge_fen"] = int(charged_map.get(pid, 0)) + int(orphan_map.get(pid, 0))+ return out++async def aggregate_usage_summary(db: AsyncSession,*,@@ -336,77 +465,30 @@ async def aggregate_usage_summary(项目级用量汇总。- 单项目:传 project_id 或 drama_project_id,返回一条 dict- 批量:传 project_ids 或 drama_project_ids,返回 {id: dict}+ 扣费 = TaskRun 实扣 + 无任务孤儿用量;调用/成本按去重后的 usage 行统计。"""- image_case, video_case, llm_case, tts_case = _usage_billing_cases()empty = _empty_usage_summary()if project_ids is not None:- if not project_ids:- return {}- result = await db.execute(- select(- UsageEvent.project_id,- func.coalesce(func.sum(UsageEvent.charge_fen), 0),- func.coalesce(func.sum(UsageEvent.cost_fen), 0),- func.coalesce(func.sum(UsageEvent.total_tokens), 0),- func.count(UsageEvent.id),- func.coalesce(func.sum(image_case), 0),- func.coalesce(func.sum(video_case), 0),- func.coalesce(func.sum(llm_case), 0),- func.coalesce(func.sum(tts_case), 0),- )- .where(UsageEvent.project_id.in_(project_ids))- .group_by(UsageEvent.project_id)+ return await _aggregate_usage_by_scope(+ db,+ scope_col=UsageEvent.project_id,+ scope_ids=project_ids,+ project_ids=project_ids,)- out: dict[int, dict[str, Any]] = {pid: dict(empty) for pid in project_ids}- for row in result.all():- pid = int(row[0])- out[pid] = _row_to_usage_summary(row[1:])- return outif drama_project_ids is not None:- if not drama_project_ids:- return {}- result = await db.execute(- select(- UsageEvent.drama_project_id,- func.coalesce(func.sum(UsageEvent.charge_fen), 0),- func.coalesce(func.sum(UsageEvent.cost_fen), 0),- func.coalesce(func.sum(UsageEvent.total_tokens), 0),- func.count(UsageEvent.id),- func.coalesce(func.sum(image_case), 0),- func.coalesce(func.sum(video_case), 0),- func.coalesce(func.sum(llm_case), 0),- func.coalesce(func.sum(tts_case), 0),- )- .where(UsageEvent.drama_project_id.in_(drama_project_ids))- .group_by(UsageEvent.drama_project_id)+ return await _aggregate_usage_by_scope(+ db,+ scope_col=UsageEvent.drama_project_id,+ scope_ids=drama_project_ids,+ drama_project_ids=drama_project_ids,)- out_d: dict[int, dict[str, Any]] = {pid: dict(empty) for pid in drama_project_ids}- for row in result.all():- pid = int(row[0])- out_d[pid] = _row_to_usage_summary(row[1:])- return out_d- filters = []if project_id is not None:- filters.append(UsageEvent.project_id == project_id)- elif drama_project_id is not None:- filters.append(UsageEvent.drama_project_id == drama_project_id)- else:- return dict(empty)-- stmt = select(- func.coalesce(func.sum(UsageEvent.charge_fen), 0),- func.coalesce(func.sum(UsageEvent.cost_fen), 0),- func.coalesce(func.sum(UsageEvent.total_tokens), 0),- func.count(UsageEvent.id),- func.coalesce(func.sum(image_case), 0),- func.coalesce(func.sum(video_case), 0),- func.coalesce(func.sum(llm_case), 0),- func.coalesce(func.sum(tts_case), 0),- )- for clause in filters:- stmt = stmt.where(clause)- row = (await db.execute(stmt)).one()- return _row_to_usage_summary(row)+ batch = await aggregate_usage_summary(db, project_ids=[project_id])+ return batch.get(project_id, dict(empty))+ if drama_project_id is not None:+ batch = await aggregate_usage_summary(db, drama_project_ids=[drama_project_id])+ return batch.get(drama_project_id, dict(empty))+ return dict(empty)diff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.pyindex 63ad5b1..b4e46fb 100644--- a/backend/app/services/billing/settlement.py+++ b/backend/app/services/billing/settlement.py@@ -62,16 +62,26 @@ async def _ledger(async def _lock_user(db: AsyncSession, user_id: int) -> User | None:- """行锁用户钱包,避免并发预扣/结算透支。"""+ """行锁用户钱包,避免并发预扣/结算透支;populate_existing 防止会话内过期余额。"""return (- await db.execute(select(User).where(User.id == int(user_id)).with_for_update())+ await db.execute(+ select(User)+ .where(User.id == int(user_id))+ .with_for_update()+ .execution_options(populate_existing=True)+ )).scalar_one_or_none()async def _lock_task(db: AsyncSession, task_id: int) -> TaskRun | None:- """行锁 TaskRun,保证结算/预扣幂等。"""+ """行锁 TaskRun,保证结算/预扣幂等;populate_existing 防止会话内过期 billing_status。"""return (- await db.execute(select(TaskRun).where(TaskRun.id == int(task_id)).with_for_update())+ await db.execute(+ select(TaskRun)+ .where(TaskRun.id == int(task_id))+ .with_for_update()+ .execution_options(populate_existing=True)+ )).scalar_one_or_none()@@ -207,6 +217,35 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:"refunded": int(task.billing_refunded_fen or 0),}+ # 钱包侧幂等:已有 unfreeze/settle 流水则只对齐状态,禁止二次退还+ if task.billing_status == "frozen":+ prior = (+ await db.execute(+ select(WalletLedger.id)+ .where(+ WalletLedger.ref_type == "task_run",+ WalletLedger.ref_id == str(task_id),+ WalletLedger.kind.in_(("unfreeze", "settle")),+ )+ .limit(1)+ )+ ).scalar_one_or_none()+ if prior is not None:+ result = await db.execute(+ select(UsageEvent).where(+ UsageEvent.task_run_id == task_id,+ UsageEvent.settled.is_(False),+ )+ )+ for e in result.scalars().all():+ e.settled = True+ task.billing_status = "settled"+ await db.flush()+ return {+ "charged": int(task.billing_charged_fen or 0),+ "refunded": int(task.billing_refunded_fen or 0),+ }+result = await db.execute(select(UsageEvent).where(UsageEvent.task_run_id == task_id,@@ -214,6 +253,18 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:))events = list(result.scalars().all())+ # 用量已结但状态仍 frozen(异常中断):按已落账实扣对齐,禁止把整笔预扣当退款+ if (+ task.billing_status == "frozen"+ and not events+ and int(task.billing_charged_fen or 0) > 0+ ):+ task.billing_status = "settled"+ await db.flush()+ return {+ "charged": int(task.billing_charged_fen or 0),+ "refunded": int(task.billing_refunded_fen or 0),+ }if task.billing_status == "skipped" and not events:# 无限额且无用量:结算完成,统一标 settled 便于管理端展示task.billing_status = "settled"diff --git a/backend/app/services/drama/billing_util.py b/backend/app/services/drama/billing_util.pyindex cabfd13..9563c81 100644--- a/backend/app/services/drama/billing_util.py+++ b/backend/app/services/drama/billing_util.py@@ -4,11 +4,13 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.config import get_settingsfrom app.models import UsageEvent, Userfrom app.services.billing import record_line+from app.services.billing.context import get_current_task_run_idfrom app.services.drama.seed import SeedAssetsResultif TYPE_CHECKING:@@ -40,7 +42,26 @@ async def record_seedance_video_usage(project_id: int | None = None,shot_id: int | None = None,) -> UsageEvent:- """按官方任务 usage / 成本或时长估算写入 Seedance 视频用量行。"""+ """按官方任务 usage / 成本或时长估算写入 Seedance 视频用量行。++ 同一 task_run + billing_key 已有用量时幂等返回首行,避免并发收尾双记。+ """+ tid = get_current_task_run_id()+ if tid is not None:+ existing = (+ await db.execute(+ select(UsageEvent)+ .where(+ UsageEvent.task_run_id == int(tid),+ UsageEvent.billing_key == billing_key,+ )+ .order_by(UsageEvent.id.asc())+ .limit(1)+ )+ ).scalar_one_or_none()+ if existing is not None:+ return existing+if ((not task_result or int(getattr(task_result, "total_tokens", 0) or 0) <= 0)and provider_task_iddiff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex 38022ce..9e1b915 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -807,6 +807,7 @@ async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:async def poll_fragment_video_task(task_id: int) -> None:from app.services.ark import get_arkfrom app.services.billing.context import billing_scope+ from app.services.billing.settlement import _lock_taskfrom app.services.tasks.executor import _complete_task, _fail_taskfrom app.services.tasks.service import activate_next_sequential_task, get_task_for_runtime@@ -825,6 +826,15 @@ async def poll_fragment_video_task(task_id: int) -> None:poll_interval = max(1.0, float(get_settings().ark_video_poll_interval or 8.0))now = datetime.now(UTC)+ # 收尾认领窗口未到期:跳过,避免并发下载双记费+ if (task.current_step_status or "") == "finalizing":+ na = task.next_action_at+ if na is not None:+ if na.tzinfo is None:+ na = na.replace(tzinfo=UTC)+ if na > now:+ return+if task.cancel_requested or _is_episode_video_cancelled(episode_id):await _fail_task(db, task, RuntimeError("任务已取消"))return@@ -863,8 +873,20 @@ async def poll_fragment_video_task(task_id: int) -> None:await _fail_task(db, task, RuntimeError("分镜已变更,请重新生成"))return- task.current_step_status = "finalizing"- task.progress_percent = max(int(task.progress_percent or 0), 90)+ # 行锁认领:仅第一个收尾者进入下载;窗口内其余看到 finalizing 后退出+ locked = await _lock_task(db, int(task.id))+ if not locked or locked.status != "awaiting_poll":+ return+ if (locked.current_step_status or "") == "finalizing":+ na = locked.next_action_at+ if na is not None:+ if na.tzinfo is None:+ na = na.replace(tzinfo=UTC)+ if na > now:+ return+ locked.current_step_status = "finalizing"+ locked.progress_percent = max(int(locked.progress_percent or 0), 90)+ locked.next_action_at = now + timedelta(minutes=30)await db.commit()local_video, local_last_frame = await get_ark().save_video_assets_from_result(diff --git a/backend/tests/test_billing_settlement.py b/backend/tests/test_billing_settlement.pyindex 57b4445..6a01f3a 100644--- a/backend/tests/test_billing_settlement.py+++ b/backend/tests/test_billing_settlement.py@@ -9,7 +9,7 @@ import pytestfrom app.models import Userfrom app.models_tasks import TaskRunfrom app.services.billing.http import http_exception_for_value_error-from app.services.billing.settlement import billing_active, freeze_for_task+from app.services.billing.settlement import billing_active, freeze_for_task, settle_taskdef test_billing_active_respects_unlimited() -> None:@@ -52,3 +52,53 @@ async def test_freeze_for_task_idempotent_when_already_frozen() -> None:# 幂等早退:不应再查用户或写 ledgerassert db.execute.await_count == 1db.flush.assert_not_awaited()+++async def test_settle_task_idempotent_when_prior_unfreeze_ledger() -> None:+ """并发二次结算:已有 unfreeze 流水时禁止再次退款。"""+ task = TaskRun(+ id=3056,+ domain="drama",+ task_type="fragment_video",+ requested_by=401,+ billing_status="frozen",+ billing_estimate_fen=2650,+ billing_charged_fen=1661,+ billing_refunded_fen=989,+ )++ lock_result = MagicMock()+ lock_result.scalar_one_or_none = MagicMock(return_value=task)+ prior_result = MagicMock()+ prior_result.scalar_one_or_none = MagicMock(return_value=1)+ usage_result = MagicMock()+ usage_result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))++ db = MagicMock()+ db.execute = AsyncMock(side_effect=[lock_result, prior_result, usage_result])+ db.flush = AsyncMock()++ out = await settle_task(db, 3056)++ assert out == {"charged": 1661, "refunded": 989}+ assert task.billing_status == "settled"+ db.flush.assert_awaited()+++async def test_settle_task_noop_when_already_settled() -> None:+ task = TaskRun(+ id=1,+ billing_status="settled",+ billing_charged_fen=100,+ billing_refunded_fen=50,+ )+ lock_result = MagicMock()+ lock_result.scalar_one_or_none = MagicMock(return_value=task)+ db = MagicMock()+ db.execute = AsyncMock(return_value=lock_result)++ out = await settle_task(db, 1)+ assert out == {"charged": 100, "refunded": 50}+ assert db.execute.await_count == 1