PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix(billing): harden fragment poll settle and remove unlimited quota
yi47fa9b39699a
diff --git a/admin/src/api/client.ts b/admin/src/api/client.tsindex c1c3e6f..a27aebf 100644--- a/admin/src/api/client.ts+++ b/admin/src/api/client.ts@@ -199,7 +199,6 @@ export type AdminUserRow = {balance_fen: number;frozen_fen: number;plan: string;- billing_unlimited: boolean;role: string;created_at?: string | null;};diff --git a/admin/src/components/admin/UserDetailDrawer.tsx b/admin/src/components/admin/UserDetailDrawer.tsxindex 24b98b4..ce25c1f 100644--- a/admin/src/components/admin/UserDetailDrawer.tsx+++ b/admin/src/components/admin/UserDetailDrawer.tsx@@ -96,7 +96,6 @@ export function UserDetailDrawer({ userId, open, onOpenChange, initialUser }: Us{ label: "余额", value: `¥${fenToYuan(user.balance_fen)}` },{ label: "冻结", value: `¥${fenToYuan(user.frozen_fen)}` },{ label: "剩余额度", value: user.quota_left },- { label: "无限额度", value: user.billing_unlimited ? "是" : "否" },{label: "注册时间",value: user.created_at ? new Date(user.created_at).toLocaleString() : "—",diff --git a/admin/src/lib/auth.ts b/admin/src/lib/auth.tsindex 0abb05c..9b9f997 100644--- a/admin/src/lib/auth.ts+++ b/admin/src/lib/auth.ts@@ -12,7 +12,6 @@ export type AdminUser = {role: string;plan: string;balance_fen: number;- billing_unlimited: boolean;};// Read stored JWTdiff --git a/admin/src/pages/UsersPage.tsx b/admin/src/pages/UsersPage.tsxindex 2b95eab..3f21287 100644--- a/admin/src/pages/UsersPage.tsx+++ b/admin/src/pages/UsersPage.tsx@@ -13,7 +13,6 @@ import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { EmptyState, PageHeader } from "@/components/ui/page";import { Select } from "@/components/ui/select";-import { Switch } from "@/components/ui/switch";import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";import { formatAccountId } from "@/lib/admin-account";@@ -27,7 +26,6 @@ export function UsersPage() {const [q, setQ] = useState("");const [planFilter, setPlanFilter] = useState("");const [roleFilter, setRoleFilter] = useState("");- const [unlimitedFilter, setUnlimitedFilter] = useState("");const [page, setPage] = useState(1);const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);const [data, setData] = useState<ListRes | null>(null);@@ -37,7 +35,6 @@ export function UsersPage() {const [detailUser, setDetailUser] = useState<AdminUserRow | null>(null);const [form, setForm] = useState({plan: "free",- billing_unlimited: false,role: "user",balance_yuan: "0",balance_note: "",@@ -55,8 +52,6 @@ export function UsersPage() {if (nextQ.trim()) params.set("q", nextQ.trim());if (planFilter) params.set("plan", planFilter);if (roleFilter) params.set("role", roleFilter);- if (unlimitedFilter === "yes") params.set("billing_unlimited", "true");- if (unlimitedFilter === "no") params.set("billing_unlimited", "false");const res = await api<ListRes>(`/api/admin/users?${params}`);setData(res);} catch (err) {@@ -90,7 +85,6 @@ export function UsersPage() {setEditing(user);setForm({plan: user.plan || "free",- billing_unlimited: !!user.billing_unlimited,role: user.role || "user",balance_yuan: fenToYuan(user.balance_fen),balance_note: "",@@ -107,7 +101,6 @@ export function UsersPage() {method: "PATCH",body: JSON.stringify({plan: form.plan,- billing_unlimited: form.billing_unlimited,role: form.role,balance_fen: balanceFen,balance_note: form.balance_note || undefined,@@ -130,7 +123,7 @@ export function UsersPage() {return (<div className="admin-list-page">- <PageHeader description="搜索用户,调整套餐、余额与无限额度" />+ <PageHeader description="搜索用户,调整套餐与余额" /><AdminFilterBar><AdminSearchInput@@ -152,13 +145,8 @@ export function UsersPage() {<option value="user">user</option><option value="admin">admin</option></Select>- <Select value={unlimitedFilter} onChange={(e) => setUnlimitedFilter(e.target.value)}>- <option value="">无限额度</option>- <option value="yes">是</option>- <option value="no">否</option>- </Select>- <Button size="sm" className="admin-filter-action" onClick={applyFilters}>- 搜索+ <Button size="sm" className="admin-filter-action" onClick={applyFilters} disabled={loading}>+ {loading ? "加载中…" : "搜索"}</Button></AdminFilterBar>@@ -167,12 +155,12 @@ export function UsersPage() {{ label: "总用户数", value: stats?.user_count ?? (loading ? "…" : "—") },{label: "本月调用",- value: stats != null ? stats.usage_calls_month ?? 0 : loading ? "…" : "—",+ value: stats != null ? (stats.usage_calls_month ?? 0) : loading ? "…" : "—",hint: stats ? `今日 ${stats.usage_calls_today ?? 0} 次` : undefined,},{label: "累计调用",- value: stats != null ? stats.usage_calls_total ?? 0 : loading ? "…" : "—",+ value: stats != null ? (stats.usage_calls_total ?? 0) : loading ? "…" : "—",},]}/>@@ -190,7 +178,6 @@ export function UsersPage() {<TableHead>冻结</TableHead><TableHead>剩余额度</TableHead><TableHead>角色</TableHead>- <TableHead>无限</TableHead><TableHead>注册时间</TableHead><TableHead className="w-[140px]">操作</TableHead></TableRow>@@ -211,11 +198,6 @@ export function UsersPage() {<TableCell><Badge variant={u.role === "admin" ? "success" : "secondary"}>{u.role}</Badge></TableCell>- <TableCell>- <Badge variant={u.billing_unlimited ? "warning" : "secondary"}>- {u.billing_unlimited ? "是" : "否"}- </Badge>- </TableCell><TableCell className="text-xs text-muted-foreground">{u.created_at ? new Date(u.created_at).toLocaleString() : "—"}</TableCell>@@ -240,7 +222,7 @@ export function UsersPage() {))}{!loading && (data?.items.length ?? 0) === 0 && (<TableRow>- <TableCell colSpan={12} className="p-0">+ <TableCell colSpan={11} className="p-0"><EmptyState title="暂无用户" description="试试换个关键词搜索" /></TableCell></TableRow>@@ -310,16 +292,6 @@ export function UsersPage() {placeholder="管理员备注"/></AdminField>- <div className="admin-form-switch-row admin-form-grid--full">- <div>- <strong>无限额度</strong>- <p>开启后该用户调用不计费上限</p>- </div>- <Switch- checked={form.billing_unlimited}- onCheckedChange={(v) => setForm((f) => ({ ...f, billing_unlimited: v }))}- />- </div></div></AdminModal></div>diff --git a/backend/app/api/admin/users.py b/backend/app/api/admin/users.pyindex cbef00b..87fee0b 100644--- a/backend/app/api/admin/users.py+++ b/backend/app/api/admin/users.py@@ -16,7 +16,6 @@ async def list_users(q: str | None = None,plan: str | None = None,role: str | None = None,- billing_unlimited: bool | None = None,page: int = Query(1, ge=1),page_size: int = Query(20, ge=1, le=100),_admin: User = Depends(get_current_admin),@@ -42,9 +41,6 @@ async def list_users(if role and role.strip():stmt = stmt.where(User.role == role.strip())count_stmt = count_stmt.where(User.role == role.strip())- if billing_unlimited is not None:- stmt = stmt.where(User.billing_unlimited == billing_unlimited)- count_stmt = count_stmt.where(User.billing_unlimited == billing_unlimited)total = int((await db.execute(count_stmt)).scalar_one() or 0)result = await db.execute(@@ -64,7 +60,7 @@ async def patch_user(admin: User = Depends(get_current_admin),db: AsyncSession = Depends(get_db),) -> AdminUserOut:- # Update plan / unlimited / role; balance changes write WalletLedger+ # Update plan / role; balance changes write WalletLedgeruser = await db.get(User, user_id)if not user:raise HTTPException(status_code=404, detail="用户不存在")@@ -72,9 +68,6 @@ async def patch_user(if body.plan is not None:user.plan = body.plan.strip() or "free"- if body.billing_unlimited is not None:- user.billing_unlimited = bool(body.billing_unlimited)-if body.role is not None:role = body.role.strip()if role not in ("user", "admin"):diff --git a/backend/app/api/billing.py b/backend/app/api/billing.pyindex 6997498..f811d38 100644--- a/backend/app/api/billing.py+++ b/backend/app/api/billing.py@@ -46,7 +46,6 @@ async def wallet(user: User = Depends(get_current_user)) -> dict:"frozen_yuan": round(int(user.frozen_fen or 0) / 100, 2),"plan": user.plan or "free","billing_enabled": settings.billing_enabled,- "billing_unlimited": bool(user.billing_unlimited),"markup": settings.billing_markup,}diff --git a/backend/app/api/projects.py b/backend/app/api/projects.pyindex 784d453..e7e5472 100644--- a/backend/app/api/projects.py+++ b/backend/app/api/projects.py@@ -1025,7 +1025,7 @@ async def quota(user: User = Depends(get_current_user)) -> dict:return {"quota_left": user.quota_left,"quota_enabled": settings.quota_enabled,- "unlimited": (not settings.billing_enabled) or bool(user.billing_unlimited),+ "unlimited": not settings.billing_enabled,"billing_enabled": settings.billing_enabled,"balance_fen": int(getattr(user, "balance_fen", 0) or 0),"frozen_fen": int(getattr(user, "frozen_fen", 0) or 0),diff --git a/backend/app/main.py b/backend/app/main.pyindex 2e9b301..454f626 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -170,10 +170,6 @@ async def _apply_schema_patches() -> None:await conn.execute(text("ALTER TABLE users ADD COLUMN frozen_fen INTEGER DEFAULT 0"))if "plan" not in ucols:await conn.execute(text("ALTER TABLE users ADD COLUMN plan VARCHAR(32) DEFAULT 'free'"))- if "billing_unlimited" not in ucols:- await conn.execute(- text("ALTER TABLE users ADD COLUMN billing_unlimited BOOLEAN DEFAULT FALSE")- )if "role" not in ucols:await conn.execute(text("ALTER TABLE users ADD COLUMN role VARCHAR(16) DEFAULT 'user'"))if "avatar_url" not in ucols:diff --git a/backend/app/models.py b/backend/app/models.pyindex 989a9e3..29edb49 100644--- a/backend/app/models.py+++ b/backend/app/models.py@@ -44,7 +44,6 @@ class User(Base):balance_fen: Mapped[int] = mapped_column(Integer, default=0)frozen_fen: Mapped[int] = mapped_column(Integer, default=0)plan: Mapped[str] = mapped_column(String(32), default="free")- billing_unlimited: Mapped[bool] = mapped_column(Boolean, default=False)# user | adminrole: Mapped[str] = mapped_column(String(16), default="user")avatar_url: Mapped[str] = mapped_column(String(512), default="")diff --git a/backend/app/schemas.py b/backend/app/schemas.pyindex 3d139f7..5d5ae5f 100644--- a/backend/app/schemas.py+++ b/backend/app/schemas.py@@ -32,7 +32,6 @@ class UserOut(BaseModel):balance_fen: int = 0frozen_fen: int = 0plan: str = "free"- billing_unlimited: bool = Falserole: str = "user"avatar_url: str = ""phone: str = ""@@ -446,7 +445,6 @@ class AdminUserOut(BaseModel):balance_fen: intfrozen_fen: intplan: str- billing_unlimited: boolrole: strphone: str = ""created_at: datetime | None = None@@ -466,7 +464,6 @@ class AdminUserListOut(BaseModel):class AdminUserPatch(BaseModel):plan: str | None = None- billing_unlimited: bool | None = Nonerole: str | None = None# Absolute target balance in fen; when set, write ledger deltabalance_fen: int | None = Nonediff --git a/backend/app/services/admin/stats.py b/backend/app/services/admin/stats.pyindex 409c830..b1d7d95 100644--- a/backend/app/services/admin/stats.py+++ b/backend/app/services/admin/stats.py@@ -5,13 +5,17 @@ from __future__ import annotationsfrom datetime import date, datetime, timedelta, timezonefrom typing import Any-from sqlalchemy import Date, case, cast, func, select+from sqlalchemy import Date, case, cast, func, or_, select, union_allfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import aliasedfrom app.models import Order, Project, UsageEvent, Userfrom app.models_drama import DramaProject+# 同一 task 内只应有一行的计费 key(并发双记时需折叠);llm/tts 等同 key 多行合法保留+_SINGLE_SHOT_BILLING_KEY_PREFIXES = ("seedance",)+_SINGLE_SHOT_BILLING_KEYS = frozenset({"seedream"})+def _utc_today_start() -> datetime:return datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)@@ -324,11 +328,20 @@ def _row_to_usage_summary(row: Any) -> dict[str, int]:}+def _single_shot_billing_key_filter():+ """单次调用类 billing_key:seedance* / seedream。"""+ clauses = [UsageEvent.billing_key.like(f"{p}%") for p in _SINGLE_SHOT_BILLING_KEY_PREFIXES]+ if _SINGLE_SHOT_BILLING_KEYS:+ clauses.append(UsageEvent.billing_key.in_(tuple(_SINGLE_SHOT_BILLING_KEYS)))+ return or_(*clauses)++def _deduped_usage_event_ids_subq():"""- 同一 task_run + billing_key 只保留最早一条用量行,避免并发重复记费把项目汇总抬高。- 无 task_run_id 的孤儿行全部保留。+ 仅对单次调用类 key 按 task_run+billing_key 保留最早一行,避免并发双记抬高汇总。+ llm_chat / tts 等同 key 多行全部保留;无 task_run_id 的孤儿行全部保留。"""+ single_shot = _single_shot_billing_key_filter()ranked = (select(UsageEvent.id.label("id"),@@ -339,12 +352,16 @@ def _deduped_usage_event_ids_subq():).label("rn"),)- .where(UsageEvent.task_run_id.is_not(None))+ .where(UsageEvent.task_run_id.is_not(None), single_shot).subquery())- with_task = select(ranked.c.id).where(ranked.c.rn == 1)+ deduped_single = select(ranked.c.id).where(ranked.c.rn == 1)+ keep_multi = select(UsageEvent.id).where(+ UsageEvent.task_run_id.is_not(None),+ ~single_shot,+ )orphans = select(UsageEvent.id).where(UsageEvent.task_run_id.is_(None))- return with_task.union_all(orphans).subquery()+ return union_all(deduped_single, keep_multi, orphans).subquery()async def _sum_task_charged_fen(diff --git a/backend/app/services/billing/alerts.py b/backend/app/services/billing/alerts.pyindex f08a519..c712c11 100644--- a/backend/app/services/billing/alerts.py+++ b/backend/app/services/billing/alerts.py@@ -104,8 +104,6 @@ async def process_user_milestone_alert(interval = int(s.billing_user_alert_interval_fen or 0)if interval <= 0:return []- if getattr(user, "billing_unlimited", False):- return []total = await _user_total_charge_fen(db, int(user.id))last = int(getattr(user, "billing_alert_last_milestone_fen", 0) or 0)diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pyindex e214d8f..e429bb6 100644--- a/backend/app/services/billing/ephemeral.py+++ b/backend/app/services/billing/ephemeral.py@@ -121,7 +121,7 @@ async def run_billed_ephemeral(task.status = "failed"task.error_code = "insufficient_balance"task.error_message = "余额不足"- # 未预扣成功,保持 none,勿标 skipped(skipped 表示无限额跳过扣费)+ # 未预扣成功,保持 none,勿标 skipped(skipped 表示全局关闭计费)task.billing_status = "none"await db.flush()raisediff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.pyindex b4e46fb..60e4b80 100644--- a/backend/app/services/billing/settlement.py+++ b/backend/app/services/billing/settlement.py@@ -29,12 +29,10 @@ _PENDING_BILLING_TASK_STATUSES = frozenset(def billing_active(user: User | None = None, settings: Settings | None = None) -> bool:+ """全局计费开关;user 参数保留兼容调用方,不再按用户跳过扣费。"""+ _ = users = settings or get_settings()- if not s.billing_enabled:- return False- if user is not None and getattr(user, "billing_unlimited", False):- return False- return True+ return bool(s.billing_enabled)async def _ledger(@@ -266,7 +264,7 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:"refunded": int(task.billing_refunded_fen or 0),}if task.billing_status == "skipped" and not events:- # 无限额且无用量:结算完成,统一标 settled 便于管理端展示+ # 全局关闭计费且无用量:结算完成,统一标 settled 便于管理端展示task.billing_status = "settled"task.billing_charged_fen = int(task.billing_charged_fen or 0)await db.flush()@@ -279,7 +277,7 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:for e in events:e.settled = True- # 无限额/跳过扣费:标记用量已结算,不动钱包,任务标 settled+ # 全局关闭计费:标记用量已结算,不动钱包,任务标 settledif task.billing_status == "skipped":task.billing_charged_fen = chargedtask.billing_status = "settled"diff --git a/backend/app/services/drama/billing_util.py b/backend/app/services/drama/billing_util.pyindex 9563c81..b156c67 100644--- a/backend/app/services/drama/billing_util.py+++ b/backend/app/services/drama/billing_util.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-from sqlalchemy import select+from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.config import get_settings@@ -28,6 +28,15 @@ def seedance_billing_key(*, generate_audio: bool = True) -> str:return "seedance2:video0" if generate_audio else "seedance2:video1"+# 匹配 raw JSON 中的 provider_task_id 字段(带 key,避免裸 ID 子串误伤;兼容 dumps 空格)+def _provider_task_id_match(provider_id: str):+ pid = provider_id.replace("\\", "\\\\").replace('"', '\\"')+ return or_(+ UsageEvent.raw_usage_json.contains(f'"provider_task_id": "{pid}"'),+ UsageEvent.raw_usage_json.contains(f'"provider_task_id":"{pid}"'),+ )++async def record_seedance_video_usage(db: AsyncSession,*,@@ -44,9 +53,11 @@ async def record_seedance_video_usage() -> UsageEvent:"""按官方任务 usage / 成本或时长估算写入 Seedance 视频用量行。- 同一 task_run + billing_key 已有用量时幂等返回首行,避免并发收尾双记。+ 幂等:同 task_run+billing_key,或同 provider_task_id 已有行时直接返回,避免并发收尾双记。"""tid = get_current_task_run_id()+ provider_id = (provider_task_id or "").strip()+if tid is not None:existing = (await db.execute(@@ -62,14 +73,32 @@ async def record_seedance_video_usage(if existing is not None:return existing+ # 无 billing_scope 时仍可按上游任务 ID 精确去重+ if provider_id:+ by_provider = (+ await db.execute(+ select(UsageEvent)+ .where(+ UsageEvent.user_id == int(user_id),+ UsageEvent.billing_key == billing_key,+ UsageEvent.raw_usage_json.is_not(None),+ _provider_task_id_match(provider_id),+ )+ .order_by(UsageEvent.id.asc())+ .limit(1)+ )+ ).scalar_one_or_none()+ if by_provider is not None:+ return by_provider+if ((not task_result or int(getattr(task_result, "total_tokens", 0) or 0) <= 0)- and provider_task_id+ and provider_id):from app.services.ark import get_arktry:- refreshed = await get_ark().fetch_task_once(provider_task_id.strip())+ refreshed = await get_ark().fetch_task_once(provider_id)if int(getattr(refreshed, "total_tokens", 0) or 0) > 0 or refreshed.raw_usage:task_result = refreshedexcept Exception: # noqa: BLE001@@ -81,8 +110,10 @@ async def record_seedance_video_usage(raw: dict[str, Any] | None = Noneif raw_usage:raw = {"usage": dict(raw_usage)}- elif provider_task_id:- raw = {"provider_task_id": provider_task_id, "usage": raw_usage or {}}+ elif provider_id:+ raw = {"usage": {}}+ if provider_id:+ raw = {**(raw or {}), "provider_task_id": provider_id}from app.services.billing.pricing import parse_upstream_cost_fendiff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex 9e1b915..16134f3 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -803,13 +803,62 @@ async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:return {"awaiting_poll": True, "provider_task_id": provider_task_id}+# 分镜视频收尾认领窗口:期内其它 poller 不得再入下载;超时仅作崩溃恢复。+_FRAGMENT_FINALIZE_CLAIM_TTL = timedelta(hours=6)+++# 统一解析 TaskRun.next_action_at 的时区,便于与 now 比较。+def _aware_utc(dt: datetime | None) -> datetime | None:+ if dt is None:+ return None+ if dt.tzinfo is None:+ return dt.replace(tzinfo=UTC)+ return dt+++# 分镜是否已落成片(崩溃恢复时可跳过重复下载)。+def _fragment_video_already_applied(frag: DramaEpisodeFragment | None) -> bool:+ if frag is None or not (frag.video or "").strip():+ return False+ params = frag.params if isinstance(frag.params, dict) else {}+ gen = params.get("generation") if isinstance(params.get("generation"), dict) else {}+ return str(gen.get("status") or "").strip().lower() == "done"+++# 行锁后补完成分镜视频任务;已非 awaiting_poll 则跳过,避免并发双 complete。+async def _recover_complete_fragment_video(+ db: AsyncSession,+ task_id: int,+ *,+ fragment_id: int,+ batch_key: str | None,+ batch_index: int,+ recovered: bool = True,+) -> bool:+ from app.services.billing.settlement import _lock_task+ from app.services.tasks.executor import _complete_task+ from app.services.tasks.service import activate_next_sequential_task++ locked = await _lock_task(db, int(task_id))+ if not locked or locked.status != "awaiting_poll":+ return False+ # 先 complete(commit 后锁释放),再激活后续;避免 activate 提前 commit 导致并发双 complete+ locked.progress_percent = 100+ result_payload: dict[str, Any] = {"ok": True, "fragment_id": int(fragment_id)}+ if recovered:+ result_payload["recovered"] = True+ await _complete_task(db, locked, result_payload)+ await activate_next_sequential_task(db, batch_key, batch_index)+ return True++# 任务平台:轮询 awaiting_poll 的分镜视频任务。async def poll_fragment_video_task(task_id: int) -> None:from app.services.ark import get_arkfrom app.services.billing.context import billing_scopefrom app.services.billing.settlement import _lock_task- from app.services.tasks.executor import _complete_task, _fail_task- from app.services.tasks.service import activate_next_sequential_task, get_task_for_runtime+ from app.services.tasks.executor import _fail_task+ from app.services.tasks.service import get_task_for_runtimeasync with billing_scope(task_id):async with AsyncSessionLocal() as db:@@ -828,12 +877,9 @@ async def poll_fragment_video_task(task_id: int) -> None:# 收尾认领窗口未到期:跳过,避免并发下载双记费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+ na = _aware_utc(task.next_action_at)+ if na is not None and na > now:+ returnif task.cancel_requested or _is_episode_video_cancelled(episode_id):await _fail_task(db, task, RuntimeError("任务已取消"))@@ -844,6 +890,17 @@ async def poll_fragment_video_task(task_id: int) -> None:await _fail_task(db, task, RuntimeError("分镜已变更,请重新生成"))return+ # 成片已落盘(含 apply 成功后 complete 失败):行锁后只补完成+ if _fragment_video_already_applied(frag_probe):+ await _recover_complete_fragment_video(+ db,+ int(task.id),+ fragment_id=fragment_id,+ batch_key=task.batch_key,+ batch_index=int(payload.get("batch_index", 0)),+ )+ return+result = await get_ark().fetch_task_once(task.provider_task_id)if result.status == "running":task.next_action_at = now + timedelta(seconds=poll_interval)@@ -878,38 +935,64 @@ async def poll_fragment_video_task(task_id: int) -> None:if not locked or locked.status != "awaiting_poll":returnif (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+ na = _aware_utc(locked.next_action_at)+ if na is not None and na > now:+ return+ # 认领前后成片已在:行锁后只补完成(避免 apply 后异常释放认领再二次下载)+ if _fragment_video_already_applied(frag):+ await _recover_complete_fragment_video(+ db,+ int(locked.id),+ fragment_id=fragment_id,+ batch_key=locked.batch_key,+ batch_index=int(payload.get("batch_index", 0)),+ )+ returnlocked.current_step_status = "finalizing"locked.progress_percent = max(int(locked.progress_percent or 0), 90)- locked.next_action_at = now + timedelta(minutes=30)+ locked.next_action_at = now + _FRAGMENT_FINALIZE_CLAIM_TTLawait db.commit()- local_video, local_last_frame = await get_ark().save_video_assets_from_result(- result,- project_id=ep.project.id,- shot_no=fragment_id,- )- await apply_fragment_video_assets(- db,- user,- ep.project,- frag,- local_video=local_video,- local_last_frame=local_last_frame,- attempts=attempts,- attempt_limit=attempt_limit,- task_result=result,- provider_task_id=task.provider_task_id,- )- batch_index = int(payload.get("batch_index", 0))- await activate_next_sequential_task(db, task.batch_key, batch_index)- task.progress_percent = 100- await _complete_task(db, task, {"ok": True, "fragment_id": fragment_id})+ try:+ local_video, local_last_frame = await get_ark().save_video_assets_from_result(+ result,+ project_id=ep.project.id,+ shot_no=fragment_id,+ )+ await apply_fragment_video_assets(+ db,+ user,+ ep.project,+ frag,+ local_video=local_video,+ local_last_frame=local_last_frame,+ attempts=attempts,+ attempt_limit=attempt_limit,+ task_result=result,+ provider_task_id=task.provider_task_id,+ )+ # 与恢复路径同一套行锁 complete,避免 apply 后并发双 complete+ await _recover_complete_fragment_video(+ db,+ int(task_id),+ fragment_id=fragment_id,+ batch_key=task.batch_key,+ batch_index=int(payload.get("batch_index", 0)),+ recovered=False,+ )+ except Exception:+ # 下载/落盘失败:释放认领,短间隔重试;勿把 next_action 缩到 8s 却仍标 finalizing+ async with AsyncSessionLocal() as release_db:+ stalled = await _lock_task(release_db, int(task_id))+ if (+ stalled+ and stalled.status == "awaiting_poll"+ and (stalled.current_step_status or "") == "finalizing"+ ):+ stalled.current_step_status = "polling"+ stalled.next_action_at = datetime.now(UTC) + timedelta(seconds=poll_interval)+ await release_db.commit()+ raise# ---------- asset image ----------diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.pyindex 8a45590..ea70f46 100644--- a/backend/app/services/tasks/executor.py+++ b/backend/app/services/tasks/executor.py@@ -51,7 +51,7 @@ async def execute_task_run(task_id: int) -> None:task.error_code = "insufficient_balance"task.error_message = str(exc)[:500]task.finished_at = datetime.now(UTC)- # 未预扣成功,保持 none(skipped 仅表示无限额跳过扣费)+ # 未预扣成功,保持 none(skipped 仅表示全局关闭计费)task.billing_status = "none"await append_task_event(db,diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.pyindex faa0dca..cf04f23 100644--- a/backend/app/services/tasks/poller.py+++ b/backend/app/services/tasks/poller.py@@ -14,6 +14,9 @@ from app.models_tasks import TaskRunfrom app.services.billing.settlement import settle_taskfrom app.services.tasks.service import append_task_event+# 与 drama.jobs 收尾认领态一致:异常时勿缩短仍在 finalizing 的 next_action_at+_FRAGMENT_FINALIZE_STEP = "finalizing"+logger = logging.getLogger("app.tasks.poller")_poller_task: asyncio.Task | None = None@@ -135,6 +138,9 @@ async def _poll_one_task(task_id: int) -> None:task = await db.get(TaskRun, task_id)if not task or task.status != "awaiting_poll":return+ # 仍在收尾认领中:保留长 TTL,避免并发 poller 挤进下载窗口+ if (task.current_step_status or "") == _FRAGMENT_FINALIZE_STEP:+ returnpoll_interval = max(1.0, float(get_settings().ark_video_poll_interval or 8.0))task.next_action_at = datetime.now(UTC) + timedelta(seconds=poll_interval)await db.commit()diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex 7f7b20f..3557734 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -72,7 +72,6 @@ async def make_user(*,balance_fen: int = 100_000,frozen_fen: int = 0,- billing_unlimited: bool = False,) -> User:"""创建测试用户。"""user = User(@@ -80,7 +79,6 @@ async def make_user(hashed_password="test",balance_fen=balance_fen,frozen_fen=frozen_fen,- billing_unlimited=billing_unlimited,)db.add(user)await db.flush()diff --git a/backend/tests/test_admin_readonly_filters.py b/backend/tests/test_admin_readonly_filters.pyindex f1afdae..3102a0a 100644--- a/backend/tests/test_admin_readonly_filters.py+++ b/backend/tests/test_admin_readonly_filters.py@@ -35,16 +35,15 @@ async def _valid_user(db: AsyncSession, **kwargs: object) -> User:@pytest.mark.asyncio-async def test_admin_users_filter_plan_and_unlimited(db_session: AsyncSession) -> None:+async def test_admin_users_filter_plan(db_session: AsyncSession) -> None:admin = await _make_admin(db_session)- pro = await _valid_user(db_session, plan="pro", billing_unlimited=True)- await _valid_user(db_session, plan="free", billing_unlimited=False)+ pro = await _valid_user(db_session, plan="pro")+ await _valid_user(db_session, plan="free")await db_session.commit()res = await list_users(plan="pro",role=None,- billing_unlimited=True,q=None,page=1,page_size=20,@@ -53,7 +52,7 @@ async def test_admin_users_filter_plan_and_unlimited(db_session: AsyncSession) -)ids = {u.id for u in res.items}assert pro.id in ids- assert all(u.plan == "pro" and u.billing_unlimited for u in res.items)+ assert all(u.plan == "pro" for u in res.items)@pytest.mark.asyncio@@ -66,7 +65,6 @@ async def test_admin_users_search_by_numeric_id(db_session: AsyncSession) -> Nonq=str(target.id),plan=None,role=None,- billing_unlimited=None,page=1,page_size=5,_admin=admin,diff --git a/backend/tests/test_admin_stats.py b/backend/tests/test_admin_stats.pyindex 5d96e70..f416e44 100644--- a/backend/tests/test_admin_stats.py+++ b/backend/tests/test_admin_stats.py@@ -30,12 +30,14 @@ async def _add_usage(project_id: int | None = None,drama_project_id: int | None = None,total_tokens: int = 100,+ task_run_id: int | None = None,) -> UsageEvent:"""写入一条用量事件。"""ev = UsageEvent(user_id=user_id,project_id=project_id,drama_project_id=drama_project_id,+ task_run_id=task_run_id,domain=domain,capability=capability,billing_key=billing_key,@@ -451,3 +453,55 @@ async def test_aggregate_drama_project_usage(db_session: AsyncSession) -> None:assert summary["cost_fen"] == 8assert summary["tokens"] == 50assert summary["tts_gens"] == 1+++async def test_aggregate_keeps_multi_llm_dedupes_seedance(db_session: AsyncSession) -> None:+ """同 task 下 llm_chat 多行保留;seedance 重复行只计一条。"""+ user = await make_user(db_session)+ # drama_project_id 无 FK,避免依赖 projects 行;用高位 id 降低脏数据干扰+ did = 880_001_903+ tid = 9001+ await _add_usage(+ db_session,+ user_id=user.id,+ drama_project_id=did,+ task_run_id=tid,+ charge_fen=5,+ billing_key="llm_chat",+ capability="llm",+ )+ await _add_usage(+ db_session,+ user_id=user.id,+ drama_project_id=did,+ task_run_id=tid,+ charge_fen=7,+ billing_key="llm_chat",+ capability="llm",+ )+ await _add_usage(+ db_session,+ user_id=user.id,+ drama_project_id=did,+ task_run_id=tid,+ charge_fen=20,+ billing_key="seedance2:video0",+ capability="video",+ )+ await _add_usage(+ db_session,+ user_id=user.id,+ drama_project_id=did,+ task_run_id=tid,+ charge_fen=20,+ billing_key="seedance2:video0",+ capability="video",+ )+ await db_session.commit()++ summary = await aggregate_usage_summary(db_session, drama_project_id=did)+ assert summary["llm_calls"] == 2+ assert summary["video_gens"] == 1+ assert summary["calls"] == 3+ assert summary["charge_fen"] == 5 + 7 + 20diff --git a/backend/tests/test_billing_alerts.py b/backend/tests/test_billing_alerts.pyindex 25c5449..5953546 100644--- a/backend/tests/test_billing_alerts.py+++ b/backend/tests/test_billing_alerts.py@@ -68,20 +68,6 @@ async def test_user_milestone_creates_popup_notification(db_session: AsyncSessioassert len(pending_after) == 1-async def test_user_milestone_skips_unlimited(db_session: AsyncSession, monkeypatch) -> None:- settings = __import__("app.config", fromlist=["get_settings"]).get_settings()- monkeypatch.setattr(settings, "billing_user_alert_enabled", True)- monkeypatch.setattr(settings, "billing_user_alert_interval_fen", 1000)-- user = await make_user(db_session, billing_unlimited=True)- await _add_settled_usage(db_session, user_id=user.id, charge_fen=5000)- await db_session.commit()-- created = await process_user_milestone_alert(db_session, user, settings=settings)- assert created == []--@pytest.mark.asyncioasync def test_admin_cost_alert_sends_email_once_per_level(db_session: AsyncSession, monkeypatch) -> None:settings = __import__("app.config", fromlist=["get_settings"]).get_settings()diff --git a/backend/tests/test_billing_integration.py b/backend/tests/test_billing_integration.pyindex dce51ce..fdf348f 100644--- a/backend/tests/test_billing_integration.py+++ b/backend/tests/test_billing_integration.py@@ -165,9 +165,16 @@ async def test_ensure_balance_for_task_batch_rejects_insufficient(db_session: As@pytest.mark.asyncio-async def test_unlimited_user_skips_wallet_but_settles_usage(db_session: AsyncSession) -> None:- """billing_unlimited:不扣钱包,但用量行应标记 settled。"""- user = await make_user(db_session, balance_fen=0, billing_unlimited=True)+async def test_billing_disabled_skips_wallet_but_settles_usage(+ db_session: AsyncSession, monkeypatch+) -> None:+ """全局关闭计费:不扣钱包,但用量行应标记 settled。"""+ from app.config import get_settings++ settings = get_settings()+ monkeypatch.setattr(settings, "billing_enabled", False)++ user = await make_user(db_session, balance_fen=0)task = await make_task(db_session, user, domain="drama", task_type="agent_chat")await db_session.commit()diff --git a/backend/tests/test_billing_settlement.py b/backend/tests/test_billing_settlement.pyindex 6a01f3a..545e975 100644--- a/backend/tests/test_billing_settlement.py+++ b/backend/tests/test_billing_settlement.py@@ -12,9 +12,15 @@ from app.services.billing.http import http_exception_for_value_errorfrom app.services.billing.settlement import billing_active, freeze_for_task, settle_task-def test_billing_active_respects_unlimited() -> None:- user = User(id=1, billing_unlimited=True)- assert billing_active(user) is False+def test_billing_active_follows_global_switch(monkeypatch) -> None:+ from app.config import get_settings++ user = User(id=1)+ settings = get_settings()+ monkeypatch.setattr(settings, "billing_enabled", True)+ assert billing_active(user, settings) is True+ monkeypatch.setattr(settings, "billing_enabled", False)+ assert billing_active(user, settings) is Falsedef test_http_exception_maps_insufficient_balance_to_402() -> None:@@ -102,3 +108,67 @@ async def test_settle_task_noop_when_already_settled() -> None:out = await settle_task(db, 1)assert out == {"charged": 100, "refunded": 50}assert db.execute.await_count == 1+++def test_fragment_video_already_applied_requires_done_generation() -> None:+ from app.models_drama import DramaEpisodeFragment+ from app.services.drama.jobs import _fragment_video_already_applied++ empty = DramaEpisodeFragment(id=1, video="", params={})+ assert _fragment_video_already_applied(empty) is False+ assert _fragment_video_already_applied(None) is False++ done = DramaEpisodeFragment(+ id=2,+ video="https://cdn.example/v.mp4",+ params={"generation": {"status": "done"}},+ )+ assert _fragment_video_already_applied(done) is True++ pending = DramaEpisodeFragment(+ id=3,+ video="https://cdn.example/v.mp4",+ params={"generation": {"status": "running"}},+ )+ assert _fragment_video_already_applied(pending) is False+++async def test_recover_complete_skips_when_not_awaiting_poll() -> None:+ """已收敛任务不再二次 activate / complete。"""+ from app.services.drama.jobs import _recover_complete_fragment_video++ done = TaskRun(id=42, status="succeeded", batch_key="b1")+ lock_result = MagicMock()+ lock_result.scalar_one_or_none = MagicMock(return_value=done)+ db = MagicMock()+ db.execute = AsyncMock(return_value=lock_result)++ ok = await _recover_complete_fragment_video(+ db, 42, fragment_id=9, batch_key="b1", batch_index=0+ )+ assert ok is False+++async def test_record_seedance_dedupes_by_provider_task_id() -> None:+ """无 billing_scope 时仍按 provider_task_id 幂等。"""+ from app.services.drama.billing_util import record_seedance_video_usage++ existing = MagicMock()+ existing.id = 11+ by_provider = MagicMock()+ by_provider.scalar_one_or_none = MagicMock(return_value=existing)+ db = MagicMock()+ db.execute = AsyncMock(return_value=by_provider)++ out = await record_seedance_video_usage(+ db,+ user_id=401,+ billing_key="seedance2:video0",+ model="seedance",+ domain="drama",+ provider_task_id="prov-abc-1",+ )+ assert out is existing+ db.execute.assert_awaited()diff --git a/docs/BILLING.md b/docs/BILLING.mdindex b7700ba..e8b2b2e 100644--- a/docs/BILLING.md+++ b/docs/BILLING.md@@ -106,9 +106,9 @@ sequenceDiagram余额不足:`freeze_for_task` 失败 → HTTP 402(`create_task` 入队前同步预检,或轻量任务预扣失败)。-`billing_unlimited`:预扣时 `billing_status=skipped`(不冻钱包);`settle_task` 后标 `settled`,usage 行 `settled=true`(仅统计,不扣钱包)。+全局关闭计费(`BILLING_ENABLED=false`):预扣时 `billing_status=skipped`(不冻钱包);`settle_task` 后标 `settled`,usage 行 `settled=true`(仅统计,不扣钱包)。-余额不足失败:`billing_status` 保持 `none`(未成功预扣,勿与无限额 `skipped` 混淆)。+余额不足失败:`billing_status` 保持 `none`(未成功预扣,勿与全局关闭计费的 `skipped` 混淆)。api/studio 轻量视频:`awaiting_poll` 由 Selector 后台轮询;超过 `ark_video_poll_timeout` 自动失败并解冻。@@ -156,5 +156,3 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=14. 管理端可按 `task_run_id` 或 `billing_key=llm_chat` 查到每条 LLM/图/视频/TTS 费用。5. Seedance 视频成功后 `usage_events.estimated=false` 且 `total_tokens` 与官方任务查询一致。6. 配置火山 AK/SK 后,管理端可刷新并查看近 30 日官方/本地成本对照。--Demo 账号可设 `billing_unlimited=true` 跳过扣费。diff --git a/frontend/src/api.ts b/frontend/src/api.tsindex 1ad4132..468b7e7 100644--- a/frontend/src/api.ts+++ b/frontend/src/api.ts@@ -169,7 +169,6 @@ export type User = {balance_fen?: numberfrozen_fen?: numberplan?: string- billing_unlimited?: booleanavatar_url?: stringphone?: string}@@ -233,7 +232,6 @@ export type Wallet = {frozen_yuan: numberplan: stringbilling_enabled: boolean- billing_unlimited: booleanmarkup: number}diff --git a/frontend/src/components/billing/PricingWalletCard.tsx b/frontend/src/components/billing/PricingWalletCard.tsxindex f6dedd0..626aebe 100644--- a/frontend/src/components/billing/PricingWalletCard.tsx+++ b/frontend/src/components/billing/PricingWalletCard.tsx@@ -12,7 +12,6 @@ type Props = {function planLabel(wallet: Wallet | null) {if (!wallet) return 'Free'- if (wallet.billing_unlimited) return 'Unlimited'const p = (wallet.plan || 'free').toLowerCase()if (p === 'free') return 'Free'if (p === 'pro') return 'Pro'diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsxindex 5b6b0d7..90b49f2 100644--- a/frontend/src/pages/SettingsPage.tsx+++ b/frontend/src/pages/SettingsPage.tsx@@ -146,11 +146,8 @@ export default function SettingsPage() {nav('/')}- const planLabel = wallet?.billing_unlimited- ? 'Unlimited'- : (wallet?.plan || 'free').toLowerCase() === 'pro'- ? 'Pro'- : 'Free'+ const plan = (wallet?.plan || 'free').toLowerCase()+ const planLabel = plan === 'pro' ? 'Pro' : plan === 'free' ? 'Free' : wallet?.plan || 'Free'return (<AppShell>