PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix: 全库扫描修复(30 项)— 安全/计费/任务平台/上游韧性/发版阻塞
yifc1329196760
diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..24eebbf--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,99 @@+# CLAUDE.md++This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++## 项目概览++PRINTFILM(仓库目录 `ai_movie`):模板驱动的 AI 短视频(科普 kepu)与漫剧创作平台。两条产品线共用同一套 AI 能力:++- **科普短视频**:主题/口播 → 模板拆镜 → 分镜图 →(可选)视频 → 旁白 → FFmpeg 合成;状态机 `SCRIPTING → IMAGING → VIDEOING/AUDIOING → COMPOSING → DONE`+- **漫剧 drama**:项目 → 剧本摘要/分集 → 资产库(角色/场景/道具/音色)→ 分集分镜 → React Flow 画布+- 另有工具中心(t2i/i2p/t2v 等)、开放 API(`/api/v1`)、管理后台、可选钱包计费(易支付)++三条独立进程 + 两个容器中间件:FastAPI(:8000)、用户端 Vite(:5173)、管理端 Vite(:5174)、Postgres(:15432)、Redis(:16379)。技术栈:Python 3.12 / FastAPI / SQLAlchemy(asyncpg) / React 19 / TS / Vite 8。需要本机安装 FFmpeg。++## 常用命令++```bash+# 中间件(先 cp deploy/.env.prod.example deploy/.env.prod 并改密码)+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod up -d++# 后端(在 backend/ 下;先 cp .env.example .env)+uvicorn app.main:app --reload --port 8000++# 用户端 / 管理端(各自目录)+npm install && npm run dev # 5173 / 5174+npm run lint # oxlint(无后端 linter/formatter 配置)+npm run build # tsc -b && vite build+```++测试(在 `backend/` 下,需 `pip install -r requirements-dev.txt`,`pytest.ini` 已设 `asyncio_mode=auto`、`pythonpath=.`):++```bash+pytest # 全量+pytest tests/test_kepu_continuity.py # 单文件+pytest tests/test_x.py::test_name # 单测+```++注意:使用 `db_session` fixture 的是集成测试,**需要 PostgreSQL 在运行**(事务回滚隔离,不写库);其余为纯单测可直接跑。conftest 已自动 stub TokenFree 价目网络请求。++健康检查 `/api/health`(含 task_runtime / db_pool / models),Swagger `/docs`。++## 架构要点(需要读多个文件才能拼出的全局)++### 统一任务平台(核心,易误判)++代码里没有独立 worker 进程:Celery 仅是遗留依赖(`USE_CELERY` 代码已不读取,`workers/` 目录不存在)。实际运行时是 **随 FastAPI 启动的进程内三件套**(`app/services/tasks/`):++- `scheduler.py`:定时租约到期任务(pending→leased→running),受全站槽位 `TASK_RUNTIME_MAX_CONCURRENCY` 与单用户槽位 `TASK_USER_MAX_CONCURRENCY` 限制;含孤儿任务回收+- `executor.py`:执行 handler+- `poller.py`:NIO 式 Selector,集中非阻塞轮询所有 `awaiting_poll` 的上游任务(信号量 `TASK_POLL_MAX_CONCURRENCY`),完成后触发计费结算+- `runtime.py` + watchdog:心跳过期自动软重启调度/轮询循环++`TaskRun` 状态与 steps/events/targets 见 `models_tasks.py`;**新任务类型必须在 `tasks/handlers.py` 的 `HANDLERS` 注册表登记 `(domain, task_type)`**(kepu/drama/api/studio/tools 五个 domain)。部分类型注册为 `_noop_ephemeral`——这些在创建请求内联执行,TaskRun 仅用于计费/留痕。管理端任务中心 `/queues` 直接读这些表。++### 科普流水线与分阶段计费共用同一就绪判定++`services/pipeline.py`(约 2000 行,历史大文件,新增逻辑优先拆新文件)是科普编排主体。`pipeline_mode`:`full`(图+视频+合成)或 `image_text`(静图+旁白)。关键约定:**`services/kepu_stages.py` 的 `resolve_kepu_billing_phase()`(script|assets|videos|compose)是计费预扣与流水线恢复共用的唯一"下一阶段"真相源**,改就绪规则必须两边语义一致。连续性(首尾帧/参考图)在 `kepu_continuity.py`;FFmpeg 合成在 `ffmpeg_compose.py`(SIGTERM 中断有自动重试)。++### 漫剧模块独立成包++`api/drama/` + `services/drama/`(30+ 小文件,按 jobs/fragment/voice/asset 等拆分)+ `models_drama.py`(projects→scripts→episodes→fragments→asset_refs)。分镜视频是一镜一 TaskRun(`fragment_video`),有预算、最大尝试次数与排队上限(见 config 中 `DRAMA_*`)。产品规则见 `docs/EPISODE_RULES.md`、`docs/SHOT_SPLITTING.md`。++### 模型路由:上游被锁定为 TokenFree++开源版**只允许 TokenFree New API 一个上游**(OpenAI 兼容 `https://www.tokenfree.com/v1`,文本与图/视频共用),由 `services/tokenfree_gateway.py` 强制(渠道 Base URL/协议不可改)。Key 与模型在**管理后台「系统设置 → 模型」**配置,存 `system_model_channels` / `app_settings` 表;启动/保存后经 `model_settings.py` 生成 overlay,`config.get_settings()`(lru_cache)以 `model_copy(update=overlay)` 叠加到 env 配置之上——所以运行时配置以 DB overlay 优先,`.env` 仅首次导入。逻辑模型→渠道绑定(priority/weight/failover)解析在 `logical_model_router.py`。无 Key 联调设 `ARK_MOCK=true` 走本地 mock 素材。++文本 `llm_client.py`;图/视频走 `ark.py` + `tokenfree_image.py` / `tokenfree_video.py`;配音豆包 openspeech(`VOLC_TTS_*`,与方舟 Key 不同),未配则回退 edge-tts。++### 计费:每个 TaskRun 走「预扣 → 用量行 → 结算」++钱包单位为**分**(`users.balance_fen/frozen_fen`)。`services/billing/`:建任务时按估价 freeze → 执行中写 `usage_events` → poller 收尾 `settle_task` 扣实费退冻结。优先取上游真实 quota(New API: 500000 quota = 1 USD,`BILLING_USD_CNY`),取不到才用本地保守估价;官方价目由 `tokenfree_pricing.py` 拉取缓存。默认 `BILLING_ENABLED=false`。详见 `docs/BILLING.md`。易支付生产回调 URL **禁止含 `/api/`**(用 `/epay/notify` + nginx 反代)。++### 数据层与"迁移"方式++- 异步引擎 asyncpg(`AsyncSessionLocal`,业务全异步);同步引擎 psycopg2 仅少量场景+- ORM 按域拆文件:`models.py`(users/projects/shots/templates/计费/订单/tool_runs 等)、`models_drama.py`、`models_tasks.py`、`models_api.py`(API Key)、`models_agent.py`(导演 Skill)、`models_settings.py`+- **没有 Alemantic 类迁移工具**:启动时 `init_db()` 做 `create_all`,新增列必须手写进 `main.py` 的 `_apply_schema_patches()`(只允许 additive 的 PG DDL;conftest 里的测试 schema 也要同步)。线上建议 uvicorn 单 worker 以规避建表竞态+- 启动还会执行:模板 seed(只插缺失,不覆盖后台改动)、内置 Skill seed、`ADMIN_BOOTSTRAP_EMAILS` 提权(只提升已注册用户,不造号,需重启)++### 媒体与 OSS++所有成片/分镜**先落本地** `backend/static/generated/p{id}/`(FFmpeg 只读本地),返回 `/static/...`;开启 OSS 后经 `oss_queue.py` 异步入队上传并回填公网 URL(`storage.py` / `oss.py`)。删除项目需级联清理素材与 works 等从属数据。++### 前端两个应用的差异++- `frontend/`:**vite 未配 proxy**。API base 规则:未设 `VITE_API_BASE` → `当前主机:8000`(开发);设为空字符串 → 同源(生产 nginx)。请求统一走 `src/api.ts` 与 `src/api/*`。样式体系是 `styles/printfilm.css` + `pf-*` 语义 class(**不要**在用户端引 Tailwind)。含中/英 i18n+- `admin/`:Tailwind v4 + Radix/shadcn 风格组件,`@` → `src`,vite 代理 `/api`、`/static` 到 :8000;用 `cn()`;列表必须服务端分页(`page/page_size/meta.total`,复用 `PaginationBar`)++两端公共逻辑放 `lib/`(用户端已有大量 `drama*` 纯函数 helper,新功能先搜再写),页面只做编排。++## 仓库约定(来自 docs/STANDARDS.md,摘要)++- **用户可见文案、提交信息、文档默认简体中文**;对外报错 `detail` 用中文短句,不回传堆栈+- 每个函数 / 组件 / Hook 顶部写功能注释(复杂的写参数/返回值),成组 state 用块注释+- 单文件尽量 ≤ 500 行;分层:`api/` 只做鉴权/校验/调 service,业务在 `services/`;前端页面不直接拼请求细节+- 列表筛选与分页一律服务端;加载/空态/错误三态齐全;危险操作需确认+- 禁止提交:`.env`(仅允许 `*.example`)、`deploy/scripts/deploy_kepu*.py`、`.tmp/`、生成媒体、`dist/`+- 改了计费/发布方式/占位入口要同步更新 `docs/` 对应文档;**每次线上发布后在 `docs/releases/` 追加一条**+- 提 PR 前对照 `docs/STANDARDS.md` 第 9 节自检清单;专项文档:`docs/DEPLOY.md`、`docs/BILLING.md`、`docs/SEEDANCE_2_5.md`diff --git a/backend/app/api/billing.py b/backend/app/api/billing.pyindex df66dab..0a291b9 100644--- a/backend/app/api/billing.py+++ b/backend/app/api/billing.py@@ -391,13 +391,9 @@ async def close_order(def _notify_success(params: dict) -> bool:- status = str(params.get("trade_status") or params.get("status") or "")- if status.upper() in {"TRADE_SUCCESS", "SUCCESS", "1"}:- return True- # some epay variants use trade_status only when paid- if str(params.get("trade_status") or "") == "TRADE_SUCCESS":- return True- return status == "TRADE_SUCCESS"+ """判断易支付回调是否支付成功(兼容 trade_status/status 两种字段)。"""+ status = str(params.get("trade_status") or params.get("status") or "").strip().upper()+ return status in {"TRADE_SUCCESS", "SUCCESS", "1"}@router.api_route("/epay/notify", methods=["GET", "POST"])@@ -421,7 +417,11 @@ async def epay_notify(request: Request, db: AsyncSession = Depends(get_db)) -> Pif not out_trade_no:return PlainTextResponse("fail", status_code=400)- result = await db.execute(select(Order).where(Order.out_trade_no == out_trade_no))+ # 行锁串行化同一订单的并发回调:第二个回调在锁释放后读到 paid 即幂等返回,+ # 避免重复入账(易支付会对同一笔支付重发多次 notify)。+ result = await db.execute(+ select(Order).where(Order.out_trade_no == out_trade_no).with_for_update()+ )order = result.scalar_one_or_none()if not order:logger.warning("epay notify unknown order %s", out_trade_no)diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.pyindex 5b7c0a4..d999026 100644--- a/backend/app/api/drama/episodes.py+++ b/backend/app/api/drama/episodes.py@@ -909,6 +909,6 @@ async def cancel_all_video_jobs() -> dict:"""取消当前用户触发的全部漫剧分镜视频任务。"""await cancel_tasks_for_scope(db, user.id, domain="drama", task_type="fragment_video")- result = await cancel_all_episode_video_jobs()+ result = await cancel_all_episode_video_jobs(user.id)logger.info("已取消全部视频任务 user_id=%s result=%s", user.id, result)return resultdiff --git a/backend/app/api/projects.py b/backend/app/api/projects.pyindex 9ba252e..70adf89 100644--- a/backend/app/api/projects.py+++ b/backend/app/api/projects.py@@ -1002,6 +1002,13 @@ async def update_shot()if "bgm_mood" in data and data["bgm_mood"] is not None:data["bgm_mood"] = clip_shot_bgm(str(data["bgm_mood"]))+ # 旁白文本真实变化(直接改旁白或脚本规范化带出的新旁白)时作废整片连贯音轨:+ # 缓存只看文件存在性不比对文本,不删会导致旧配音配新字幕。+ new_narration = data.get("narration")+ audio_dirty = (+ new_narration is not None+ and str(new_narration).strip() != str(shot.narration or "").strip()+ )for k, v in data.items():setattr(shot, k, v)# Invalidate downstream if visual prompts changed@@ -1009,8 +1016,8 @@ async def update_shot(shot.image_url = Noneshot.video_url = Noneshot.last_frame_url = None- shot.status = "PENDING"- project.final_video_url = None+ shot.video_skip_reason = None # 画面变更,隐私拦截结论失效+ shot.status = ShotStatus.PENDINGelif ("video_prompt" in dataor "segment_script" in data@@ -1019,7 +1026,14 @@ async def update_shot():shot.video_url = Noneshot.last_frame_url = None- project.final_video_url = None+ shot.video_skip_reason = None+ if audio_dirty:+ full_narration = storage.project_dir(project_id) / "full_narration.mp3"+ full_narration.unlink(missing_ok=True)+ for sibling in project.shots:+ sibling.audio_url = None+ # 统一按素材进度把终态打回对应阶段并作废成片(本端点此前漏调,状态会卡在 DONE)+ _demote_after_edit(project)shot.version += 1await db.commit()await db.refresh(shot)diff --git a/backend/app/api/tools.py b/backend/app/api/tools.pyindex 353e0e2..f47ecf3 100644--- a/backend/app/api/tools.py+++ b/backend/app/api/tools.py@@ -143,14 +143,18 @@ async def get_tool_task()).scalar_one_or_none()billing_task_id: int | None = None- if row and isinstance(row.params, dict):+ # 本地无归属记录即拒绝:上游 task_id 可被持有者之外的人猜测传递,+ # 不能在没有归属凭据时代理查上游(视频 URL 会被拖走)。+ if not row:+ raise HTTPException(status_code=404, detail="任务不存在")+ if isinstance(row.params, dict):raw_bid = row.params.get("billing_task_id")if raw_bid is not None:try:billing_task_id = int(raw_bid)except (TypeError, ValueError):billing_task_id = None- if row and row.kind == "image":+ if row.kind == "image":data = await poll_image_tool_task(db, user, tid)else:data = await poll_video_task(user, tid)diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.pyindex e867b30..20aad5c 100644--- a/backend/app/api/v1/generation.py+++ b/backend/app/api/v1/generation.py@@ -3,12 +3,14 @@from __future__ import annotationsfrom fastapi import APIRouter, Depends, Header, HTTPException+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.config import get_settingsfrom app.database import get_dbfrom app.deps import get_api_userfrom app.models import User+from app.models_tasks import TaskRunfrom app.schemas_api import (V1GenerationOut,V1ImageGenerateRequest,@@ -202,10 +204,20 @@ async def get_task(db: AsyncSession = Depends(get_db),user: User = Depends(_resolve_api_user),) -> V1GenerationOut:- """查询 Seedance 视频任务状态。"""+ """查询 Seedance 视频任务状态(仅可查询本人提交的任务)。"""if not task_id.strip():raise HTTPException(status_code=400, detail="缺少 task_id")tid = task_id.strip()+ # 归属校验:上游 task_id 本身是可传递的凭据,不校验会拖走他人视频+ owned = (+ await db.execute(+ select(TaskRun.id)+ .where(TaskRun.requested_by == user.id, TaskRun.provider_task_id == tid)+ .limit(1)+ )+ ).scalar_one_or_none()+ if owned is None:+ raise HTTPException(status_code=404, detail="任务不存在")data = await poll_video_task(user, tid)await settle_deferred_video_poll(db,diff --git a/backend/app/deps.py b/backend/app/deps.pyindex 47ed216..def64f9 100644--- a/backend/app/deps.py+++ b/backend/app/deps.py@@ -2,13 +2,6 @@ from fastapi import Depends, HTTPException, Header, statusfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom sqlalchemy.ext.asyncio import AsyncSession-from app.database import get_db-from app.models import User-from app.services.auth import decode_token, get_user_by_id--security = HTTPBearer(auto_error=False)--from app.database import get_dbfrom app.models import Userfrom app.services.api_keys import API_KEY_PREFIX, user_from_api_key@@ -18,12 +11,17 @@ security = HTTPBearer(auto_error=False)async def _user_from_bearer(db: AsyncSession, token: str) -> User | None:+ """Bearer 令牌换用户:pf_ 前缀走 API Key,否则按 JWT 解析。"""if token.startswith(API_KEY_PREFIX):return await user_from_api_key(db, token)sub = decode_token(token)if not sub:return None- return await get_user_by_id(db, int(sub))+ try:+ user_id = int(sub)+ except (TypeError, ValueError):+ return None+ return await get_user_by_id(db, user_id)async def get_current_user(diff --git a/backend/app/main.py b/backend/app/main.pyindex 81407a1..6ba2b99 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -142,6 +142,8 @@ async def _apply_schema_patches() -> None:await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))if "last_frame_url" not in scols:await conn.execute(text("ALTER TABLE shots ADD COLUMN last_frame_url VARCHAR(1024)"))+ if "video_skip_reason" not in scols:+ await conn.execute(text("ALTER TABLE shots ADD COLUMN video_skip_reason VARCHAR(32)"))pcols = await _pg_columns(conn, "projects")if "pipeline_mode" not in pcols:diff --git a/backend/app/models.py b/backend/app/models.pyindex 16f8be9..96bd089 100644--- a/backend/app/models.py+++ b/backend/app/models.py@@ -166,6 +166,8 @@ class Shot(Base):video_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)last_frame_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)audio_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)+ # 跳过 AI 视频的原因(privacy=真人隐私拦截,静图合成);NULL 表示正常出视频+ video_skip_reason: Mapped[str | None] = mapped_column(String(32), nullable=True)status: Mapped[str] = mapped_column(String(32), default=ShotStatus.PENDING)version: Mapped[int] = mapped_column(Integer, default=1)diff --git a/backend/app/services/ark.py b/backend/app/services/ark.pyindex 37d36e8..b707ccc 100644--- a/backend/app/services/ark.py+++ b/backend/app/services/ark.py@@ -228,6 +228,24 @@ class TaskResult:upstream_cost_fen: int | None = None+# 任务查询的瞬时 HTTP 状态:限流/网关故障,任务本身仍可能在跑,+# 必须交给轮询退避(poller 有总超时兜底),单次命中绝不能判任务 failed。+def _is_transient_http_status(status_code: int) -> bool:+ """429 限流或 5xx 网关/上游故障视为可重试。"""+ return status_code == 429 or status_code >= 500+++def _retry_after_seconds(resp: httpx.Response, default: float) -> float:+ """尊重 Retry-After(delta-seconds);缺失或 HTTP-date 形式时用默认间隔,上限 60s。"""+ raw = resp.headers.get("Retry-After")+ if raw:+ try:+ return max(0.0, min(60.0, float(raw.strip())))+ except ValueError:+ pass+ return default++# 从 Seedance / New API 任务查询响应解析状态、媒体 URL 与官方 usagedef _build_task_result_from_payload(data: dict[str, Any]) -> TaskResult:payload = unwrap_video_task_payload(data)@@ -1401,28 +1419,51 @@ class ArkGateway:last_err: Exception | None = Nonefallback_body = bodyaudio_fallback_used = False++ def _audio_fallback(exc: Exception, *, accepted: bool) -> bool:+ """仅"参考音频下载失败"允许去掉参考音频重提一次;其他错误一律不重建任务。++ 上游接受任务后的重提会产生第二个计费任务,故必须严格白名单,+ 隐私拦截/失败/轮询超时等异常必须立即上抛,避免重复扣费。+ """+ nonlocal fallback_body, audio_fallback_used, last_err+ last_err = exc+ if audio_fallback_used or not _is_audio_download_error(exc):+ return False+ stripped = _strip_reference_audio(fallback_body)+ if not stripped:+ return False+ logger.warning(+ "Seedance reference_audio download failed (%s); retry once without audio refs project=%s shot=%s",+ "after accept" if accepted else "at submit",+ project_id,+ shot_no,+ )+ fallback_body = stripped+ audio_fallback_used = True+ return True+for _attempt in range(max_attempts):+ # 提交阶段失败:除参考音频错误外立即上抛,绝不盲目重新建单try:task_id = await self.gen_video_seedance_body(fallback_body,project_id=project_id,content_labels=content_labels,)+ except Exception as exc: # noqa: BLE001+ if _audio_fallback(exc, accepted=False):+ continue+ raise+ # 等待阶段失败:隐私/任务失败/超时等立即上抛;仅参考音频下载失败重提一次+ try:return await self.wait_video_assets(task_id, project_id=project_id, shot_no=shot_no)except Exception as exc: # noqa: BLE001- last_err = exc- if not audio_fallback_used and _is_audio_download_error(exc):- stripped = _strip_reference_audio(fallback_body)- if stripped:- logger.warning(- "Seedance reference_audio download failed; retry without audio refs project=%s shot=%s",- project_id,- shot_no,- )- fallback_body = stripped- audio_fallback_used = True+ if _audio_fallback(exc, accepted=True):+ continue+ raiseraise RuntimeError(str(last_err) if last_err else "Seedance multimodal failed")async def poll_task(self, task_id: str) -> TaskResult:@@ -1436,11 +1477,33 @@ class ArkGateway:deadline = time.monotonic() + self.settings.ark_video_poll_timeoutasync with httpx.AsyncClient(timeout=60.0) as client:while time.monotonic() < deadline:- resp = await client.get(- self._url(f"/contents/generations/tasks/{task_id}"),- headers=self._headers(),- )+ try:+ resp = await client.get(+ self._url(f"/contents/generations/tasks/{task_id}"),+ headers=self._headers(),+ )+ except httpx.HTTPError as exc:+ # 单次网络抖动:退避后继续轮询,由 deadline 收敛,不直接判失败+ logger.warning(+ "Seedance poll network error task=%s: %s; backing off", task_id, exc+ )+ await asyncio.sleep(float(self.settings.ark_video_poll_interval))+ continueif resp.status_code >= 400:+ # 429/5xx 是上游瞬时故障,任务状态未知,按轮询间隔退避继续,+ # 由 deadline 总超时收敛;400/401/403/404 等才是确定终态。+ if _is_transient_http_status(resp.status_code):+ logger.warning(+ "Seedance poll transient HTTP %s task=%s; backing off",+ resp.status_code,+ task_id,+ )+ await asyncio.sleep(+ _retry_after_seconds(+ resp, float(self.settings.ark_video_poll_interval)+ )+ )+ continuereturn TaskResult(status="failed", error=resp.text[:500])data = resp.json()result = self._finalize_video_result(_build_task_result_from_payload(data), task_id)@@ -1459,12 +1522,24 @@ class ArkGateway:url=f"/static/mock/video_{task_id[-8:]}.mp4",last_frame_url=f"/static/mock/last_{task_id[-8:]}.jpg",)- async with httpx.AsyncClient(timeout=30.0) as client:- resp = await client.get(- self._url(f"/contents/generations/tasks/{task_id}"),- headers=self._headers(),- )+ try:+ async with httpx.AsyncClient(timeout=30.0) as client:+ resp = await client.get(+ self._url(f"/contents/generations/tasks/{task_id}"),+ headers=self._headers(),+ )+ except httpx.HTTPError as exc:+ # 网络抖动对 poller 是下轮重试、对同步端点是继续转圈,均优于 500/误判失败+ logger.warning("Seedance fetch network error task=%s: %s", task_id, exc)+ return TaskResult(status="running", provider_task_id=task_id)if resp.status_code >= 400:+ if _is_transient_http_status(resp.status_code):+ logger.warning(+ "Seedance fetch transient HTTP %s task=%s; treat as running",+ resp.status_code,+ task_id,+ )+ return TaskResult(status="running", provider_task_id=task_id)return TaskResult(status="failed", error=resp.text[:500], provider_task_id=task_id)return self._finalize_video_result(_build_task_result_from_payload(resp.json()), task_id)diff --git a/backend/app/services/ark_control_usage.py b/backend/app/services/ark_control_usage.pydeleted file mode 100644index 5df1a63..0000000--- a/backend/app/services/ark_control_usage.py+++ /dev/null@@ -1,204 +0,0 @@-"""火山方舟管控面 GetInferenceUsage 客户端(HMAC 签名)。"""--from __future__ import annotations--import hashlib-import hmac-import json-import logging-from datetime import UTC, datetime-from typing import Any-from urllib.parse import quote--import httpx--from app.config import Settings, get_settings--logger = logging.getLogger(__name__)--HOST = "open.volcengineapi.com"-SERVICE = "ark"-VERSION = "2024-01-01"-ACTION = "GetInferenceUsage"---def volc_usage_configured(settings: Settings | None = None) -> bool:- s = settings or get_settings()- return bool(- s.volc_ark_usage_enabled- and (s.volc_access_key_id or "").strip()- and (s.volc_secret_access_key or "").strip()- )---def _hash_sha256(content: str) -> str:- return hashlib.sha256(content.encode("utf-8")).hexdigest()---def _hmac_sha256(key: bytes, msg: str) -> bytes:- return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()---def _signing_key(secret_key: str, date_stamp: str, region: str, service: str) -> bytes:- k_date = _hmac_sha256(secret_key.encode("utf-8"), date_stamp)- k_region = _hmac_sha256(k_date, region)- k_service = _hmac_sha256(k_region, service)- return _hmac_sha256(k_service, "request")---def _canonical_query(action: str, version: str) -> str:- params = [("Action", action), ("Version", version)]- return "&".join(f"{quote(k, safe='')}={quote(v, safe='')}" for k, v in sorted(params))---def _signed_headers(- *,- method: str,- query: str,- body: str,- access_key: str,- secret_key: str,- region: str,- service: str,-) -> dict[str, str]:- now = datetime.now(UTC)- amz_date = now.strftime("%Y%m%dT%H%M%SZ")- date_stamp = now.strftime("%Y%m%d")- payload_hash = _hash_sha256(body)- canonical_headers = (- f"host:{HOST}\n"- f"x-content-sha256:{payload_hash}\n"- f"x-date:{amz_date}\n"- )- signed_headers = "host;x-content-sha256;x-date"- canonical_request = "\n".join(- [- method.upper(),- "/",- query,- canonical_headers,- signed_headers,- payload_hash,- ]- )- credential_scope = f"{date_stamp}/{region}/{service}/request"- string_to_sign = "\n".join(- [- "HMAC-SHA256",- amz_date,- credential_scope,- _hash_sha256(canonical_request),- ]- )- signature = hmac.new(- _signing_key(secret_key, date_stamp, region, service),- string_to_sign.encode("utf-8"),- hashlib.sha256,- ).hexdigest()- authorization = (- f"HMAC-SHA256 Credential={access_key}/{credential_scope}, "- f"SignedHeaders={signed_headers}, Signature={signature}"- )- return {- "Host": HOST,- "Content-Type": "application/json; charset=utf-8",- "X-Date": amz_date,- "X-Content-Sha256": payload_hash,- "Authorization": authorization,- }---def parse_inference_usage_rows(result: dict[str, Any]) -> list[dict[str, Any]]:- """把 GetInferenceUsage 的 Fields/Data 表结构解析为行 dict。"""- fields = result.get("Fields") or []- data = result.get("Data") or []- names: list[str] = []- for field in fields:- if isinstance(field, dict):- names.append(str(field.get("Name") or ""))- rows: list[dict[str, Any]] = []- for item in data:- if not isinstance(item, list):- continue- row = {names[i]: item[i] for i in range(min(len(names), len(item))) if names[i]}- rows.append(row)- return rows---def aggregate_usage_by_day(rows: list[dict[str, Any]]) -> dict[str, int]:- """按日聚合 token(优先 Value / TotalTokens 字段)。"""- daily: dict[str, int] = {}- for row in rows:- day_raw = row.get("Day") or row.get("Date") or row.get("day")- if not day_raw:- continue- day_key = str(day_raw)[:10]- model_name = str(row.get("ModelName") or row.get("Model") or row.get("Endpoint") or "").lower()- if model_name and "seedance" not in model_name and "video" not in model_name:- # 未标注模型时仍计入;有模型名则尽量只统计视频- if any(token in model_name for token in ("gpt", "llm", "chat", "seedream", "tts", "text")):- continue- value = row.get("Value")- if value is None:- value = row.get("TotalTokens") or row.get("Tokens") or row.get("Token") or 0- try:- tokens = int(value or 0)- except (TypeError, ValueError):- tokens = 0- if tokens <= 0:- continue- daily[day_key] = daily.get(day_key, 0) + tokens- return daily---def build_inference_usage_request_body(start_date: str, end_date: str) -> dict[str, Any]:- """构造 GetInferenceUsage 请求体(按日粒度)。"""- return {- "StartTime": start_date,- "EndTime": end_date,- "QueryInterval": "Day",- }---async def get_inference_usage(- start_date: str,- end_date: str,- *,- settings: Settings | None = None,-) -> dict[str, Any]:- """调用方舟 GetInferenceUsage,返回原始 Result 与按日 token 聚合。"""- s = settings or get_settings()- if not volc_usage_configured(s):- raise RuntimeError("请先在后台「支付计费 → 上游成本监控」配置火山 Access Key")-- body_obj = build_inference_usage_request_body(start_date, end_date)- body = json.dumps(body_obj, ensure_ascii=False, separators=(",", ":"))- query = _canonical_query(ACTION, VERSION)- headers = _signed_headers(- method="POST",- query=query,- body=body,- access_key=s.volc_access_key_id.strip(),- secret_key=s.volc_secret_access_key.strip(),- region=(s.volc_ark_region or "cn-beijing").strip(),- service=SERVICE,- )- url = f"https://{HOST}/?{query}"- async with httpx.AsyncClient(timeout=60.0) as client:- resp = await client.post(url, content=body.encode("utf-8"), headers=headers)- if resp.status_code >= 400:- raise RuntimeError(f"GetInferenceUsage HTTP {resp.status_code}: {resp.text[:500]}")- payload = resp.json()- metadata = payload.get("ResponseMetadata") or {}- if metadata.get("Error"):- err = metadata["Error"]- raise RuntimeError(f"GetInferenceUsage error: {err}")- result = payload.get("Result") or {}- rows = parse_inference_usage_rows(result)- daily_tokens = aggregate_usage_by_day(rows)- return {- "result": result,- "rows": rows,- "daily_tokens": daily_tokens,- "request_id": metadata.get("RequestId"),- }diff --git a/backend/app/services/billing/__init__.py b/backend/app/services/billing/__init__.pyindex 619282e..5a0741a 100644--- a/backend/app/services/billing/__init__.py+++ b/backend/app/services/billing/__init__.py@@ -7,7 +7,6 @@ from app.services.billing.ephemeral import (create_ephemeral_task_row,run_billed_ephemeral,run_billed_ephemeral_deferred,- run_with_registered_handler,settle_deferred_video_poll,)from app.services.billing.estimates import estimate_phase_fen, estimate_task_fen@@ -32,7 +31,6 @@ from app.services.billing.settlement import (get_task_billing_summary,get_task_usage_lines,pending_task_commitment_fen,- settle_project,settle_task,settle_usage_charge,)@@ -66,10 +64,8 @@ __all__ = ["record_usage","run_billed_ephemeral","run_billed_ephemeral_deferred",- "run_with_registered_handler","settle_deferred_video_poll","set_current_task_run_id",- "settle_project","settle_task","settle_usage_charge","sku_by_id",diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pyindex e429bb6..5248db6 100644--- a/backend/app/services/billing/ephemeral.py+++ b/backend/app/services/billing/ephemeral.py@@ -17,7 +17,6 @@ from app.config import get_settingsfrom app.services.billing.context import billing_scopefrom app.services.billing.settlement import freeze_for_task, settle_taskfrom app.services.billing.usage import record_line-from app.services.tasks.executor import execute_task_runfrom app.services.tasks.handlers import get_task_handlerfrom app.services.tasks.service import append_task_event, build_task_event, build_task_step@@ -390,19 +389,3 @@ async def settle_deferred_video_poll()await settle_task(db, task.id)---async def run_with_registered_handler(- db: AsyncSession,- user: User,- body: TaskCreateRequest,- *,- commit: bool = True,-) -> TaskRun:- """创建任务并同步执行已注册 handler(跳过后台调度器)。"""- from app.services.tasks.service import create_task-- task = await create_task(db, user, body, commit=commit)- await execute_task_run(task.id)- refreshed = await db.get(TaskRun, task.id)- return refreshed or taskdiff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.pyindex 60e4b80..5c27eb3 100644--- a/backend/app/services/billing/settlement.py+++ b/backend/app/services/billing/settlement.py@@ -3,6 +3,7 @@from __future__ import annotationsimport logging+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom sqlalchemy import select@@ -350,69 +351,44 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:return {"charged": charged, "refunded": refund}-async def settle_project(db: AsyncSession, project_id: int) -> dict[str, int]:- """兼容旧科普项目结算:按 project_id 汇总未结算 usage(无 task_run_id 的历史行)。"""- from app.models import Project+# 终态与结算之间的正常窗口:_complete/_fail/_mark_cancelled 都是先置终态再 settle,+# 对账扫描须越过该窗口,避免与进行中的正常收尾竞争。+TERMINAL_FROZEN_RECONCILE_GRACE_SEC = 120- project = await db.get(Project, project_id)- if not project:- return {"charged": 0, "refunded": 0}- user = await _lock_user(db, int(project.user_id))- result = await db.execute(- select(UsageEvent).where(- UsageEvent.project_id == project_id,- UsageEvent.settled.is_(False),- )- )- events = list(result.scalars().all())- charged = sum(int(e.charge_fen or 0) for e in events)- for e in events:- e.settled = True+_RECONCILABLE_TERMINAL_STATUSES = ("succeeded", "failed", "cancelled")- if not user or not billing_active(user):- await db.flush()- return {"charged": 0, "refunded": 0}- frozen_before = int(user.frozen_fen or 0)- extra = max(0, charged - frozen_before)- refund = max(0, frozen_before - charged)- user.frozen_fen = 0+async def reconcile_terminal_frozen_tasks(db: AsyncSession, *, limit: int = 100) -> int:+ """对账补偿:终态但 billing_status 仍 frozen 的任务重新结算。- if extra > 0:- await _ledger(- db,- user,- -extra,- "settle",- ref_type="project",- ref_id=str(project_id),- note="settle_overage",+ 来源是 settle_task 异常中断(如结算瞬间 DB 故障)的遗留行;不处理会造成+ 冻结额长期不退、usage_events 悬空。settle_task 自带钱包流水幂等门闩,重复调用安全。+ 注意:finalizing 窗口内的任务状态是 awaiting_poll/cancel_requested(非终态),+ 不会被本扫描误伤,窗口协程按实结算的语义不受影响。+ """+ cutoff = datetime.now(UTC) - timedelta(seconds=TERMINAL_FROZEN_RECONCILE_GRACE_SEC)+ stmt = (+ select(TaskRun)+ .where(+ TaskRun.billing_status == "frozen",+ TaskRun.status.in_(_RECONCILABLE_TERMINAL_STATUSES),+ TaskRun.finished_at.is_not(None),+ TaskRun.finished_at < cutoff,)- if refund > 0:- await _ledger(- db,- user,- refund,- "unfreeze",- ref_type="project",- ref_id=str(project_id),- note="refund_unused_freeze",- )- await _ledger(- db,- user,- 0,- "settle",- ref_type="project",- ref_id=str(project_id),- note=f"charged={charged} refund={refund}",+ .limit(limit))- await db.flush()- if charged > 0 and user:- from app.services.billing.alerts import process_billing_alerts_after_charge-- await process_billing_alerts_after_charge(db, user, charged_fen=charged)- return {"charged": charged, "refunded": refund}+ rows = list((await db.execute(stmt)).scalars().all())+ fixed = 0+ for task in rows:+ try:+ await settle_task(db, int(task.id))+ fixed += 1+ except Exception: # noqa: BLE001+ logger.exception("reconcile terminal frozen task failed task_id=%s", task.id)+ if fixed:+ await db.commit()+ logger.warning("reconciled terminal frozen task runs count=%s", fixed)+ return fixedasync def credit_topup(diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex 1394371..6445dc0 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -81,10 +81,18 @@ async def _reset_fragment_video_generation(db,*,episode_id: int | None = None,+ user_id: int | None = None,) -> int:q = select(DramaEpisodeFragment)if episode_id is not None:q = q.where(DramaEpisodeFragment.episode_id == int(episode_id))+ if user_id is not None:+ # 按项目归属收敛:禁止跨用户重置分镜+ q = (+ q.join(DramaEpisode, DramaEpisodeFragment.episode_id == DramaEpisode.id)+ .join(DramaProject, DramaEpisode.project_id == DramaProject.id)+ .where(DramaProject.user_id == int(user_id))+ )frags = (await db.execute(q)).scalars().all()changed = 0for frag in frags:@@ -121,11 +129,22 @@ async def cancel_episode_video_jobs(episode_id: int) -> dict[str, Any]:}-async def cancel_all_episode_video_jobs() -> dict[str, Any]:- """取消全部漫剧分镜视频任务。"""- episode_ids = set(_video_cancelled_episodes)+async def cancel_all_episode_video_jobs(user_id: int) -> dict[str, Any]:+ """取消指定用户的全部漫剧分镜视频任务,严禁波及其他用户。"""+ episode_ids: set[int] = set()async with AsyncSessionLocal() as db:- frags = (await db.execute(select(DramaEpisodeFragment))).scalars().all()+ frags = (+ (+ await db.execute(+ select(DramaEpisodeFragment)+ .join(DramaEpisode, DramaEpisodeFragment.episode_id == DramaEpisode.id)+ .join(DramaProject, DramaEpisode.project_id == DramaProject.id)+ .where(DramaProject.user_id == int(user_id))+ )+ )+ .scalars()+ .all()+ )for frag in frags:params = frag.params or {}gen = params.get("generation") if isinstance(params, dict) else None@@ -136,9 +155,10 @@ async def cancel_all_episode_video_jobs() -> dict[str, Any]:_mark_episode_video_cancelled(ep_id)async with AsyncSessionLocal() as db:- fragments = await _reset_fragment_video_generation(db)+ fragments = await _reset_fragment_video_generation(db, user_id=user_id)logger.info(- "取消全部视频任务 fragments=%s episodes=%s",+ "取消用户全部视频任务 user_id=%s fragments=%s episodes=%s",+ user_id,fragments,len(episode_ids),)@@ -1305,6 +1325,42 @@ async def _recover_complete_fragment_video(return True+async def _settle_cancelled_after_finalized(db: AsyncSession, task_id: int) -> bool:+ """取消在 finalizing 窗口内生效、但成片已下载落盘:按实际用量结算,终态保持 cancelled。++ 若不收敛,usage_events 会永久 settled=False、冻结额被 _mark_cancelled 全额退回,+ 形成钱货两失。settle_task 对 frozen 任务按 events 多退少补,对已结算任务幂等。+ 不激活后续顺序任务(用户取消应阻断队列)。+ """+ from app.services.billing.settlement import _lock_task, settle_task+ from app.services.tasks.service import append_task_event, clear_finalizing_window++ locked = await _lock_task(db, task_id)+ if not locked:+ return False+ locked.payload = clear_finalizing_window(locked.payload)+ locked.status = "cancelled"+ locked.cancel_requested = True+ locked.current_step_status = "done"+ locked.progress_percent = 100+ locked.finished_at = datetime.now(UTC)+ locked.next_action_at = None+ locked.lease_token = None+ locked.lease_until = None+ # frozen:按已落账用量退差额;已 settled(竞态中先被结算):幂等对齐+ await settle_task(db, task_id)+ await append_task_event(+ db,+ task_id,+ event_type="task.cancelled",+ status="cancelled",+ phase="fragment_video",+ message="取消在成片收尾窗口内生效,成片已交付,按实际用量结算",+ )+ await db.commit()+ return True++# 任务平台:轮询 awaiting_poll 的分镜视频任务。async def poll_fragment_video_task(task_id: int) -> None:from app.services.ark import get_ark@@ -1399,6 +1455,10 @@ async def poll_fragment_video_task(task_id: int) -> None:na = _aware_utc(locked.next_action_at)if na is not None and na > now:return+ # 等锁期间用户可能已取消:放弃下载,交由 executor 按未交付全额退款+ if locked.cancel_requested or _is_episode_video_cancelled(episode_id):+ await _fail_task(db, locked, RuntimeError("任务已取消"))+ return# 认领前后成片已在:行锁后只补完成(避免 apply 后异常释放认领再二次下载)if _fragment_video_already_applied(frag):await _recover_complete_fragment_video(@@ -1409,9 +1469,15 @@ async def poll_fragment_video_task(task_id: int) -> None:batch_index=int(payload.get("batch_index", 0)),)return+ # 置 finalizing 并写窗口截止:_mark_cancelled 在窗口内不做全额退款,+ # 防止下载/落账与取消并发造成 usage 悬空、钱货两失+ finalizing_until = now + _FRAGMENT_FINALIZE_CLAIM_TTL+ final_payload = dict(locked.payload if isinstance(locked.payload, dict) else {})+ final_payload["finalizing_until"] = finalizing_until.isoformat()+ locked.payload = final_payloadlocked.current_step_status = "finalizing"locked.progress_percent = max(int(locked.progress_percent or 0), 90)- locked.next_action_at = now + _FRAGMENT_FINALIZE_CLAIM_TTL+ locked.next_action_at = finalizing_untilawait db.commit()try:@@ -1432,7 +1498,22 @@ async def poll_fragment_video_task(task_id: int) -> None:task_result=result,provider_task_id=task.provider_task_id,)- # apply 已 commit:立刻把 next_action 拉回现在,complete 失败时也能马上被 Selector 捞到+ # apply 已 commit:行锁复查。下载期间用户可能已取消(status=cancel_requested),+ # 此时不能走常规 complete,也不能放任 frozen 全额退款,按实际用量结算为 cancelled。+ async with AsyncSessionLocal() as recheck_db:+ rechecked = await _lock_task(recheck_db, int(task.id))+ was_cancelled = bool(+ rechecked+ and (+ rechecked.cancel_requested+ or rechecked.status in ("cancel_requested", "cancelled")+ )+ )+ if was_cancelled:+ async with AsyncSessionLocal() as cancel_db:+ await _settle_cancelled_after_finalized(cancel_db, int(task.id))+ return+ # 未取消:立刻把 next_action 拉回现在,complete 失败时也能马上被 Selector 捞到async with AsyncSessionLocal() as nudge_db:nudged = await nudge_db.get(TaskRun, int(task_id))if nudged and nudged.status == "awaiting_poll":@@ -1449,6 +1530,8 @@ async def poll_fragment_video_task(task_id: int) -> None:)except BaseException:# 含 CancelledError:poller wait_for 超时会取消协程,必须释放认领,否则 next_action 卡数小时+ from app.services.tasks.service import clear_finalizing_window+async with AsyncSessionLocal() as release_db:stalled = await _lock_task(release_db, int(task_id))if (@@ -1457,11 +1540,18 @@ async def poll_fragment_video_task(task_id: int) -> None:and (stalled.current_step_status or "") == "finalizing"):frag_done = await release_db.get(DramaEpisodeFragment, fragment_id)- if _fragment_video_already_applied(frag_done):+ finalized = _fragment_video_already_applied(frag_done)+ if finalized and stalled.cancel_requested:+ # 成片已落盘且用户在窗口内取消:按实结算(与成功路径同一收敛)+ await _settle_cancelled_after_finalized(release_db, int(task.id))+ elif finalized:# 成片已落盘:只补 complete,勿退回 polling 以免误伤+ stalled.payload = clear_finalizing_window(stalled.payload)stalled.next_action_at = datetime.now(UTC)await release_db.commit()else:+ # 未交付:退回 polling 并清窗口标记,取消可立即走全额退款+ stalled.payload = clear_finalizing_window(stalled.payload)stalled.current_step_status = "polling"stalled.next_action_at = datetime.now(UTC) + timedelta(seconds=poll_interval)await release_db.commit()diff --git a/backend/app/services/epay.py b/backend/app/services/epay.pyindex ff71139..5ae4027 100644--- a/backend/app/services/epay.py+++ b/backend/app/services/epay.py@@ -3,6 +3,7 @@from __future__ import annotationsimport hashlib+import hmacimport loggingfrom typing import Anyfrom urllib.parse import urlencode@@ -37,7 +38,7 @@ def verify(params: dict[str, Any]) -> bool:if not got:return Falseexpect = sign({k: v for k, v in params.items() if k != "sign"})- return got == expect+ return hmac.compare_digest(got, expect)def build_submit_fields(diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.pyindex d12a3ac..8af9958 100644--- a/backend/app/services/ffmpeg_compose.py+++ b/backend/app/services/ffmpeg_compose.py@@ -522,111 +522,6 @@ def _timed_caption_windows(return windows-def _ass_ts(seconds: float) -> str:- cs = int(round(max(seconds, 0) * 100))- h, rem = divmod(cs, 3600_00)- m, rem = divmod(rem, 60_00)- s, c = divmod(rem, 100)- return f"{h}:{m:02d}:{s:02d}.{c:02d}"---def _escape_ass_text(text: str) -> str:- return text.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")---def _write_ass(- shots: list[ShotMedia],- path: Path,- *,- w: int,- h: int,- font: str | None,-) -> None:- """Write ASS with PlayRes matching canvas; captions refresh by clause over time."""- portrait = (h / max(w, 1)) > 1.2- font_size = 36 if portrait else 30- margin_v = 56 if portrait else 40- max_chars = 16 if portrait else 24- font_name = "Microsoft YaHei"- if font:- stem = Path(font).stem.lower()- if stem.startswith("msyh"):- font_name = "Microsoft YaHei"- elif stem == "simhei":- font_name = "SimHei"- elif stem == "simkai":- font_name = "KaiTi"- elif stem == "simsun":- font_name = "SimSun"-- header = f"""[Script Info]-ScriptType: v4.00+-PlayResX: {w}-PlayResY: {h}-WrapStyle: 2-ScaledBorderAndShadow: yes--[V4+ Styles]-Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding-Style: Caption,{font_name},{font_size},&H00FFFFFF,&H000000FF,&H80000000,&H64000000,0,0,0,0,100,100,0,0,1,2,0,2,36,36,{margin_v},1--[Events]-Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text-"""- events: list[str] = []- cursor = 0.0- for shot in shots:- shot_start = cursor- shot_dur = max(shot.duration, 0.5)- windows = _timed_caption_windows(- shot.narration,- start=shot_start,- duration=shot_dur,- max_chars=max_chars,- )- if not windows:- windows = [(shot_start, shot_start + shot_dur, f"镜头{shot.shot_no}")]- for a, b, text in windows:- if b - a < 0.25:- continue- events.append(- f"Dialogue: 0,{_ass_ts(a)},{_ass_ts(b)},Caption,,0,0,0,,{_escape_ass_text(text)}"- )- cursor = shot_start + shot_dur- path.write_text(header + "\n".join(events) + "\n", encoding="utf-8-sig")---def _write_srt(shots: list[ShotMedia], path: Path) -> None:- """Legacy SRT helper with timed clause captions."""- lines: list[str] = []- cursor = 0.0- idx = 1-- def ts(seconds: float) -> str:- ms = int(round(seconds * 1000))- h, rem = divmod(ms, 3600_000)- m, rem = divmod(rem, 60_000)- s, milli = divmod(rem, 1000)- return f"{h:02d}:{m:02d}:{s:02d},{milli:03d}"-- for shot in shots:- shot_start = cursor- shot_dur = max(shot.duration, 0.5)- windows = _timed_caption_windows(- shot.narration,- start=shot_start,- duration=shot_dur,- max_chars=22,- )- for a, b, text in windows:- lines.append(str(idx))- lines.append(f"{ts(a)} --> {ts(b)}")- lines.append(text)- lines.append("")- idx += 1- cursor = shot_start + shot_dur- path.write_text("\n".join(lines), encoding="utf-8")-def _make_silent_audio(path: Path, duration: float) -> None:ffmpeg = _which("ffmpeg")_run(@@ -1440,129 +1335,6 @@ def compose_project(return output-def concat_native_videos(video_paths: list[Path], output: Path) -> Path:- """仅拼接已含配音的 Seedance 镜头,不叠 TTS / 不烧字幕 / 不加 BGM。"""- if not video_paths:- raise ValueError("no videos to concat")- ffmpeg = _which("ffmpeg")- output.parent.mkdir(parents=True, exist_ok=True)- if len(video_paths) == 1:- src = video_paths[0]- _run(- [- ffmpeg,- "-y",- "-i",- str(src),- "-c",- "copy",- "-movflags",- "+faststart",- str(output),- ]- )- return output-- with tempfile.TemporaryDirectory(prefix="native_concat_") as tmp:- tmp_path = Path(tmp)- # normalized 统一为可 stream-copy 的中间段(失败则整片重编码)- normalized: list[Path] = []- for idx, src in enumerate(video_paths):- if not src.exists():- raise FileNotFoundError(f"missing video: {src}")- dest = tmp_path / f"seg_{idx:03d}.mp4"- try:- _run(- [- ffmpeg,- "-y",- "-i",- str(src),- "-c",- "copy",- str(dest),- ]- )- except RuntimeError:- _run(- [- ffmpeg,- "-y",- "-i",- str(src),- "-c:v",- "libx264",- "-pix_fmt",- "yuv420p",- "-c:a",- "aac",- "-ar",- "44100",- "-ac",- "2",- str(dest),- ]- )- normalized.append(dest)-- concat_list = tmp_path / "concat.txt"- concat_list.write_text(- "\n".join(f"file '{p.resolve().as_posix()}'" for p in normalized),- encoding="utf-8",- )- merged = tmp_path / "merged.mp4"- try:- _run(- [- ffmpeg,- "-y",- "-f",- "concat",- "-safe",- "0",- "-i",- str(concat_list),- "-c",- "copy",- str(merged),- ]- )- except RuntimeError:- _run(- [- ffmpeg,- "-y",- "-f",- "concat",- "-safe",- "0",- "-i",- str(concat_list),- "-c:v",- "libx264",- "-pix_fmt",- "yuv420p",- "-c:a",- "aac",- str(merged),- ]- )- _run(- [- ffmpeg,- "-y",- "-i",- str(merged),- "-c",- "copy",- "-movflags",- "+faststart",- str(output),- ]- )- return output--def _mix_bgm(video: Path, bgm: Path, output: Path, *, volume: float = 0.22) -> None:"""Loop/trim BGM under existing audio; duck volume below narration."""ffmpeg = _which("ffmpeg")diff --git a/backend/app/services/kepu_stages.py b/backend/app/services/kepu_stages.pyindex f993452..8b1aaa4 100644--- a/backend/app/services/kepu_stages.py+++ b/backend/app/services/kepu_stages.py@@ -8,6 +8,10 @@ from app.services import storagefrom app.services.ffmpeg_compose import is_near_silent_audio+# 真人隐私被 Seedance 拦截、确认跳过 AI 视频(成片用静图)的镜头标记+VIDEO_SKIP_REASON_PRIVACY = "privacy"++def _is_image_text(project: Any) -> bool:return (getattr(project, "pipeline_mode", None) or "full") == "image_text"@@ -17,9 +21,14 @@ def shot_image_ready(shot: Any) -> bool:return bool(getattr(shot, "image_url", None) or getattr(shot, "image_ark_url", None))+def shot_video_skipped(shot: Any) -> bool:+ """分镜是否被确认跳过 AI 视频(如真人隐私拦截),无需再提交上游。"""+ return getattr(shot, "video_skip_reason", None) == VIDEO_SKIP_REASON_PRIVACY++def shot_video_ready(shot: Any) -> bool:- """分镜是否已有镜头视频。"""- return bool(getattr(shot, "video_url", None))+ """分镜视频是否已收敛:已有视频,或已确认跳过(隐私拦截后用静图合成)。"""+ return bool(getattr(shot, "video_url", None)) or shot_video_skipped(shot)def shot_audio_file_ok(shot: Any) -> bool:diff --git a/backend/app/services/kie_catalog.py b/backend/app/services/kie_catalog.pyindex c4914af..cea02ab 100644--- a/backend/app/services/kie_catalog.py+++ b/backend/app/services/kie_catalog.py@@ -173,8 +173,3 @@ def kie_upstream_catalog(*, capability: str = "all") -> list[dict[str, str]]:})return out---def default_kie_channel_models() -> list[str]:- """新建/引导 Kie 渠道时预填的主流模型 id。"""- return [m.id for m in (*IMAGE_MODELS, *VIDEO_MODELS) if m.provider == "kie"]diff --git a/backend/app/services/kie_client.py b/backend/app/services/kie_client.pyindex fe25aa8..3bbc70e 100644--- a/backend/app/services/kie_client.py+++ b/backend/app/services/kie_client.py@@ -15,7 +15,7 @@ from app.config import get_settingsfrom app.services import storagefrom app.services.ark import ImageResult, TaskResultfrom app.services.billing.pricing import kie_credits_to_cost_fen-from app.services.kie_catalog import MediaModelSpec, get_media_model+from app.services.kie_catalog import MediaModelSpeclogger = logging.getLogger(__name__)@@ -23,6 +23,10 @@ KIE_DEFAULT_BASE = "https://api.kie.ai"KIE_CHANNEL_ID = "kie-default"+class KiePollTransientError(RuntimeError):+ """recordInfo 单次查询瞬时故障(429/5xx/网络异常/坏响应/业务错误码),轮询应退避重试。"""++def resolve_kie_credentials() -> tuple[str, str]:"""优先后台 Kie 渠道 Key,env 仅作兜底。返回 (api_key, base_url)。"""try:@@ -81,25 +85,6 @@ class KieClient:}return raw, cost_fen- async def get_account_credits(self) -> int:- """GET /api/v1/chat/credit — 查询 Kie 账户剩余 credit。"""- async with httpx.AsyncClient(timeout=30.0) as client:- resp = await client.get(- f"{self.base_url}/api/v1/chat/credit",- headers=self._headers(),- )- data = resp.json() if resp.content else {}- if resp.status_code >= 400 or int(data.get("code") or 0) not in (0, 200):- raise RuntimeError(- f"Kie credit error {resp.status_code}: "- f"{(data.get('msg') or resp.text or '')[:500]}"- )- raw = data.get("data")- try:- return int(raw)- except (TypeError, ValueError) as exc:- raise RuntimeError(f"Kie credit 响应无法解析: {json.dumps(data)[:300]}") from exc-async def create_job(self, model: str, input_payload: dict[str, Any]) -> str:"""POST /api/v1/jobs/createTask,返回 taskId。"""body = {"model": model, "input": input_payload}@@ -169,39 +154,53 @@ class KieClient:raise RuntimeError(f"Kie veo missing taskId: {json.dumps(data)[:400]}")return str(task_id)+ async def _get_record(self, path: str, task_id: str, label: str) -> dict[str, Any]:+ """recordInfo 类轮询端点的统一处理。++ - 429/5xx、网络异常、非 JSON、HTTP 200 但业务 code 非 0/200:KiePollTransientError(退避重试);+ - 其余 4xx(鉴权失败/任务不存在):RuntimeError 终态;+ - 空载荷返回 {},由调用方按 running 处理。+ """+ try:+ async with httpx.AsyncClient(timeout=60.0) as client:+ resp = await client.get(+ f"{self.base_url}{path}",+ headers=self._headers(),+ params={"taskId": task_id},+ )+ except httpx.HTTPError as exc:+ raise KiePollTransientError(f"{label} network error: {exc}") from exc+ try:+ data = resp.json() if resp.content else {}+ except ValueError as exc:+ raise KiePollTransientError(+ f"{label} non-JSON HTTP {resp.status_code}: {resp.text[:200]}"+ ) from exc+ msg = str(data.get("msg") or "") if isinstance(data, dict) else ""+ if resp.status_code == 429 or resp.status_code >= 500:+ raise KiePollTransientError(+ f"{label} HTTP {resp.status_code}: {(msg or resp.text or '')[:300]}"+ )+ if resp.status_code >= 400:+ raise RuntimeError(f"{label} error {resp.status_code}: {(msg or resp.text or '')[:500]}")+ # 网关可能以 HTTP 200 + code 报错(限流/内部错误);无 code 字段时不误伤+ if isinstance(data, dict) and data.get("code") is not None:+ try:+ code_int = int(data.get("code"))+ except (TypeError, ValueError):+ code_int = -1+ if code_int not in (0, 200):+ raise KiePollTransientError(f"{label} biz code={code_int}: {msg[:300]}")+ payload = data.get("data") if isinstance(data, dict) and isinstance(data.get("data"), dict) else data+ return payload if isinstance(payload, dict) else {}+async def get_job(self, task_id: str) -> dict[str, Any]:"""GET /api/v1/jobs/recordInfo?taskId=…"""- async with httpx.AsyncClient(timeout=60.0) as client:- resp = await client.get(- f"{self.base_url}/api/v1/jobs/recordInfo",- headers=self._headers(),- params={"taskId": task_id},- )- data = resp.json() if resp.content else {}- if resp.status_code >= 400:- raise RuntimeError(- f"Kie recordInfo error {resp.status_code}: "- f"{(data.get('msg') or resp.text or '')[:500]}"- )- payload = data.get("data") if isinstance(data.get("data"), dict) else data- return payload if isinstance(payload, dict) else {}+ return await self._get_record("/api/v1/jobs/recordInfo", task_id, "Kie recordInfo")async def get_veo(self, task_id: str) -> dict[str, Any]:"""GET /api/v1/veo/record-info?taskId=…"""- async with httpx.AsyncClient(timeout=60.0) as client:- resp = await client.get(- f"{self.base_url}/api/v1/veo/record-info",- headers=self._headers(),- params={"taskId": task_id},- )- data = resp.json() if resp.content else {}- if resp.status_code >= 400:- raise RuntimeError(- f"Kie veo.record-info error {resp.status_code}: "- f"{(data.get('msg') or resp.text or '')[:500]}"- )- payload = data.get("data") if isinstance(data.get("data"), dict) else data- return payload if isinstance(payload, dict) else {}+ return await self._get_record("/api/v1/veo/record-info", task_id, "Kie veo.record-info")async def wait_job_success(self,@@ -215,7 +214,12 @@ class KieClient:interval = float(poll_interval or getattr(s, "ark_video_poll_interval", 8) or 8)deadline = time.monotonic() + float(timeout or getattr(s, "ark_video_poll_timeout", 900) or 900)while time.monotonic() < deadline:- info = await self.get_job(task_id)+ try:+ info = await self.get_job(task_id)+ except Exception as exc: # 单次查询失败(429/5xx/4xx/网络)不杀任务,退避后由 deadline 收敛+ logger.warning("Kie wait_job poll error task=%s: %s", task_id, exc)+ await asyncio.sleep(max(2.0, interval))+ continuestate = str(info.get("state") or "").lower()if state == "success":return info@@ -238,7 +242,12 @@ class KieClient:interval = float(poll_interval or getattr(s, "ark_video_poll_interval", 8) or 8)deadline = time.monotonic() + float(timeout or getattr(s, "ark_video_poll_timeout", 900) or 900)while time.monotonic() < deadline:- info = await self.get_veo(task_id)+ try:+ info = await self.get_veo(task_id)+ except Exception as exc: # 单次查询失败不杀任务,退避后由 deadline 收敛+ logger.warning("Kie wait_veo poll error task=%s: %s", task_id, exc)+ await asyncio.sleep(max(2.0, interval))+ continueflag = info.get("successFlag")if flag in (1, "1", True):return info@@ -415,16 +424,34 @@ class KieClient:return await self.create_job(spec.upstream_model, input_payload)async def fetch_video_once(self, task_id: str, *, api_kind: str = "jobs") -> TaskResult:- """单次查询视频任务状态(不下载)。"""+ """单次查询视频任务状态(不下载)。++ 瞬时查询故障返回 running(由轮询方写退避,总超时兜底);+ 终态 4xx(鉴权/任务不存在)返回 failed;+ 上游报成功但结果 URL 尚未落地时继续 running,避免下载方必炸空转。+ """+ try:+ if api_kind == "veo":+ info = await self.get_veo(task_id)+ else:+ info = await self.get_job(task_id)+ except KiePollTransientError as exc:+ logger.warning("Kie fetch transient task=%s: %s", task_id, exc)+ return TaskResult(status="running", provider_task_id=task_id)+ except RuntimeError as exc:+ return TaskResult(status="failed", error=str(exc), provider_task_id=task_id)+if api_kind == "veo":- info = await self.get_veo(task_id)flag = info.get("successFlag")if flag in (1, "1", True):urls = self._veo_result_urls(info)+ if not urls:+ logger.warning("Kie veo success without resultUrls task=%s; keep polling", task_id)+ return TaskResult(status="running", provider_task_id=task_id)raw_usage, cost_fen = self._billing_from_credits(task_id, info.get("creditsConsumed"))return TaskResult(status="succeeded",- url=urls[0] if urls else None,+ url=urls[0],provider_task_id=task_id,raw_usage=raw_usage,upstream_cost_fen=cost_fen,@@ -437,14 +464,16 @@ class KieClient:)return TaskResult(status="running", provider_task_id=task_id)- info = await self.get_job(task_id)state = str(info.get("state") or "").lower()if state == "success":urls = self._job_result_urls(info)+ if not urls:+ logger.warning("Kie task success without resultUrls task=%s; keep polling", task_id)+ return TaskResult(status="running", provider_task_id=task_id)raw_usage, cost_fen = self._billing_from_credits(task_id, info.get("creditsConsumed"))return TaskResult(status="succeeded",- url=urls[0] if urls else None,+ url=urls[0],provider_task_id=task_id,raw_usage=raw_usage,upstream_cost_fen=cost_fen,@@ -512,9 +541,3 @@ class KieClient:def get_kie() -> KieClient:"""无状态工厂。"""return KieClient()---def uses_kie(model_id: str | None) -> bool:- """项目所选模型是否走 Kie。"""- spec = get_media_model(model_id)- return bool(spec and spec.provider == "kie")diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.pyindex 72da1b8..82a405d 100644--- a/backend/app/services/model_settings.py+++ b/backend/app/services/model_settings.py@@ -94,10 +94,13 @@ def get_overlay_dict() -> dict[str, Any]:def _refresh_overlay(config: dict[str, Any]) -> None:global _overlayflat = config.get("flat") if isinstance(config.get("flat"), dict) else config+ # 空串必须保留:它是管理端「清除密钥」写入的显式值,+ # 若在此过滤,get_settings() 会回落 .env 中的旧密钥——界面显示已清除、请求仍带旧 Key。+ # 仅 None(DB 未设置该字段)跳过,让 base Settings 默认值生效。_overlay = {field: flat[field]for field in model_config_field_names()- if field in flat and flat[field] is not None and flat[field] != ""+ if field in flat and flat[field] is not None}diff --git a/backend/app/services/password_reset.py b/backend/app/services/password_reset.pyindex a792a1f..a068483 100644--- a/backend/app/services/password_reset.py+++ b/backend/app/services/password_reset.py@@ -91,16 +91,16 @@ def consume_reset_token(redis_client: Any, token: str) -> int:raise InvalidTokenError("重置链接无效或已过期")th = _token_hash(raw)key = _token_key(th)- user_id_raw = redis_client.get(key)+ # GETDEL 原子取删:并发的两次重置请求只有一次能拿到 user_id+ user_id_raw = redis_client.getdel(key)if not user_id_raw:raise InvalidTokenError("重置链接无效或已过期")try:user_id = int(user_id_raw)except (TypeError, ValueError) as exc:- redis_client.delete(key)raise InvalidTokenError("重置链接无效或已过期") from exc- redis_client.delete(key, _user_key(user_id))+ redis_client.delete(_user_key(user_id))return user_iddiff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.pyindex d6e1ccf..83504f2 100644--- a/backend/app/services/pipeline.py+++ b/backend/app/services/pipeline.py@@ -21,7 +21,6 @@ from app.services.ffmpeg_compose import (ShotMedia,allocate_durations_by_narration,compose_project,- concat_native_videos,is_ffmpeg_interrupted_error,is_near_silent_audio,probe_duration,@@ -51,7 +50,6 @@ logger = logging.getLogger(__name__)# 成片 FFmpeg 被 SIGTERM 打断时的自动重试次数_COMPOSE_SIGTERM_MAX_ATTEMPTS = 3-_running: dict[int, asyncio.Task] = {}_cancelled: set[int] = set()@@ -163,130 +161,20 @@ class PipelineCancelled(Exception):"""Raised when user cancels a running pipeline."""-def start_pipeline(project_id: int) -> str:- """Start one in-process pipeline task."""- _cancelled.discard(project_id)- if project_id in _running and not _running[project_id].done():- return "in-process"- _running[project_id] = asyncio.create_task(run_pipeline(project_id))- return "in-process"--def cancel_pipeline(project_id: int) -> bool:- """Request cancel for one in-process pipeline task."""+ """标记项目取消;流水线由任务平台 executor 驱动,无进程内任务可停,恒返回 False。"""_cancelled.add(project_id)- stopped = False-- task = _running.get(project_id)- if task and not task.done():- task.cancel()- stopped = True-- return stopped+ return Falsedef is_cancelled(project_id: int) -> bool:return project_id in _cancelled-# 单镜重生 / 合成等短任务的进程内异步执行。-_regen_tasks: dict[str, asyncio.Task] = {}---def _dispatch_side_task(- key: str,- *,- coro_factory,-) -> str:- """Start one in-process side task."""- existing = _regen_tasks.get(key)- if existing and not existing.done():- return "in-process"-- async def _runner() -> None:- try:- await coro_factory()- except Exception: # noqa: BLE001- logger.exception("in-process side task failed key=%s", key)-- _regen_tasks[key] = asyncio.create_task(_runner())- return "in-process"---def dispatch_regen_image(project_id: int, shot_id: int) -> str:- """异步重绘单镜首帧图。"""- key = f"regen-image:{project_id}:{shot_id}"-- async def _coro() -> None:- await regen_shot_image(project_id, shot_id)-- return _dispatch_side_task(- key,- coro_factory=_coro,- )---def dispatch_regen_video(project_id: int, shot_id: int) -> str:- """异步重生单镜 Seedance 视频。"""- key = f"regen-video:{project_id}:{shot_id}"-- async def _coro() -> None:- await regen_shot_video(project_id, shot_id)-- return _dispatch_side_task(- key,- coro_factory=_coro,- )---def dispatch_regen_audio(project_id: int, shot_id: int) -> str:- """异步重配单镜旁白(整片连贯 TTS)。"""- key = f"regen-audio:{project_id}:{shot_id}"-- async def _coro() -> None:- await regen_shot_audio(project_id, shot_id)-- return _dispatch_side_task(- key,- coro_factory=_coro,- )---def dispatch_regen_project_audio_and_compose(project_id: int) -> str:- """异步整片重配音并合成成片。"""- key = f"regen-all-audio:{project_id}"-- async def _coro() -> None:- await regen_project_audio_and_compose(project_id)-- return _dispatch_side_task(- key,- coro_factory=_coro,- )---def dispatch_compose_only(project_id: int) -> str:- """异步仅合成成片(不重跑 AI 阶段)。"""- key = f"compose:{project_id}"-- async def _coro() -> None:- await compose_only(project_id)-- return _dispatch_side_task(- key,- coro_factory=_coro,- )--def _is_image_text(project: Project) -> bool:return (project.pipeline_mode or "full") == "image_text"-def _use_native_video_audio(project: Project | None = None) -> bool:- """是否跳过 TTS、直拼 Seedance 口播。科普已改回外部合成,恒为 False。"""- return False--def _kepu_seedance_sfx_audio(project: Project | None = None) -> bool:"""科普 full:向 Seedance 要操作/环境音效(不含口播与 BGM)。"""if project is not None and _is_image_text(project):@@ -407,7 +295,8 @@ async def _synthesize_continuous_audio(raise ValueError("全部镜头旁白为空,无法配音")ark = get_ark()- if force or not _continuous_audio_ok(project_id):+ regenerated = force or not _continuous_audio_ok(project_id)+ if regenerated:hint = sum(max(float(getattr(s, "duration", 4) or 4), 2.0) for s in shot_rows)audio_url = await ark.tts(full_text,@@ -428,6 +317,9 @@ async def _synthesize_continuous_audio(raise RuntimeError("整片配音生成失败")if src.resolve() != dest.resolve():dest.write_bytes(src.read_bytes())+ # 新合成必须复查近静音:TTS 偶发返回极低音量音频,静默合成会产出无声成片+ if is_near_silent_audio(dest):+ raise RuntimeError("整片配音近静音(音量异常),请重新配音")dur = await asyncio.to_thread(probe_duration, dest)if not dur or dur < 0.8:@@ -467,11 +359,10 @@ async def _resume_plan(project_id: int) -> tuple[bool, bool, bool, bool]:if not project or not project.shots:return False, False, False, Falseimage_text = _is_image_text(project)- native_audio = _use_native_video_audio(project)shots = list(project.shots)has_images = all(shot_image_ready(s) for s in shots)# 与计费 resolve_kepu_billing_phase 共用旁白就绪规则- has_audio = True if native_audio else project_audio_ready(project)+ has_audio = project_audio_ready(project)has_videos = all(shot_video_ready(s) for s in shots)skip_script = len(shots) > 0skip_assets = has_images and has_audio@@ -666,6 +557,8 @@ async def run_pipeline(project_id: int, *, phase: str | None = None) -> None:{"event": "done", "percent": 100, "video_url": await _final_url(project_id)},)except (PipelineCancelled, asyncio.CancelledError):+ # 落项目态、推 SSE 后必须 re-raise:本函数由任务平台 executor 驱动,+ # 吞掉会让 TaskRun 误判 succeeded 扣费,并破坏 asyncio 任务取消语义。logger.info("pipeline cancelled project=%s", project_id)async with AsyncSessionLocal() as db:project = await db.get(Project, project_id)@@ -683,6 +576,7 @@ async def run_pipeline(project_id: int, *, phase: str | None = None) -> None:"code": "CANCELLED",},)+ raiseexcept Exception as exc: # noqa: BLE001if is_cancelled(project_id):logger.info("pipeline cancelled (during error) project=%s", project_id)@@ -728,7 +622,6 @@ async def run_pipeline(project_id: int, *, phase: str | None = None) -> None:raisefinally:_cancelled.discard(project_id)- _running.pop(project_id, None)async def delete_project_assets(project_id: int) -> None:@@ -963,7 +856,6 @@ async def _parallel_image_and_audio(project_id: int) -> None:project = result.scalar_one()tpl = project.templateimage_text = _is_image_text(project)- native_audio = _use_native_video_audio(project)shot_rows = sorted(project.shots, key=lambda s: s.shot_no)total = len(shot_rows)shot_meta = [@@ -1005,14 +897,14 @@ async def _parallel_image_and_audio(project_id: int) -> None:done_img = 0progress_lock = asyncio.Lock()# 静图成片与完整模式都合成连贯旁白;已有音轨则跳过- need_audio = (not native_audio) and (not _continuous_audio_ok(project_id))+ need_audio = not _continuous_audio_ok(project_id)async def bump_images() -> None:nonlocal done_imgasync with progress_lock:done_img += 1# 18 → ~55 while images; audio fills the rest when done- img_w = 0.7 if image_text else (0.85 if native_audio else 0.55)+ img_w = 0.7 if image_text else 0.55frac = (done_img / max(total, 1)) * img_wpct = 18 + int(40 * frac)async with _db_write_lock():@@ -1022,12 +914,9 @@ async def _parallel_image_and_audio(project_id: int) -> None:project.progress = pctproject.status = ProjectStatus.IMAGINGawait db.commit()- if native_audio:- msg = f"出图 {done_img}/{total}(配音交由视频模型)"- else:- msg = f"出图 {done_img}/{total}" + (- " · 整片配音生成中…" if need_audio else " · 配音已就绪"- )+ msg = f"出图 {done_img}/{total}" + (+ " · 整片配音生成中…" if need_audio else " · 配音已就绪"+ )await publish_progress(project_id,{@@ -1185,6 +1074,8 @@ async def _parallel_image_and_audio(project_id: int) -> None:async def _parallel_videos(project_id: int) -> None:"""按镜序逐个出视频;后镜参考上一镜尾帧。"""+ from app.services.kepu_stages import VIDEO_SKIP_REASON_PRIVACY+await _set_status(project_id, ProjectStatus.VIDEOING, 55, "VIDEOING")cfg = get_settings()ark = get_ark()@@ -1222,6 +1113,7 @@ async def _parallel_videos(project_id: int) -> None:"last_frame_url": getattr(s, "last_frame_url", None),"video_url": s.video_url,"has_video": bool(s.video_url),+ "video_skip_reason": getattr(s, "video_skip_reason", None),}for s in sorted(project.shots, key=lambda s: s.shot_no)]@@ -1242,9 +1134,23 @@ async def _parallel_videos(project_id: int) -> None:image_url=meta.get("image_url"),last_frame_url=meta.get("last_frame_url"),)- if meta.get("has_video"):+ if meta.get("has_video") or meta.get("video_skip_reason") == VIDEO_SKIP_REASON_PRIVACY:done += 1pct = 55 + int(30 * done / max(total, 1))+ if meta.get("video_skip_reason") == VIDEO_SKIP_REASON_PRIVACY:+ # 上一轮已确认真人隐私拦截:不再重提上游,直接沿用静图+ await publish_progress(+ project_id,+ {+ "event": "progress",+ "stage": "VIDEOING",+ "shot": meta["shot_no"],+ "total": total,+ "percent": pct,+ "message": f"镜头 {meta['shot_no']} 含真人已跳过 AI 视频,将用静图合成",+ },+ )+ return proxyif not proxy.last_frame_url and meta.get("video_url"):last = persist_last_frame_from_video(project_id, int(meta["shot_no"]), str(meta["video_url"])@@ -1314,6 +1220,13 @@ async def _parallel_videos(project_id: int) -> None:meta["shot_no"],msg[:240],)+ # 持久跳过标记:后续轮次不再重提上游(否则每轮都被拦截、白等配额)+ async with _db_write_lock():+ async with AsyncSessionLocal() as db:+ skipped_shot = await db.get(Shot, meta["id"])+ if skipped_shot:+ skipped_shot.video_skip_reason = VIDEO_SKIP_REASON_PRIVACY+ await db.commit()done += 1pct = 55 + int(30 * done / max(total, 1))await publish_progress(@@ -1407,200 +1320,6 @@ async def _parallel_videos(project_id: int) -> None:)-async def _image_stage(project_id: int) -> None:- """逐镜出图;后镜 Seedream 参考上一镜静帧。"""- await _set_status(project_id, ProjectStatus.IMAGING, 20, "IMAGING")- ark = get_ark()- async with AsyncSessionLocal() as db:- result = await db.execute(- select(Project)- .where(Project.id == project_id)- .options(selectinload(Project.shots), selectinload(Project.template))- )- project = result.scalar_one()- tpl = project.template- total = len(project.shots)- ref_urls = _project_base_refs(project)- image_size = _image_size_for(project)- negative = _project_image_negative(project)- style_prefix = _effective_style(project)- bible = getattr(project, "character_bible", None) or ""- photoreal = template_is_photoreal(tpl)- consist = template_consistency_mode(tpl)- lock_character = consist == "character"- prev_shot = None- image_model = (getattr(project, "image_model", None) or "").strip()- output_ratio = _project_output_ratio(project) or ""-- for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):- await _ensure_not_cancelled(project_id)- if shot.image_url or shot.image_ark_url:- prev_shot = shot- continue- refs = image_refs_for_shot(prev_shot, ref_urls)- prompt = build_locked_image_prompt(- style_prefix,- strip_lock_blocks(shot.img_prompt),- bible if lock_character else "",- photoreal=photoreal,- lock_character=lock_character,- lock_style=True,- )- img = await ark.gen_image(- prompt,- negative,- refs,- project_id=project_id,- shot_no=shot.shot_no,- size=image_size,- model=image_model,- aspect_ratio=output_ratio or None,- )- shot.image_url = img.local_url- shot.image_ark_url = img.remote_url- shot.status = ShotStatus.IMAGE_READY- prev_shot = shot- span = 55 if _is_image_text(project) else 25- pct = 20 + int(span * (idx + 1) / max(total, 1))- project.progress = pct- await db.commit()- await publish_progress(- project_id,- {- "event": "progress",- "stage": "IMAGING",- "shot": shot.shot_no,- "total": total,- "percent": pct,- },- )- if project.shots:- project.cover_url = sorted(project.shots, key=lambda s: s.shot_no)[0].image_url- project.status = ProjectStatus.IMAGE_READY- project.progress = 75 if _is_image_text(project) else 45- await db.commit()---async def _video_stage(project_id: int) -> None:- """逐镜出视频;后镜参考上一镜尾帧(无尾帧则用静帧)。"""- await _set_status(project_id, ProjectStatus.VIDEOING, 50, "VIDEOING")- ark = get_ark()- async with AsyncSessionLocal() as db:- result = await db.execute(- select(Project)- .where(Project.id == project_id)- .options(selectinload(Project.shots), selectinload(Project.template))- )- project = result.scalar_one()- tpl = project.template- generate_audio = _kepu_seedance_sfx_audio(project)- ambient_only = generate_audio- consistency = template_consistency_mode(tpl) == "character" and bool(- tpl.seedance_config.get("character_consistency", True)- )- motion = str(tpl.seedance_config.get("motion_bias", ""))- total = len(project.shots)- cfg = get_settings()- resolution = cfg.ark_video_resolution- if project.resolution_mode == "hd" and resolution == "480p":- resolution = "720p"- ratio = _project_output_ratio(project) or cfg.ark_video_ratio- style_prefix = _effective_style(project)- video_model = (getattr(project, "video_model", None) or "").strip()- for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):- await _ensure_not_cancelled(project_id)- if shot.video_url:- if not shot.last_frame_url:- shot.last_frame_url = persist_last_frame_from_video(- project_id, int(shot.shot_no), str(shot.video_url)- )- await db.commit()- continue- script = (getattr(shot, "segment_script", "") or shot.video_prompt or "").strip()- prompt = _kepu_video_prompt(- script,- style_prefix=style_prefix,- motion_bias=motion,- camera=shot.camera or "",- ambient_only=ambient_only,- )- dur = segplan.resolve_api_duration(- script,- fallback=shot.duration,- lo=cfg.seedance_duration_min,- hi=cfg.seedance_duration_max,- )- image_ref = shot.image_ark_url or shot.image_url or ""- extra_refs = video_extra_refs_for_shot(previous_usable_shot(list(project.shots), shot.shot_no))- local_video, task_result = await ark.gen_and_wait_video(- image_ref,- prompt,- int(dur),- project_id=project_id,- shot_no=shot.shot_no,- character_consistency=consistency,- resolution=resolution,- ratio=ratio,- generate_audio=generate_audio,- model=video_model,- extra_image_urls=extra_refs or None,- )- shot.video_url = local_video- shot.last_frame_url = persist_last_frame_from_video(- project_id,- int(shot.shot_no),- local_video,- preferred_url=getattr(task_result, "last_frame_url", None),- )- shot.status = ShotStatus.VIDEO_READY- billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"- await _record_seedance_usage(- project_id,- billing_key=billing_key,- model=cfg.model_video,- task_result=task_result,- fallback_duration_sec=max(float(dur), 2.0),- shot_id=shot.id,- )- pct = 50 + int(25 * (idx + 1) / max(total, 1))- project.progress = pct- await db.commit()- await publish_progress(- project_id,- {- "event": "progress",- "stage": "VIDEOING",- "shot": shot.shot_no,- "total": total,- "percent": pct,- },- )- project.status = ProjectStatus.VIDEO_READY- project.progress = 75- await db.commit()---async def _audio_stage(project_id: int) -> None:- """Fallback audio stage — continuous narration for the whole film."""- await _set_status(project_id, ProjectStatus.AUDIOING, 80, "AUDIOING")- async with AsyncSessionLocal() as db:- result = await db.execute(- select(Project)- .where(Project.id == project_id)- .options(selectinload(Project.shots), selectinload(Project.template))- )- project = result.scalar_one()- voice = _project_voice(project)- shots = sorted(project.shots, key=lambda s: s.shot_no)- await _synthesize_continuous_audio(- project_id, voice=voice, shot_rows=shots, force=False- )- await publish_progress(- project_id,- {"event": "progress", "stage": "AUDIOING", "percent": 88, "message": "整片配音完成"},- )--async def _compose_stage(project_id: int) -> None:await _set_status(project_id, ProjectStatus.COMPOSING, 92, "COMPOSING")async with AsyncSessionLocal() as db:@@ -1610,135 +1329,100 @@ async def _compose_stage(project_id: int) -> None:.options(selectinload(Project.shots), selectinload(Project.template)))project = result.scalar_one()- native_audio = _use_native_video_audio(project)out = storage.project_dir(project_id) / "final.mp4"- if native_audio:- # 模型已含配音/字幕:只拼接镜头,不再 TTS 叠轨与烧字- video_paths: list[Path] = []- for shot in sorted(project.shots, key=lambda s: s.shot_no):- pdir = storage.project_dir(project_id)- video_path = storage.local_path_from_url(shot.video_url or "")- if shot.video_url and (not video_path or not video_path.exists()):- if shot.video_url.startswith("http"):- video_path = await storage.ensure_local_media(- shot.video_url, pdir / f"shot_{shot.shot_no:03d}.mp4"- )- if video_path and video_path.exists():- video_paths.append(video_path)- if not video_paths:- raise RuntimeError("没有可用镜头视频,无法拼接成片(视频模型配音模式)")- await publish_progress(- project_id,- {- "event": "progress",- "stage": "COMPOSING",- "percent": 94,- "message": f"拼接 {len(video_paths)} 段带配音视频…",- },- )- await _run_ffmpeg_compose_with_retry(- project_id,- lambda: concat_native_videos(video_paths, out),- )- project.final_video_url = storage.publish_local(out)- if project.status != ProjectStatus.CANCELLED:- project.status = ProjectStatus.AUDITING- project.progress = 96- await db.commit()- else:- media: list[ShotMedia] = []- for shot in sorted(project.shots, key=lambda s: s.shot_no):- pdir = storage.project_dir(project_id)- # Resolve/download to local for FFmpeg; keep OSS URLs in DB for frontend preview- video_path = storage.local_path_from_url(shot.video_url or "")- audio_path = storage.local_path_from_url(shot.audio_url or "")- image_path = storage.local_path_from_url(shot.image_url or "")- if shot.video_url and (not video_path or not video_path.exists()):- if shot.video_url.startswith("http"):- video_path = await storage.ensure_local_media(- shot.video_url, pdir / f"shot_{shot.shot_no:03d}.mp4"- )- if shot.audio_url and (not audio_path or not audio_path.exists()):- if shot.audio_url.startswith("http"):- audio_path = await storage.ensure_local_media(- shot.audio_url, pdir / f"shot_{shot.shot_no:03d}_tts.mp3"- )- if shot.image_url and (not image_path or not image_path.exists()):- if shot.image_url.startswith("http"):- image_path = await storage.ensure_local_media(- shot.image_url, pdir / f"shot_{shot.shot_no:03d}.png"- )- media.append(- ShotMedia(- shot_no=shot.shot_no,- duration=float(shot.duration),- narration=shot.narration,- overlay_title=getattr(shot, "overlay_title", "") or "",- overlay_subtitle=getattr(shot, "overlay_subtitle", "") or "",- video_path=video_path if video_path and video_path.exists() else None,- audio_path=audio_path if audio_path and audio_path.exists() else None,- image_path=image_path if image_path and image_path.exists() else None,+ media: list[ShotMedia] = []+ for shot in sorted(project.shots, key=lambda s: s.shot_no):+ pdir = storage.project_dir(project_id)+ # Resolve/download to local for FFmpeg; keep OSS URLs in DB for frontend preview+ video_path = storage.local_path_from_url(shot.video_url or "")+ audio_path = storage.local_path_from_url(shot.audio_url or "")+ image_path = storage.local_path_from_url(shot.image_url or "")+ if shot.video_url and (not video_path or not video_path.exists()):+ if shot.video_url.startswith("http"):+ video_path = await storage.ensure_local_media(+ shot.video_url, pdir / f"shot_{shot.shot_no:03d}.mp4"+ )+ if shot.audio_url and (not audio_path or not audio_path.exists()):+ if shot.audio_url.startswith("http"):+ audio_path = await storage.ensure_local_media(+ shot.audio_url, pdir / f"shot_{shot.shot_no:03d}_tts.mp3")+ if shot.image_url and (not image_path or not image_path.exists()):+ if shot.image_url.startswith("http"):+ image_path = await storage.ensure_local_media(+ shot.image_url, pdir / f"shot_{shot.shot_no:03d}.png"+ )+ media.append(+ ShotMedia(+ shot_no=shot.shot_no,+ duration=float(shot.duration),+ narration=shot.narration,+ overlay_title=getattr(shot, "overlay_title", "") or "",+ overlay_subtitle=getattr(shot, "overlay_subtitle", "") or "",+ video_path=video_path if video_path and video_path.exists() else None,+ audio_path=audio_path if audio_path and audio_path.exists() else None,+ image_path=image_path if image_path and image_path.exists() else None,)+ )- ratio = _project_output_ratio(project)- mode = project.pipeline_mode or "full"+ ratio = _project_output_ratio(project)+ mode = project.pipeline_mode or "full"- full_audio = _full_narration_path(project_id)- if not full_audio.exists():- full_audio = None+ full_audio = _full_narration_path(project_id)+ if not full_audio.exists():+ full_audio = None- sub_cfg = _merge_subtitle_preset(- (project.template.subtitle_config if project.template else None) or {},- getattr(project, "subtitle_preset", "") or "",- )- layout = str(sub_cfg.get("position") or "top")- if layout not in {"top", "split", "bottom", "center"}:- layout = "top"- # bottom/center still use top dual-line unless explicitly split- subtitle_layout = "split" if layout == "split" else "top"-- def _f(key: str, default: float) -> float:- try:- return float(sub_cfg.get(key, default))- except (TypeError, ValueError):- return default-- bgm_mood = (getattr(project, "bgm_lock", None) or "").strip()- if not bgm_mood and project.shots:- bgm_mood = (project.shots[0].bgm_mood or "").strip()- if not bgm_mood and project.template and isinstance(project.template.audio_config, dict):- bgm_mood = str(project.template.audio_config.get("bgm_mood") or "").strip()- bgm_path = resolve_bgm_path(bgm_mood)- keep_video_sfx = _kepu_seedance_sfx_audio(project)-- await _run_ffmpeg_compose_with_retry(- project_id,- lambda: compose_project(- media,- out,- ComposeOptions(- ratio=ratio,- mode=mode,- resolution_mode=project.resolution_mode or "preview",- full_audio_path=full_audio,- subtitle_layout=subtitle_layout,- title_scale=_f("title_scale", 1.35),- sub_scale=_f("sub_scale", 1.3),- caption_scale=_f("caption_scale", 1.25),- bgm_path=bgm_path,- bgm_volume=0.22,- keep_video_sfx=keep_video_sfx,- sfx_volume=0.22,- ),+ sub_cfg = _merge_subtitle_preset(+ (project.template.subtitle_config if project.template else None) or {},+ getattr(project, "subtitle_preset", "") or "",+ )+ layout = str(sub_cfg.get("position") or "top")+ if layout not in {"top", "split", "bottom", "center"}:+ layout = "top"+ # bottom/center still use top dual-line unless explicitly split+ subtitle_layout = "split" if layout == "split" else "top"++ def _f(key: str, default: float) -> float:+ try:+ return float(sub_cfg.get(key, default))+ except (TypeError, ValueError):+ return default++ bgm_mood = (getattr(project, "bgm_lock", None) or "").strip()+ if not bgm_mood and project.shots:+ bgm_mood = (project.shots[0].bgm_mood or "").strip()+ if not bgm_mood and project.template and isinstance(project.template.audio_config, dict):+ bgm_mood = str(project.template.audio_config.get("bgm_mood") or "").strip()+ bgm_path = resolve_bgm_path(bgm_mood)+ keep_video_sfx = _kepu_seedance_sfx_audio(project)++ await _run_ffmpeg_compose_with_retry(+ project_id,+ lambda: compose_project(+ media,+ out,+ ComposeOptions(+ ratio=ratio,+ mode=mode,+ resolution_mode=project.resolution_mode or "preview",+ full_audio_path=full_audio,+ subtitle_layout=subtitle_layout,+ title_scale=_f("title_scale", 1.35),+ sub_scale=_f("sub_scale", 1.3),+ caption_scale=_f("caption_scale", 1.25),+ bgm_path=bgm_path,+ bgm_volume=0.22,+ keep_video_sfx=keep_video_sfx,+ sfx_volume=0.22,),- )- project.final_video_url = storage.publish_local(out)- if project.status != ProjectStatus.CANCELLED:- project.status = ProjectStatus.AUDITING- project.progress = 96- await db.commit()+ ),+ )+ project.final_video_url = storage.publish_local(out)+ if project.status != ProjectStatus.CANCELLED:+ project.status = ProjectStatus.AUDITING+ project.progress = 96+ await db.commit()async with AsyncSessionLocal() as db:project = await db.get(Project, project_id)@@ -1830,27 +1514,34 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:model=image_model,aspect_ratio=aspect_ratio,)+ cancelled = Falseasync with AsyncSessionLocal() as db:shot = await db.get(Shot, shot_id)project = await db.get(Project, project_id)if not shot or not project:raise ValueError("shot not found")- shot.image_url = img.local_url- shot.image_ark_url = img.remote_url- shot.video_url = None- shot.last_frame_url = None- shot.status = ShotStatus.IMAGE_READY- shot.version += 1- project.status = ProjectStatus.IMAGE_READY- project.final_video_url = None- await db.commit()+ cancelled = project.status == ProjectStatus.CANCELLED+ if not cancelled:+ shot.image_url = img.local_url+ shot.image_ark_url = img.remote_url+ shot.video_url = None+ shot.last_frame_url = None+ shot.video_skip_reason = None # 换了首帧图,真人隐私可能已消失+ shot.status = ShotStatus.IMAGE_READY+ shot.version += 1+ project.status = ProjectStatus.IMAGE_READY+ project.final_video_url = None+ await db.commit()s = get_settings()+ # 上游成本已真实发生:即使项目刚被取消也要记账,随后抛出让任务收敛取消态await _record_seedream_usage(project_id,image_result=img,model=s.model_image,shot_id=shot_id,)+ if cancelled:+ raise PipelineCancelled(f"project {project_id} cancelled during regen image")@storage.without_intermediate_oss@@ -1916,19 +1607,24 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:local_video,preferred_url=getattr(task_result, "last_frame_url", None),)+ cancelled = Falseasync with AsyncSessionLocal() as db:shot = await db.get(Shot, shot_id)project = await db.get(Project, project_id)if not shot or not project:raise ValueError("shot not found")- shot.video_url = local_video- shot.last_frame_url = last- shot.status = ShotStatus.VIDEO_READY- shot.version += 1- project.final_video_url = None- project.status = ProjectStatus.VIDEO_READY- await db.commit()+ cancelled = project.status == ProjectStatus.CANCELLED+ if not cancelled:+ shot.video_url = local_video+ shot.last_frame_url = last+ shot.video_skip_reason = None # 视频成功生成,清除跳过标记+ shot.status = ShotStatus.VIDEO_READY+ shot.version += 1+ project.final_video_url = None+ project.status = ProjectStatus.VIDEO_READY+ await db.commit()billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"+ # 上游成本已真实发生:即使项目刚被取消也要记账,随后抛出让任务收敛取消态await _record_seedance_usage(project_id,billing_key=billing_key,@@ -1937,6 +1633,8 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:fallback_duration_sec=max(float(dur), 2.0),shot_id=shot_id,)+ if cancelled:+ raise PipelineCancelled(f"project {project_id} cancelled during regen video")@storage.without_intermediate_oss@@ -1949,8 +1647,6 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:.options(selectinload(Project.template), selectinload(Project.shots)))project = result.scalar_one()- if _use_native_video_audio(project):- raise ValueError("当前为视频模型配音,请使用「重生视频」重做该镜旁白")shot = next((s for s in project.shots if s.id == shot_id), None)if not shot:raise ValueError("shot not found")@@ -1963,6 +1659,7 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:await _synthesize_continuous_audio(project_id, voice=voice, shot_rows=shots, force=True)+ cancelled = Falseasync with AsyncSessionLocal() as db:result = await db.execute(select(Project)@@ -1971,9 +1668,11 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:)project = result.scalar_one_or_none()shot = await db.get(Shot, shot_id)- if shot:+ if project and project.status == ProjectStatus.CANCELLED:+ cancelled = True+ elif shot:shot.version += 1- if project:+ if project and not cancelled:project.final_video_url = Noneshots = list(project.shots or [])if _is_image_text(project):@@ -1983,15 +1682,13 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:else:project.status = ProjectStatus.IMAGE_READYawait db.commit()+ if cancelled:+ raise PipelineCancelled(f"project {project_id} cancelled during regen audio")@storage.without_intermediate_ossasync def regen_project_audio_and_compose(project_id: int) -> None:"""Force continuous re-TTS with current voice, then compose."""- async with AsyncSessionLocal() as db:- project = await db.get(Project, project_id)- if project and _use_native_video_audio(project):- raise ValueError("当前为视频模型配音,请重生各镜视频后点「拼接成片」")await _set_status(project_id, ProjectStatus.AUDIOING, 80, "AUDIOING")async with AsyncSessionLocal() as db:result = await db.execute(diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.pyindex 21d744e..c4d9529 100644--- a/backend/app/services/tasks/executor.py+++ b/backend/app/services/tasks/executor.py@@ -50,22 +50,23 @@ async def execute_task_run(task_id: int) -> None:try:await freeze_for_task(db, task)except ValueError as exc:- await _fail_drama_asset_generation_if_needed(db, task, str(exc))- task.status = "failed"- task.error_code = "insufficient_balance"- task.error_message = str(exc)[:500]- task.finished_at = datetime.now(UTC)- # 未预扣成功,保持 none(skipped 仅表示全局关闭计费)- task.billing_status = "none"- await append_task_event(+ # 余额不足:可预期失败,专用错误码便于前端引导充值+ await _fail_task_before_start(+ db, task, step, error_code="insufficient_balance", message=str(exc)+ )+ return+ except Exception as exc: # noqa: BLE001+ # DB 瞬断等非 ValueError 不能裸逃:否则任务永久卡 leased,只能等 watchdog 周期兜底+ logger.exception("freeze_for_task failed task_id=%s", task.id)+ from app.services.exc_format import format_exception_message++ await _fail_task_before_start(db,- task.id,- event_type="task.failed",- status=task.status,- phase=task.current_step_key,- message=task.error_message,+ task,+ step,+ error_code=type(exc).__name__,+ message=format_exception_message(exc, fallback="预扣失败", limit=500),)- await db.commit()returnnow = datetime.now(UTC)@@ -102,9 +103,6 @@ async def execute_task_run(task_id: int) -> None:if task.status == "awaiting_poll":await db.commit()return- if task.status == "pending" and isinstance(result, dict) and result.get("deferred"):- await db.commit()- returnif isinstance(result, dict) and result.get("cancelled"):await _mark_cancelled(db, task)return@@ -157,6 +155,35 @@ async def _complete_task(db, task, result: dict) -> None:await db.commit()+# 预扣阶段(handler 尚未执行)失败收敛:此时 _lock_task(populate_existing) 已卸掉+# task.steps 关系,不能像 _fail_task 那样再访问 task.steps[0],step 由调用方预读传入。+async def _fail_task_before_start(db, task, step, *, error_code: str, message: str) -> None:+ now = datetime.now(UTC)+ set_task_step_state(task, step, status="failed", now=now)+ task.status = "failed"+ task.error_code = error_code+ task.error_message = message[:500]+ task.finished_at = now+ # frozen 之后的异常(如落流水失败)保留 frozen 交 settle_task 对账;未预扣成功保持 none+ if task.billing_status != "frozen":+ task.billing_status = "none"+ await append_task_event(+ db,+ task.id,+ event_type="task.failed",+ status=task.status,+ phase=task.current_step_key,+ message=task.error_message,+ )+ # 资产生图/视频:同步写回 asset.params.generation,避免前端只看到空的「生图失败」+ await _fail_drama_asset_generation_if_needed(db, task, task.error_message)+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)+ await db.commit()++# 把任务收敛到失败态。async def _fail_task(db, task, exc: Exception) -> None:from app.services.exc_format import format_exception_message@@ -227,6 +254,17 @@ async def _fail_task(db, task, exc: Exception) -> None:# 把任务收敛到取消态。async def _mark_cancelled(db, task) -> None:+ # finalizing 收尾窗口内让位:poller 协程可能正在下载成片并落真实用量,+ # 此时全额退款会导致 usage_events 悬空、钱货两失;协程会按实结算或退回 polling。+ # 任务保持 cancel_requested,scheduler 下轮重试,窗口 TTL(10 分钟)兜底。+ from app.services.tasks.service import task_finalizing_window_open++ if task_finalizing_window_open(task):+ logger.info(+ "cancel deferred: task %s inside finalizing window, poller will settle",+ task.id,+ )+ returnnow = datetime.now(UTC)step = task.steps[0] if task.steps else Noneset_task_step_state(task, step, status="cancelled", now=now)diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex 841c050..0307c5d 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -132,66 +132,96 @@ async def _run_drama_seed_assets(task: TaskRun) -> dict[str, Any] | None:)+# 执行科普可取消子流程:项目已被用户请求取消时,PipelineCancelled 收敛为+# {"cancelled": True}(executor 据此落取消态并退回冻结);其余异常照常抛出。+async def _await_kepu(task: TaskRun, aw: Awaitable[Any], **extra: Any) -> dict[str, Any]:+ from app.services.pipeline import PipelineCancelled++ try:+ await aw+ except PipelineCancelled:+ if task.cancel_requested:+ return {"cancelled": True, "project_id": task.project_id, **extra}+ raise+ return {"ok": True, "project_id": task.project_id, **extra}++# 执行科普分阶段流水线(严格按 payload.phase 预扣对应阶段)。async def _run_kepu_project_pipeline(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import run_pipelinepayload = task.payload if isinstance(task.payload, dict) else {}phase = payload.get("phase")- await run_pipeline(- _require_int(task.project_id, "project_id"),- phase=str(phase) if phase is not None else None,+ return await _await_kepu(+ task,+ run_pipeline(+ _require_int(task.project_id, "project_id"),+ phase=str(phase) if phase is not None else None,+ ),+ phase=phase,)- return {"ok": True, "project_id": task.project_id, "phase": phase}# 执行科普单镜生图任务。async def _run_kepu_shot_image(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import regen_shot_image- await regen_shot_image(- _require_int(task.project_id, "project_id"),- _require_int(task.shot_id, "shot_id"),+ return await _await_kepu(+ task,+ regen_shot_image(+ _require_int(task.project_id, "project_id"),+ _require_int(task.shot_id, "shot_id"),+ ),+ shot_id=task.shot_id,)- return {"ok": True, "project_id": task.project_id, "shot_id": task.shot_id}# 执行科普单镜生视频任务。async def _run_kepu_shot_video(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import regen_shot_video- await regen_shot_video(- _require_int(task.project_id, "project_id"),- _require_int(task.shot_id, "shot_id"),+ return await _await_kepu(+ task,+ regen_shot_video(+ _require_int(task.project_id, "project_id"),+ _require_int(task.shot_id, "shot_id"),+ ),+ shot_id=task.shot_id,)- return {"ok": True, "project_id": task.project_id, "shot_id": task.shot_id}# 执行科普单镜配音任务。async def _run_kepu_shot_audio(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import regen_shot_audio- await regen_shot_audio(- _require_int(task.project_id, "project_id"),- _require_int(task.shot_id, "shot_id"),+ return await _await_kepu(+ task,+ regen_shot_audio(+ _require_int(task.project_id, "project_id"),+ _require_int(task.shot_id, "shot_id"),+ ),+ shot_id=task.shot_id,)- return {"ok": True, "project_id": task.project_id, "shot_id": task.shot_id}# 执行科普整片重配音任务。async def _run_kepu_project_audio(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import regen_project_audio_and_compose- await regen_project_audio_and_compose(_require_int(task.project_id, "project_id"))- return {"ok": True, "project_id": task.project_id}+ return await _await_kepu(+ task,+ regen_project_audio_and_compose(_require_int(task.project_id, "project_id")),+ )# 执行科普仅合成任务。async def _run_kepu_compose(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import compose_only- await compose_only(_require_int(task.project_id, "project_id"))- return {"ok": True, "project_id": task.project_id}+ return await _await_kepu(+ task,+ compose_only(_require_int(task.project_id, "project_id")),+ )# 执行延时模拟任务,便于验证任务平台状态流转。diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.pyindex 9e69d06..c75b192 100644--- a/backend/app/services/tasks/poller.py+++ b/backend/app/services/tasks/poller.py@@ -7,7 +7,7 @@ import loggingimport timefrom datetime import UTC, datetime, timedelta-from sqlalchemy import select+from sqlalchemy import or_, selectfrom app.config import get_settingsfrom app.database import AsyncSessionLocal@@ -127,10 +127,13 @@ async def _select_and_poll_due() -> None:now = datetime.now(UTC)batch_limit = max(1, int(get_settings().task_poll_max_concurrency or 20))async with AsyncSessionLocal() as db:+ # 仅 drama fragment_video 走 drama 收尾轮询;api/studio 的轻量 deferred+ # 视频由 _poll_ephemeral_deferred_tasks 处理,误送 drama poller 会被立即判失败。stmt = (select(TaskRun.id).where(TaskRun.status == "awaiting_poll",+ TaskRun.task_type == "fragment_video",TaskRun.next_action_at.is_not(None),TaskRun.next_action_at <= now,)@@ -213,12 +216,15 @@ async def _poll_ephemeral_deferred_tasks() -> None:timeout_sec = float(get_settings().ark_video_poll_timeout or 900.0)async with AsyncSessionLocal() as db:+ # next_action_at 为 NULL(尚未安排退避)视为到期;否则只查到期任务,+ # 避免每个轮询周期都对全部在途任务请求上游。stmt = (select(TaskRun).where(TaskRun.status == "awaiting_poll",TaskRun.domain.in_(["api", "studio"]),TaskRun.billing_status == "frozen",+ or_(TaskRun.next_action_at.is_(None), TaskRun.next_action_at <= now),).order_by(TaskRun.next_action_at.asc().nullsfirst(), TaskRun.id.asc()).limit(20)@@ -227,57 +233,72 @@ async def _poll_ephemeral_deferred_tasks() -> None:for row in rows:task_id = int(row.id)- async with AsyncSessionLocal() as db:- task = await db.get(TaskRun, task_id)- if not task or task.status != "awaiting_poll":- continue-- started = task.started_at or task.created_at- if started is not None and started.tzinfo is None:- started = started.replace(tzinfo=UTC)- if started and (now - started).total_seconds() > timeout_sec:- task.status = "failed"- task.error_code = "poll_timeout"- task.error_message = "视频轮询超时,预扣已退回"- task.finished_at = now- await append_task_event(- db,- task.id,- event_type="task.failed",- status=task.status,- phase=task.current_step_key,- message=task.error_message,- )- try:- await settle_task(db, task.id)- except Exception: # noqa: BLE001- logger.exception("settle_task failed task_id=%s", task.id)- await db.commit()- continue-- user = await db.get(User, task.requested_by)- provider_id = (task.provider_task_id or "").strip()- if not user or not provider_id:- continue-- data = await poll_video_task(user, provider_id)- status = str(data.get("status") or "").strip().lower()- if status in {"", "running", "queued"}:- task.next_action_at = now + timedelta(- seconds=max(1.0, float(get_settings().ark_video_poll_interval or 8.0))- )- await db.commit()- continue-- await settle_deferred_video_poll(+ try:+ await _poll_one_ephemeral_task(task_id, now=now, timeout_sec=timeout_sec)+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001+ # 单条失败不影响本批其余任务,下个周期自然重试+ logger.exception("ephemeral deferred poll failed task_id=%s", task_id)+++# 轮询单条 api/studio 轻量 deferred 视频任务:超时判失败、运行中写回退避、终态结算。+async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) -> None:+ from app.models import User+ from app.services.billing.ephemeral import settle_deferred_video_poll+ from app.services.studio_tools import poll_video_task++ async with AsyncSessionLocal() as db:+ task = await db.get(TaskRun, task_id)+ if not task or task.status != "awaiting_poll":+ return++ started = task.started_at or task.created_at+ if started is not None and started.tzinfo is None:+ started = started.replace(tzinfo=UTC)+ if started and (now - started).total_seconds() > timeout_sec:+ task.status = "failed"+ task.error_code = "poll_timeout"+ task.error_message = "视频轮询超时,预扣已退回"+ task.finished_at = now+ await append_task_event(db,- user,- provider_task_id=provider_id,- poll_status=status,- error=str(data.get("error") or "") or None,- billing_task_id=task.id,- usage_tokens=int((data.get("usage") or {}).get("total_tokens") or 0),- completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),- raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,+ task.id,+ event_type="task.failed",+ status=task.status,+ phase=task.current_step_key,+ message=task.error_message,)+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)await db.commit()+ return++ user = await db.get(User, task.requested_by)+ provider_id = (task.provider_task_id or "").strip()+ if not user or not provider_id:+ return++ data = await poll_video_task(user, provider_id)+ status = str(data.get("status") or "").strip().lower()+ if status in {"", "running", "queued"}:+ task.next_action_at = now + timedelta(+ seconds=max(1.0, float(get_settings().ark_video_poll_interval or 8.0))+ )+ await db.commit()+ return++ await settle_deferred_video_poll(+ db,+ user,+ provider_task_id=provider_id,+ poll_status=status,+ error=str(data.get("error") or "") or None,+ billing_task_id=task.id,+ usage_tokens=int((data.get("usage") or {}).get("total_tokens") or 0),+ completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),+ raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,+ )+ await db.commit()diff --git a/backend/app/services/tasks/scheduler.py b/backend/app/services/tasks/scheduler.pyindex 0df404f..538c08f 100644--- a/backend/app/services/tasks/scheduler.py+++ b/backend/app/services/tasks/scheduler.py@@ -13,6 +13,7 @@ from sqlalchemy import and_, or_, select, updatefrom app.config import get_settingsfrom app.database import AsyncSessionLocalfrom app.models_tasks import TaskRun+from app.services.billing.settlement import reconcile_terminal_frozen_tasksfrom app.services.tasks.executor import execute_task_runfrom app.services.tasks.service import (append_task_event,@@ -144,6 +145,9 @@ async def _tick() -> None:orphan_every = max(5, int(get_settings().task_runtime_orphan_check_sec))if time.monotonic() - _last_orphan_check_mono >= orphan_every:await recover_orphaned_tasks()+ # 低频对账:收敛 settle 异常中断遗留的"终态 + frozen"任务(幂等)+ async with AsyncSessionLocal() as reconcile_db:+ await reconcile_terminal_frozen_tasks(reconcile_db)_last_orphan_check_mono = time.monotonic()async with AsyncSessionLocal() as db:diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.pyindex 436ae1a..a9fdbba 100644--- a/backend/app/services/tasks/service.py+++ b/backend/app/services/tasks/service.py@@ -13,7 +13,7 @@ from sqlalchemy.orm import selectinloadfrom app.models import Project, Shot, Userfrom app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject, DramaScriptfrom app.models_tasks import TaskEvent, TaskRun, TaskStep, TaskTarget-from app.schemas_tasks import TaskCreateRequest, TaskEventCreate, TaskStepCreate, TaskUpdateRequest+from app.schemas_tasks import TaskCreateRequest, TaskEventCreate, TaskStepCreatefrom app.services.tasks.handlers import get_task_handlerlogger = logging.getLogger("app.tasks.service")@@ -37,6 +37,39 @@ def task_detail_options() -> tuple:)+# payload 中标记 poller 成片收尾窗口截止时间的键+FINALIZING_UNTIL_KEY = "finalizing_until"+++def task_finalizing_window_open(task: TaskRun, *, now: datetime | None = None) -> bool:+ """任务是否处于 poller 的 finalizing 收尾窗口(成片正在下载落盘并记用量)。++ 窗口内收到取消不得直接全额退款:成片可能恰好在落盘,先退款会造成+ usage_events 悬空(settled=0)且钱货两失。应收敛取消动作,+ 由持有收尾流程的协程完成后按实际用量结算(settle_task 多退少补)。+ """+ payload = getattr(task, "payload", None)+ if not isinstance(payload, dict):+ return False+ raw = payload.get(FINALIZING_UNTIL_KEY)+ if not raw:+ return False+ try:+ until = datetime.fromisoformat(str(raw))+ except ValueError:+ return False+ if until.tzinfo is None:+ until = until.replace(tzinfo=UTC)+ return until > (now or datetime.now(UTC))+++def clear_finalizing_window(payload: Any) -> dict:+ """返回移除 finalizing 窗口标记后的 payload 副本(无标记时原样拷贝)。"""+ data = dict(payload) if isinstance(payload, dict) else {}+ data.pop(FINALIZING_UNTIL_KEY, None)+ return data++def build_task_event(task_id: int, event: TaskEventCreate) -> TaskEvent:return TaskEvent(task_id=task_id,@@ -820,12 +853,6 @@ async def count_user_active_runtime_tasks(db: AsyncSession, user_id: int) -> intreturn int((await db.execute(stmt)).scalar_one() or 0)-# 统计已注册、等待 Selector 轮询的上游任务数。-async def count_awaiting_poll_tasks(db: AsyncSession) -> int:- stmt = select(func.count()).select_from(TaskRun).where(TaskRun.status == "awaiting_poll")- return int((await db.execute(stmt)).scalar_one() or 0)--async def _validate_task_scope(db: AsyncSession, user: User, body: TaskCreateRequest) -> None:if body.project_id is not None:project = await db.get(Project, body.project_id)@@ -963,67 +990,6 @@ async def count_active_tasks_for_user(return int((await db.execute(stmt)).scalar_one() or 0)-async def update_task_for_user(- db: AsyncSession,- user: User,- task_id: int,- body: TaskUpdateRequest,-) -> TaskRun:- task = await get_task_for_user(db, user, task_id)- now = datetime.now(UTC)- prev_status = task.status- prev_step_key = task.current_step_key- prev_step_status = task.current_step_status- if body.status is not None:- task.status = body.status- if body.current_step_key is not None:- task.current_step_key = body.current_step_key- if body.current_step_status is not None:- task.current_step_status = body.current_step_status- if body.provider_task_id is not None:- task.provider_task_id = body.provider_task_id- if body.scheduled_at is not None:- task.scheduled_at = body.scheduled_at- if body.next_action_at is not None:- task.next_action_at = body.next_action_at- if body.lease_token is not None:- task.lease_token = body.lease_token- if body.lease_until is not None:- task.lease_until = body.lease_until- if body.progress_percent is not None:- task.progress_percent = body.progress_percent- if body.error_code is not None:- task.error_code = body.error_code- if body.error_message is not None:- task.error_message = body.error_message- if body.payload is not None:- task.payload = body.payload- if body.result_payload is not None:- task.result_payload = body.result_payload- if prev_status != "running" and task.status == "running" and task.started_at is None:- task.started_at = now- if body.status in TERMINAL_TASK_STATUSES:- task.finished_at = now- db.add(- build_task_event(- task.id,- TaskEventCreate(- event_type="task.updated",- status=task.status,- phase=task.current_step_key,- message=f"{prev_status}/{prev_step_status} -> {task.status}/{task.current_step_status}",- payload={- "previous_status": prev_status,- "previous_step_key": prev_step_key,- "previous_step_status": prev_step_status,- },- ),- )- )- await db.commit()- return await get_task_for_user(db, user, task.id)--async def cancel_task_for_user(db: AsyncSession, user: User, task_id: int) -> TaskRun:task = await get_task_for_user(db, user, task_id)if not task.cancelable:@@ -1048,72 +1014,6 @@ async def cancel_task_for_user(db: AsyncSession, user: User, task_id: int) -> Tareturn await get_task_for_user(db, user, task.id)-async def retry_task_for_user(db: AsyncSession, user: User, task_id: int) -> TaskRun:- task = await get_task_for_user(db, user, task_id)- if task.status not in {"failed", "cancelled"}:- raise ValueError("仅失败或已取消任务支持重试")- # 分镜视频:旧任务绑定的分镜若已删,禁止重试,须在分集页按当前分镜重新生成- if task.domain == "drama" and task.task_type == "fragment_video":- frag_ids = task_fragment_ids(task)- if not frag_ids:- raise ValueError(_STALE_FRAGMENT_REASON)- for frag_id in frag_ids:- frag = await db.get(DramaEpisodeFragment, frag_id)- if frag is None:- raise ValueError(_STALE_FRAGMENT_REASON)- # 用户/后台点重试:清零内部重试计数,并从 prepare 阶段重跑- params = dict(frag.params or {})- params.pop("generation_attempts", None)- params["generation"] = {- "status": "queued",- "queued_at": datetime.now(UTC).isoformat(),- "message": "任务重试已入队",- }- frag.params = params- payload = dict(task.payload or {}) if isinstance(task.payload, dict) else {}- # 分镜视频重试不沿用旧 nio 阶段与内部 attempt,避免被「超过上限」直接拦住- if task.domain == "drama" and task.task_type == "fragment_video":- for key in (- "nio_phase",- "generation_attempts",- "attempt_limit",- "prepared",- "provider_task_id",- ):- payload.pop(key, None)- body = TaskCreateRequest(- domain=task.domain,- task_type=task.task_type,- priority=task.priority,- client_request_id=task.client_request_id,- dedupe_key=None,- batch_key=task.batch_key,- provider_task_id=None,- cancelable=task.cancelable,- scheduled_at=datetime.now(UTC),- payload=payload or None,- result_payload=None,- project_id=task.project_id,- drama_project_id=task.drama_project_id,- script_id=task.script_id,- episode_id=task.episode_id,- fragment_id=task.fragment_id,- asset_id=task.asset_id,- shot_id=task.shot_id,- targets=[- {- "target_type": item.target_type,- "target_id": item.target_id,- "sort_order": item.sort_order,- "metadata_json": item.metadata_json,- }- for item in task.targets- ],- )- create_body = TaskCreateRequest.model_validate(body.model_dump())- return await create_task(db, user, create_body)--async def list_active_tasks_for_owner(db: AsyncSession,user_id: int,diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex f6696f2..bcd3209 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -1,11 +1,20 @@-"""计费/管理端集成测试:PostgreSQL + 开启 billing。"""+"""计费/管理端集成测试:PostgreSQL + 开启 billing。++安全约定:集成测试永不直连业务库。db_session 自动把 DATABASE_URL 的库名+派生为 ``<库名>_test``(如 printfilm → printfilm_test),不存在则自动创建;+已指向含 "test" 的库时原样使用(CI 可直接注入测试库 URL)。+每个用例仍跑在外层事务回滚里,测试数据不落库。+"""from __future__ import annotations+import reimport uuidfrom collections.abc import AsyncIteratorimport pytestimport pytest_asyncio+from sqlalchemy import text+from sqlalchemy.engine.url import make_urlfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_enginefrom app.config import get_settings@@ -13,6 +22,36 @@ from app.database import Basefrom app.models import Userfrom app.models_tasks import TaskRun+_DB_NAME_RE = re.compile(r"^[A-Za-z0-9_]+$")+++def _resolve_test_database_url(raw_url: str) -> tuple[str, str]:+ """业务库 URL → (测试库 URL, 测试库名);库名非法时直接拒绝。"""+ parsed = make_url(raw_url)+ name = parsed.database or "postgres"+ if "test" in name:+ return raw_url, name+ test_name = f"{name}_test"+ if not _DB_NAME_RE.fullmatch(test_name):+ raise RuntimeError(f"拒绝在非法库名上创建测试库: {test_name!r}")+ return parsed.set(database=test_name).render_as_string(hide_password=False), test_name+++async def _ensure_test_database(test_url: str, test_name: str) -> None:+ """连维护库 postgres 检查并创建测试库(AUTOCOMMIT,CREATE DATABASE 不能入事务)。"""+ maint_url = make_url(test_url).set(database="postgres").render_as_string(hide_password=False)+ engine = create_async_engine(maint_url, isolation_level="AUTOCOMMIT")+ try:+ async with engine.connect() as conn:+ exists = await conn.scalar(+ text("SELECT 1 FROM pg_database WHERE datname = :name"),+ {"name": test_name},+ )+ if not exists:+ await conn.execute(text(f'CREATE DATABASE "{test_name}"'))+ finally:+ await engine.dispose()+@pytest.fixture(autouse=True)def skip_tokenfree_pricing_network(monkeypatch: pytest.MonkeyPatch) -> None:@@ -52,23 +91,24 @@ async def db_session(billing_enabled: None) -> AsyncIterator[AsyncSession]:if not url.startswith("postgresql"):raise RuntimeError("集成测试需要 PostgreSQL DATABASE_URL(postgresql+asyncpg://...)")- engine = create_async_engine(url, pool_pre_ping=True)+ # 强制隔离到独立测试库,杜绝污染/损坏开发库真实数据+ test_url, test_name = _resolve_test_database_url(url)+ await _ensure_test_database(test_url, test_name)++ engine = create_async_engine(test_url, pool_pre_ping=True)async with engine.begin() as conn:await conn.run_sync(Base.metadata.create_all)- # 增量列(与 main._apply_schema_patches 保持一致)- from sqlalchemy import text- result = await conn.execute(- text(- "SELECT column_name FROM information_schema.columns "- "WHERE table_schema = 'public' AND table_name = 'users'"- )- )- ucols = {row[0] for row in result.fetchall()}- if "billing_alert_last_milestone_fen" not in ucols:- await conn.execute(- text("ALTER TABLE users ADD COLUMN billing_alert_last_milestone_fen INTEGER DEFAULT 0")- )+ # 增量列直接复用 main._apply_schema_patches(权威清单,避免测试补丁与线上漂移);+ # 该函数闭包 app.main.engine,临时指向测试 engine 后再还原。+ import app.main as main_module++ original_engine = main_module.engine+ main_module.engine = engine+ try:+ await main_module._apply_schema_patches()+ finally:+ main_module.engine = original_engineasync with engine.connect() as conn:outer = await conn.begin()diff --git a/backend/tests/test_admin_stats.py b/backend/tests/test_admin_stats.pyindex f416e44..6924884 100644--- a/backend/tests/test_admin_stats.py+++ b/backend/tests/test_admin_stats.py@@ -389,8 +389,20 @@ async def test_dashboard_capability_derived_from_billing_key(db_session: AsyncSe@pytest.mark.asyncioasync def test_aggregate_usage_summary_breakdown(db_session: AsyncSession) -> None:"""单项目用量拆分图/视/LLM/TTS。"""+ import uuid as _uuid++ from app.models import Project, Template+user = await make_user(db_session)- pid = 42+ # usage_events.project_id 有真实 FK 约束,必须先建项目行+ tpl = Template(id=f"tpl-agg-{_uuid.uuid4().hex[:8]}", name="聚合模板", style_prefix="x")+ db_session.add(tpl)+ project = Project(user_id=user.id, template_id=tpl.id, source_text="x", title="聚合项目")+ other_project = Project(user_id=user.id, template_id=tpl.id, source_text="y", title="其他项目")+ db_session.add_all([project, other_project])+ await db_session.flush()+ pid = project.id+ other_pid = other_project.idawait _add_usage(db_session, user_id=user.id, project_id=pid, charge_fen=10, billing_key="seedream", capability="image")@@ -410,7 +422,12 @@ async def test_aggregate_usage_summary_breakdown(db_session: AsyncSession) -> No)# 其他项目不应计入await _add_usage(- db_session, user_id=user.id, project_id=99, charge_fen=999, billing_key="seedream", capability="image"+ db_session,+ user_id=user.id,+ project_id=other_pid,+ charge_fen=999,+ billing_key="seedream",+ capability="image",)await db_session.commit()@@ -422,12 +439,13 @@ async def test_aggregate_usage_summary_breakdown(db_session: AsyncSession) -> Noassert summary["llm_calls"] == 1assert summary["tts_gens"] == 1- batch = await aggregate_usage_summary(db_session, project_ids=[pid, 99, 7])+ missing_pid = 9_999_999+ batch = await aggregate_usage_summary(db_session, project_ids=[pid, other_pid, missing_pid])assert batch[pid]["tts_gens"] == 1- assert batch[99]["image_gens"] == 1- assert batch[99]["charge_fen"] == 999- assert batch[7]["calls"] == 0- assert batch[7]["tts_gens"] == 0+ assert batch[other_pid]["image_gens"] == 1+ assert batch[other_pid]["charge_fen"] == 999+ assert batch[missing_pid]["calls"] == 0+ assert batch[missing_pid]["tts_gens"] == 0@pytest.mark.asynciodiff --git a/backend/tests/test_ark_control_usage.py b/backend/tests/test_ark_control_usage.pydeleted file mode 100644index 202caea..0000000--- a/backend/tests/test_ark_control_usage.py+++ /dev/null@@ -1,47 +0,0 @@-"""方舟管控面用量响应解析。"""--from __future__ import annotations--from app.services.ark_control_usage import (- aggregate_usage_by_day,- build_inference_usage_request_body,- parse_inference_usage_rows,-)---def test_build_inference_usage_request_body_uses_query_interval():- body = build_inference_usage_request_body("2026-08-01", "2026-08-07")- assert body == {- "StartTime": "2026-08-01",- "EndTime": "2026-08-07",- "QueryInterval": "Day",- }---def test_parse_inference_usage_rows_table():- result = {- "Fields": [- {"Name": "Day", "Type": "DATE"},- {"Name": "ModelName", "Type": "STRING"},- {"Name": "Value", "Type": "BIGINT"},- ],- "Data": [- ["2026-08-26", "doubao-seedance-2-0", 500000],- ["2026-08-27", "doubao-seedance-2-0", 800000],- ],- }- rows = parse_inference_usage_rows(result)- assert len(rows) == 2- assert rows[0]["Day"] == "2026-08-26"- daily = aggregate_usage_by_day(rows)- assert daily["2026-08-26"] == 500000- assert daily["2026-08-27"] == 800000---def test_aggregate_usage_by_day_skips_non_video_models():- rows = [- {"Day": "2026-08-26", "ModelName": "doubao-seedream", "Value": 1000},- {"Day": "2026-08-26", "ModelName": "doubao-seedance-2-0", "Value": 2000},- ]- daily = aggregate_usage_by_day(rows)- assert daily.get("2026-08-26") == 2000diff --git a/backend/tests/test_ark_poll_resilience.py b/backend/tests/test_ark_poll_resilience.pynew file mode 100644index 0000000..329bd5a--- /dev/null+++ b/backend/tests/test_ark_poll_resilience.py@@ -0,0 +1,265 @@+# -*- coding: utf-8 -*-+"""上游轮询韧性回归:++- fetch_task_once / poll_task 遇到 429、5xx 或单次网络故障时,+ 任务状态未知,必须按 running 退避,不能单次误判 failed;+- 400/404 等确定 4xx 仍是终态 failed;+- gen_and_wait_seedance_body 只允许在"参考音频下载失败"时去掉参考音频重提一次,+ 隐私拦截/任务失败/超时等异常必须立即上抛,禁止用同 body 重新建单重复计费。+"""+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest++from app.services import ark as ark_module+from app.services.ark import (+ ArkGateway,+ TaskResult,+ _is_transient_http_status,+ _retry_after_seconds,+)+++class _FakeResponse:+ """最小 httpx.Response 替身:状态码 + JSON 载荷 + 文本 + 响应头。"""++ def __init__(self, status_code: int, payload: dict | None = None, text: str = "err", headers=None):+ self.status_code = status_code+ self.text = text+ self.headers = headers or {}+ self._payload = payload if payload is not None else {}++ def json(self) -> dict:+ return self._payload+++def _install_fake_http(monkeypatch, handler):+ """把 httpx.AsyncClient 替换为按 handler 脚本应答的假客户端,返回 URL 调用记录。"""+ calls: list[str] = []++ class _FakeAsyncClient:+ def __init__(self, *args, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def get(self, url, headers=None):+ calls.append(url)+ outcome = handler()+ if isinstance(outcome, Exception):+ raise outcome+ return outcome++ monkeypatch.setattr(ark_module.httpx, "AsyncClient", _FakeAsyncClient)+ return calls+++def ark_client(monkeypatch) -> ArkGateway:+ """非 mock、零轮询间隔的客户端(mock 属性会因无渠道 Key 为 True,需显式关掉)。"""+ settings = SimpleNamespace(+ ark_video_poll_timeout=30.0,+ ark_video_poll_interval=0.0,+ ark_base_url="https://ark.cn-beijing.volces.com",+ ark_api_key="test-key",+ )+ client = ArkGateway(settings)+ monkeypatch.setattr(ArkGateway, "mock", property(lambda self: False))+ return client+++# ---------- 纯函数 ----------+[email protected]("code", [429, 500, 502, 503, 504])+def test_transient_status_set(code: int) -> None:+ assert _is_transient_http_status(code)++[email protected]("code", [200, 400, 401, 403, 404, 409, 422])+def test_terminal_status_not_transient(code: int) -> None:+ assert not _is_transient_http_status(code)+++def test_retry_after_seconds_honors_header_and_caps() -> None:+ assert _retry_after_seconds(_FakeResponse(429, headers={"Retry-After": "3"}), 8.0) == 3.0+ assert _retry_after_seconds(_FakeResponse(429, headers={"Retry-After": "120"}), 8.0) == 60.0+ # HTTP-date 形式与缺失时回落默认间隔+ assert _retry_after_seconds(_FakeResponse(429), 8.0) == 8.0+ assert (+ _retry_after_seconds(_FakeResponse(429, headers={"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}), 8.0)+ == 8.0+ )+++# ---------- fetch_task_once ----------+[email protected]("code", [429, 500, 502, 503, 504])+async def test_fetch_once_transient_http_treated_running(ark_client, monkeypatch, code: int) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(code, text="upstream busy"))+ result = await ark_client.fetch_task_once("task-abc")+ assert result.status == "running"+ assert result.provider_task_id == "task-abc"+ assert not result.error++[email protected]("code", [400, 404])+async def test_fetch_once_terminal_4xx_is_failed(ark_client, monkeypatch, code: int) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(code, text="task gone"))+ result = await ark_client.fetch_task_once("task-abc")+ assert result.status == "failed"+ assert result.error == "task gone"+++async def test_fetch_once_network_error_treated_running(ark_client, monkeypatch) -> None:+ _install_fake_http(monkeypatch, lambda: httpx.ConnectError("connection reset"))+ result = await ark_client.fetch_task_once("task-abc")+ assert result.status == "running"+ assert result.provider_task_id == "task-abc"+++async def test_fetch_once_succeeded_passthrough(ark_client, monkeypatch) -> None:+ payload = {+ "id": "task-abc",+ "status": "succeeded",+ "content": {"video_url": "https://cdn.example.com/v.mp4"},+ }+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await ark_client.fetch_task_once("task-abc")+ assert result.status == "succeeded"+ assert result.url == "https://cdn.example.com/v.mp4"+++# ---------- poll_task 长轮询 ----------++async def test_poll_retries_after_503_then_succeeds(ark_client, monkeypatch) -> None:+ responses = iter(+ [+ _FakeResponse(503, text="gateway"),+ _FakeResponse(+ 200,+ payload={+ "id": "task-abc",+ "status": "succeeded",+ "content": {"video_url": "https://cdn.example.com/v.mp4"},+ },+ ),+ ]+ )+ calls = _install_fake_http(monkeypatch, lambda: next(responses))+ result = await ark_client.poll_task("task-abc")+ assert result.status == "succeeded"+ assert len(calls) == 2+++async def test_poll_persistent_429_ends_in_poll_timeout(ark_client, monkeypatch) -> None:+ # 0.05s 总超时 + interval=0:持续 429 必须被 deadline 收敛,而不是首轮判 failed+ ark_client.settings.ark_video_poll_timeout = 0.05+ calls = _install_fake_http(monkeypatch, lambda: _FakeResponse(429, text="rate limited"))+ result = await ark_client.poll_task("task-abc")+ assert result.status == "failed"+ assert result.error == "poll timeout"+ assert len(calls) >= 2+++async def test_poll_404_fails_immediately_without_retry(ark_client, monkeypatch) -> None:+ calls = _install_fake_http(monkeypatch, lambda: _FakeResponse(404, text="task gone"))+ result = await ark_client.poll_task("task-abc")+ assert result.status == "failed"+ assert result.error == "task gone"+ assert len(calls) == 1+++# ---------- gen_and_wait_seedance_body 重试收窄 ----------++def _audio_body() -> dict:+ return {+ "content": [+ {"type": "text", "text": "镜头画面:星空\n参考音频:素材一\n角色音色:旁白A"},+ {"type": "audio_url", "role": "reference_audio", "audio_url": "https://x/a.mp3"},+ ]+ }+++_AUDIO_ERR = 'upstream failure: audio_url resource download failed at task start'+_OK_RESULT = ("/static/x.mp4", None, TaskResult(status="succeeded", url="https://x/v.mp4"))+++def seedance_client() -> ArkGateway:+ return ArkGateway(SimpleNamespace())+++async def test_seedance_wait_failure_does_not_recreate_task(seedance_client) -> None:+ """等待阶段的非音频错误(如隐私拦截)必须立即上抛,只建过一次单。"""+ seedance_client.gen_video_seedance_body = AsyncMock(return_value="t1")+ seedance_client.wait_video_assets = AsyncMock(side_effect=RuntimeError("privacy blocked"))+ with pytest.raises(RuntimeError, match="privacy blocked"):+ await seedance_client.gen_and_wait_seedance_body(+ _audio_body(), project_id=1, shot_no=2+ )+ seedance_client.gen_video_seedance_body.assert_awaited_once()+++async def test_seedance_submit_failure_does_not_recreate_task(seedance_client) -> None:+ """提交阶段的非音频错误立即上抛,不进入第二次建单。"""+ seedance_client.gen_video_seedance_body = AsyncMock(+ side_effect=RuntimeError("400 InvalidParameter: bad body")+ )+ seedance_client.wait_video_assets = AsyncMock()+ with pytest.raises(RuntimeError, match="InvalidParameter"):+ await seedance_client.gen_and_wait_seedance_body(+ _audio_body(), project_id=1, shot_no=2+ )+ seedance_client.gen_video_seedance_body.assert_awaited_once()+ seedance_client.wait_video_assets.assert_not_awaited()+++async def test_seedance_wait_audio_error_retries_once_without_audio(seedance_client) -> None:+ """等待阶段报参考音频下载失败:剥离 reference_audio 重提一次并成功。"""+ gen_mock = AsyncMock(side_effect=["t1", "t2"])+ seedance_client.gen_video_seedance_body = gen_mock+ seedance_client.wait_video_assets = AsyncMock(+ side_effect=[RuntimeError(_AUDIO_ERR), _OK_RESULT]+ )+ video_url, _last, result = await seedance_client.gen_and_wait_seedance_body(+ _audio_body(), project_id=1, shot_no=2+ )+ assert video_url == "/static/x.mp4"+ assert result.status == "succeeded"+ assert gen_mock.await_count == 2+ second_body = gen_mock.await_args_list[1].args[0]+ assert not any(+ item.get("type") == "audio_url" and item.get("role") == "reference_audio"+ for item in second_body["content"]+ if isinstance(item, dict)+ )+++async def test_seedance_submit_audio_error_retries_once(seedance_client) -> None:+ """提交阶段报参考音频下载失败:剥离后重提一次,随后等待成功。"""+ gen_mock = AsyncMock(side_effect=[RuntimeError(_AUDIO_ERR), "t2"])+ seedance_client.gen_video_seedance_body = gen_mock+ seedance_client.wait_video_assets = AsyncMock(return_value=_OK_RESULT)+ await seedance_client.gen_and_wait_seedance_body(_audio_body(), project_id=1, shot_no=2)+ assert gen_mock.await_count == 2+ seedance_client.wait_video_assets.assert_awaited_once()+++async def test_seedance_audio_fallback_used_no_third_submit(seedance_client) -> None:+ """剥离参考音频后仍然失败:最多两次建单,绝无第三次。"""+ gen_mock = AsyncMock(side_effect=[RuntimeError(_AUDIO_ERR), RuntimeError(_AUDIO_ERR)])+ seedance_client.gen_video_seedance_body = gen_mock+ seedance_client.wait_video_assets = AsyncMock(side_effect=RuntimeError(_AUDIO_ERR))+ with pytest.raises(RuntimeError, match="resource download failed"):+ await seedance_client.gen_and_wait_seedance_body(+ _audio_body(), project_id=1, shot_no=2, max_attempts=2+ )+ assert gen_mock.await_count == 2diff --git a/backend/tests/test_billing_integration.py b/backend/tests/test_billing_integration.pyindex fdf348f..ed14496 100644--- a/backend/tests/test_billing_integration.py+++ b/backend/tests/test_billing_integration.py@@ -347,7 +347,14 @@ async def test_record_llm_chat_line_skips_without_billing_scope(db_session: Asyndrama_project_id=1,)assert ev is None- count = len((await db_session.execute(select(UsageEvent))).scalars().all())+ # 只统计本用户事件(集成测试共享 dev 库,不能全表计数)+ count = len(+ (+ await db_session.execute(+ select(UsageEvent).where(UsageEvent.user_id == user.id)+ )+ ).scalars().all()+ )assert count == 0diff --git a/backend/tests/test_billing_reconcile.py b/backend/tests/test_billing_reconcile.pynew file mode 100644index 0000000..2c0a468--- /dev/null+++ b/backend/tests/test_billing_reconcile.py@@ -0,0 +1,125 @@+# -*- coding: utf-8 -*-+"""终态但 billing_status=frozen 的对账补偿测试。++正常路径下 _complete_task/_fail_task/_mark_cancelled 都会在置终态后立即+settle_task;若该步因 DB 故障等异常中断,任务会停在「终态 + frozen」:+冻结额不退、usage_events 悬空。reconcile_terminal_frozen_tasks 周期收敛。+"""+from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import UsageEvent+from app.services.billing.settlement import (+ TERMINAL_FROZEN_RECONCILE_GRACE_SEC,+ freeze_for_task,+ reconcile_terminal_frozen_tasks,+)++from tests.conftest import make_task, make_user+++async def _frozen_task(db: AsyncSession, user, *, status: str = "succeeded", age_minutes: int = 5):+ """freeze 后手工置终态(模拟置终态后 settle 失败的遗留行)。"""+ task = await make_task(db, user, domain="drama", task_type="fragment_video", status=status)+ await db.commit()+ need = await freeze_for_task(db, task)+ assert need > 0+ task.status = status+ task.finished_at = datetime.now(UTC) - timedelta(minutes=age_minutes)+ await db.commit()+ return task, need+++async def test_reconcile_settles_succeeded_frozen_after_grace(db_session: AsyncSession) -> None:+ """超过宽限期的 succeeded+frozen:按已落账用量结算并退差额。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_task(db_session, user)+ charge = max(1, need - 200)+ db_session.add(+ UsageEvent(+ user_id=user.id,+ task_run_id=task.id,+ billing_key="drama_fragment_video",+ domain="drama",+ capability="video",+ provider="ark",+ charge_fen=charge,+ cost_fen=charge,+ settled=False,+ )+ )+ await db_session.commit()++ fixed = await reconcile_terminal_frozen_tasks(db_session)+ assert fixed == 1+ await db_session.commit()++ from app.models import User++ row = await db_session.get(type(task), int(task.id))+ owner = await db_session.get(User, int(user.id))+ assert row.billing_status == "settled"+ assert row.billing_charged_fen == charge+ assert row.billing_refunded_fen == need - charge+ assert owner.frozen_fen == 0+ assert owner.balance_fen == 100_000 - charge+++async def test_reconcile_skips_tasks_inside_grace_window(db_session: AsyncSession) -> None:+ """宽限期内的终态 frozen(可能正在正常收尾)不动。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_task(db_session, user, age_minutes=0)+ # 刚结束:越过宽限截止线之前+ task.finished_at = datetime.now(UTC) - timedelta(+ seconds=max(0, TERMINAL_FROZEN_RECONCILE_GRACE_SEC - 30)+ )+ await db_session.commit()++ fixed = await reconcile_terminal_frozen_tasks(db_session)+ assert fixed == 0+ await db_session.refresh(task)+ assert task.billing_status == "frozen"+ assert user.frozen_fen == need+++async def test_reconcile_ignores_non_terminal_and_settled(db_session: AsyncSession) -> None:+ """进行中任务(awaiting_poll)与已结算终态都不应被扫描。"""+ user = await make_user(db_session, balance_fen=100_000)+ polling, _ = await _frozen_task(db_session, user, status="awaiting_poll")+ settled, _ = await _frozen_task(db_session, user, status="succeeded")+ settled.billing_status = "settled"+ await db_session.commit()++ fixed = await reconcile_terminal_frozen_tasks(db_session)+ assert fixed == 0+ await db_session.refresh(polling)+ assert polling.billing_status == "frozen"+ assert polling.status == "awaiting_poll"+++async def test_reconcile_full_refund_when_no_usage(db_session: AsyncSession) -> None:+ """终态 frozen 且无用量(如失败任务):全额退回冻结。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_task(db_session, user, status="failed")++ fixed = await reconcile_terminal_frozen_tasks(db_session)+ assert fixed == 1+ await db_session.commit()++ from app.models import User++ row = await db_session.get(type(task), int(task.id))+ owner = await db_session.get(User, int(user.id))+ assert row.billing_status == "settled"+ assert row.billing_charged_fen == 0+ assert row.billing_refunded_fen == need+ assert owner.frozen_fen == 0+ assert owner.balance_fen == 100_000diff --git a/backend/tests/test_drama_cancel_scope.py b/backend/tests/test_drama_cancel_scope.pynew file mode 100644index 0000000..10a8ca3--- /dev/null+++ b/backend/tests/test_drama_cancel_scope.py@@ -0,0 +1,71 @@+"""取消全部漫剧分镜视频必须限定在当前用户范围内。"""+from __future__ import annotations++from contextlib import asynccontextmanager+from unittest.mock import patch++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject+from app.services.drama.jobs import cancel_all_episode_video_jobs++from tests.conftest import make_user+++@asynccontextmanager+async def _same_session(db: AsyncSession):+ """把 jobs 内自开 session 钉到用例事务。"""+ yield db+++async def _make_running_fragment(db: AsyncSession, user, *, title: str) -> DramaEpisodeFragment:+ """构造 用户→项目→分集→一条生成中分镜。"""+ project = DramaProject(user_id=user.id, title=title)+ db.add(project)+ await db.flush()+ episode = DramaEpisode(project_id=project.id, name="第 1 集")+ db.add(episode)+ await db.flush()+ fragment = DramaEpisodeFragment(+ episode_id=episode.id,+ sort_order=1,+ content="测试镜头",+ params={"generation": {"status": "running"}},+ )+ db.add(fragment)+ await db.flush()+ return fragment+++async def test_cancel_all_only_affects_requesting_user(db_session: AsyncSession) -> None:+ """用户 A 取消全部不得把用户 B 在生成的分镜置 cancelled。"""+ user_a = await make_user(db_session)+ user_b = await make_user(db_session)+ frag_a = await _make_running_fragment(db_session, user_a, title="A 的漫剧")+ frag_b = await _make_running_fragment(db_session, user_b, title="B 的漫剧")+ await db_session.commit()++ with patch(+ "app.services.drama.jobs.AsyncSessionLocal", lambda: _same_session(db_session)+ ):+ result = await cancel_all_episode_video_jobs(user_a.id)++ # 显式选列重查,避免 expire 后同步属性访问触发懒加载+ rows = dict(+ (+ await db_session.execute(+ select(DramaEpisodeFragment.id, DramaEpisodeFragment.params).where(+ DramaEpisodeFragment.id.in_([frag_a.id, frag_b.id])+ )+ )+ )+ .tuples()+ .all()+ )+ assert rows[frag_a.id]["generation"]["status"] == "cancelled"+ assert result["fragments"] == 1+ # 关键回归:其他用户的分镜保持生成中+ assert rows[frag_b.id]["generation"]["status"] == "running"diff --git a/backend/tests/test_finalizing_cancel_race.py b/backend/tests/test_finalizing_cancel_race.pynew file mode 100644index 0000000..02a465f--- /dev/null+++ b/backend/tests/test_finalizing_cancel_race.py@@ -0,0 +1,400 @@+# -*- coding: utf-8 -*-+"""finalizing 成片收尾窗口与取消竞态的回归测试。++场景:poller 已认领分镜视频、进入 finalizing 窗口(成片正在下载落盘)时,+scheduler/executor 侧的取消不得直接全额退款,否则:+ 1. 随后落盘的 usage_events 永久 settled=False(悬空);+ 2. 冻结额被全额退回 → 钱货两失。+修复三层:service 窗口判定 helper / executor._mark_cancelled 窗口内让位 /+jobs._settle_cancelled_after_finalized 下载后按实结算。+"""+from __future__ import annotations++from datetime import UTC, datetime, timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinload++from app.models import UsageEvent, WalletLedger+from app.models_tasks import TaskEvent, TaskRun+from app.services.billing.settlement import freeze_for_task+from app.services.drama import jobs as drama_jobs+from app.services.tasks import executor+from app.services.tasks.service import (+ FINALIZING_UNTIL_KEY,+ clear_finalizing_window,+ task_finalizing_window_open,+)++from tests.conftest import make_task, make_user+++def _task_ns(payload: object, *, status: str = "cancel_requested") -> SimpleNamespace:+ """构造 _mark_cancelled 所需的最小任务对象(steps 为空,避免懒加载)。"""+ return SimpleNamespace(+ id=11,+ payload=payload,+ status=status,+ steps=[],+ current_step_key="fragment_video",+ current_step_status="polling",+ finished_at=None,+ next_action_at=datetime.now(UTC),+ lease_until=datetime.now(UTC),+ )+++# ---------------------------------------------------------------------------+# 一、纯函数:窗口判定+# ---------------------------------------------------------------------------+++def test_window_open_true_for_future_timestamp() -> None:+ task = SimpleNamespace(payload={FINALIZING_UNTIL_KEY: (datetime.now(UTC) + timedelta(minutes=5)).isoformat()})+ assert task_finalizing_window_open(task) is True+++def test_window_closed_for_past_timestamp() -> None:+ task = SimpleNamespace(payload={FINALIZING_UNTIL_KEY: (datetime.now(UTC) - timedelta(minutes=5)).isoformat()})+ assert task_finalizing_window_open(task) is False+++def test_window_naive_timestamp_treated_as_utc() -> None:+ # naive 时间按 UTC 解释:未来的 naive 时间戳在窗口内+ future_naive = datetime.now(UTC).replace(tzinfo=None) + timedelta(minutes=5)+ assert task_finalizing_window_open(SimpleNamespace(payload={FINALIZING_UNTIL_KEY: future_naive.isoformat()})) is True+ past_naive = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=5)+ assert task_finalizing_window_open(SimpleNamespace(payload={FINALIZING_UNTIL_KEY: past_naive.isoformat()})) is False+++def test_window_closed_without_key_or_bad_payload() -> None:+ assert task_finalizing_window_open(SimpleNamespace(payload={})) is False+ assert task_finalizing_window_open(SimpleNamespace(payload=None)) is False+ assert task_finalizing_window_open(SimpleNamespace(payload="not-a-dict")) is False+ assert task_finalizing_window_open(SimpleNamespace(payload={FINALIZING_UNTIL_KEY: None})) is False+ assert task_finalizing_window_open(SimpleNamespace(payload={FINALIZING_UNTIL_KEY: "not-a-date"})) is False+++def test_window_respects_injected_now() -> None:+ until = datetime(2026, 9, 14, 12, 0, tzinfo=UTC)+ task = SimpleNamespace(payload={FINALIZING_UNTIL_KEY: until.isoformat()})+ assert task_finalizing_window_open(task, now=datetime(2026, 9, 14, 11, 59, tzinfo=UTC)) is True+ assert task_finalizing_window_open(task, now=datetime(2026, 9, 14, 12, 1, tzinfo=UTC)) is False+++def test_clear_window_returns_copy_without_mutating_original() -> None:+ original = {FINALIZING_UNTIL_KEY: "2026-09-14T12:00:00+00:00", "episode_id": 7}+ cleared = clear_finalizing_window(original)+ assert FINALIZING_UNTIL_KEY not in cleared+ assert cleared["episode_id"] == 7+ # 原 dict 不被修改(不可变风格)+ assert FINALIZING_UNTIL_KEY in original+++def test_clear_window_handles_missing_key_and_non_dict() -> None:+ assert clear_finalizing_window({"a": 1}) == {"a": 1}+ assert clear_finalizing_window(None) == {}+ assert clear_finalizing_window("x") == {}+++# ---------------------------------------------------------------------------+# 二、executor._mark_cancelled:窗口内让位,窗口外收敛+# ---------------------------------------------------------------------------+++async def test_mark_cancelled_defers_inside_finalizing_window() -> None:+ task = _task_ns({FINALIZING_UNTIL_KEY: (datetime.now(UTC) + timedelta(minutes=5)).isoformat()})+ db = MagicMock()+ db.commit = AsyncMock()++ with (+ patch.object(executor, "settle_task", new=AsyncMock()) as settle_mock,+ patch.object(executor, "append_task_event", new=AsyncMock()) as event_mock,+ ):+ await executor._mark_cancelled(db, task)++ # 任务保持取消请求态:不结算、不记事件、不提交,等待收尾协程按实结算+ assert task.status == "cancel_requested"+ assert task.finished_at is None+ settle_mock.assert_not_awaited()+ event_mock.assert_not_awaited()+ db.commit.assert_not_awaited()+++async def test_mark_cancelled_settles_after_window_expired() -> None:+ task = _task_ns(+ {FINALIZING_UNTIL_KEY: (datetime.now(UTC) - timedelta(minutes=11)).isoformat()},+ status="cancel_requested",+ )+ db = MagicMock()+ db.commit = AsyncMock()++ with (+ patch.object(executor, "settle_task", new=AsyncMock()) as settle_mock,+ patch.object(executor, "append_task_event", new=AsyncMock()) as event_mock,+ ):+ await executor._mark_cancelled(db, task)++ assert task.status == "cancelled"+ assert task.finished_at is not None+ assert task.next_action_at is None+ assert task.lease_until is None+ settle_mock.assert_awaited_once_with(db, task.id)+ event_mock.assert_awaited_once()+ db.commit.assert_awaited_once()+++# ---------------------------------------------------------------------------+# 三、jobs._settle_cancelled_after_finalized:单元级字段收敛+# ---------------------------------------------------------------------------+++async def test_settle_cancelled_after_finalized_returns_false_without_lock() -> None:+ db = MagicMock()+ db.commit = AsyncMock()+ with (+ patch("app.services.billing.settlement._lock_task", new=AsyncMock(return_value=None)),+ patch("app.services.billing.settlement.settle_task", new=AsyncMock()) as settle_mock,+ ):+ ok = await drama_jobs._settle_cancelled_after_finalized(db, 99)+ assert ok is False+ settle_mock.assert_not_awaited()+ db.commit.assert_not_awaited()+++async def test_settle_cancelled_after_finalized_marks_done_and_clears_window() -> None:+ locked = SimpleNamespace(+ id=77,+ payload={FINALIZING_UNTIL_KEY: "2026-09-14T12:00:00+00:00", "episode_id": 3},+ status="awaiting_poll",+ cancel_requested=False,+ current_step_status="finalizing",+ progress_percent=90,+ finished_at=None,+ next_action_at=datetime.now(UTC),+ lease_token="tok",+ lease_until=datetime.now(UTC),+ )+ db = MagicMock()+ db.commit = AsyncMock()++ with (+ patch("app.services.billing.settlement._lock_task", new=AsyncMock(return_value=locked)),+ patch("app.services.billing.settlement.settle_task", new=AsyncMock()) as settle_mock,+ patch("app.services.tasks.service.append_task_event", new=AsyncMock()) as event_mock,+ ):+ ok = await drama_jobs._settle_cancelled_after_finalized(db, 77)++ assert ok is True+ assert locked.status == "cancelled"+ assert locked.cancel_requested is True+ assert locked.current_step_status == "done"+ assert locked.progress_percent == 100+ assert locked.finished_at is not None+ assert locked.next_action_at is None+ assert locked.lease_token is None+ assert locked.lease_until is None+ # 窗口键清除,其余 payload 保留+ assert FINALIZING_UNTIL_KEY not in locked.payload+ assert locked.payload["episode_id"] == 3+ settle_mock.assert_awaited_once_with(db, 77)+ event_mock.assert_awaited_once()+ db.commit.assert_awaited_once()+++# ---------------------------------------------------------------------------+# 四、DB 集成:真实 freeze/settle,验证"按实结算、不退全款、账实相符"+# ---------------------------------------------------------------------------+++async def _frozen_fragment_task(db: AsyncSession, user) -> tuple[TaskRun, int]:+ """造一个已预扣、处于 finalizing 窗口的分镜视频任务。"""+ task = await make_task(+ db,+ user,+ domain="drama",+ task_type="fragment_video",+ status="awaiting_poll",+ )+ task.payload = {FINALIZING_UNTIL_KEY: (datetime.now(UTC) + timedelta(minutes=10)).isoformat()}+ await db.commit()+ need = await freeze_for_task(db, task)+ assert need > 0+ await db.commit()+ return task, need+++async def test_finalized_cancel_settles_actual_usage_not_full_refund(db_session: AsyncSession) -> None:+ """窗口内取消、成片已落账:退差额而非全款,usage 行全部 settled。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_fragment_task(db_session, user)+ # 成片下载后落入的真实用量(小于冻结额,应退 need-charge)+ charge = max(1, need - 100)+ db_session.add(+ UsageEvent(+ user_id=user.id,+ task_run_id=task.id,+ billing_key="drama_fragment_video",+ domain="drama",+ capability="video",+ provider="ark",+ charge_fen=charge,+ cost_fen=charge,+ settled=False,+ )+ )+ await db_session.commit()++ ok = await drama_jobs._settle_cancelled_after_finalized(db_session, int(task.id))+ assert ok is True+ await db_session.commit()++ row = await db_session.get(TaskRun, int(task.id))+ assert row.status == "cancelled"+ assert row.billing_status == "settled"+ assert row.billing_charged_fen == charge+ assert row.billing_refunded_fen == need - charge+ assert FINALIZING_UNTIL_KEY not in (row.payload or {})+ # 钱包:冻结清零,余额 = 初始 - 实扣+ assert user.frozen_fen == 0+ assert user.balance_fen == 100_000 - charge++ events = list(+ (+ await db_session.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id))+ ).scalars()+ )+ assert events and all(e.settled for e in events)++ unfreeze = list(+ (+ await db_session.execute(+ select(WalletLedger).where(+ WalletLedger.ref_type == "task_run",+ WalletLedger.ref_id == str(task.id),+ WalletLedger.kind == "unfreeze",+ )+ )+ ).scalars()+ )+ assert len(unfreeze) == 1+ assert unfreeze[0].delta_fen == need - charge++ task_events = list(+ (+ await db_session.execute(select(TaskEvent).where(TaskEvent.task_id == task.id))+ ).scalars()+ )+ assert any(e.event_type == "task.cancelled" for e in task_events)+++async def test_mark_cancelled_inside_window_keeps_freeze_intact(db_session: AsyncSession) -> None:+ """executor 窗口内让位:冻结额不动、无退款流水、任务仍 cancel_requested。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_fragment_task(db_session, user)+ task.status = "cancel_requested"+ task.cancel_requested = True+ await db_session.commit()++ # selectinload steps,避免 async 懒加载+ loaded = (+ await db_session.execute(+ select(TaskRun).where(TaskRun.id == task.id).options(selectinload(TaskRun.steps))+ )+ ).scalar_one()+ await executor._mark_cancelled(db_session, loaded)+ await db_session.commit()++ row = await db_session.get(TaskRun, int(task.id))+ assert row.status == "cancel_requested"+ assert row.billing_status == "frozen"+ assert user.frozen_fen == need+ assert user.balance_fen == 100_000 - need+ refund_count = (+ await db_session.execute(+ select(WalletLedger).where(+ WalletLedger.ref_type == "task_run",+ WalletLedger.ref_id == str(task.id),+ WalletLedger.kind.in_(("unfreeze", "settle")),+ )+ )+ ).scalars().all()+ assert refund_count == []+++async def test_mark_cancelled_after_window_refunds_full_freeze(db_session: AsyncSession) -> None:+ """窗口已过(收尾协程未交付):正常取消收敛,全额退款。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_fragment_task(db_session, user)+ task.status = "cancel_requested"+ task.cancel_requested = True+ task.payload = {FINALIZING_UNTIL_KEY: (datetime.now(UTC) - timedelta(minutes=11)).isoformat()}+ await db_session.commit()++ loaded = (+ await db_session.execute(+ select(TaskRun).where(TaskRun.id == task.id).options(selectinload(TaskRun.steps))+ )+ ).scalar_one()+ await executor._mark_cancelled(db_session, loaded)+ await db_session.commit()++ row = await db_session.get(TaskRun, int(task.id))+ assert row.status == "cancelled"+ assert row.billing_status == "settled"+ assert row.billing_refunded_fen == need+ assert user.frozen_fen == 0+ assert user.balance_fen == 100_000+++async def test_finalized_cancel_settlement_is_idempotent(db_session: AsyncSession) -> None:+ """重复收敛不得二次退款(钱包侧 prior 流水门闩 + settled 门闩)。"""+ user = await make_user(db_session, balance_fen=100_000)+ task, need = await _frozen_fragment_task(db_session, user)+ charge = max(1, need - 100)+ db_session.add(+ UsageEvent(+ user_id=user.id,+ task_run_id=task.id,+ billing_key="drama_fragment_video",+ domain="drama",+ capability="video",+ provider="ark",+ charge_fen=charge,+ cost_fen=charge,+ settled=False,+ )+ )+ await db_session.commit()++ assert await drama_jobs._settle_cancelled_after_finalized(db_session, int(task.id)) is True+ await db_session.commit()+ # 竞态:收尾协程/取消路径再收敛一次+ assert await drama_jobs._settle_cancelled_after_finalized(db_session, int(task.id)) is True+ await db_session.commit()++ unfreeze = (+ await db_session.execute(+ select(WalletLedger).where(+ WalletLedger.ref_type == "task_run",+ WalletLedger.ref_id == str(task.id),+ WalletLedger.kind == "unfreeze",+ )+ )+ ).scalars().all()+ assert len(unfreeze) == 1+ assert unfreeze[0].delta_fen == need - charge+ assert user.balance_fen == 100_000 - charge+ assert user.frozen_fen == 0diff --git a/backend/tests/test_kepu_cancel_propagation.py b/backend/tests/test_kepu_cancel_propagation.pynew file mode 100644index 0000000..8cf8c8b--- /dev/null+++ b/backend/tests/test_kepu_cancel_propagation.py@@ -0,0 +1,117 @@+# -*- coding: utf-8 -*-+"""科普流水线取消语义:异常必须传播到任务平台,regen 不得复活已取消项目。"""+from __future__ import annotations++import inspect+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import Project, ProjectStatus, Shot, Template, User+from app.models_tasks import TaskRun+from app.services import pipeline+from app.services.pipeline import PipelineCancelled+from app.services.tasks.handlers import _await_kepu++from tests.conftest import make_user+++@asynccontextmanager+async def _same_session(db: AsyncSession):+ """把 pipeline 内自开 session 钉到用例事务。"""+ yield db+++async def _boom() -> None:+ raise PipelineCancelled("cancelled")+++async def _ok() -> None:+ return None+++def _fake_task(*, cancel_requested: bool) -> TaskRun:+ return SimpleNamespace(cancel_requested=cancel_requested, project_id=7)+++async def test_await_kepu_maps_cancelled_when_requested() -> None:+ """任务已被请求取消:PipelineCancelled 收敛为 cancelled 结果。"""+ out = await _await_kepu(_fake_task(cancel_requested=True), _boom())+ assert out["cancelled"] is True+ assert out["project_id"] == 7+++async def test_await_kepu_reraises_without_request() -> None:+ """未走取消流程却收到 PipelineCancelled(异常状态):必须抛出,按失败收敛。"""+ with pytest.raises(PipelineCancelled):+ await _await_kepu(_fake_task(cancel_requested=False), _boom())+++async def test_await_kepu_success_payload() -> None:+ out = await _await_kepu(_fake_task(cancel_requested=False), _ok(), shot_id=3)+ assert out == {"ok": True, "project_id": 7, "shot_id": 3}+++def test_run_pipeline_reraises_after_cancel_side_effects() -> None:+ """源码守卫:run_pipeline 取消分支落库/推 SSE 后必须 re-raise(旧实现吞异常致误扣费)。"""+ source = inspect.getsource(pipeline.run_pipeline)+ cancel_block = source.split("except (PipelineCancelled, asyncio.CancelledError):")[-1]+ cancel_block = cancel_block.split("except Exception", 1)[0]+ assert "raise" in cancel_block+++async def test_regen_image_does_not_revive_cancelled_project(+ db_session: AsyncSession,+) -> None:+ """等待 AI 期间用户取消项目:结果不得写回、状态不得复活,但上游用量照记。"""+ user = await make_user(db_session)+ tpl = Template(id="tpl-cancel-1", name="取消测试模板", style_prefix="x")+ db_session.add(tpl)+ await db_session.flush()+ project = Project(+ user_id=user.id,+ template_id=tpl.id,+ source_text="测试",+ status=ProjectStatus.CANCELLED,+ )+ db_session.add(project)+ await db_session.flush()+ shot = Shot(project_id=project.id, shot_no=1, img_prompt="一只猫", status=ProjectStatus.IMAGING)+ shot.image_url = "/static/old.png"+ db_session.add(shot)+ await db_session.flush()++ fake_ark = SimpleNamespace(+ gen_image=AsyncMock(+ return_value=SimpleNamespace(local_url="/static/new.png", remote_url="http://up/new.png")+ )+ )+ record = AsyncMock()+ with (+ patch.object(pipeline, "AsyncSessionLocal", lambda: _same_session(db_session)),+ patch.object(pipeline, "get_ark", return_value=fake_ark),+ patch.object(pipeline, "image_refs_for_shot", return_value=[]),+ patch.object(pipeline, "previous_usable_shot", return_value=None),+ patch.object(pipeline, "_record_seedream_usage", record),+ ):+ with pytest.raises(PipelineCancelled):+ await pipeline.regen_shot_image(project.id, shot.id)++ # 显式选列重查,避免 expire 后同步属性访问触发懒加载+ from sqlalchemy import select++ row = (+ await db_session.execute(+ select(Shot.image_url, Shot.version).where(Shot.id == shot.id)+ )+ ).one()+ assert row.image_url == "/static/old.png" # 新图未写回+ assert row.version == 1+ status = (+ await db_session.execute(select(Project.status).where(Project.id == project.id))+ ).scalar_one()+ assert status == ProjectStatus.CANCELLED # 未复活+ record.assert_awaited_once() # 上游真实成本仍记账diff --git a/backend/tests/test_kepu_continuous_audio_qc.py b/backend/tests/test_kepu_continuous_audio_qc.pynew file mode 100644index 0000000..84fa509--- /dev/null+++ b/backend/tests/test_kepu_continuous_audio_qc.py@@ -0,0 +1,35 @@+# -*- coding: utf-8 -*-+"""整片连贯配音新合成后必须复查近静音,拒绝产出无声成片。"""+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from app.services import pipeline+++async def test_synthesize_rejects_near_silent_tts(tmp_path, monkeypatch) -> None:+ """TTS 返回近静音音频时抛错收敛,不继续按时长分配与合成。"""+ src = tmp_path / "tts_raw.mp3"+ src.write_bytes(b"x" * 4000)+ monkeypatch.setattr(+ "app.services.storage.local_path_from_url", lambda url: src+ )+ monkeypatch.setattr("app.services.storage.project_dir", lambda _pid: tmp_path)+ ark = SimpleNamespace(tts=AsyncMock(return_value="/static/p1/tts_raw.mp3"))+ with (+ patch.object(pipeline, "get_ark", return_value=ark),+ patch.object(pipeline, "_record_usage_est", AsyncMock()),+ patch.object(pipeline, "is_near_silent_audio", return_value=True),+ patch.object(pipeline, "probe_duration", AsyncMock(side_effect=AssertionError("不应继续探测时长"))),+ ):+ with pytest.raises(RuntimeError, match="近静音"):+ await pipeline._synthesize_continuous_audio(+ 1,+ voice="zh-F1",+ shot_rows=[SimpleNamespace(id=1, duration=4.0, narration="你好")],+ force=True,+ )+ ark.tts.assert_awaited_once()diff --git a/backend/tests/test_kepu_privacy_skip.py b/backend/tests/test_kepu_privacy_skip.pynew file mode 100644index 0000000..0e533df--- /dev/null+++ b/backend/tests/test_kepu_privacy_skip.py@@ -0,0 +1,140 @@+# -*- coding: utf-8 -*-+"""真人隐私拦截:持久跳过标记,后续轮次不再重提 Seedance。"""+from __future__ import annotations++from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import Project, ProjectStatus, Shot, ShotStatus, Template+from app.services import pipeline+from app.services.kepu_stages import (+ VIDEO_SKIP_REASON_PRIVACY,+ resolve_kepu_billing_phase,+ shot_video_ready,+ shot_video_skipped,+)++from tests.conftest import make_user+++@asynccontextmanager+async def _same_session(db: AsyncSession):+ """把 pipeline 内自开 session 钉到用例事务。"""+ yield db+++def test_skipped_shot_counts_as_video_ready() -> None:+ """带隐私跳过标记的镜头视为视频阶段已收敛,不再预估/重提。"""+ skipped = SimpleNamespace(video_url=None, video_skip_reason=VIDEO_SKIP_REASON_PRIVACY)+ normal = SimpleNamespace(video_url=None, video_skip_reason=None)+ assert shot_video_skipped(skipped)+ assert shot_video_ready(skipped)+ assert not shot_video_ready(normal)+++async def test_phase_resolves_when_all_videos_skipped(+ db_session: AsyncSession, monkeypatch, tmp_path+) -> None:+ """全部镜头跳过视频后,下一阶段直接是 compose。"""+ (tmp_path / "full_narration.mp3").write_bytes(b"x" * 3000)+ monkeypatch.setattr("app.services.storage.project_dir", lambda _pid: tmp_path)+ user = await make_user(db_session)+ tpl = Template(id="tpl-privacy-1", name="隐私模板", style_prefix="x", seedance_config={})+ db_session.add(tpl)+ await db_session.flush()+ project = Project(+ user_id=user.id,+ template_id=tpl.id,+ source_text="测试",+ pipeline_mode="full",+ status=ProjectStatus.VIDEOING,+ )+ db_session.add(project)+ await db_session.flush()+ shot = Shot(+ project_id=project.id,+ shot_no=1,+ image_url="/static/p.png",+ video_url=None,+ video_skip_reason=VIDEO_SKIP_REASON_PRIVACY,+ status=ShotStatus.IMAGE_READY,+ )+ db_session.add(shot)+ await db_session.commit()++ from sqlalchemy import select+ from sqlalchemy.orm import selectinload++ loaded = (+ await db_session.execute(+ select(Project)+ .where(Project.id == project.id)+ .options(selectinload(Project.shots))+ )+ ).scalar_one()+ assert resolve_kepu_billing_phase(loaded) == "compose"+++async def test_parallel_videos_does_not_resubmit_skipped_shot(+ db_session: AsyncSession,+) -> None:+ """已标记隐私跳过的镜头走静图短路,绝不重新调用上游生视频。"""+ user = await make_user(db_session)+ tpl = Template(id="tpl-privacy-2", name="隐私模板2", style_prefix="x", seedance_config={})+ db_session.add(tpl)+ await db_session.flush()+ project = Project(+ user_id=user.id,+ template_id=tpl.id,+ source_text="测试",+ pipeline_mode="full",+ status=ProjectStatus.VIDEOING,+ )+ db_session.add(project)+ await db_session.flush()+ db_session.add_all(+ [+ Shot(+ project_id=project.id,+ shot_no=1,+ image_url="/static/p1.png",+ video_url="/static/v1.mp4",+ last_frame_url="/static/lf1.png",+ status=ShotStatus.VIDEO_READY,+ ),+ Shot(+ project_id=project.id,+ shot_no=2,+ image_url="/static/p2.png",+ video_url=None,+ video_skip_reason=VIDEO_SKIP_REASON_PRIVACY,+ status=ShotStatus.IMAGE_READY,+ ),+ ]+ )+ await db_session.commit()++ messages: list[str] = []++ async def _collect(_pid: int, payload: dict) -> None:+ messages.append(str(payload.get("message") or ""))++ ark = SimpleNamespace(+ gen_and_wait_video=AsyncMock(+ side_effect=AssertionError("隐私跳过镜头不得重新提交 Seedance")+ )+ )+ with (+ patch.object(pipeline, "AsyncSessionLocal", lambda: _same_session(db_session)),+ patch.object(pipeline, "publish_progress", _collect),+ patch.object(pipeline, "get_ark", return_value=ark),+ ):+ await pipeline._parallel_videos(project.id)++ assert any("已跳过 AI 视频" in m for m in messages)+ ark.gen_and_wait_video.assert_not_called()diff --git a/backend/tests/test_kepu_shot_edit_demote.py b/backend/tests/test_kepu_shot_edit_demote.pynew file mode 100644index 0000000..e4c32e9--- /dev/null+++ b/backend/tests/test_kepu_shot_edit_demote.py@@ -0,0 +1,121 @@+# -*- coding: utf-8 -*-+"""PATCH 分镜:改旁白作废整片连贯音轨,任何编辑都要把终态打回对应阶段。"""+from __future__ import annotations++from pathlib import Path++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.projects import update_shot+from app.models import Project, ProjectStatus, Shot, ShotStatus, Template+from app.schemas import ShotUpdate++from tests.conftest import make_user+++async def _make_done_project(db: AsyncSession, user, tmp_path: Path) -> tuple[Project, Shot, Shot]:+ """构造 DONE 项目:两镜均有图/视频/配音,整片连贯音轨文件存在。"""+ tpl = Template(id="tpl-demote-1", name="作废测试模板", style_prefix="x")+ db.add(tpl)+ await db.flush()+ project = Project(+ user_id=user.id,+ template_id=tpl.id,+ source_text="测试",+ status=ProjectStatus.DONE,+ final_video_url="/static/final.mp4",+ )+ db.add(project)+ await db.flush()+ shots = []+ for no in (1, 2):+ shot = Shot(+ project_id=project.id,+ shot_no=no,+ narration=f"旧旁白{no}",+ image_url=f"/static/p{project.id}/old_{no}.png",+ image_ark_url=f"http://up/old_{no}.png",+ video_url=f"/static/p{project.id}/v_{no}.mp4",+ audio_url=f"/static/p{project.id}/full_narration.mp3",+ status=ShotStatus.VIDEO_READY,+ )+ db.add(shot)+ shots.append(shot)+ await db.flush()+ narration = tmp_path / "full_narration.mp3"+ narration.write_bytes(b"x" * 3000)+ return project, shots[0], shots[1]+++async def test_narration_edit_invalidates_continuous_audio(+ db_session: AsyncSession, monkeypatch, tmp_path+) -> None:+ """改旁白后:旧整片音轨删除、所有镜头 audio_url 清空、成片作废、状态回退。"""+ user = await make_user(db_session)+ project, shot1, shot2 = await _make_done_project(db_session, user, tmp_path)+ monkeypatch.setattr(+ "app.services.storage.project_dir", lambda _pid: tmp_path+ )++ await update_shot(+ project.id,+ shot1.id,+ ShotUpdate(narration="这是全新的旁白内容"),+ db=db_session,+ user=user,+ )++ assert not (tmp_path / "full_narration.mp3").exists()+ await db_session.refresh(shot1)+ await db_session.refresh(shot2)+ assert shot1.audio_url is None+ assert shot2.audio_url is None # 整片连贯音轨,姊妹镜同步失效+ await db_session.refresh(project)+ assert project.final_video_url is None+ assert project.status == ProjectStatus.SCRIPT_READY # assets 阶段:需重配音+++async def test_img_prompt_edit_demotes_done_project(db_session: AsyncSession) -> None:+ """改首帧提示词:清下游素材,DONE 项目必须回退而非保留完成态。"""+ user = await make_user(db_session)+ tpl = Template(id="tpl-demote-2", name="作图废测试模板", style_prefix="x")+ db_session.add(tpl)+ await db_session.flush()+ project = Project(+ user_id=user.id,+ template_id=tpl.id,+ source_text="测试",+ status=ProjectStatus.DONE,+ final_video_url="/static/final2.mp4",+ )+ db_session.add(project)+ await db_session.flush()+ shot = Shot(+ project_id=project.id,+ shot_no=1,+ img_prompt="旧图提示",+ image_url="/static/old.png",+ video_url="/static/old.mp4",+ status=ShotStatus.VIDEO_READY,+ )+ db_session.add(shot)+ await db_session.flush()++ await update_shot(+ project.id,+ shot.id,+ ShotUpdate(img_prompt="全新的画面要求"),+ db=db_session,+ user=user,+ )++ await db_session.refresh(shot)+ assert shot.image_url is None+ assert shot.video_url is None+ assert shot.status == ShotStatus.PENDING+ await db_session.refresh(project)+ assert project.final_video_url is None+ assert project.status != ProjectStatus.DONEdiff --git a/backend/tests/test_kie_poll_resilience.py b/backend/tests/test_kie_poll_resilience.pynew file mode 100644index 0000000..1fcc69d--- /dev/null+++ b/backend/tests/test_kie_poll_resilience.py@@ -0,0 +1,206 @@+# -*- coding: utf-8 -*-+"""Kie 轮询韧性回归:++- fetch_video_once:429/5xx、网络异常、HTTP 200 业务错误码、成功但结果 URL 缺失,+ 一律按 running 退避;404/401 等终态 4xx 判 failed;+- wait_job_success / wait_veo_success:单次查询故障不杀整任务,退避后继续,总超时收敛。+"""+from __future__ import annotations++import json+from unittest.mock import AsyncMock++import httpx+import pytest++from app.services import kie_client as kie_module+from app.services.kie_client import KieClient, KiePollTransientError+++class _FakeResponse:+ """最小 httpx.Response 替身。"""++ def __init__(self, status_code: int = 200, payload=None, text: str = "err", content: bytes = b"x"):+ self.status_code = status_code+ self.text = text+ self.content = content+ self._payload = payload if payload is not None else {}++ def json(self):+ if isinstance(self._payload, Exception):+ raise self._payload+ return self._payload+++def _install_fake_http(monkeypatch, handler):+ """把 httpx.AsyncClient 替换为按 handler 脚本应答的假客户端。"""++ class _FakeAsyncClient:+ def __init__(self, *args, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def get(self, url, headers=None, params=None):+ outcome = handler()+ if isinstance(outcome, Exception):+ raise outcome+ return outcome++ monkeypatch.setattr(kie_module.httpx, "AsyncClient", _FakeAsyncClient)+++def kie(monkeypatch) -> KieClient:+ monkeypatch.setattr(KieClient, "_headers", lambda self: {"Authorization": "Bearer test"})+ return KieClient(api_key="test-key")+++def no_sleep(monkeypatch):+ monkeypatch.setattr(kie_module.asyncio, "sleep", AsyncMock())+++# ---------- fetch_video_once:jobs ----------+[email protected]("code", [429, 500, 502, 503, 504])+async def test_fetch_jobs_transient_http_is_running(kie, monkeypatch, code: int) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(code, payload={}, text="busy"))+ result = await kie.fetch_video_once("t1")+ assert result.status == "running"+ assert result.provider_task_id == "t1"+++async def test_fetch_jobs_network_error_is_running(kie, monkeypatch) -> None:+ _install_fake_http(monkeypatch, lambda: httpx.ConnectError("reset"))+ result = await kie.fetch_video_once("t1")+ assert result.status == "running"+++async def test_fetch_jobs_biz_code_error_is_running(kie, monkeypatch) -> None:+ _install_fake_http(+ monkeypatch,+ lambda: _FakeResponse(200, payload={"code": 500, "msg": "internal"}),+ )+ result = await kie.fetch_video_once("t1")+ assert result.status == "running"++[email protected]("code", [401, 404])+async def test_fetch_jobs_terminal_4xx_is_failed(kie, monkeypatch, code: int) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(code, payload={"msg": "denied"}))+ result = await kie.fetch_video_once("t1")+ assert result.status == "failed"+ assert "denied" in (result.error or "")+++async def test_fetch_jobs_empty_payload_is_running(kie, monkeypatch) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload={}))+ result = await kie.fetch_video_once("t1")+ assert result.status == "running"+++async def test_fetch_jobs_success_with_urls(kie, monkeypatch) -> None:+ payload = {+ "code": 0,+ "data": {+ "state": "success",+ "creditsConsumed": 10,+ "resultJson": json.dumps({"resultUrls": ["https://cdn.example.com/v.mp4"]}),+ },+ }+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await kie.fetch_video_once("t1")+ assert result.status == "succeeded"+ assert result.url == "https://cdn.example.com/v.mp4"+ assert result.raw_usage and result.raw_usage["creditsConsumed"] == 10+++async def test_fetch_jobs_success_without_urls_keeps_running(kie, monkeypatch) -> None:+ payload = {"code": 0, "data": {"state": "success", "resultJson": json.dumps({"resultUrls": []})}}+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await kie.fetch_video_once("t1")+ assert result.status == "running"+++async def test_fetch_jobs_failed_state(kie, monkeypatch) -> None:+ payload = {"code": 0, "data": {"state": "fail", "failMsg": "content policy", "failCode": "POL"}}+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await kie.fetch_video_once("t1")+ assert result.status == "failed"+ assert "content policy" in (result.error or "")+++# ---------- fetch_video_once:veo ----------++async def test_fetch_veo_success(kie, monkeypatch) -> None:+ payload = {+ "code": 0,+ "data": {+ "successFlag": 1,+ "creditsConsumed": 5,+ "response": {"resultUrls": ["https://cdn.example.com/veo.mp4"]},+ },+ }+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await kie.fetch_video_once("t1", api_kind="veo")+ assert result.status == "succeeded"+ assert result.url == "https://cdn.example.com/veo.mp4"+++async def test_fetch_veo_success_without_urls_keeps_running(kie, monkeypatch) -> None:+ payload = {"code": 0, "data": {"successFlag": 1, "response": {"resultUrls": []}}}+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await kie.fetch_video_once("t1", api_kind="veo")+ assert result.status == "running"+++async def test_fetch_veo_flag_failed(kie, monkeypatch) -> None:+ payload = {"code": 0, "data": {"successFlag": 3, "errorMessage": "blocked", "errorCode": "X"}}+ _install_fake_http(monkeypatch, lambda: _FakeResponse(200, payload=payload))+ result = await kie.fetch_video_once("t1", api_kind="veo")+ assert result.status == "failed"+ assert "blocked" in (result.error or "")+++async def test_fetch_veo_transient_is_running(kie, monkeypatch) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(500, payload={"msg": "upstream"}))+ result = await kie.fetch_video_once("t1", api_kind="veo")+ assert result.status == "running"+++# ---------- wait_* 长轮询容错 ----------++async def test_wait_job_survives_transient_then_succeeds(kie, monkeypatch, no_sleep) -> None:+ success = _FakeResponse(+ 200,+ payload={"code": 0, "data": {"state": "success", "resultJson": '{"resultUrls": ["https://x/v.mp4"]}'}},+ )+ script = iter([_FakeResponse(503, payload={"msg": "busy"}), success])+ _install_fake_http(monkeypatch, lambda: next(script))+ info = await kie.wait_job_success("t1", poll_interval=0.01, timeout=30)+ assert info["state"] == "success"+++async def test_wait_job_persistent_failure_times_out(kie, monkeypatch, no_sleep) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(503, payload={"msg": "busy"}))+ with pytest.raises(RuntimeError, match="Kie poll timeout"):+ await kie.wait_job_success("t1", poll_interval=0.01, timeout=0.02)+++async def test_wait_veo_survives_transient_then_succeeds(kie, monkeypatch, no_sleep) -> None:+ success = _FakeResponse(200, payload={"code": 0, "data": {"successFlag": 1, "response": {"resultUrls": ["https://x/v.mp4"]}}})+ script = iter([_FakeResponse(429, payload={"msg": "rate"}), success])+ _install_fake_http(monkeypatch, lambda: next(script))+ info = await kie.wait_veo_success("t1", poll_interval=0.01, timeout=30)+ assert info["successFlag"] == 1+++async def test_get_record_raises_transient_type(kie, monkeypatch) -> None:+ _install_fake_http(monkeypatch, lambda: _FakeResponse(500, payload={"msg": "x"}))+ with pytest.raises(KiePollTransientError):+ await kie.get_job("t1")diff --git a/backend/tests/test_model_settings_overlay.py b/backend/tests/test_model_settings_overlay.pynew file mode 100644index 0000000..3583872--- /dev/null+++ b/backend/tests/test_model_settings_overlay.py@@ -0,0 +1,61 @@+# -*- coding: utf-8 -*-+"""管理端模型配置 overlay 回归:++后台「清除密钥」会在 DB flat 中写入空串。空串是显式清空信号,+_refresh_overlay 必须保留它;否则 get_settings() 会回落 .env 旧密钥,+造成界面显示已清除、上游请求仍携带旧 Key 的危险不一致。+"""+from __future__ import annotations++import pytest++from app import config as config_module+from app.services import model_settings++[email protected](autouse=True)+def _isolate_overlay() -> None:+ """每个用例后还原全局 overlay 并清 settings 缓存,避免污染其他测试。"""+ saved = dict(model_settings._overlay)+ yield+ model_settings._overlay.clear()+ model_settings._overlay.update(saved)+ config_module.get_settings.cache_clear()+++def test_refresh_overlay_keeps_empty_string_secret() -> None:+ model_settings._refresh_overlay(+ {"flat": {"ark_api_key": "", "model_llm": "doubao-test"}}+ )+ overlay = model_settings.get_overlay_dict()+ assert "ark_api_key" in overlay+ assert overlay["ark_api_key"] == ""+ assert overlay["model_llm"] == "doubao-test"+++def test_refresh_overlay_skips_only_none() -> None:+ model_settings._refresh_overlay(+ {"flat": {"ark_api_key": None, "model_llm": "doubao-test"}}+ )+ overlay = model_settings.get_overlay_dict()+ assert "ark_api_key" not in overlay+ assert overlay["model_llm"] == "doubao-test"+++def test_cleared_secret_overrides_env_value(monkeypatch: pytest.MonkeyPatch) -> None:+ """env/.env 中存在旧密钥时,overlay 空串必须真正把它清空。"""+ monkeypatch.setenv("ARK_API_KEY", "env-old-secret")+ config_module.get_settings.cache_clear()+ assert config_module.get_settings().ark_api_key == "env-old-secret"++ model_settings._refresh_overlay({"flat": {"ark_api_key": ""}})+ config_module.get_settings.cache_clear()+ assert config_module.get_settings().ark_api_key == ""+++def test_unset_secret_falls_back_to_env(monkeypatch: pytest.MonkeyPatch) -> None:+ """overlay 不含该字段(None 被跳过)时仍正常回落 env 配置。"""+ monkeypatch.setenv("ARK_API_KEY", "env-live-key")+ model_settings._refresh_overlay({"flat": {"ark_api_key": None, "model_llm": "x"}})+ config_module.get_settings.cache_clear()+ assert config_module.get_settings().ark_api_key == "env-live-key"diff --git a/backend/tests/test_password_reset.py b/backend/tests/test_password_reset.pyindex dea8701..530cbf1 100644--- a/backend/tests/test_password_reset.py+++ b/backend/tests/test_password_reset.py@@ -23,6 +23,12 @@ class FakeRedis:def get(self, key: str) -> str | None:return self.store.get(key)+ def getdel(self, key: str) -> str | None:+ """原子取删(对应 Redis 6.2+ GETDEL)。"""+ value = self.store.pop(key, None)+ self.ttls.pop(key, None)+ return value+def setex(self, key: str, ttl: int, value: str) -> bool:self.store[key] = str(value)self.ttls[key] = int(ttl)diff --git a/backend/tests/test_security_hardening.py b/backend/tests/test_security_hardening.pynew file mode 100644index 0000000..a6ee55a--- /dev/null+++ b/backend/tests/test_security_hardening.py@@ -0,0 +1,164 @@+# -*- coding: utf-8 -*-+"""A3 安全加固回归:支付回调幂等、IDOR、令牌解析、签名常量时间比较。"""+from __future__ import annotations++import inspect+import uuid+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest+from fastapi import HTTPException+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api import billing as billing_api+from app.api import tools as tools_api+from app.api.v1 import generation as v1_generation+from app.deps import _user_from_bearer+from app.models import Order, User, WalletLedger+from app.services import epay++from tests.conftest import make_task, make_user+++class _FakeNotifyRequest:+ """模拟易支付回调的 POST 表单请求。"""++ def __init__(self, params: dict[str, str]) -> None:+ self.method = "POST"+ self._params = params+ self.query_params: dict[str, str] = {}++ async def form(self) -> dict[str, str]:+ return self._params+++async def _make_pending_order(db: AsyncSession, user: User) -> Order:+ """构造一笔 1 元待支付订单。"""+ order = Order(+ out_trade_no=f"TEST{uuid.uuid4().hex[:16]}",+ user_id=user.id,+ sku_id="test_100",+ amount_fen=100,+ credit_fen=100,+ pay_type="alipay",+ status="pending",+ )+ db.add(order)+ await db.flush()+ return order+++async def test_epay_notify_duplicate_callback_credits_once(+ db_session: AsyncSession,+) -> None:+ """易支付重复回调只入账一次(行锁 + paid 幂等返回)。"""+ user = await make_user(db_session, balance_fen=0)+ order = await _make_pending_order(db_session, user)+ params = {+ "trade_status": "TRADE_SUCCESS",+ "out_trade_no": order.out_trade_no,+ "trade_no": "upstream-t-1",+ "money": "1.00",+ "sign": "x",+ }++ with patch.object(epay, "verify", return_value=True):+ resp1 = await billing_api.epay_notify(_FakeNotifyRequest(params), db=db_session)+ resp2 = await billing_api.epay_notify(_FakeNotifyRequest(params), db=db_session)++ assert resp1.body == b"success"+ assert resp2.body == b"success"+ topup_count = (+ await db_session.execute(+ select(func.count())+ .select_from(WalletLedger)+ .where(+ WalletLedger.user_id == user.id,+ WalletLedger.kind == "topup",+ WalletLedger.ref_id == order.out_trade_no,+ )+ )+ ).scalar_one()+ assert topup_count == 1+ await db_session.refresh(user)+ assert user.balance_fen == 100+++def test_epay_notify_source_locks_order_row() -> None:+ """源码守卫:回调必须用 SELECT ... FOR UPDATE 锁订单行,防并发双入账。"""+ assert "with_for_update" in inspect.getsource(billing_api.epay_notify)+++def test_epay_verify_constant_time_signature() -> None:+ """正确签名通过、篡改签名拒绝;比较走 hmac.compare_digest。"""+ key = "unit-key"+ params = {"a": "1", "b": "2"}+ sign = epay._sign_pairs(params, key)+ fake_settings = SimpleNamespace(epay_key=key)+ forged = sign[:-1] + ("0" if sign[-1] != "0" else "1")+ with patch.object(epay, "get_settings", return_value=fake_settings):+ assert epay.verify({**params, "sign": sign}) is True+ assert epay.verify({**params, "sign": forged}) is False+ assert epay.verify({**params, "sign": ""}) is False+ assert "compare_digest" in inspect.getsource(epay.verify)+++async def test_v1_get_task_rejects_other_user(db_session: AsyncSession) -> None:+ """B 用户不得凭上游 task_id 查询 A 用户的视频任务(IDOR)。"""+ user_a = await make_user(db_session)+ user_b = await make_user(db_session)+ await make_task(+ db_session,+ user_a,+ domain="api",+ task_type="v1_seedance",+ status="awaiting_poll",+ billing_status="frozen",+ provider_task_id="prov-idor-1",+ )++ poll = AsyncMock(return_value={"status": "running"})+ with patch.object(v1_generation, "poll_video_task", poll):+ with pytest.raises(HTTPException) as exc:+ await v1_generation.get_task("prov-idor-1", db=db_session, user=user_b)+ assert exc.value.status_code == 404+ poll.assert_not_called()+++async def test_v1_get_task_allows_owner(db_session: AsyncSession) -> None:+ """归属人查询自己的任务正常透传上游状态。"""+ user = await make_user(db_session)+ await make_task(+ db_session,+ user,+ domain="api",+ task_type="v1_seedance",+ status="awaiting_poll",+ billing_status="frozen",+ provider_task_id="prov-owner-1",+ )++ poll = AsyncMock(return_value={"status": "running"})+ with patch.object(v1_generation, "poll_video_task", poll):+ out = await v1_generation.get_task("prov-owner-1", db=db_session, user=user)+ assert out.status == "running"+ poll.assert_awaited_once()+++async def test_tools_get_task_404_without_local_row(db_session: AsyncSession) -> None:+ """/api/tools/tasks 本地无归属记录时不得代理查询上游。"""+ user = await make_user(db_session)+ poll = AsyncMock()+ with patch.object(tools_api, "poll_video_task", poll):+ with pytest.raises(HTTPException) as exc:+ await tools_api.get_tool_task("stranger-task", db=db_session, user=user)+ assert exc.value.status_code == 404+ poll.assert_not_called()+++async def test_bearer_rejects_non_numeric_jwt_sub(db_session: AsyncSession) -> None:+ """JWT sub 非数字时返回匿名 None,不抛 ValueError。"""+ with patch("app.deps.decode_token", return_value="not-an-int"):+ assert await _user_from_bearer(db_session, "fake.jwt.token") is Nonediff --git a/backend/tests/test_seedance_billing_usage.py b/backend/tests/test_seedance_billing_usage.pyindex 9d0c6c9..d915fc8 100644--- a/backend/tests/test_seedance_billing_usage.py+++ b/backend/tests/test_seedance_billing_usage.py@@ -2,16 +2,28 @@from __future__ import annotations+import uuid+import pytestfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from app.models import UsageEvent+from app.models import Project, Template, UsageEventfrom app.services.ark import TaskResultfrom app.services.drama.billing_util import record_seedance_video_usagefrom tests.conftest import make_user+async def _make_project(db: AsyncSession, user_id: int) -> int:+ """建真实项目并返回 id(usage_events.project_id 有 FK 约束)。"""+ tpl = Template(id=f"tpl-sd-{uuid.uuid4().hex[:8]}", name="计费模板", style_prefix="x")+ db.add(tpl)+ project = Project(user_id=user_id, template_id=tpl.id, source_text="x", title="计费项目")+ db.add(project)+ await db.flush()+ return int(project.id)++@pytest.mark.asyncioasync def test_record_seedance_video_usage_real_tokens(db_session: AsyncSession) -> None:user = await make_user(db_session)@@ -41,6 +53,7 @@ async def test_record_seedance_video_usage_real_tokens(db_session: AsyncSession)@pytest.mark.asyncioasync def test_record_seedance_video_usage_fallback_estimate(db_session: AsyncSession) -> None:user = await make_user(db_session)+ project_id = await _make_project(db_session, user.id)await record_seedance_video_usage(db_session,user_id=user.id,@@ -49,7 +62,7 @@ async def test_record_seedance_video_usage_fallback_estimate(db_session: AsyncSedomain="kepu",task_result=None,fallback_duration_sec=5,- project_id=9,+ project_id=project_id,)await db_session.commit()row = (await db_session.execute(select(UsageEvent).where(UsageEvent.user_id == user.id))).scalar_one()diff --git a/backend/tests/test_task_executor_freeze_steps.py b/backend/tests/test_task_executor_freeze_steps.pyindex d7c4ab4..55db764 100644--- a/backend/tests/test_task_executor_freeze_steps.py+++ b/backend/tests/test_task_executor_freeze_steps.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport inspectfrom contextlib import asynccontextmanagerfrom datetime import UTC, datetime-from unittest.mock import patch+from unittest.mock import AsyncMock, patchimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession@@ -156,3 +156,71 @@ async def test_execute_task_run_marks_failed_when_handler_returns_ok_false(assert "seedream_policy" in (done.error_message or "")assert done.steps and done.steps[0].status == "failed"++async def _lease_task_with_step(db_session: AsyncSession):+ """造一个 leased + 单 step 的任务,返回 (task_id, same_session CM)。"""+ from contextlib import asynccontextmanager as _acm++ user = await make_user(db_session, balance_fen=50_000)+ task = await make_task(db_session, user, domain="api", task_type="v1_image", status="leased")+ db_session.add(TaskStep(task_id=task.id, step_key="main", step_type="run", status="pending"))+ await db_session.commit()++ @_acm+ async def same_session():+ yield db_session++ return int(task.id), same_session+++async def test_execute_task_run_fails_task_when_freeze_raises_non_valueerror(+ db_session: AsyncSession,+) -> None:+ """freeze 抛 DB 瞬断等非 ValueError:任务必须 failed 收敛,不得裸逃卡 leased。"""+ task_id, same_session = await _lease_task_with_step(db_session)++ with (+ patch("app.services.tasks.executor.AsyncSessionLocal", same_session),+ patch(+ "app.services.tasks.executor.freeze_for_task",+ new=AsyncMock(side_effect=RuntimeError("connection reset")),+ ),+ ):+ await execute_task_run(task_id)++ db_session.expire_all()+ done = await get_task_for_runtime(db_session, task_id)+ assert done is not None+ assert done.status == "failed"+ assert done.error_code == "RuntimeError"+ assert "connection reset" in (done.error_message or "")+ assert done.finished_at is not None+ assert done.billing_status == "none"+ assert done.steps and done.steps[0].status == "failed"+++async def test_execute_task_run_insufficient_balance_keeps_special_error_code(+ db_session: AsyncSession,+) -> None:+ """余额不足 ValueError 仍收敛为专用错误码(供前端引导充值),未预扣保持 none。"""+ task_id, same_session = await _lease_task_with_step(db_session)++ with (+ patch("app.services.tasks.executor.AsyncSessionLocal", same_session),+ patch(+ "app.services.tasks.executor.freeze_for_task",+ new=AsyncMock(side_effect=ValueError("余额不足:需要 ¥1.00,当前 ¥0.00")),+ ),+ ):+ await execute_task_run(task_id)++ db_session.expire_all()+ done = await get_task_for_runtime(db_session, task_id)+ assert done is not None+ assert done.status == "failed"+ assert done.error_code == "insufficient_balance"+ assert done.billing_status == "none"+ assert done.steps and done.steps[0].status == "failed"+diff --git a/backend/tests/test_task_poller_dispatch.py b/backend/tests/test_task_poller_dispatch.pynew file mode 100644index 0000000..3030f74--- /dev/null+++ b/backend/tests/test_task_poller_dispatch.py@@ -0,0 +1,132 @@+"""Selector 分派回归:非 drama 的 awaiting_poll 任务不得进入 drama 轮询处理器。"""+from __future__ import annotations++from contextlib import asynccontextmanager+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, patch++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models_tasks import TaskRun+from app.services.tasks import poller as poller_mod++from tests.conftest import make_task, make_user+++@asynccontextmanager+async def _same_session(db: AsyncSession):+ """把服务内 AsyncSessionLocal 钉到用例事务 session。"""+ yield db+++async def test_selector_only_dispatches_fragment_video_to_drama_poller(+ db_session: AsyncSession,+) -> None:+ """api/studio deferred 视频任务必须只走 ephemeral 轮询,不能被 drama poller 判失败。"""+ user = await make_user(db_session)+ now = datetime.now(UTC)+ # 漫剧分镜视频:唯一允许进入 drama poller 的任务+ drama_task = await make_task(+ db_session,+ user,+ domain="drama",+ task_type="fragment_video",+ status="awaiting_poll",+ provider_task_id="prov-drama-1",+ )+ # 开放 API / 工具的 deferred 视频:旧实现下会被误送 drama poller 并立即判失败+ api_task = await make_task(+ db_session,+ user,+ domain="api",+ task_type="v1_seedance",+ status="awaiting_poll",+ provider_task_id="prov-api-1",+ )+ drama_task.next_action_at = now - timedelta(seconds=1)+ api_task.next_action_at = now - timedelta(seconds=1)+ await db_session.commit()+ api_task_id = int(api_task.id)++ drama_poll = AsyncMock()+ with (+ patch("app.services.tasks.poller.AsyncSessionLocal", lambda: _same_session(db_session)),+ patch("app.services.drama.jobs.poll_fragment_video_task", drama_poll),+ ):+ await poller_mod._select_and_poll_due()++ called_ids = {call.args[0] for call in drama_poll.await_args_list}+ assert called_ids == {int(drama_task.id)}+ assert api_task_id not in called_ids+++async def test_selector_sql_filters_fragment_video_type() -> None:+ """源码守卫:到期查询必须带 task_type=fragment_video,避免回归成无 domain 过滤。"""+ captured: dict[str, object] = {}++ class _Result:+ def scalars(self):+ return self++ def all(self):+ return []++ class _Session:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return None++ async def execute(self, stmt):+ captured["sql"] = str(stmt.compile(compile_kwargs={"literal_binds": True}))+ return _Result()++ with patch.object(poller_mod, "AsyncSessionLocal", _Session):+ await poller_mod._select_and_poll_due()++ assert "fragment_video" in str(captured["sql"])+++async def test_ephemeral_poller_respects_next_action_at_gate(+ db_session: AsyncSession,+) -> None:+ """next_action_at 在未来的在途任务本轮不查上游;NULL/到期才查。"""+ user = await make_user(db_session)+ now = datetime.now(UTC)++ due_task = await make_task(+ db_session,+ user,+ domain="api",+ task_type="v1_video",+ status="awaiting_poll",+ provider_task_id="prov-due",+ )+ waiting_task = await make_task(+ db_session,+ user,+ domain="studio",+ task_type="tool_video",+ status="awaiting_poll",+ provider_task_id="prov-wait",+ )+ due_task.billing_status = "frozen"+ waiting_task.billing_status = "frozen"+ due_task.next_action_at = now - timedelta(seconds=1)+ waiting_task.next_action_at = now + timedelta(minutes=5)+ await db_session.commit()++ upstream_poll = AsyncMock(return_value={"status": "running"})+ with (+ patch("app.services.tasks.poller.AsyncSessionLocal", lambda: _same_session(db_session)),+ patch("app.services.studio_tools.poll_video_task", upstream_poll),+ ):+ await poller_mod._poll_ephemeral_deferred_tasks()++ polled_users = [call.args[1] for call in upstream_poll.await_args_list]+ assert len(polled_users) == 1 # 仅到期任务查了上游diff --git a/backend/tests/test_voice_design.py b/backend/tests/test_voice_design.pyindex 5eb9d01..d206856 100644--- a/backend/tests/test_voice_design.py+++ b/backend/tests/test_voice_design.py@@ -36,5 +36,11 @@ def test_voice_design_enabled_requires_pool_and_auth(monkeypatch) -> None:)assert voice_design_enabled(cfg) is True- cfg2 = Settings(volc_tts_voice_design_speaker_ids="S_test")+ # 显式清空三组凭证:构造参数可能被 .env/环境变量回填,不能依赖默认值+ cfg2 = Settings(+ volc_tts_voice_design_speaker_ids="S_test",+ volc_tts_api_key="",+ volc_tts_app_id="",+ volc_tts_access_key="",+ )assert voice_design_enabled(cfg2) is Falsediff --git a/backend/tests/test_voice_synthesis.py b/backend/tests/test_voice_synthesis.pyindex 747e85a..c6966b1 100644--- a/backend/tests/test_voice_synthesis.py+++ b/backend/tests/test_voice_synthesis.py@@ -15,12 +15,19 @@ def test_normalize_character_name_strips_suffix() -> None:def test_build_voice_sample_line_short() -> None:- assert build_voice_sample_line_short("禹") == "你好,我是禹。"- assert build_voice_sample_line_short("很长的角色名称测试") == "你好,我是很长的角色名称测。"+ # 试听句须 ≥2s,固定句在自我介绍后追加声线说明(voice_synthesis.py)+ assert build_voice_sample_line_short("禹") == (+ "你好,我是禹。请听我的语气与声线,之后我会用这样的声音来讲述故事。"+ )+ assert build_voice_sample_line_short("很长的角色名称测试") == (+ "你好,我是很长的角色名称测。请听我的语气与声线,之后我会用这样的声音来讲述故事。"+ )def test_build_voice_sample_text_short_mode() -> None:- assert build_voice_sample_text("任意描述", "伯益", short=True) == "你好,我是伯益。"+ assert build_voice_sample_text("任意描述", "伯益", short=True) == (+ "你好,我是伯益。请听我的语气与声线,之后我会用这样的声音来讲述故事。"+ )def test_infer_drama_speaker_differs_by_role() -> None:diff --git "a/docs/reports/\344\273\243\347\240\201\346\211\253\346\217\217\344\277\256\345\244\215\346\212\245\345\221\212_20260914.md" "b/docs/reports/\344\273\243\347\240\201\346\211\253\346\217\217\344\277\256\345\244\215\346\212\245\345\221\212_20260914.md"new file mode 100644index 0000000..0196209--- /dev/null+++ "b/docs/reports/\344\273\243\347\240\201\346\211\253\346\217\217\344\277\256\345\244\215\346\212\245\345\221\212_20260914.md"@@ -0,0 +1,68 @@+# 全库代码扫描与修复报告++- 日期:2026-09-14+- 分支:`feat/kepu-optimize`+- 方式:8 个只读 agent 分域并行扫描(任务平台 / 科普流水线 / 上游客户端 / 计费认证 / 漫剧 / 基建 / 用户端前端 / 管理端前端),主会话逐条人工复核(排除误报)后分批修复,每批跑测试与静态检查。+- 验证:后端 `.venv/Scripts/python.exe -m pytest`;前端 `tsc -b --noEmit` + `oxlint`。++## 修改清单++| # | 级别 | 域 | 文件 | 问题 | 修改 | 验证 |+|---|------|----|------|------|------|------|+| 1 | CRITICAL | 任务平台 | `app/services/tasks/poller.py` | Selector 到期查询无 task_type 过滤,api/studio 的 deferred 视频被送进 drama 的 `poll_fragment_video_task`,因 fragment_id≤0 8 秒内必判"分镜已变更"失败,开放 API 文生视频实际不可用且永不计费 | 查询加 `task_type=="fragment_video"` 过滤;轻量任务由 ephemeral 轮询处理 | 新增 `tests/test_task_poller_dispatch.py` 3 测试 + 任务平台既有 35 测试通过 |+| 2 | HIGH | 任务平台 | `app/services/tasks/poller.py` | ephemeral 轮询每 8 秒对全部在途任务查上游(无 next_action_at 门控),放大上游压力 | 加 `next_action_at IS NULL OR <= now` 门控;循环体抽 `_poll_one_ephemeral_task`,单行异常隔离(CancelledError 透传) | 同上(门控测试) |+| 3 | HIGH | 漫剧 | `app/services/drama/jobs.py`、`app/api/drama/episodes.py` | `cancel_all_episode_video_jobs()` 无参全表取消:任一用户"取消全部"会把**所有用户**生成中的分镜置 cancelled;`_reset_fragment_video_generation` 同病 | 双 JOIN 到 DramaProject 按 user_id 过滤;签名改必传 `user_id`;API 调用点传 `user.id` | 新增 `tests/test_drama_cancel_scope.py`;漫剧相关 123 测试通过 |+| 4 | HIGH | 计费 | `app/api/billing.py` | 易支付回调读订单无行锁,并发重复 notify 可重复入账(钱包流水无唯一约束兜底) | 订单查询加 `with_for_update` 行锁,paid 状态二次复查走幂等返回 | `tests/test_security_hardening.py` 重复回调仅入账一次 |+| 5 | MEDIUM | 认证 | `app/api/v1/generation.py` | `GET /v1/tasks/{task_id}` 不校验归属,任意用户凭上游 task_id 可拖走他人视频 | 先查本地 TaskRun 归属(requested_by),无记录 404,再代理上游 | IDOR 拒绝/属主放行 2 测试 |+| 6 | MEDIUM | 认证 | `app/api/tools.py` | `GET /api/tools/tasks/{id}` 本地无 ToolRun 归属行时仍代理 `poll_video_task` 查上游,同 IDOR | 无本地行直接 404(image 路径本就有 user 过滤) | 404 测试 |+| 7 | LOW | 认证 | `app/services/epay.py` | 回调签名用 `==` 比较,非常量时间 | 改 `hmac.compare_digest` | 签名正反用例 + 源码守卫 |+| 8 | LOW | 认证 | `app/deps.py` | 顶部 import 块与 `security` 整体重复一份;`int(sub)` 对畸形 JWT 抛 ValueError(500) | 去重复块;sub 解析包 try/except 返回 401 | 非数字 sub 返回 None 测试 |+| 9 | LOW | 认证 | `app/services/password_reset.py` | 重置令牌 GET+DELETE 非原子,并发可消费两次 | 改 Redis `GETDEL` 原子取删 | 既有 4 测试(FakeRedis 补 getdel)通过 |+| 10 | LOW | 计费 | `app/api/billing.py` | `_notify_success` 三段重复判断且后两段为死分支 | 合并为一次状态集合判断 | 重复回调用例覆盖 |+| 11 | 死代码 | 计费 | `app/services/billing/settlement.py`、`billing/__init__.py` | `settle_project`(旧项目维度结算,跨项目串退风险)全库无调用 | 删除函数及包导出 | 全量测试 |+| 12 | 死代码 | 计费 | `app/services/billing/ephemeral.py`、`billing/__init__.py` | `run_with_registered_handler` 全库无调用;删后连带未用 import | 删除函数、导出与 `execute_task_run` 导入 | 全量测试 |+| 13 | HIGH | 科普流水线 | `app/services/pipeline.py` | `run_pipeline` 捕获 PipelineCancelled 后吞异常不 re-raise,TaskRun 误判 succeeded 照常扣费,并破坏 asyncio 取消语义 | 取消分支末尾补 `raise` | `test_kepu_cancel_propagation.py` 含源码守卫 |+| 14 | HIGH | 科普流水线 | `app/services/pipeline.py` | 三个 regen(image/video/audio)在项目已 CANCELLED 后仍写回素材并把项目"复活";但上游成本真实发生 | 写回前读项目状态,已取消则跳过写回/复活,**用量记账照常**后抛 PipelineCancelled;image/video 成功写回时清 `video_skip_reason` | 同文件 5 测试 |+| 15 | HIGH | 科普流水线 | `app/services/tasks/handlers.py` | 6 个 kepu handler 取消语义不统一 | 新增 `_await_kepu` 统一包装:PipelineCancelled 且 `cancel_requested` 时返回 `{"cancelled": True}` 退冻结,否则上抛 | SimpleNamespace 三态测试 |+| 16 | MEDIUM | 科普流水线 | `app/api/projects.py`(update_shot) | 改旁白后旧 `full_narration.mp3` 与各镜 audio_url 仍被使用;改 img_prompt 不清隐私跳过标记;本端点是唯一漏调 `_demote_after_edit` 的编辑口(DONE 不回退) | setattr 前比较旁白真实变化(audio_dirty),删整片音频并清各镜 audio_url;素材类编辑清 `video_skip_reason`;结尾统一 demote | `test_kepu_shot_edit_demote.py` 2 测试 |+| 17 | MEDIUM | 科普流水线 | `app/models.py`、`app/main.py`、`pipeline.py`、`kepu_stages.py` | 真人隐私拦截只在当轮内存生效,每轮轮询/重试都重新提交 Seedance(重复扣费、重复触违规) | 新增 `shots.video_skip_reason` 列(additive schema 补丁,已对 dev 库执行);拦截分支持久化 `privacy` 标记;`shot_video_ready/skipped` 让阶段判定与计费预估把"已跳过"视为收敛,静图合成 | `test_kepu_privacy_skip.py` 3 测试 |+| 18 | MEDIUM | 科普流水线 | `app/services/pipeline.py` | `_synthesize_continuous_audio` 新合成后不复查,近静音 TTS 会产出无声成片 | 拷贝新文件后 `is_near_silent_audio` 复查,近静音抛错终止 | `test_kepu_continuous_audio_qc.py` |+| 19 | HIGH | 上游客户端 | `app/services/ark.py` | `poll_task`/`fetch_task_once` 单次 GET 收到 429/5xx 即判任务 failed(上游一次限流就误杀计费任务);网络异常在同步端点直接 500 | 新增 `_is_transient_http_status`/`_retry_after_seconds`:429/5xx 与网络异常按 running 退避(尊重 Retry-After,上限 60s),长轮询由 deadline 收敛,400/404 等 4xx 保持终态 | `test_ark_poll_resilience.py` 30 测试 |+| 20 | MEDIUM | 上游客户端 | `app/services/ark.py` | `gen_and_wait_seedance_body` 一个大 try 包住"建单+等待",隐私拦截/失败/超时等任意异常都用同一 body **重新建单**,产生第二个计费任务 | 提交与等待分层捕获:仅"参考音频下载失败"剥离 reference_audio 重提一次(audio_fallback 门闩),其余异常立即上抛 | 同文件 5 场景(wait/submit × 音频/非音频/重提上限) |+| 21 | HIGH | 上游客户端 | `app/services/model_settings.py` | `_refresh_overlay` 过滤空串:后台「清除密钥」写入的 `""` 被丢弃,`get_settings()` 回落 `.env` 旧密钥——界面显示已清除,请求仍带旧 Key | overlay 仅跳过 None,空串作为"显式清空"保留 | `test_model_settings_overlay.py` 4 测试(含 env 旧值对照) |+| 22 | 死代码 | 上游客户端 | `app/services/ark_control_usage.py`、`tests/test_ark_control_usage.py` | 火山管控面 GetInferenceUsage HMAC 客户端(204 行)产品代码零引用,上游成本监控已改走 TokenFree(`services/admin/upstream_usage.py`) | 整模块连同专属测试删除(47 行) | 全量测试 |+| 23 | HIGH | 上游客户端 | `app/services/kie_client.py` | `get_job`/`get_veo` 单次 429/5xx/网络异常/非 JSON 即抛,wait 循环零容忍致生图/视频误失败收费;不校验 HTTP 200 包裹的业务错误码;success 无结果 URL 时返回 succeeded+空 URL,下载方必炸;重复的两个查询方法 | 新增 `KiePollTransientError`,抽公共 `_get_record`(瞬时/终态分类 + 业务 code 校验);wait 循环容错退避到总超时;`fetch_video_once` 瞬时→running、终态 4xx→failed、success 无 URL→继续轮询 | `test_kie_poll_resilience.py` 21 测试 |+| 24 | 死代码 | 上游客户端 | `kie_client.py`、`kie_catalog.py` | `uses_kie`、`get_account_credits`、`default_kie_channel_models` 全库零调用;连带未用导入 | 删除三个函数并清 `get_media_model` 导入 | 全量测试 |+| 25 | 死代码 | 科普流水线 | `app/services/pipeline.py`、`app/services/ffmpeg_compose.py` | 去 worker 化后旧进程内入口与死阶段长期残留:`start_pipeline`、`_regen_tasks`、`_dispatch_side_task`、`dispatch_regen_image/video/audio/project_audio_and_compose/compose_only`、`_running` 字典、`_image_stage/_video_stage/_audio_stage`;ffmpeg 的 `concat_native_videos`、`_write_ass/_write_srt/_ass_ts/_escape_ass_text`;恒 False 的 `_use_native_video_audio` 死分支 | 全部删除(grep 双向验证零调用,任务平台 handler 驱动的 run_pipeline/regen_* 保留);`cancel_pipeline` 简化为标记+恒 False(两处 API 调用不取返回值,行为等价);native 分支删除后存活路径去缩进。pipeline 2145→1792 行,ffmpeg_compose 1596→1368 行 | 受影响 40 测试通过;全量回归无新增失败 |+| 26 | HIGH | 任务平台/漫剧 | `app/services/tasks/service.py`、`app/services/tasks/executor.py`、`app/services/drama/jobs.py` | 分镜视频轮询成功后存在下载落盘收尾窗口:用户恰在此时取消,`_mark_cancelled` 立即把冻结额**全额退款**,而收尾协程随后写入的 `usage_events` 永久 `settled=False`(悬空),钱货两失;并发认领也缺少收尾期防护(可能重复下载双记费) | 三层修复:① service 新增 `task_finalizing_window_open`/`clear_finalizing_window`(`payload.finalizing_until` 窗口键,naive 按 UTC、坏值/无键视为窗口外);② poller 行锁认领后置 10 分钟 finalizing 窗口(`_FRAGMENT_FINALIZE_CLAIM_TTL`),`_mark_cancelled` 在窗口内让位(任务保持 cancel_requested,不结算不退款,由 poller 下轮与 TTL 兜底),认领后复查取消标志直接 fail 不下载;③ 下载落盘后行锁复查:已取消则新函数 `_settle_cancelled_after_finalized` 收敛为 cancelled 终态并 `settle_task` 按实多退少补(不激活后续顺序任务);`BaseException` 释放认领时按"已落盘且取消→按实结算 / 已落盘→清标记唤醒 / 未落盘→回 polling"三分支处理 | 新增 `tests/test_finalizing_cancel_race.py` 15 测试(纯函数 7、mock 3、真实 freeze/settle 的 DB 集成 5:差额退款、窗口内冻结不动、过期全退、重复收敛幂等);全量 511 passed / 9 基线失败 |+| 27 | MEDIUM | 测试基建 | `tests/conftest.py` | `db_session` 直连 `.env` 业务库 `printfilm`:① 仪表盘/财务等全局统计断言被真实数据污染(今日 calls 实际 50/102,断言 1);② `create_all`/`ALTER TABLE` 等 DDL 自动提交直接作用于开发库;③ 缺 FK 行的测试靠业务库残留数据侥幸通过,掩盖真实缺陷;④ 增量列在 conftest 手写单列清单,与 `main._apply_schema_patches` 漂移(新库缺 `subtitle_preset` 等 10+ 列) | 新增 `_resolve_test_database_url`(业务库名派生 `<库名>_test`;已含 `test` 时原样使用,便于 CI 注入;库名字符白名单拒绝)与 `_ensure_test_database`(连 `postgres` 维护库 AUTOCOMMIT 检查并建库);fixture 强制连独立测试库;增量列改为临时把 `app.main.engine` 指向测试 engine 后复用权威 `_apply_schema_patches`,finally 还原,杜绝补丁清单漂移 | 隔离后原 9 个基线失败中 4 个自动转绿;同时暴露并修复 1 个被脏数据掩盖的 FK 缺陷(见 #28);全量 **520 passed / 0 failed** |+| 28 | 测试修复 | 测试 | `test_admin_stats.py`、`test_billing_integration.py`、`test_voice_design.py`、`test_voice_synthesis.py`、`test_seedance_billing_usage.py` | 扫描开始前即存在的 9 个基线失败 + 独立测试库暴露的 1 个隐藏失败:① 3 个 dashboard 用例写死全局计数(随 #27 数据隔离转绿,断言不改);② `test_aggregate_usage_summary_breakdown` 插 `project_id=42/99/7` 无真实行违反 FK;③ `test_record_llm_chat_line_skips_without_billing_scope` 用 `select(UsageEvent)` 全表计数;④ voice_design 第二组 Settings 未显式清空凭证,被 `.env` 回填致判定 True;⑤ voice_synthesis 2 个用例仍断言旧短句,产品已改为 ≥2s 的新试听文案;⑥ seedance fallback 用例传 `project_id=9` 靠开发库残留行通过;⑦ upstream 快照插今日日期撞唯一约束(空库消失) | ② 建真实 Template+Project 并以实际 id 入参,不存在项目用 9999999;③ 计数加 `user_id` 过滤;④ 显式传三个空凭证;⑤ 断言更新为新文案(自我介绍+声线说明)并保留 8 字截断用例;⑥ 同样建真实项目行;①⑦ 无需改码 | 全量 **520 passed / 0 failed**(此前 496 passed / 9 failed) |+| 29 | MEDIUM | 任务平台/计费 | `app/services/tasks/executor.py`、`app/services/tasks/service.py`、`app/services/billing/settlement.py`、`app/services/tasks/scheduler.py` | ① `freeze_for_task` 仅捕获 ValueError:DB 瞬断等非 ValueError 裸逃出执行协程,任务永久卡 `leased` 只能等 watchdog 周期回收;② executor 结果分支有不可达死代码(`pending + deferred` 判断被上一联合分支先吞);③ service 三个全库零调用死函数(`update_task_for_user`/`retry_task_for_user`/`count_awaiting_poll_tasks` + `TaskUpdateRequest` 导入);④ 终态任务 billing_status 仍 `frozen` 无对账扫描(settle 瞬间进程被杀即冻结额不退、usage 悬空) | ① 抽 `_fail_task_before_start`(step 预读传入规避 populate_existing 卸关系;frozen 保留交 settle、否则归 none;记事件+settle+commit),ValueError 走 `insufficient_balance` 专用码、其他异常记异常类型码并 failed 收敛;② 删除不可达分支;③ 删三个死函数与未用导入(grep 双向验证);④ settlement 新增 `reconcile_terminal_frozen_tasks`(只扫 succeeded/failed/cancelled 且 finished_at 超 120s 宽限的 frozen 行,逐行 settle_task 并吞单条异常;幂等门闩保证重复安全;finalizing 任务非终态不会被误伤),scheduler 孤儿扫描周期低频驱动 | executor 新增 2 测试(RuntimeError 收敛/余额不足专用码);新增 `tests/test_billing_reconcile.py` 4 测试(超宽限按实结算、宽限内不动、非终态/已结算跳过、无用量全退);全量 **526 passed / 0 failed** |+| 30 | HIGH(发版阻塞) | 用户端前端 | `frontend/src/pages/studio/StyleConfigPage.tsx`、`pages/drama/AssetsStep.tsx`、`pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx`、`pages/drama/ProjectWorkspacePage.tsx` | `npm run build` 的 tsc 阶段 5 个错误直接阻断出包:① StyleConfigPage 守卫为 `if (!project && !error)`,项目初始加载失败时 error 非空穿透主页面,623 行 `project.shots` 非空访问白屏崩溃(真缺陷);②③ 两处 `resolveDramaMediaUrl` 未用导入;④ ProjectWorkspacePage 路由改版后遗留死代码 `steps`/`goToStep`(及连带 `useMemo`/`buildProjectSteps`/`hasScript` 未用) | ① 守卫收紧为 `if (!project)`,error 态渲染 BillingErrorNotice,类型收窄后全页非空访问安全;②③ 删未用导入;④ 删死函数/死变量与连带导入,步骤导航已由 `applyLocationState` 路由态驱动(行为不变) | `npx tsc -b --noEmit` 零错误;`npm run build` 复验(见验证状态);管理端 tsc/build 本就全绿 |++## 经评估暂不修改(需产品/架构决策,记录在案)++| 项 | 原因 |+|----|------|+| 登录接口无限流 / JWT 改密不可吊销 / API Key 与 JWT 权限等价无 scope | 影响面大的鉴权策略变更,需产品确认限流阈值与令牌体系设计 |+| 生产环境默认 secret_key / debug 无启动校验 | 部署通过环境变量注入;加硬失败可能阻断现有部署,拟与运维确认后加 warning |+| wallet_ledger 加 `(ref_type, ref_id)` 唯一约束 | 需先排查历史重复数据并做数据迁移,作为后续独立变更 |+| `config.py`/`schemas_settings.py` 的 `volc_*` 配置字段(4 字段 + 后台 overlay/clear 契约) | 唯一消费方 ark_control_usage 已删(#22),但管理端设置页表单可能仍渲染/提交;留待管理端前端批次连同 UI 一并删除,避免前后端不同步 |++## 当前验证状态++- 后端全量:**526 passed, 0 failed**(2026-09-14,#1–#30 完成后;扫描开始时为 496 passed / 9 failed)。+- 用户端 `frontend`:`npx tsc -b --noEmit` 零错误,`npm run build` 出包成功(#30)。+- 管理端 `admin`:`tsc` 零错误,`npm run build` 出包成功(本就全绿,未改动)。+- 数据库安全(#27):`db_session` 强制 `<库名>_test` 独立测试库并自动建库(本地新增 `printfilm_test` 库),不再对开发库执行 DDL;增量列复用 `main._apply_schema_patches` 权威清单;CI 注入含 `test` 的 DATABASE_URL 即可适配。+- 后端语法/导入:改动模块均可正常 import;死代码符号 grep 零残留。++## 发版后待办(2026-09-14 发版时有意保留,按优先级排序)++1. **部署安全(建议尽快,改动各 1 行)**:`deploy/docker-compose.yml` Postgres/Redis 端口显式绑 `0.0.0.0`,公网主机应改 `127.0.0.1`;`main.py` CORS 在未配 `CORS_ORIGINS` 时回落 `["*"]` 且带凭证,生产默认应收敛。+2. **用户端运行时 HIGH**:EpisodeEditPage 10 分钟 while 轮询无 runToken、空 catch busy 死锁、duplicateFrag 拷贝产物、generateSelected 的 selectedIndex 漂移可能错扣费、useCanvasAutoSave inflight 丢编辑、CanvasPage key={id}、StoryboardPage 批量重配音改 regenAllAudio、EditorPage regen 后轮询。改后需逐页手测。+3. **管理端瑕疵**:OrdersPage `?trade=` 深链 effect 依赖与补拉、ProjectsPage 双 GET、WorksPage 审核确认、TemplatesPage premium 后端过滤、QueuesPage 防抖、client.ts JSON.parse try/catch、删 ArkVolcMediaPanel.tsx;并连同 #22 遗留的 `volc_*` 配置字段/表单一并清除。+4. **基建技术债**:main.py 三个 TIMESTAMP→TIMESTAMPTZ 迁移;on_event→lifespan;c000003 补丁断裂排查;补丁缺索引;oss ensure_browser_cors 启动阻塞;config 死字段、schemas ProgressEvent 死类;requirements 残留 celery==5.5.1 及 9 处引用;scripts/gen_template_covers.py 默认连库回退封面(加 --dry-run/--apply);脚本 engine.dispose;gen_image_style_previews 扩展名错误。+5. **谨慎重构(测试护航)**:pipeline.py(1792 行)拆模块、reconcile N+1、_fail_task 拆分、前端 client/格式化函数去重。++(报告完)diff --git a/frontend/src/pages/drama/AssetsStep.tsx b/frontend/src/pages/drama/AssetsStep.tsxindex e4f1360..76748c3 100644--- a/frontend/src/pages/drama/AssetsStep.tsx+++ b/frontend/src/pages/drama/AssetsStep.tsx@@ -2,7 +2,7 @@import { useEffect, useMemo, useState } from 'react'import { Link } from 'react-router-dom'import { Boxes, Sparkles } from 'lucide-react'-import { dramaApi, resolveDramaAssetPreviewUrl, resolveDramaMediaUrl, type DramaAsset, type DramaProject } from '../../api/drama'+import { dramaApi, resolveDramaAssetPreviewUrl, type DramaAsset, type DramaProject } from '../../api/drama'import { api, type BillingPreflight } from '../../api'import { useDramaImageGenQueue } from '../../hooks/useDramaImageGenQueue'import { enqueueDramaImageGen, resumeDramaImageGensFromAssets } from '../../lib/dramaImageGenQueue'diff --git a/frontend/src/pages/drama/ProjectWorkspacePage.tsx b/frontend/src/pages/drama/ProjectWorkspacePage.tsxindex 15d98de..64225f5 100644--- a/frontend/src/pages/drama/ProjectWorkspacePage.tsx+++ b/frontend/src/pages/drama/ProjectWorkspacePage.tsx@@ -1,12 +1,11 @@/** 漫剧项目工作流:剧情大纲 → 分镜 → 生成视频;资产库为独立入口 */-import { useEffect, useMemo, useRef, useState } from 'react'+import { useEffect, useRef, useState } from 'react'import { useLocation, useNavigate, useParams } from 'react-router-dom'import { Boxes, ChevronLeft } from 'lucide-react'import BillingErrorNotice from '../../components/billing/BillingErrorNotice'import AppShell from '../../components/layout/AppShell'import { dramaApi, type DramaProject } from '../../api/drama'import {- buildProjectSteps,getInitialProjectStep,isEpisodesRouteStep,isProjectStepKey,@@ -53,24 +52,6 @@ function WorkspaceInner() {const [error, setError] = useState('')const locationApplied = useRef(false)- const hasScript = Boolean(project?.script)- const steps = useMemo(() => buildProjectSteps(hasScript), [hasScript])-- // 切到步骤;分镜/生成视频直达首集编辑- async function goToStep(step: ProjectStepKey) {- if (isEpisodesRouteStep(step)) {- try {- const path = await resolveStoryboardPath(id)- navigate(path)- } catch (err) {- setError(err instanceof Error ? err.message : '无法进入分镜')- }- return- }- setAssetsOpen(false)- setActiveStep(step)- }-// 应用路由 state:assets / 分镜类步骤跳转function applyLocationState(state: WorkspaceLocationState | null) {const normalized = normalizeWorkspaceStep(state?.activeStep || state?.returnStep)diff --git a/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx b/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsxindex 9d160c9..0241177 100644--- a/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx+++ b/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx@@ -19,7 +19,6 @@ import { useNavigate, useParams } from 'react-router-dom'import {dramaApi,resolveDramaAssetPreviewUrl,- resolveDramaMediaUrl,type DramaAsset,type DramaEpisode,type DramaFragment,diff --git a/frontend/src/pages/studio/StyleConfigPage.tsx b/frontend/src/pages/studio/StyleConfigPage.tsxindex 3e86469..6bc3875 100644--- a/frontend/src/pages/studio/StyleConfigPage.tsx+++ b/frontend/src/pages/studio/StyleConfigPage.tsx@@ -245,10 +245,11 @@ export default function StyleConfigPage() {}}- if (!project && !error) {+ // project 初始加载失败时不得穿透主页面(下方存在 project.xxx 非空访问,会白屏崩溃)+ if (!project) {return (<AppShell active="studio">- <p className="pf-muted">加载中…</p>+ {error ? <BillingErrorNotice message={error} /> : <p className="pf-muted">加载中…</p>}</AppShell>)}