diff --git a/.dockerignore b/.dockerignore index 5727e31..9ce1ae4 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,3 +9,8 @@ **/*.log **/.inference-key qa +.deploy +.local +.superpowers +outputs +**/.ruff_cache diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..39a11db --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +[*.py] +indent_size = 4 + +[*.md] +trim_trailing_whitespace = false diff --git a/.env.example b/.env.example index bffc6bc..f00f414 100644 --- a/.env.example +++ b/.env.example @@ -18,6 +18,19 @@ MAX_INTERACTIVE_GPU_JOBS=0 MAX_CREATION_COMMANDS_PER_MINUTE=6 MAX_OWNER_JOBS=500 MAX_GLOBAL_JOBS=2000 +# Pending story candidates are durable plans; only admitted leaves consume Job slots. +MAX_OWNER_STORY_CANDIDATES=4000 +MAX_GLOBAL_STORY_CANDIDATES=16000 +# Enable only after validating the identical profile in the inference service. +REFERENCE_GENERATION_ENABLED=false +REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1 +REFERENCE_MAX_IMAGES=3 +# Both business and inference must certify/enable the same video editing profile. +VIDEO_EDIT_ENABLED=false +VIDEO_EDIT_PROFILE=wan-animate-replace-v1 +VIDEO_EDIT_MAX_SECONDS=120 +VIDEO_EDIT_MAX_PEOPLE=12 +VIDEO_EDIT_MAX_PIXELS=399360 MAX_OWNER_RUNS=100 MAX_GLOBAL_RUNS=1000 MAX_OWNER_BATCHES=20 @@ -26,5 +39,11 @@ MAX_OWNER_ASSET_BYTES=107374182400 MAX_DATA_BYTES=2199023255552 MIN_FREE_BYTES=53687091200 TTS_API_KEY= +# Qwen 按需启动:等待 GPU 交接和冷加载使用独立超时,单位秒。 +QWEN_TIMEOUT_SECONDS=1800 +# 配音包含有界排队、CPU冷加载与下载。 +SPEECH_TIMEOUT_SECONDS=330 +SPEECH_TOTAL_TIMEOUT_SECONDS=360 +TTS_QUEUE_TIMEOUT_SECONDS=30 WORKSPACE_HOST=/data/llmusers/llmuser/workspace WEB_PORT=18193 diff --git a/.env.local.example b/.env.local.example new file mode 100644 index 0000000..5f2b412 --- /dev/null +++ b/.env.local.example @@ -0,0 +1,48 @@ +# Windows 本地 Vue + FastAPI;MySQL/模型仍使用既有远端服务。 +# 复制为私有 .env.local 后填写秘密;不要覆盖已有私有配置或提交它。 +# KEY=value 为字面值;单引号保留字面内容,双引号使用 JSON 转义;不展开 $变量。 +CMVR_MODE=production +MYSQL_HOST=192.168.28.10 +MYSQL_PORT=3306 +MYSQL_DATABASE=cmvr-visual +MYSQL_USER= +MYSQL_PASSWORD= +ADMIN_USERNAME=admin +ADMIN_DISPLAY_NAME=管理员 +ADMIN_PASSWORD= +COOKIE_SECURE=false +PUBLIC_ACCESS=false +WORKSPACE_ROOT=E:/workspace/hybrid/cmvr-visual/.local/workspace +# 服务端 API 停止、当前任务/文件迁移核对完成后,才在本机启用协调器。 +RUN_COORDINATOR=false +# 当前开发机经内网HTTP入口直连;入口保留来源IP限制和API Key验证。 +INFERENCE_BASE_URL=http://192.168.28.10:18190 +INFERENCE_REMOTE_FILES=true +# Default off for a new installation; API and inference settings must both enable this profile. +REFERENCE_GENERATION_ENABLED=false +REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1 +REFERENCE_MAX_IMAGES=3 +VIDEO_EDIT_ENABLED=false +VIDEO_EDIT_PROFILE=wan-animate-replace-v1 +VIDEO_EDIT_MAX_SECONDS=120 +VIDEO_EDIT_MAX_PEOPLE=12 +VIDEO_EDIT_MAX_PIXELS=399360 +MAX_OWNER_STORY_CANDIDATES=4000 +MAX_GLOBAL_STORY_CANDIDATES=16000 +INFERENCE_API_KEY_FILE=E:/workspace/hybrid/cmvr-visual/.local/config/inference.key +GPU_STATUS_PATH= +GPU_SCHEDULER_PATH= +# Provider 从远端能力/状态接口同步策略;首次启动前由运维同步有效策略文件。 +RUNTIME_POLICY_FILE=E:/workspace/hybrid/cmvr-visual/.local/workspace/config/runtime-policy.json +QWEN_BASE_URL=http://192.168.28.10:14081/v1 +QWEN_MODEL=Qwen/Qwen3.8-27B-FP8 +QWEN_API_KEY= +# 通过内网HTTP入口连接配音;仍需填写原有TTS_API_KEY。 +TTS_BASE_URL=http://192.168.28.10:18192/v1 +TTS_MODEL=kokoro-82m +TTS_API_KEY= +SPEECH_TIMEOUT_SECONDS=330 +SPEECH_TOTAL_TIMEOUT_SECONDS=360 +NODE_BIN=E:/developmentTool/nodejs/node.exe +FFMPEG_BIN=ffmpeg +FFPROBE_BIN=ffprobe diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..11c85b9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# Keep formatter output stable on Windows and Linux. +* text=auto eol=lf +*.bat text eol=crlf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore index 62e52f6..45541dd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ **/.env **/.env.* !**/.env.example +!/.env.local.example !**/.env.test.example **/.venv/ **/__pycache__/ @@ -18,4 +19,8 @@ /.deploy/ /.cache-models/ /.local/ -/qa/generated/ +/qa/ +/outputs/ +/.superpowers/ +**/.ruff_cache/ +.idea/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e0e151b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,11 @@ +# 协作约定 + +- 用户要求:仅修改和验证工作区;没有用户明确指令,不得自动暂存,也不得执行 Git commit、push、amend、reset 或 revert。已有本地提交先保留。 +- 保留工作区已有未提交改动,不把结构重构当成重置文件或覆盖其他功能的理由。 +- 前端和业务后端独立运行;推理服务和共享 Qwen 是外部依赖。普通代码整理不得启动真实模型、停止共享服务或改变 GPU 优先策略。 +- 结构调整须保持 HTTP/SSE 合同、路由、用户隔离、幂等键、Pinia ID、本地存储键、数据库表及历史迁移兼容。 +- 关键注释优先使用中文,解释事务、并发、权限、恢复和数据保护的原因;避免逐行翻译代码。 +- 验证完成后说明修改与检查结果,将代码留在工作区供用户检查。 +- 测试通过后,立即清理本次生成的临时脚本、截图、测试媒体、日志、隔离数据库、打包文件及代理过程记录,不把验收产物长期留在项目中。 +- 可重复使用的自动化测试代码和必要的最小夹具属于项目质量保障,应保留;一次性验证脚本与测试生成文件在通过后删除。测试优先使用自动清理的临时目录及隔离数据,避免往真实素材库造测试数据。 +- 清理只针对已确认的临时内容;保留业务素材、用户要求的成片及音频字幕、运行依赖、私有配置、数据库备份和历史迁移。业务交付文件统一放在 outputs/,长期设计说明放在 docs/design/。 diff --git a/README.md b/README.md index 9e3191b..fc51b5e 100644 --- a/README.md +++ b/README.md @@ -5,24 +5,29 @@ ## 当前交付状态 - 工程目录:`E:\workspace\hybrid\cmvr-visual`;服务器源码目录:`/workspace/projects/cmvr-visual`。 -- 已连接用户指定的正式数据库 `192.168.28.10:3306/cmvr-visual`,按要求暂用 root;V2 使用17张 `visual_*` 表及 Alembic 版本表,当前 schema 为003。生产启动只校验,不自动改表。 -- 默认管理员为 `admin`,初始密码保持用户指定的私有配置;重启不重置已有密码。账号页已支持本人改密、管理员维护用户,以及创建/撤销仅展示一次的机器令牌。普通新密码要求12位以上。 -- 本机私有 `.env.server` 保存当前服务器配置,`.env.preview` 仅保留旧验收库配置。原独立 MySQL 与样例数据没有自动迁入正式库;秘密不提交Git、不打印到日志、不复制进文档。`.env.example` 不含可用密码。 -- 网站仅发布服务器 `127.0.0.1:18193`,当前通过受信 SSH 隧道本地访问;不直接向局域网或互联网公开。 +- 已连接用户指定的 MySQL `192.168.28.10:3306/cmvr-visual`;使用 `visual_*` 表及 Alembic 版本表,当前 schema 为007(2026-11-13完成迁移)。启动只校验结构,不自动改表;数据库账号由私有配置提供。 +- 可编辑自动成片支持一次自动生成、局部重生成、旁白/字幕编辑和从运行恢复版本。2026-11-13经用户授权,已联合备份、演练恢复并升级实际业务库,重启本机业务API和前端;原有23张表6749条记录及原有字段数据比对一致,新编辑接口鉴权读取通过。真实模型质量和产能仍需单独验收。 +- 默认管理员为 `admin`,初始密码保持用户指定的私有配置;重启不重置已有密码。头像菜单支持本人修改登录用户名和密码;账户页仅供管理员新增、启停或删除用户。新增用户初始密码允许6–256字符,主动修改密码要求12位以上。 +- 本机私有 `.env.local` 保存本地真实服务配置,`.env.server` 保存服务器配置,`.env.preview` 仅保留旧验收库配置。原独立 MySQL 与样例数据没有自动迁入正式库;秘密不提交Git、不打印到日志、不复制进文档。`.env.example` 不含可用密码。 +- 当前开发采用本机 Vue `127.0.0.1:5173` + FastAPI `127.0.0.1:8000`,MySQL 和模型推理保留在远端;服务器网站前后端在本地接管后停止,后续正式发布再启用。 + +素材、任务和故事支持数据库逻辑文件夹;创建故事可自动建立同名文件夹,创作时可指定成果位置。素材支持多目录复用、批量整理、删除及发布到共享库。 + +入口 `/studio` 为跨镜头锚定故事工作室:统一风格/环境、角色形态和造型、`@`实体绑定、首帧候选确认、视频选片及冻结合成。当前多镜头创作统一从“故事”进入,可选择可编辑自动成片或人工候选确认,在故事内“03 成片”调整时间线并合成。独立“工作流”“批量”“成片”页面已移除;旧链接会转至故事或任务,既有草稿、批次、运行、素材和共享后端API仍保留。使用说明见[锚定工作室操作手册](docs/锚定工作室操作手册_20261111.md)。故事、候选、批准及运行元数据保存在MySQL,素材文件保存在工作空间。 + +创作页新增 `/create/image-edit` 与 `/create/video-edit`:按顺序绑定最多三张参考图生成图片;分析源视频,选择一个或多个人物并分别绑定身份图生成替换视频。后者使用独立 Wan2.2-Animate-14B 时序模型,复用现有任务、私有素材和 GPU 优先队列,无新增业务表。开放状态以实际能力和模型验收为准;步骤和部署配置见[图生图与视频人物替换操作手册](docs/图生图与视频人物替换操作手册_20261112.md)。 执行结果以实际验收记录及接口状态为准。单元测试、模拟上游边界和构建成功分别验证各自范围,不等同于真实模型生成或正式数据库验收。 -本轮交付见 [V2开发与验收记录](docs/V2开发与验收记录_20261110.md):默认规格真实三镜头成片、窗口/队列、迁移恢复及当前公开发布边界均有单独记录。 +历史兼容:2026-11-11扩展的可变多镜头工作流保留数据与API合同,原独立编辑页不再提供。旧版支持增删/排序、每镜头选用1–15秒、动态音轨字幕范围、JSON导入导出及鲲鹏示例。总时长由镜头选用帧数之和决定,旧三镜头草稿与成片继续兼容;单模型原生视频支持1–15秒参数,默认5秒,实际耗时和资源随帧数增加。 -历史功能基线见 [验收报告](docs/验收报告.md):75项自动化测试、八类真实服务调用及桌面/手机验证。正式库接入后新增初始账号回归,后端52项通过;[实际接入记录](qa/mysql-integration-20261110.json)验证正式库登录、读写与SSE。 +当前使用说明见[操作手册](docs/操作手册_20261111.md):第0节说明六项能力入口,第4节说明故事自动与人工创作,第7节说明故事内的批量执行模式与日夜节拍,第12节说明可编辑自动成片。故事页可打开在线帮助,网页主手册为 `/help/manual.html`。02分镜内容超出工作区时仅在对应容器内滚动;滚动条悬停或键盘操作时显示,移出后隐藏,触屏可直接滑动。[鲲鹏长视频制作指南](docs/鲲鹏长视频制作指南_20261111.md)中的旧JSON与实测记录保留作历史参考,`frontend/public/examples/kunpeng-storyboard.json`不提供当前故事页直接导入。 -2026-11-11扩展为可变多镜头工作流:增删/排序、每镜头选用1–5秒、动态音轨字幕范围、JSON导入导出及20镜头100秒鲲鹏示例。总时长由镜头选用帧数之和决定,旧三镜头草稿与成片继续兼容;单模型原生视频任务仍约5秒。 +现有“审核”为本人确认首帧和视频选片;生产节拍统计、严格夜间范围和可选多人审批的缺口及实施路径见[生产流程完善方案](docs/design/2026-11-12-production-workflow-design.md),网页版本为 `/help/production.html`。该方案明确区分已实现功能与待实施内容,不代表新增功能已上线。 -使用说明见[操作手册](docs/操作手册_20261111.md)和[鲲鹏长视频制作指南](docs/鲲鹏长视频制作指南_20261111.md),网站工作流页也提供两份在线帮助。模板位于`frontend/public/examples/kunpeng-storyboard.json`,载入后不会自动生成或保存。 +手册更新后可运行`python scripts/render_manuals.py`生成HTML,再构建前端发布;45秒配音版模板同目录另有`kunpeng-storyboard-45s.json`。 -本轮部署与真实验证见[2026-11-11开发与验收记录](docs/开发与验收记录_20261111.md)。手册更新后可运行`python scripts/render_manuals.py`生成HTML,再构建前端发布;45秒配音版模板同目录另有`kunpeng-storyboard-45s.json`。 - -另有[单镜头超过5秒实测](docs/单镜头超过5秒实测报告_20261111.md):既有环境成功生成241帧、24fps、约10秒的原片和增强版;当前网页仍保留5秒上限,尚未正式开放10秒参数。 +业务交付的成片、配音、配乐和字幕保存在 `outputs/`;素材库运行数据仍在 `.local/workspace`。测试通过后清理临时验收文件,保留可复用的自动化测试与最小夹具,详见[协作约定](AGENTS.md)。 批量时段由API与GPU worker共读的`/workspace/projects/llm-services/config/runtime-policy.json`决定。`batch_window_enabled=false`为开发全天模式,`true`恢复北京时间21:00–08:00准入;开启时08:00关闭新镜头/新处理阶段准入,当前阶段自然完成,后续排队。文件热读取,样例见`deploy/runtime-policy.development.json`与`deploy/runtime-policy.production.json`。文件缺失默认启用限制,格式错误关闭新batch准入。`workflow_max_shots`默认120,可配置1–1000,只限制新草稿/运行/编排的准入。 @@ -30,12 +35,14 @@ Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源 初始额度:每用户未结束叶任务500、全局2000;每用户未结束Run100、Batch20,全局Run1000、Batch200;每批最多100项。创建Job/Run/Batch共用每用户每分钟6次命令额度,内部子步骤不重复扣命令数,原键重放不扣额。所有数字可通过配置调整。 -## 八项能力与实际限制 +## 模型与媒体能力 | 任务类型 | 后端 | 实际能力与边界 | | --- | --- | --- | | `image.generate` | 既有 Qwen-Image GPU 队列 | 文本生成图片;默认 1024²、50 步。不提供图像编辑或 LoRA 管理。 | -| `video.generate` | 既有 Wan2.2-TI2V-5B,可接 Real-ESRGAN | 文生视频或参考首帧;最多 121 帧、24 fps,约 **5 秒**,可选 1080p 增强。不是 15 秒生成,也不附带声音。 | +| `image.reference.generate` | Qwen-Image-Edit-2511 / vLLM-Omni | 创作图生图及故事首帧真实多图参考,普通profile最多3张有序去重图片,支持方/横/竖;两端能力开关一致才开放,不默降文字生成。 | +| `video.people.analyze` / `video.replace` | 独立 Wan2.2-Animate-14B / Diffusers,YOLO、ViTPose、SAM2 | 选择多人并分别绑定身份参考图,时序替换后合成同一成片,可保留原音轨;默认120秒、12人和约480p预算,可配置,须双端认证开放。 | +| `video.generate` | 既有 Wan2.2-TI2V-5B,可接 Real-ESRGAN | 文生视频或参考首帧;1–15秒、24 fps,最大361帧,默认5秒/121帧,可选1080p增强;视频本身不附带声音。 | | `defect.generate` | SDXL + Canny ControlNet | 根据参考图片边缘约束生成条件样本,输出合成图和控制图;**控制图不是缺陷真值 mask**。 | | `audio.transcribe` | 既有 Whisper large-v3-turbo | 音频或有声视频转写;视频先在 CPU 提取音轨,最长 1800 秒。时间戳是约 30 秒分块边界,不是逐词对齐。 | | `math.solve` | 既有 Qwen 文本 HTTP 服务 | 数学解答文本;没有形式化证明或专业正确率验收承诺。 | @@ -43,7 +50,7 @@ Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源 | `video.compose` | CPU FFmpeg | 片段排序、裁切、直切拼接、单音轨和人工字幕;片段数量由配置控制,总时长由片段决定,帧率24/25/30/60。保留磁盘、输出大小、源媒体和超时预算。 | | `audio.speech` | 独立 Kokoro-82M **CPU** 服务 | 中文配音 WAV,当前音色 `zf_xiaobei`、`zm_yunxi`;语速 0.5–2。仅在配置真实服务后启用,不提供音乐生成。 | -参数约束以登录后的 `/api/capabilities` 为准。生成步数字段为 `num_inference_steps`。只有图片和条件样本支持 `count=1..4`,批次拆成独立任务,种子按序递增。没有真实生成进度来源时 `progress=null`,界面不编造百分比。 +参数约束以登录后的 `/api/capabilities` 及 `/api/stories/capabilities` 为准。生成步数字段为 `num_inference_steps`。普通任务接口的图片和条件样本支持 `count=1..4`,故事候选另支持每镜头1–4个首帧或视频候选,均拆成独立任务,种子按序递增。没有真实生成进度来源时 `progress=null`,界面不编造百分比。 ## 项目分层与通信 @@ -58,7 +65,9 @@ Nginx → FastAPI 业务 API → MySQL visual_* 表 └─ CPU FFmpeg / 独立 CPU Kokoro ``` -`frontend/` 为界面;`backend/app/` 为账号、素材、任务、工作流和协调器;`backend/alembic/` 为迁移;`inference/` 保存既有唯一GPU服务的版本化源码;`tts/` 为CPU配音;`deploy/`、`compose.yaml` 为部署文件。[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。 +`frontend/` 和 `backend/` 是独立工程。前端按 `api/types/domain/services/stores/views/components/styles` 分工;后端按 `api/schemas/core/models/domain/services/adapters` 分层,`app.main:app` 保持稳定入口。模型适配器已按协议、远端文件、GPU、Qwen、语音和成片拆分,媒体处理不再反向依赖整个Provider。 + +`backend/alembic/` 为迁移;`inference/` 保存既有GPU队列服务的版本化源码;`tts/` 为CPU配音;`deploy/`、`compose.yaml` 为部署文件。目录、依赖方向、注释约定和检查命令见[工程结构与开发约定](docs/工程结构与开发约定.md)。[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。用户未明确要求时不创建Git提交或推送,详见[协作约定](AGENTS.md)。 任务提交是短 HTTP 请求,长任务通过 SSE 单向通知浏览器,不需要双向 WebSocket。事件先和数据库状态一起提交;`Last-Event-ID` 用于重连重放,Cookie 使原生 EventSource 无需把令牌放进 URL。SSE 断开不会取消生成,重连后还会重新获取 HTTP 状态快照。[SSE 标准](https://html.spec.whatwg.org/multipage/server-sent-events.html) @@ -81,11 +90,48 @@ Nginx → FastAPI 业务 API → MySQL visual_* 表 | 模型 API | Docker 网络内 `http://llmuser-workspace:18190` | | 模型认证文件 | `/workspace/projects/llm-services/config/api_key`,仅后端读取 | -用户只提交素材 ID;服务器校验 owner 后解析共享工作区路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。被任务引用的已删除输入仍保留物理文件。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。 +用户只提交素材 ID;业务后端校验 owner 后解析素材路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。素材仍被任务或工作流使用时拒绝删除;允许删除后同步移除原文件、缩略图和数据库文件记录。共享发布和引用者的私有副本各自独立,删除其中一份不会删除其他副本。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。 API 和 TTS 容器不挂GPU、宿主`/proc`或Docker socket,根文件系统只读;API仅挂本应用数据、只读模型认证和调度状态目录。模型权重不随网站镜像打包。`inference/` 的更新部署到既有模型服务路径,保留原队列和监管,不启动第二个GPU worker,不修改共享Qwen容器。 -## 本地开发 +## Windows 本地开发:连接真实 MySQL 与远端模型 + +当前使用 `E:\workspace\hybrid\cmvr-visual`。前端和业务 API 在 Windows 本机运行;MySQL 继续使用既有 `192.168.28.10:3306/cmvr-visual`,模型继续使用既有服务器推理队列,不能同时运行两个连接正式库的业务协调器。服务器网站 API 停止并完成文件/任务迁移核对后,才把本地私有配置中的 `RUN_COORDINATOR` 改成 `true`。正式模式只校验既有表结构,不自动建库、改表或回退 SQLite。 + +准备本机 Python 3.11+、Node/pnpm,以及 `ffmpeg`/`ffprobe`。已有虚拟环境、依赖和 `.env.local` 时跳过相应步骤,避免覆盖私有配置: + +```powershell +Set-Location E:\workspace\hybrid\cmvr-visual +python -m venv backend/.venv +& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements-dev.txt +& E:/developmentTool/nodejs/pnpm.cmd --dir frontend install --frozen-lockfile +Copy-Item .env.local.example .env.local +# 用本机编辑器填写 .env.local;数据库、账号和模型密钥不要写进命令行历史。 +``` + +`.env.local.example` 仅提供配置项,无有效密码。把既有获准的 MySQL/管理员配置放进被 Git 忽略的 `.env.local`,模型密钥保存在 `.local/config/inference.key`;不要把后端秘密放入 `VITE_*`。启动器只加载 `.env.local`,其内容覆盖当前终端同名环境变量;不执行脚本、不展开变量。单引号是字面值,双引号按 JSON 转义;Windows 路径建议使用 `/`。`NODE_BIN` 可以指定 `node.exe`,也支持 PATH 或本机 `E:/developmentTool/nodejs/node.exe`;缺失依赖会明确报错,不会自动安装。 + +当前开发机直接通过内网 HTTP 连接模型 `http://192.168.28.10:18190` 和配音 `http://192.168.28.10:18192/v1`,无需建立模型 SSH 隧道。服务器独立入口限定开发机来源 IP 并保留 API Key 鉴权,配置见 [model-gateway](deploy/model-gateway/README.md)。本地设置 `INFERENCE_REMOTE_FILES=true`,通过认证 HTTP 上传模型输入和下载产物;Windows 本地路径不交给远端模型作为服务器文件路径。`WORKSPACE_ROOT` 使用本机 `.local/workspace`;接管前须同步正式库中既有素材和任务文件。`RUNTIME_POLICY_FILE` 指向已同步的本地策略文件,Provider 从远端能力/状态同步有效策略,保持 API 与推理队列规则一致。 + +在项目根目录执行: + +```powershell +& ./backend/.venv/Scripts/python.exe scripts/local_dev.py start +& ./backend/.venv/Scripts/python.exe scripts/local_dev.py status +& ./backend/.venv/Scripts/python.exe scripts/local_dev.py stop +``` + +访问 `http://127.0.0.1:5173`;Vite 将 `/api` 同源代理到 `127.0.0.1:8000`。启动器在后台隐藏启动单进程 uvicorn 和 Vite,等待实际 HTTP 状态并确认子进程仍存活。`api: ready` 表示本地数据库、协调器和准入检查通过;`upstream_protocol=unavailable` 会单独提示模型连接退化,此时网站可打开,应检查内网 HTTP 入口和上游服务。GPU 忙碌本身不算连接故障。`status` 任一本机服务未就绪时返回非零退出码;完整模型协议状态以 API `/api/ready` 为准。 + +日志位于 `.local/logs/api.log` 和 `.local/logs/frontend.log`,进程记录位于 `.local/dev-processes.json`。端口已被占用时启动失败,请先识别占用者;启动器不会抢占或停止无关进程。`stop` 使用 PID、Windows 创建时间和可执行文件身份核对,只停止本次启动器记录的本机进程;API 先执行正常关闭,超过20秒会保留进程和记录供排查。它不会停止 SSH、MySQL、远端模型或服务器网站。既有上游任务不会因停止本机网页而自动取消。 + +启动器测试不连接正式 MySQL 或真实模型;API 正常关闭测试使用自动清理的临时 SQLite: + +```powershell +& ./backend/.venv/Scripts/python.exe -m unittest discover -s scripts/tests -v +``` + +## 可选 SQLite 开发预览 需要 Python 3.11+、Node/pnpm;媒体探测和合成需 `ffmpeg`、`ffprobe` 在 PATH。本地 SQLite 仅是显式开发预览,不是 MySQL 故障后的自动回退。 @@ -93,7 +139,7 @@ PowerShell,在项目根目录执行: ```powershell python -m venv backend/.venv -& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements.txt +& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements-dev.txt New-Item -ItemType Directory -Force .local/workspace | Out-Null $env:CMVR_MODE = 'preview' $env:WORKSPACE_ROOT = (Resolve-Path .local/workspace).Path @@ -117,16 +163,19 @@ pnpm dev 访问 `http://127.0.0.1:5173`。Vite 将 `/api` 同源代理到 `127.0.0.1:8000`。开发进程不会自动加载 `.env`;须显式设置环境或使用受控的环境文件加载方式。首次启动仅在账号不存在时创建管理员,重复启动不会用环境变量重置已有密码。无默认密码、无公开注册。 -上例主动禁用 GPU 入口:Windows 本地文件路径不能作为远端模型的 `/workspace` 路径。真实生成使用下述同机 Docker 部署。数学/视觉、FFmpeg、配音是否可用取决于实际服务和本地程序配置;不会在缺失时生成假结果。 +上例主动禁用 GPU 入口;它只用于独立 SQLite 预览。需要真实生成时使用上文的本机业务服务 + 远端文件传输配置,或下述正式同机 Docker 部署。数学/视觉、FFmpeg、配音是否可用取决于实际服务和本地程序配置;不会在缺失时生成假结果。 测试与前端构建: ```powershell cd backend & ./.venv/Scripts/python.exe -m pytest -q +& ./.venv/Scripts/python.exe -m ruff check app tests alembic/env.py +& ./.venv/Scripts/python.exe -m ruff format --check app tests alembic/env.py cd ../frontend pnpm test pnpm build +pnpm format:check ``` 缺少 FFmpeg 时相关媒体集成测试会跳过,Linux 的实际媒体测试应单独执行。不要据 SQLite 测试推断正式 MySQL 已连接。 @@ -137,7 +186,7 @@ pnpm build 私有 `.env` 至少配置 `CMVR_MODE=production`、`MYSQL_HOST`、`MYSQL_PORT`、`MYSQL_DATABASE`、`MYSQL_USER`、`MYSQL_PASSWORD` 及管理员初始化信息。推荐这些分离字段,后端用 `URL.create` 处理数据库名与密码特殊字符;不要手工拼接连接串。正式库不可达时启动失败,不会切换 SQLite。 -现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold。生产启动要求003,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行: +现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold,004增加私有内容及共享素材支持。当前生产启动要求004,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行: ```bash # 仅匹配的、尚未版本化的旧六表数据库执行一次: @@ -147,7 +196,9 @@ alembic -c alembic.ini upgrade head 空库直接`upgrade head`。已有003库无需stamp。迁移不提供破坏性downgrade;MySQL DDL可能已提交,失败时保持维护并使用已演练的联合恢复点或修复迁移。 -## Docker Compose 启动 +## Docker Compose 正式部署(后续启用) + +本节保留正式发布步骤。当前 Windows 本地开发不执行这些命令;服务器网站前后端保持停止,模型服务继续运行。 运维在宿主源码目录 `/data/llmusers/llmuser/workspace/projects/cmvr-visual` 操作。先将前端构建为 `frontend/dist`,因为前端镜像直接复制该目录: @@ -199,13 +250,13 @@ docker compose logs --tail=100 api ## 访问方式与对外安全边界 -当前宿主只监听 `127.0.0.1:18193`。从客户端建立隧道: +后续恢复服务器网站部署时,宿主网站只监听 `127.0.0.1:18193`。从客户端建立网站隧道: ```bash ssh -N -L 127.0.0.1:18193:127.0.0.1:18193 root@192.168.28.10 ``` -使用已有获准的运维 SSH 账号;`root` 仅是当前运维连接示例,命令没有内嵌密码。受限 `llmuser` 的 SSH 转发已禁用,不要为了网站访问放开其隔离规则。上述命令后访问 `http://127.0.0.1:18193`;当前已建立的隧道入口为 `http://127.0.0.1:8000`。默认管理员配置由本机私有 `.env.server` 安全取得,不在控制台回显。 +使用已有获准的运维 SSH 账号;`root` 仅是当前运维连接示例,命令没有内嵌密码。受限 `llmuser` 的 SSH 转发已禁用,不要为了网站访问放开其隔离规则。上述命令后访问 `http://127.0.0.1:18193`;Windows 本地开发的 `8000` 端口由本机 API 使用,不应再把服务器网站隧道绑定到该端口。默认管理员配置由本机私有 `.env.server` 安全取得,不在控制台回显。 当前回环 HTTP/SSH 验收使用 `COOKIE_SECURE=false`。互联网或不可信网络访问必须先配置 HTTPS 反代或受信加密隧道,并在 HTTPS 浏览器入口使用 `COOKIE_SECURE=true`。保持前后端同源;Cookie 为 HttpOnly/SameSite,CSRF 校验不得移除,推理密钥不得进入前端变量或 URL。 @@ -247,3 +298,5 @@ docker compose up -d api 每张符合条件的空闲GPU同时运行一个任务,最多四卡并行。就绪任务按持久入队顺序派发,完成顺序可不同;独立分镜和批次成员有界补队,合成等待全部选定输出。外部用户占用某张卡时,只让出该卡并重排对应任务。 工作容器内存上限为384 GiB(内存加swap总上限同为384 GiB);派发同时检查主存和共享内存预算。单卡68 GiB分配预算、8 GiB空闲预留和连续空闲15秒准入保持有效。管理员设置放在推理服务config/settings.json;修改runtime-policy.json仍只控制其已支持的时段/工作流字段。 + +2026-11-13按用户要求,共享 `Qwen/Qwen3.8-27B-FP8` 恢复常驻 GPU0,调用地址仍为 `http://192.168.28.10:14081/v1`。GPU0 持续预约给共享模型,媒体任务使用其余符合准入条件的 GPU1–3;停止了调用结束自动卸载模型的网关。运行方式及切换记录见 [Qwen运行说明](docs/Qwen按需运行_20261112.md)。 diff --git a/backend/.env.example b/backend/.env.example index 4e44ebb..38b74dc 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -23,5 +23,15 @@ QWEN_API_KEY= TTS_BASE_URL= TTS_MODEL= TTS_API_KEY= +SPEECH_TIMEOUT_SECONDS=330 +SPEECH_TOTAL_TIMEOUT_SECONDS=360 FFMPEG_BIN=ffmpeg FFPROBE_BIN=ffprobe +REFERENCE_GENERATION_ENABLED=false +REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1 +REFERENCE_MAX_IMAGES=3 +VIDEO_EDIT_ENABLED=false +VIDEO_EDIT_PROFILE=wan-animate-replace-v1 +VIDEO_EDIT_MAX_SECONDS=120 +VIDEO_EDIT_MAX_PEOPLE=12 +VIDEO_EDIT_MAX_PIXELS=399360 diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 34fe56b..b5d810c 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -1,26 +1,44 @@ -import asyncio,os +import asyncio from alembic import context from sqlalchemy.ext.asyncio import create_async_engine from app.models import Base -from app import v2_models -from app.config import Settings -config=context.config -target_metadata=Base.metadata +from app.core.config import Settings + +config = context.config +target_metadata = Base.metadata + + +def include_object(obj, name, type_, reflected, compare_to): + return name.startswith("visual_") if type_ == "table" else True -def include_object(obj,name,type_,reflected,compare_to): - return name.startswith("visual_") if type_=="table" else True def run(connection): - context.configure(connection=connection,target_metadata=target_metadata,include_object=include_object,compare_type=True) - with context.begin_transaction():context.run_migrations() + context.configure( + connection=connection, + target_metadata=target_metadata, + include_object=include_object, + compare_type=True, + ) + with context.begin_transaction(): + context.run_migrations() + async def online(): - url=config.attributes.get("url") or Settings.from_env().sqlalchemy_url - engine=create_async_engine(url) - async with engine.connect() as connection:await connection.run_sync(run) + url = config.attributes.get("url") or Settings.from_env().sqlalchemy_url + engine = create_async_engine(url) + async with engine.connect() as connection: + await connection.run_sync(run) await engine.dispose() + if context.is_offline_mode(): - context.configure(url=config.get_main_option("sqlalchemy.url"),target_metadata=target_metadata,literal_binds=True,include_object=include_object) - with context.begin_transaction():context.run_migrations() -else:asyncio.run(online()) + context.configure( + url=config.get_main_option("sqlalchemy.url"), + target_metadata=target_metadata, + literal_binds=True, + include_object=include_object, + ) + with context.begin_transaction(): + context.run_migrations() +else: + asyncio.run(online()) diff --git a/backend/alembic/versions/005_story_studio.py b/backend/alembic/versions/005_story_studio.py new file mode 100644 index 0000000..ab1dbeb --- /dev/null +++ b/backend/alembic/versions/005_story_studio.py @@ -0,0 +1,63 @@ +"""Append-only story selections and durable candidate plans; no legacy table changes.""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects.mysql import DATETIME + +revision = "005" +down_revision = "004" +branch_labels = None +depends_on = None + + +def referenced_type(bind, name): + column = next(c["type"].copy() for c in sa.inspect(bind).get_columns(name) if c["name"] == "id") + if bind.dialect.name == "mysql": + charset, collation = bind.execute(sa.text("SELECT CHARACTER_SET_NAME,COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:name AND COLUMN_NAME='id'"), {"name": name}).one() + column.charset, column.collation = charset, collation + return column + + +def upgrade(): + bind = op.get_bind() + timestamp = sa.DateTime().with_variant(DATETIME(fsp=6), "mysql") + metadata = sa.MetaData() + uid, did = referenced_type(bind, "visual_users"), referenced_type(bind, "visual_drafts") + sa.Table("visual_users", metadata, sa.Column("id", uid.copy(), primary_key=True)) + sa.Table("visual_drafts", metadata, sa.Column("id", did.copy(), primary_key=True)) + common = lambda: [ + sa.Column("id", sa.String(32), primary_key=True), + sa.Column("owner_id", uid.copy(), sa.ForeignKey("visual_users.id"), nullable=False, index=True), + sa.Column("draft_id", did.copy(), sa.ForeignKey("visual_drafts.id"), nullable=False, index=True), + sa.Column("shot_id", sa.String(32), nullable=False, index=True), + sa.Column("kind", sa.String(16), nullable=False), + sa.Column("context_hash", sa.String(64), nullable=False), + sa.Column("version", sa.Integer(), nullable=False), + sa.Column("created_at", timestamp, nullable=False), + ] + candidate = sa.Table("visual_shot_candidates", metadata, *common(), + sa.Column("source_kind", sa.String(16), nullable=False), + sa.Column("job_id", sa.String(32), nullable=True, index=True), + sa.Column("asset_id", sa.String(32), nullable=True), + sa.Column("asset_sha256", sa.String(64), nullable=True), + sa.Column("generation_hash", sa.String(64), nullable=False), + sa.Column("created_revision", sa.Integer(), nullable=False), + sa.Column("state", sa.String(32), nullable=False), + sa.Column("plan_json", sa.JSON(), nullable=False), + sa.Column("error_json", sa.JSON(), nullable=True), + sa.Column("batch_id", sa.String(32), nullable=True, index=True), + sa.Column("deleted_at", timestamp, nullable=True)) + selection = sa.Table("visual_shot_selections", metadata, *common(), + sa.Column("candidate_id", sa.String(32), nullable=True), + sa.Column("asset_id", sa.String(32), nullable=True), + sa.Column("decision_json", sa.JSON(), nullable=False), + sa.UniqueConstraint("draft_id", "shot_id", "kind", "version")) + for table in (candidate, selection): + table.create(bind, checkfirst=True) + existing = {i["name"] for i in sa.inspect(bind).get_indexes(table.name)} + for index in table.indexes: + if index.name not in existing: + index.create(bind, checkfirst=True) + + +def downgrade(): + raise RuntimeError("Destructive downgrade unsupported; restore a verified joint checkpoint") diff --git a/backend/alembic/versions/006_logical_folders.py b/backend/alembic/versions/006_logical_folders.py new file mode 100644 index 0000000..374ed26 --- /dev/null +++ b/backend/alembic/versions/006_logical_folders.py @@ -0,0 +1,67 @@ +"""Database-only logical folders; existing business rows and paths stay intact.""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects.mysql import DATETIME + +revision = '006' +down_revision = '005' +branch_labels = None +depends_on = None + + +def referenced_type(bind, name): + column = next(c['type'].copy() for c in sa.inspect(bind).get_columns(name) if c['name'] == 'id') + if bind.dialect.name == 'mysql': + charset, collation = bind.execute(sa.text("SELECT CHARACTER_SET_NAME,COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:name AND COLUMN_NAME='id'"), {'name': name}).one() + column.charset, column.collation = charset, collation + return column + + +def upgrade(): + bind = op.get_bind() + uid = referenced_type(bind, 'visual_users') + aid = referenced_type(bind, 'visual_assets') + # 新目录 ID 继承用户 ID 的字符集/排序规则;所有引用使用反射类型。 + fid = uid.copy() + timestamp = sa.DateTime().with_variant(DATETIME(fsp=6), 'mysql') + metadata = sa.MetaData() + sa.Table('visual_users', metadata, sa.Column('id', uid.copy(), primary_key=True)) + sa.Table('visual_assets', metadata, sa.Column('id', aid.copy(), primary_key=True)) + folders = sa.Table('visual_folders', metadata, + sa.Column('id', fid.copy(), primary_key=True), + sa.Column('owner_id', uid.copy(), sa.ForeignKey('visual_users.id'), nullable=False, index=True), + sa.Column('name', sa.String(255), nullable=False), + sa.Column('parent_id', fid.copy(), sa.ForeignKey('visual_folders.id', ondelete='CASCADE'), nullable=True, index=True), + sa.Column('parent_key', sa.String(32), nullable=False, server_default=''), + sa.Column('created_at', timestamp, nullable=False), + sa.Column('updated_at', timestamp, nullable=False), + sa.UniqueConstraint('owner_id', 'parent_key', 'name', name='uq_visual_folders_sibling')) + links = sa.Table('visual_asset_folders', metadata, + sa.Column('asset_id', aid.copy(), sa.ForeignKey('visual_assets.id', ondelete='CASCADE'), primary_key=True), + sa.Column('folder_id', fid.copy(), sa.ForeignKey('visual_folders.id', ondelete='CASCADE'), primary_key=True, index=True)) + for table in (folders, links): + table.create(bind, checkfirst=True) + existing = {i['name'] for i in sa.inspect(bind).get_indexes(table.name)} + for index in table.indexes: + if index.name not in existing: + index.create(bind, checkfirst=True) + # SQLite 用 batch 新增外键;MySQL 保留原表与历史数据,使用原生 ALTER。 + for table_name in ('visual_jobs', 'visual_drafts', 'visual_workflow_runs'): + fields = ['folder_id'] + ([] if table_name == 'visual_drafts' else ['output_folder_id']) + inspector = sa.inspect(bind) + columns = {c['name'] for c in inspector.get_columns(table_name)} + fks = {tuple(f['constrained_columns']) for f in inspector.get_foreign_keys(table_name)} + indexes = {i['name'] for i in inspector.get_indexes(table_name)} + with op.batch_alter_table(table_name) as batch: + for field in fields: + if field not in columns: + batch.add_column(sa.Column(field, fid.copy(), nullable=True)) + if (field,) not in fks: + batch.create_foreign_key(f'fk_{table_name}_{field}', 'visual_folders', [field], ['id'], ondelete='SET NULL') + index = f'ix_{table_name}_{field}' + if index not in indexes: + batch.create_index(index, [field]) + + +def downgrade(): + raise RuntimeError('Destructive downgrade unsupported; restore a verified joint checkpoint') diff --git a/backend/alembic/versions/007_editable_automation.py b/backend/alembic/versions/007_editable_automation.py new file mode 100644 index 0000000..75b2ee5 --- /dev/null +++ b/backend/alembic/versions/007_editable_automation.py @@ -0,0 +1,32 @@ +"""可恢复自动成片;仅追加字段,历史运行保留 legacy 语义。""" +from alembic import op +import sqlalchemy as sa +revision = '007' +down_revision = '006' +branch_labels = None +depends_on = None + + +def upgrade(): + columns = { + 'visual_drafts': [sa.Column('editor_manifest', sa.JSON(), nullable=True)], + 'visual_workflow_runs': [ + sa.Column('run_kind', sa.String(32), nullable=False, server_default='legacy'), + sa.Column('output_goal', sa.String(16), nullable=False, server_default='film'), + sa.Column('base_run_id', sa.String(32), nullable=True), + sa.Column('source_draft_version', sa.Integer(), nullable=True), + sa.Column('plan_snapshot', sa.JSON(), nullable=True), + sa.Column('result_manifest', sa.JSON(), nullable=True), + sa.Column('apply_state', sa.String(16), nullable=True)], + 'visual_workflow_steps': [sa.Column(name, sa.JSON(), nullable=True) for name in ('recipe_json','resolved_input_json','result_json')], + } + bind = op.get_bind() + for table, fields in columns.items(): + existing = {c['name'] for c in sa.inspect(bind).get_columns(table)} + for field in fields: + if field.name not in existing: + op.add_column(table, field) + + +def downgrade(): + raise RuntimeError('Destructive downgrade unsupported; restore a verified joint checkpoint') diff --git a/backend/app/adapters/__init__.py b/backend/app/adapters/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/adapters/media.py b/backend/app/adapters/media.py new file mode 100644 index 0000000..7801669 --- /dev/null +++ b/backend/app/adapters/media.py @@ -0,0 +1,681 @@ +"""Bounded CPU media operations. No shell, CUDA, external URLs or user filters.""" + +from __future__ import annotations + +import asyncio +import json +import math +import os +from pathlib import Path +import uuid + +from PIL import Image, ImageOps, UnidentifiedImageError + + +from app.domain.errors import MediaError +from app.domain.execution import CpuResult +from app.adapters.storage import file_thread + + +def confined(path: Path, settings, *, exists: bool = True, root: Path | None = None) -> Path: + try: + candidate = Path(path) + boundary = Path(root or settings.workspace_root).resolve() + if not candidate.is_absolute(): + raise ValueError + resolved = candidate.resolve() + if not resolved.is_relative_to(boundary) or (exists and not resolved.is_file()): + raise ValueError + return resolved + except (OSError, ValueError, TypeError): + raise MediaError("invalid_asset", "素材文件不存在或不可访问。") from None + + +async def _stop(process): + if process.returncode is None: + try: + process.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(process.wait(), 2) + except asyncio.TimeoutError: + try: + process.kill() + except ProcessLookupError: + pass + await asyncio.wait_for(process.wait(), 5) + + +async def _cleanup(process, readers): + for task in readers: + if not task.done(): + task.cancel() + await asyncio.gather(*readers, return_exceptions=True) + + async def discard(stream): + while await stream.read(65536): + pass + + # 超限或取消后也要排空管道,否则子进程退出后 transport 仍可能被满管道占住。 + drains = [ + asyncio.create_task(discard(process.stdout)), + asyncio.create_task(discard(process.stderr)), + ] + try: + await _stop(process) + await asyncio.wait_for(asyncio.gather(*drains), 5) + finally: + for task in drains: + if not task.done(): + task.cancel() + await asyncio.gather(*drains, return_exceptions=True) + + +async def run_process( + argv: list[str], + *, + timeout: float = 120, + max_output: int = 1024 * 1024, + cwd: Path | None = None, + return_stderr: bool = False, +) -> bytes | tuple[bytes, bytes]: + """只管理本次 FFmpeg/ffprobe 子进程,取消时执行 TERM/KILL/wait。 + + 读取期间就限制管道大小,避免任意诊断输出耗尽内存;不会停止共享模型服务。 + """ + process = None + readers = [] + + async def read_bounded(stream): + chunks, count = [], 0 + while chunk := await stream.read(65536): + count += len(chunk) + if count > max_output: + raise MediaError("media_output_limit", "媒体处理诊断超出限制。") + chunks.append(chunk) + return b"".join(chunks) + + try: + process = await asyncio.create_subprocess_exec( + *[str(value) for value in argv], + stdin=asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + cwd=str(cwd) if cwd else None, + start_new_session=(os.name == "posix"), + ) + readers = [ + asyncio.create_task(read_bounded(process.stdout)), + asyncio.create_task(read_bounded(process.stderr)), + ] + async with asyncio.timeout(timeout): + stdout, stderr = await asyncio.gather(*readers) + await process.wait() + if process.returncode != 0: + raise MediaError("media_processing_failed", "媒体解码或处理失败,请检查素材格式。") + return (stdout, stderr) if return_stderr else stdout + except asyncio.CancelledError: + raise + except asyncio.TimeoutError: + raise MediaError("media_timeout", "媒体处理超时,请缩短素材后重试。", True) from None + except (OSError, ValueError): + raise MediaError("media_unavailable", "媒体处理程序不可用。", True) from None + finally: + if process is not None: + cleanup = asyncio.create_task(_cleanup(process, readers)) + recancelled = False + while not cleanup.done(): + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError: + recancelled = True + await cleanup + if recancelled: + raise asyncio.CancelledError + + +def input_options() -> list[str]: + # 限制输入协议与容器,排除播放列表、网络协议和嵌套文件列表。 + return [ + "-protocol_whitelist", + "file,pipe", + "-format_whitelist", + "mov,matroska,webm,avi,wav,mp3,flac,ogg,aac,mpeg,mpegts", + ] + + +def _image_info(path): + try: + with Image.open(path) as image: + mime = {"PNG": "image/png", "JPEG": "image/jpeg", "WEBP": "image/webp"}.get( + image.format + ) + if mime is None or image.width * image.height > 40_000_000: + raise MediaError("invalid_image", "仅支持像素数受限的 PNG、JPEG、WebP 图片。") + image.load() + return { + "kind": "image", + "mime_type": mime, + "width": image.width, + "height": image.height, + "duration_seconds": None, + } + except UnidentifiedImageError: + return None + except (OSError, ValueError, Image.DecompressionBombError): + raise MediaError("invalid_image", "图片文件无法解码。") from None + + +def _text_info(path): + if path.suffix.lower() not in {".json", ".txt", ".md", ".srt", ".vtt"}: + return None + try: + if path.stat().st_size > 4 * 1024 * 1024: + raise ValueError + text = path.read_text(encoding="utf-8-sig") + if "\x00" in text or not text.strip(): + raise ValueError + is_json = path.suffix.lower() == ".json" + if is_json: + json.loads(text, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) + return { + "kind": "json" if is_json else "text", + "mime_type": "application/json" if is_json else "text/plain", + "width": None, + "height": None, + "duration_seconds": None, + } + except (OSError, UnicodeError, ValueError, RecursionError): + raise MediaError("invalid_text", "文本或 JSON 文件格式无效。") from None + + +async def inspect_media(path: Path, settings) -> dict: + source = confined(path, settings) + if source.stat().st_size <= 0: + raise MediaError("invalid_asset", "素材文件为空。") + text = await asyncio.to_thread(_text_info, source) + if text is not None: + return text + image = await asyncio.to_thread(_image_info, source) + if image is not None: + return image + if source.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}: + raise MediaError("invalid_image", "图片文件无法解码。") + raw = await run_process( + [ + settings.ffprobe_bin, + "-v", + "error", + *input_options(), + "-show_entries", + "format=format_name,duration,start_time:stream=codec_type,codec_name,width,height,duration:stream_disposition=attached_pic", + "-of", + "json", + str(source), + ], + timeout=30, + max_output=256 * 1024, + ) + try: + data = json.loads(raw) + streams = data["streams"] + videos = [ + item + for item in streams + if item.get("codec_type") == "video" + and not item.get("disposition", {}).get("attached_pic") + ] + audios = [item for item in streams if item.get("codec_type") == "audio"] + if not videos and not audios: + raise ValueError + stream = videos[0] if videos else audios[0] + duration = float(data.get("format", {}).get("duration", stream.get("duration", 0))) + start_time = float(data.get("format", {}).get("start_time", 0)) + if not math.isfinite(start_time): + raise ValueError + if not math.isfinite(duration) or not 0 < duration <= 86400: + raise ValueError + width, height = stream.get("width"), stream.get("height") + if videos and ( + type(width) is not int + or type(height) is not int + or width <= 0 + or height <= 0 + or width * height > 40_000_000 + ): + raise ValueError + formats = str(data.get("format", {}).get("format_name", "")).split(",") + if videos: + mime = ( + "video/webm" + if "webm" in formats and source.suffix.lower() == ".webm" + else "video/mp4" + if "mov" in formats + else "video/x-matroska" + if "matroska" in formats + else "video/mp2t" + if "mpegts" in formats + else "video/mpeg" + if "mpeg" in formats + else "video/x-msvideo" + ) + else: + mime = ( + "audio/wav" + if "wav" in formats + else "audio/mpeg" + if "mp3" in formats + else "audio/flac" + if "flac" in formats + else "audio/ogg" + if "ogg" in formats + else "audio/aac" + if "aac" in formats + else "audio/mp4" + ) + return { + "kind": "video" if videos else "audio", + "mime_type": mime, + "has_audio": bool(audios), + "width": width if videos else None, + "height": height if videos else None, + "duration_seconds": duration, + "start_seconds": start_time, + } + except (ValueError, TypeError, KeyError, AttributeError): + raise MediaError("invalid_media", "媒体文件信息无效。") from None + + +async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None: + source, target = confined(path, settings), confined(destination, settings, exists=False) + info = await inspect_media(source, settings) + if info["kind"] not in {"image", "video"}: + return None + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_name(target.name + ".part-" + uuid.uuid4().hex + ".jpg") + try: + if info["kind"] == "image": + + def convert(): + with Image.open(source) as image: + image = ImageOps.exif_transpose(image).convert("RGB") + image.thumbnail((512, 512)) + image.save(temporary, format="JPEG", quality=85) + + await file_thread(convert) + else: + await run_process( + [ + settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + *input_options(), + "-i", + str(source), + "-frames:v", + "1", + "-vf", + "scale=512:512:force_original_aspect_ratio=decrease", + "-threads", + "2", + "-f", + "image2", + "-update", + "1", + str(temporary), + ], + timeout=60, + ) + if not temporary.is_file() or temporary.stat().st_size == 0: + raise MediaError("thumbnail_failed", "预览图生成失败。") + os.replace(temporary, target) + return target + finally: + temporary.unlink(missing_ok=True) + + +async def inspect_video_track(path: Path, settings) -> dict: + """Count decoded video frames; container or audio duration cannot mask a short source.""" + from fractions import Fraction + + source = confined(path, settings) + raw = await run_process( + [ + settings.ffprobe_bin, + "-v", + "error", + *input_options(), + "-select_streams", + "v:0", + "-count_frames", + "-show_entries", + "stream=width,height,avg_frame_rate,nb_read_frames,duration,time_base:format=duration", + "-of", + "json", + str(source), + ], + timeout=120, + max_output=256 * 1024, + ) + try: + data = json.loads(raw) + stream = data["streams"][0] + frames = int(stream["nb_read_frames"]) + fps = Fraction(stream["avg_frame_rate"]) + width, height = int(stream["width"]), int(stream["height"]) + if frames <= 0 or fps <= 0 or width <= 0 or height <= 0 or width * height > 40000000: + raise ValueError + return { + "frames": frames, + "fps": float(fps), + "width": width, + "height": height, + "duration": float(data["format"]["duration"]), + "time_base": stream.get("time_base"), + } + except (KeyError, IndexError, TypeError, ValueError, ZeroDivisionError): + raise MediaError("invalid_media", "Video frame decoding failed.") from None + + +async def compose_workflow(plan, work_dir, control=None, *, settings, sources, audio=None): + """Render a frozen multi-shot timeline from internal resolved asset paths.""" + if len(sources) != len(plan.spec["shots"]): + raise MediaError("invalid_timeline", "Source videos differ from the frozen shot count.") + story_clips = getattr(plan, "clips", None) + shot_frames = ( + tuple(c["duration_frames"] for c in story_clips) + if story_clips + else plan.shot_frames or (plan.clip_frames,) * len(sources) + ) + starts = tuple(c["start_frame"] for c in story_clips) if story_clips else (0,) * len(sources) + duration = plan.frames / plan.fps + duration_text = f"{duration:.9f}".rstrip("0").rstrip(".") + sources = [confined(p, settings) for p in sources] + work = Path(work_dir).resolve() + if not work.is_relative_to(Path(settings.workspace_root).resolve()): + raise MediaError("invalid_asset", "Invalid work directory.") + width, height = plan.canvas + expected = ( + None + if story_clips + else ( + plan.generation_parameters["upscale_width"], + plan.generation_parameters["upscale_height"], + ) + ) + for index, (source, frames, start) in enumerate(zip(sources, shot_frames, starts)): + info = await inspect_video_track(source, settings) + if info["frames"] < frames + start: + raise MediaError( + "short_source", + f"Each source needs at least {frames} decoded video frames for its selected duration.", + ) + dimensions = ( + (story_clips[index]["width"], story_clips[index]["height"]) if story_clips else expected + ) + if story_clips and ( + ("fps" in story_clips[index] and story_clips[index]["fps"] != info["fps"]) + or ( + "source_frames" in story_clips[index] + and story_clips[index]["source_frames"] != info["frames"] + ) + ): + raise MediaError( + "invalid_video_profile", "Source facts differ from frozen decoded video." + ) + if info["fps"] != 24 or (info["width"], info["height"]) != dimensions: + raise MediaError( + "invalid_video_profile", "Source video differs from frozen enhanced profile." + ) + audio_spec = plan.spec["render"]["audio"] + if bool(audio_spec) != bool(audio): + raise MediaError("invalid_timeline", "Audio source does not match timeline.") + if audio: + audio = confined(audio, settings) + info = await inspect_media(audio, settings) + if info["kind"] != "audio" or audio_spec["source_end_ms"] > round( + info["duration_seconds"] * 1000 + ): + raise MediaError("invalid_timeline", "Audio cut exceeds decoded source.") + work.mkdir(parents=True, exist_ok=True) + + async def checkpoint(): + if control is not None: + result = control() if callable(control) else control.checkpoint() + if hasattr(result, "__await__"): + await result + + parts = [] + for index, (source, frames, start) in enumerate(zip(sources, shot_frames, starts)): + await checkpoint() + target = work / f"shot-{index}.mp4" + fit = plan.spec["render"]["fit"] + canvas = f"scale={width}:{height}:force_original_aspect_ratio=" + ( + "decrease" if fit == "contain" else "increase" + ) + canvas += ( + f",pad={width}:{height}:(ow-iw)/2:(oh-ih)/2" + if fit == "contain" + else f",crop={width}:{height}" + ) + vf = ( + f"trim=start_frame={start}:end_frame={start + frames},setpts=PTS-STARTPTS," + + canvas + + ",setsar=1" + ) + await run_process( + [ + settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + *input_options(), + "-i", + str(source), + "-map", + "0:v:0", + "-an", + "-vf", + vf, + "-r", + "24", + "-frames:v", + str(frames), + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "20", + "-pix_fmt", + "yuv420p", + "-threads", + "2", + "-fs", + str(settings.max_output_bytes), + str(target), + ], + timeout=600, + ) + parts.append(target) + if sum(p.stat().st_size for p in parts) >= settings.max_output_bytes: + raise MediaError("output_too_large", "Intermediate media exceeds size budget.") + listing = work / "concat.txt" + listing.write_text("".join(f"file '{p.name}'\n" for p in parts), encoding="utf-8") + target = work / "workflow.mp4" + command = [ + settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + "-f", + "concat", + "-safe", + "1", + "-i", + listing.name, + ] + if audio: + command += [*input_options(), "-i", str(audio)] + else: + command += ["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000"] + filters = [] + # Windows 未安装 Noto 时 FFmpeg 会静默回退至西文字体,必须选用已有中文字库。 + subtitle_font = "Microsoft YaHei" if os.name == "nt" else "Noto Sans CJK SC" + for index, cue in enumerate(plan.spec["render"]["subtitles"]): + name = f"cue-{index:04d}.txt" + (work / name).write_text(cue["text"], encoding="utf-8") + filters.append( + f"drawtext=font='{subtitle_font}':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'" + ) + if audio: + start, end = audio_spec["source_start_ms"] / 1000, audio_spec["source_end_ms"] / 1000 + delay = audio_spec["offset_frame"] * 1000 / 24 + af = f"atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}" + else: + af = f"atrim=duration={duration_text}" + command += ["-map", "0:v:0", "-map", "1:a:0"] + if filters: + command += ["-vf", ",".join(filters)] + command += [ + "-af", + af, + "-frames:v", + str(plan.frames), + "-r", + "24", + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "20", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-ar", + "48000", + "-ac", + "2", + "-threads", + "2", + "-movflags", + "+faststart", + "-fs", + str(settings.max_output_bytes), + str(target), + ] + await checkpoint() + await run_process(command, timeout=min(3600, max(600, duration * 5)), cwd=work) + info = await inspect_video_track(target, settings) + if ( + info["frames"] != plan.frames + or info["fps"] != 24 + or (info["width"], info["height"]) != plan.canvas + or abs(info["duration"] - duration) > 0.10 + or target.stat().st_size >= settings.max_output_bytes + ): + raise MediaError( + "composition_incomplete", + "Final video differs from the frozen frame count, profile or duration.", + ) + result = { + "frames": plan.frames, + "fps": 24, + "duration_seconds": duration, + "width": width, + "height": height, + "clip_count": len(sources), + "subtitle_count": len(filters), + } + return CpuResult( + [target], + result, + {"provider": "ffmpeg-cpu", "profile": plan.spec["profile"], "template_version": "plain-v1"}, + ) + + +async def compose_story(plan, work_dir, control=None, *, settings, sources, audio=None): + """v3 专用计划,保持独立验证,不经过旧 compile_timeline。""" + from app.domain.stories import StoryRenderPlan + from dataclasses import replace + import hashlib + + recovered_clips = [] + + if not isinstance(plan, StoryRenderPlan): + raise MediaError("invalid_timeline", "需要冻结的故事合成计划") + for source, clip in zip(sources, plan.clips): + source = confined(source, settings) + + def checksum(): + h = hashlib.sha256() + with source.open("rb") as stream: + while chunk := stream.read(1024 * 1024): + h.update(chunk) + return h.hexdigest() + + if await asyncio.to_thread(checksum) != clip["sha256"]: + raise MediaError("dependency_changed", "冻结视频 SHA 不匹配") + # 旧自动快照缺少解码尺寸;只在原字节SHA确认后补齐执行副本,不重写历史冻结输入。 + recovered = dict(clip) + if "width" not in clip or "height" not in clip: + info = await inspect_video_track(source, settings) + for key in ("width", "height"): + if key not in recovered: + recovered[key] = info[key] + recovered_clips.append(recovered) + plan = replace(plan, clips=tuple(recovered_clips)) + return await compose_workflow( + plan, work_dir, control, settings=settings, sources=sources, audio=audio + ) + + +async def inspect_video_timeline(path: Path, settings) -> float: + """用真实视频帧的时间戳计时;容器时长可能被更长的音轨撑大。""" + from fractions import Fraction + from statistics import median + + source = confined(path, settings) + raw = await run_process( + [ + settings.ffprobe_bin, + "-v", + "error", + *input_options(), + "-select_streams", + "v:0", + "-show_frames", + "-show_entries", + "frame=best_effort_timestamp_time,duration_time,pkt_duration_time:stream=avg_frame_rate", + "-of", + "json", + str(source), + ], + timeout=120, + max_output=16 * 1024 * 1024, + ) + try: + data = json.loads(raw) + frames = data["frames"] + timestamps = [float(frame["best_effort_timestamp_time"]) for frame in frames] + if not timestamps or any(not math.isfinite(t) for t in timestamps): + raise ValueError + gaps = [b - a for a, b in zip(timestamps, timestamps[1:])] + if any(gap <= 0 for gap in gaps): + raise ValueError + last = frames[-1] + duration = float(last.get("duration_time", last.get("pkt_duration_time", 0))) + if not math.isfinite(duration) or duration <= 0: + duration = ( + median(gaps) if gaps else 1 / float(Fraction(data["streams"][0]["avg_frame_rate"])) + ) + total = timestamps[-1] + duration - timestamps[0] + if not math.isfinite(total) or total <= 0: + raise ValueError + return total + except (KeyError, IndexError, TypeError, ValueError, ZeroDivisionError): + raise MediaError("invalid_media", "视频时间轴无法解码。") from None diff --git a/backend/app/adapters/provider/__init__.py b/backend/app/adapters/provider/__init__.py new file mode 100644 index 0000000..804fc24 --- /dev/null +++ b/backend/app/adapters/provider/__init__.py @@ -0,0 +1 @@ +"""已部署推理服务与 CPU 媒体适配;公共入口为 client。""" diff --git a/backend/app/adapters/provider/client.py b/backend/app/adapters/provider/client.py new file mode 100644 index 0000000..c69c038 --- /dev/null +++ b/backend/app/adapters/provider/client.py @@ -0,0 +1,154 @@ +"""推理适配公共门面:无数据库依赖,HTTP 客户端可替换。""" + +from __future__ import annotations + +import asyncio +import httpx + +from app.domain.errors import MediaError as ProviderError +from app.domain.execution import CpuResult, current_phase_callback, enter_phase +from .contracts import capabilities, validate_arguments +from . import composition, cpu, files, gpu, qwen, runtime, speech, transport + +__all__ = [ + "Provider", + "capabilities", + "validate_arguments", + "ProviderError", + "CpuResult", + "current_phase_callback", + "enter_phase", +] + + +class Provider: + def __init__(self, settings): + self.settings = settings + self._runtime_lock = asyncio.Lock() + # 组合模块每次读取此属性,替换客户端后不会继续使用旧连接。 + self.client = httpx.AsyncClient( + trust_env=False, + follow_redirects=False, + timeout=httpx.Timeout(float(settings.request_timeout_seconds)), + limits=httpx.Limits(max_connections=4, max_keepalive_connections=2), + ) + + async def aclose(self): + await self.client.aclose() + + def _headers(self, family="inference"): + return transport._headers(self, family) + + @staticmethod + def _http_error(status): + return transport._http_error(status) + + async def _json(self, method, url, *, payload=None, headers=None, timeout=None): + return await transport._json( + self, method, url, payload=payload, headers=headers, timeout=timeout + ) + + async def health(self): + return await runtime.health(self) + + @staticmethod + def _runtime_value(value): + return runtime._runtime_value(value) + + async def runtime_status(self): + return await runtime.runtime_status(self) + + def _mirror_runtime_policy(self, policy): + return runtime._mirror_runtime_policy(self, policy) + + async def scheduler_status(self): + return await runtime.scheduler_status(self) + + def _work(self, path): + return files._work(self, path) + + def _asset(self, asset_id, assets): + return files._asset(self, asset_id, assets) + + async def _upload_input(self, source): + return await files._upload_input(self, source) + + async def _download_url( + self, url, destination, headers, *, payload=None, timeout=None, total_timeout=None + ): + return await files._download_url( + self, + url, + destination, + headers, + payload=payload, + timeout=timeout, + total_timeout=total_timeout, + ) + + async def speech_health(self): + return await speech.health(self) + + async def download(self, upstream_id, index, destination): + return await files.download(self, upstream_id, index, destination) + + @staticmethod + def _json_file(work, name, value): + return files._json_file(work, name, value) + + async def prepare_gpu_payload( + self, task_type, inputs, parameters, assets, work_dir, *, analysis_binding=None + ): + return await gpu.prepare_gpu_payload( + self, task_type, inputs, parameters, assets, work_dir, analysis_binding=analysis_binding + ) + + async def submit(self, payload, idempotency_key): + return await gpu.submit(self, payload, idempotency_key) + + @staticmethod + def _job_id(value): + return gpu._job_id(value) + + @staticmethod + def _sanitize_job(value): + return gpu._sanitize_job(value) + + async def query(self, upstream_id): + return await gpu.query(self, upstream_id) + + async def upstream_capabilities(self): + return await gpu.upstream_capabilities(self) + + async def control( + self, + upstream_id, + desired_state, + command_id, + expected_version=None, + expected_execution_id=None, + ): + return await gpu.control( + self, upstream_id, desired_state, command_id, expected_version, expected_execution_id + ) + + async def cancel(self, upstream_id): + return await gpu.cancel(self, upstream_id) + + async def _chat(self, messages, *, max_tokens=2048, thinking=False): + return await qwen._chat(self, messages, max_tokens=max_tokens, thinking=thinking) + + async def _image_uri(self, source): + return await qwen._image_uri(self, source) + + async def _structure(self, inputs, p, assets, work): + return await qwen._structure(self, inputs, p, assets, work) + + async def _speech(self, inputs, p, work): + return await speech._speech(self, inputs, p, work) + + async def _compose(self, inputs, p, assets, work): + return await composition._compose(self, inputs, p, assets, work) + + async def run_cpu(self, task_type, inputs, parameters, assets, work_dir): + return await cpu.run_cpu(self, task_type, inputs, parameters, assets, work_dir) diff --git a/backend/app/adapters/provider/composition.py b/backend/app/adapters/provider/composition.py new file mode 100644 index 0000000..62f193a --- /dev/null +++ b/backend/app/adapters/provider/composition.py @@ -0,0 +1,258 @@ +"""固定 FFmpeg 参数的素材编排适配。""" + +from __future__ import annotations + +import asyncio +import html +import re + +from app.adapters.media import input_options, inspect_media, run_process +from app.domain.execution import CpuResult +from app.domain.errors import MediaError as ProviderError +from .contracts import _invalid, _keys, _int, _float, _string +from .contracts import validate_arguments + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +async def _compose(provider: Provider, inputs, p, assets, work): + if "story_spec" in p: + from app.domain.stories import compile_story_render + from app.adapters.media import compose_story + + validate_arguments("video.compose", inputs, p, provider.settings) + plan = compile_story_render(p["story_spec"], p["render_inputs"]) + audio_id = inputs.get("audio_asset_id") + frozen_audio = p["render_inputs"].get("audio") + if frozen_audio: + import hashlib + + def digest_file(path): + h = hashlib.sha256() + with path.open("rb") as stream: + while chunk := stream.read(1024 * 1024): + h.update(chunk) + return h.hexdigest() + + # 音轨与视频都校验已冻结字节,不能在等待合成期间替换源文件。 + if ( + await asyncio.to_thread(digest_file, provider._asset(audio_id, assets)) + != frozen_audio["sha256"] + ): + raise _invalid("Frozen story audio SHA differs.") + return await compose_story( + plan, + work, + settings=provider.settings, + sources=[provider._asset(c["asset_id"], assets) for c in plan.clips], + audio=provider._asset(audio_id, assets) if audio_id else None, + ) + if "workflow_spec" in p: + from app.domain.timeline import compile_timeline + from app.adapters.media import compose_workflow + + validate_arguments("video.compose", inputs, p, provider.settings) + audio_id = inputs.get("audio_asset_id") + audio = provider._asset(audio_id, assets) if audio_id else None + owned = {audio_id: await inspect_media(audio, provider.settings)} if audio else {} + try: + plan = compile_timeline(p["workflow_spec"], owned) + except ValueError: + raise _invalid("Invalid workflow audio timeline.") from None + return await compose_workflow( + plan, + work, + settings=provider.settings, + sources=[provider._asset(c["asset_id"], assets) for c in p["clips"]], + audio=audio, + ) + _keys(inputs, {"asset_ids", "audio_asset_id"}) + _keys(p, {"clips", "audio_asset_id", "subtitles", "width", "height", "fps"}) + clips = p.get("clips") + if not isinstance(clips, list) or not 1 <= len(clips) <= 1000: + raise _invalid("请选择1至1000个视频片段。") + width, height, fps = p.get("width", 1280), p.get("height", 720), p.get("fps", 24) + _int(width, 256, 3840, 2) + _int(height, 256, 2160, 2) + if type(fps) is not int or fps not in {24, 25, 30, 60}: + raise _invalid("不支持此成片帧率。") + normalized = [] + for clip in clips: + _keys(clip, {"asset_id", "start_seconds", "end_seconds"}) + start = _float(clip.get("start_seconds", 0), 0, 86400) + end = clip.get("end_seconds") + if end is not None and _float(end, 0, 86400) <= start: + raise _invalid("片段结束时间必须大于开始时间。") + normalized.append((provider._asset(clip.get("asset_id"), assets), start, end)) + if "asset_ids" in inputs and inputs["asset_ids"] != [clip["asset_id"] for clip in clips]: + raise _invalid("素材顺序应与编排片段一致。") + a, b = inputs.get("audio_asset_id"), p.get("audio_asset_id") + if a and b and a != b: + raise _invalid("请只选择一个成片音轨。") + audio = provider._asset(a or b, assets) if a or b else None + subtitles = p.get("subtitles", []) + if not isinstance(subtitles, list) or len(subtitles) > 1000: + raise _invalid("人工字幕数量超出限制。") + cues = [] + for cue in subtitles: + _keys(cue, {"start", "end", "text"}) + start, end = ( + _float(cue.get("start"), 0, 86400 * 1000), + _float(cue.get("end"), 0, 86400 * 1000), + ) + text = _string(cue.get("text"), 2000) + if end <= start or "\n\n" in text or re.search(r"[\\{}\x00-\x08\x0b-\x1f]", text): + raise _invalid("字幕时间或纯文本内容无效;不支持ASS控制语法。") + cues.append((start, end, html.escape(text, quote=False))) + parts, total = [], 0.0 + for source, start, end in normalized: + info = await inspect_media(source, provider.settings) + if info["kind"] != "video": + raise _invalid("编排片段必须是视频素材。") + end = info["duration_seconds"] if end is None else end + if start >= end or end > info["duration_seconds"] + 0.05 or end - start < 0.05: + raise _invalid("裁剪范围超出视频实际时长。") + total += end - start + parts.append((source, start, end - start, info.get("has_audio", False))) + if any(end > total + 0.05 for _, end, _ in cues): + raise _invalid("字幕超出成片时长。") + if audio and (await inspect_media(audio, provider.settings))["kind"] != "audio": + raise _invalid("成片音轨必须为音频素材。") + files = [] + async with asyncio.timeout(900): + for index, (source, start, duration, has_audio) in enumerate(parts): + target = work / f"clip-{index:03d}.mp4" + command = [ + provider.settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + *input_options(), + "-i", + str(source), + ] + if not has_audio: + command += ["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000"] + command += [ + "-ss", + f"{start:.6f}", + "-t", + f"{duration:.6f}", + "-map", + "0:v:0", + "-map", + "0:a:0" if has_audio else "1:a:0", + "-vf", + f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}", + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "20", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-ar", + "48000", + "-ac", + "2", + "-threads", + "2", + "-fs", + str(provider.settings.max_output_bytes), + str(target), + ] + await run_process(command, timeout=min(600, max(60, duration * 5))) + files.append(target) + if sum(path.stat().st_size for path in files) >= provider.settings.max_output_bytes: + raise ProviderError("output_too_large", "成片中间文件超出大小限制。") + listing = work / "concat.txt" + listing.write_text("".join(f"file '{path.name}'\n" for path in files), encoding="utf-8") + if cues: + + def stamp(value): + milliseconds = round(value * 1000) + hours, milliseconds = divmod(milliseconds, 3600000) + minutes, milliseconds = divmod(milliseconds, 60000) + seconds, milliseconds = divmod(milliseconds, 1000) + return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}" + + (work / "subtitles.srt").write_text( + "".join( + f"{index}\n{stamp(start)} --> {stamp(end)}\n{text}\n\n" + for index, (start, end, text) in enumerate(cues, 1) + ), + encoding="utf-8", + ) + target = work / "composition.mp4" + command = [ + provider.settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + "-f", + "concat", + "-safe", + "1", + "-i", + listing.name, + ] + if audio: + command += [*input_options(), "-i", str(audio)] + command += ["-map", "0:v:0", "-map", "1:a:0" if audio else "0:a:0"] + if cues: + command += [ + "-vf", + "subtitles=filename=subtitles.srt", + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "20", + "-pix_fmt", + "yuv420p", + ] + else: + command += ["-c:v", "copy"] + command += [ + "-af", + "apad", + "-t", + f"{total:.6f}", + "-c:a", + "aac", + "-threads", + "2", + "-movflags", + "+faststart", + "-fs", + str(provider.settings.max_output_bytes), + str(target), + ] + await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work) + info = await inspect_media(target, provider.settings) + if ( + abs(info["duration_seconds"] - total) > max(0.2, 2 / fps) + or target.stat().st_size >= provider.settings.max_output_bytes + ): + raise ProviderError("composition_incomplete", "成片未完整输出或超出大小限制。") + result = { + "duration_seconds": info["duration_seconds"], + "width": width, + "height": height, + "fps": fps, + "clip_count": len(parts), + "subtitle_count": len(cues), + } + manifest = provider._json_file(work, "composition.json", result) + return CpuResult( + [target, manifest], + result, + {"provider": "ffmpeg-cpu", "audio": "uploaded" if audio else "original-or-silence"}, + ) diff --git a/backend/app/adapters/provider/contracts.py b/backend/app/adapters/provider/contracts.py new file mode 100644 index 0000000..901412f --- /dev/null +++ b/backend/app/adapters/provider/contracts.py @@ -0,0 +1,560 @@ +"""能力声明、默认值与提交参数校验,不执行模型任务。""" + +from __future__ import annotations + +import math +import re + +from app.domain.errors import MediaError as ProviderError +from app.domain.tasks import GPU_TYPES as GPU_TASKS + + +LANGUAGES = ["zh", "en", "ja", "ko", "de", "fr", "es", "ru", "ar", "pt", "it", "auto"] +REFERENCE_PROFILES = { + "qwen-image-edit-2511-v1": ("Qwen-Image-Edit-2511", 3), + "qwen-image-edit-2509-v1": ("Qwen-Image-Edit-2509", 3), + "qwen-image-edit-2511-experimental-4-v1": ("Qwen-Image-Edit-2511", 4), +} + + +def reference_capability(settings): + profile = getattr(settings, "reference_generation_profile", "qwen-image-edit-2511-v1") + model, maximum = REFERENCE_PROFILES.get(profile, ("Unrecognized edit profile", 0)) + maximum = min(maximum, getattr(settings, "reference_max_images", 3)) + return { + "profile": profile, + "model": model, + "max_reference_images": maximum, + "available": bool( + maximum + and getattr(settings, "reference_generation_enabled", False) + and getattr(settings, "inference_base_url", "") + ), + } + + +def _invalid(message="任务输入或参数无效。"): + return ProviderError("invalid_input", message) + + +def _keys(value, allowed): + if not isinstance(value, dict) or set(value) - set(allowed): + raise _invalid("包含不支持的输入或参数。") + + +def _int(value, low, high, step=1): + if type(value) is not int or not low <= value <= high or value % step: + raise _invalid("整数参数超出范围或步长不正确。") + return value + + +def _float(value, low, high): + if isinstance(value, bool) or not isinstance(value, (float, int)): + raise _invalid("数值参数无效。") + try: + normalized = float(value) + except (ValueError, OverflowError): + raise _invalid("数值参数无效。") from None + if not math.isfinite(normalized) or not low <= normalized <= high: + raise _invalid("数值参数超出范围。") + return normalized + + +def _string(value, maximum=8000, *, required=True): + if not isinstance(value, str) or len(value) > maximum or (required and not value.strip()): + raise _invalid("文字内容为空或超出长度限制。") + return value + + +def _voices(settings): + values = getattr(settings, "tts_voices", ["zf_xiaobei", "zm_yunxi"]) + if isinstance(values, str): + values = [item.strip() for item in values.split(",") if item.strip()] + return [ + value + for value in values + if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_-]{1,64}", value) + ] + + +def capabilities(settings) -> list[dict]: + from app.core.runtime_policy import read_runtime_policy + + compose_limit = read_runtime_policy(settings)["workflow_max_shots"] + image_defaults = { + "width": 1024, + "height": 1024, + "num_inference_steps": 50, + "seed": 42, + "guidance_scale": 4.0, + } + image_limits = { + "width": {"min": 256, "max": 2048, "step": 16}, + "height": {"min": 256, "max": 2048, "step": 16}, + "num_inference_steps": {"min": 1, "max": 100}, + "guidance_scale": {"min": 1, "max": 20}, + "seed": {"min": 0, "max": 2**32 - 1}, + "count": {"min": 1, "max": 4}, + "max_pixels": 2048 * 2048, + } + video_defaults = dict( + image_defaults, + width=1280, + height=704, + guidance_scale=5.0, + num_frames=121, + fps=24, + upscale=True, + upscale_width=1920, + upscale_height=1080, + tile_size=128, + ) + video_limits = { + **image_limits, + "width": {"min": 256, "max": 1280, "step": 32}, + "height": {"min": 256, "max": 1280, "step": 32}, + "max_pixels": 1280 * 704, + "count": {"min": 1, "max": 1}, + "num_frames": {"min": 5, "max": 361, "step": 4}, + "fps": {"values": [24]}, + "upscale": {"values": [True, False]}, + "upscale_width": {"min": 256, "max": 3840, "step": 2}, + "upscale_height": {"min": 256, "max": 2160, "step": 2}, + "tile_size": {"min": 64, "max": 256, "step": 16}, + } + configured = bool(getattr(settings, "inference_base_url", "")) + qwen = bool(getattr(settings, "qwen_base_url", "") and getattr(settings, "qwen_model", "")) + speech = bool( + getattr(settings, "tts_base_url", "") + and getattr(settings, "tts_model", "") + and _voices(settings) + ) + reference = reference_capability(settings) + + def item(task_type, label, model, available, types, defaults, constraints, description): + return dict( + task_type=task_type, + label=label, + model=model, + available=available, + input_types=types, + defaults=defaults, + constraints=constraints, + description=description, + ) + + from app.domain.video_editing import video_capability, video_defaults as edit_defaults + + edit = video_capability(settings) + story_tasks = [ + *[ + item( + task, + label, + edit["model"], + edit["available"], + ["video"], + edit_defaults(task, settings), + {k: edit[k] for k in ("max_seconds", "max_people", "max_pixels", "fps")}, + edit["reason"] or "按视频实例选择多人替换,保留未选人物与背景。", + ) + for task, label in ( + ("video.people.analyze", "识别视频人物"), + ("video.replace", "视频多人替换"), + ) + ], + item( + "image.reference.generate", + "多图锚定首帧", + reference["model"], + reference["available"], + ["text", "images"], + { + "profile": reference["profile"], + "width": 1280, + "height": 704, + "num_inference_steps": 40, + "seed": 42, + "guidance_scale": 1.0, + "true_cfg_scale": 4.0, + "max_sequence_length": 1024, + }, + { + "max_reference_images": reference["max_reference_images"], + "sizes": [[1280, 704], [704, 1280], [1024, 1024]], + "count": {"min": 1, "max": 4}, + "max_sequence_length": {"min": 1, "max": 1024}, + "num_inference_steps": {"min": 1, "max": 100}, + "guidance_scale": {"min": 1, "max": 20}, + "true_cfg_scale": {"min": 1, "max": 20}, + "seed": {"min": 0, "max": 2**32 - 1}, + }, + "按顺序使用全部真实参考图片;需完成服务端认证,缺图不会降级文生图。", + ), + item( + "image.prepare_frame", + "首帧规范化", + "Pillow CPU", + True, + ["image"], + {"width": 1280, "height": 704, "fit": "contain"}, + { + "width": {"min": 256, "max": 2048, "step": 16}, + "height": {"min": 256, "max": 2048, "step": 16}, + "fit": {"values": ["contain", "cover"]}, + }, + "生成独立RGB PNG,按指定尺寸留边或居中裁剪,不覆盖原素材。", + ), + ] + # 旧快速创作依赖首项为文生图,新增内部阶段追加在原能力之后。 + return [ + item( + "image.generate", + "图像生成", + "Qwen-Image", + configured, + ["text"], + image_defaults, + image_limits, + "文字生成图片;不包含图像编辑或风格 LoRA 管理。", + ), + item( + "video.generate", + "视频生成", + "Wan2.2-TI2V-5B + Real-ESRGAN", + configured, + ["text", "image"], + video_defaults, + video_limits, + "单镜头最多361帧、24fps,约15秒无声视频;默认约5秒,可选1080p增强。", + ), + item( + "defect.generate", + "条件样本生成", + "SDXL + Canny ControlNet", + configured, + ["text", "image"], + dict( + image_defaults, + guidance_scale=7.5, + controlnet_conditioning_scale=0.8, + canny_low=100, + canny_high=200, + ), + { + **image_limits, + "controlnet_conditioning_scale": {"min": 0, "max": 2}, + "canny_low": {"min": 0, "max": 255}, + "canny_high": {"min": 0, "max": 255}, + }, + "参考图片提供边缘结构;输出控制图不是缺陷真值掩膜。", + ), + item( + "audio.transcribe", + "语音转写", + "Whisper-large-v3-turbo", + configured, + ["audio", "video"], + {"language": "zh", "max_audio_seconds": 1800}, + {"language": {"values": LANGUAGES}, "max_audio_seconds": {"min": 1, "max": 1800}}, + "支持音频和有声视频;时间戳为30秒块边界,不是字词对齐。", + ), + item( + "math.solve", + "数学推演", + getattr(settings, "qwen_model", ""), + qwen, + ["text"], + {"max_tokens": 2048, "enable_thinking": False}, + {"max_tokens": {"min": 1, "max": 4096}}, + "调用现有文本服务给出解答,未集成形式化证明或准确率评测。", + ), + item( + "media.structure", + "素材理解", + getattr(settings, "qwen_model", ""), + qwen, + ["image", "video"], + {"frame_count": 6}, + {"frame_count": {"min": 1, "max": 12}}, + "视频均匀抽帧后理解画面、文字和标签;不承诺镜头切分准确率。", + ), + item( + "video.compose", + "成片编排", + "FFmpeg CPU", + True, + ["video", "audio"], + {"width": 1280, "height": 720, "fps": 24}, + { + "width": {"min": 256, "max": 3840, "step": 2}, + "height": {"min": 256, "max": 2160, "step": 2}, + "fps": {"values": [24, 25, 30, 60]}, + "clips": {"min": 1, "max": compose_limit}, + "source_duration_seconds": {"min": 0.05, "max": 86400}, + }, + "按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。", + ), + item( + "audio.speech", + "中文配音", + getattr(settings, "tts_model", "") or "尚未配置", + speech, + ["text"], + {"voice": (_voices(settings) or [""])[0], "speed": 1.0}, + { + "voice": {"values": _voices(settings)}, + "speed": {"min": 0.5, "max": 2}, + "text": {"max": 2000}, + }, + "仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。", + ), + item( + "text.script.generate", + "镜头旁白文案", + getattr(settings, "qwen_model", ""), + qwen, + ["text"], + {}, + {"max_shots": 1000}, + "按稳定镜头ID生成可编辑的简短旁白。", + ), + item( + "audio.assemble", + "旁白音轨装配", + "FFmpeg", + True, + ["audio"], + {"fps": 24}, + {"max_segments": 1000}, + "将已选用配音段按24fps位置装配为单音轨。", + ), + *story_tasks, + ] + + +def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=None) -> None: + """Pure submission validation: no HTTP, file decoding, mkdir or model work.""" + p = parameters + if task_type in {"text.script.generate", "audio.assemble"}: + from .editor_media import validate + + validate(task_type, inputs, parameters) + return + if task_type == "image.prepare_frame": + _keys(inputs, {"image_asset_id"}) + _keys(p, {"width", "height", "fit"}) + _string(inputs.get("image_asset_id"), 64) + for name in ("width", "height"): + _int(p.get(name, 1280 if name == "width" else 704), 256, 2048, 16) + if p.get("fit", "contain") not in {"contain", "cover"}: + raise _invalid("首帧适配方式无效。") + return + if task_type in {"video.people.analyze", "video.replace"}: + from app.domain.video_editing import validate_video_arguments + + validate_video_arguments(task_type, inputs, p, settings) + return + if task_type == "image.reference.generate": + reference = reference_capability(settings) + if not reference["available"]: + raise ProviderError("capability_unavailable", "多图参考生成尚未通过认证或未启用。") + _keys(inputs, {"prompt", "negative_prompt", "reference_asset_ids"}) + _string(inputs.get("prompt")) + _string(inputs.get("negative_prompt", ""), required=False) + defaults = next( + i["defaults"] for i in capabilities(settings) if i["task_type"] == task_type + ) + _keys(p, set(defaults)) + p = {**defaults, **p} + if p["profile"] != reference["profile"]: + raise _invalid("参考生成必须使用已配置且认证的模型版本。") + ids = inputs.get("reference_asset_ids") + if not isinstance(ids, list) or not 1 <= len(ids) <= reference["max_reference_images"]: + raise _invalid("参考图片数量超出已认证范围。") + if any(not isinstance(v, str) for v in ids) or len(set(ids)) != len(ids): + raise _invalid("参考图片不能重复。") + for asset_id in ids: + _string(asset_id, 64) + if (p["width"], p["height"]) not in {(1280, 704), (704, 1280), (1024, 1024)}: + raise _invalid("参考图仅支持1280×704、704×1280或1024×1024。") + _int(p["num_inference_steps"], 1, 100) + _int(p["seed"], 0, 2**32 - 1) + _int(p["max_sequence_length"], 1, 1024) + _float(p["guidance_scale"], 1, 20) + _float(p["true_cfg_scale"], 1, 20) + return + if task_type in GPU_TASKS: + allowed = ( + {"audio_asset_id", "asset_id"} + if task_type == "audio.transcribe" + else {"prompt", "negative_prompt"} + ) + if task_type in {"video.generate", "defect.generate"}: + allowed.add("image_asset_id") + _keys(inputs, allowed) + defaults = next( + item["defaults"] for item in capabilities(settings) if item["task_type"] == task_type + ) + _keys( + p, set(defaults) | ({"negative_prompt"} if task_type != "audio.transcribe" else set()) + ) + p = {**defaults, **p} + if task_type == "audio.transcribe": + if not (inputs.get("audio_asset_id") or inputs.get("asset_id")): + raise _invalid("请选择转写素材。") + if ( + inputs.get("audio_asset_id") + and inputs.get("asset_id") + and inputs["audio_asset_id"] != inputs["asset_id"] + ): + raise _invalid("请仅选择一个转写素材。") + if p["language"] not in LANGUAGES: + raise _invalid("不支持此转写语言。") + _int(p["max_audio_seconds"], 1, 1800) + return + _string(inputs.get("prompt")) + _string(inputs.get("negative_prompt", ""), required=False) + if "negative_prompt" in p: + _string(p["negative_prompt"], required=False) + video = task_type == "video.generate" + for key in ("width", "height"): + _int(p[key], 256, 1280 if video else 2048, 32 if video else 16) + if p["width"] * p["height"] > (1280 * 704 if video else 2048 * 2048): + raise _invalid("画面像素总数超出服务限制。") + _int(p["num_inference_steps"], 1, 100) + _int(p["seed"], 0, 2**32 - 1) + _float(p["guidance_scale"], 1, 20) + if task_type == "defect.generate": + if not inputs.get("image_asset_id"): + raise _invalid("条件样本任务需要参考图片。") + _float(p["controlnet_conditioning_scale"], 0, 2) + _int(p["canny_low"], 0, 255) + _int(p["canny_high"], 0, 255) + if p["canny_low"] >= p["canny_high"]: + raise _invalid("Canny低阈值必须小于高阈值。") + if video: + _int(p["num_frames"], 5, 361) + if ( + p["num_frames"] % 4 != 1 + or type(p["fps"]) is not int + or p["fps"] != 24 + or type(p["upscale"]) is not bool + ): + raise _invalid("视频帧数、帧率或增强开关无效。") + _int(p["upscale_width"], 256, 3840, 2) + _int(p["upscale_height"], 256, 2160, 2) + _int(p["tile_size"], 64, 256, 16) + return + if task_type == "math.solve": + _keys(inputs, {"prompt"}) + _keys(p, {"max_tokens", "enable_thinking"}) + _string(inputs.get("prompt")) + _int(p.get("max_tokens", 2048), 1, 4096) + if type(p.get("enable_thinking", False)) is not bool: + raise _invalid("思考开关必须为布尔值。") + return + if task_type == "media.structure": + _keys(inputs, {"asset_id", "image_asset_id"}) + _keys(p, {"frame_count"}) + if not (inputs.get("asset_id") or inputs.get("image_asset_id")): + raise _invalid("请选择待理解素材。") + if ( + inputs.get("asset_id") + and inputs.get("image_asset_id") + and inputs["asset_id"] != inputs["image_asset_id"] + ): + raise _invalid("请选择一个待理解素材。") + _int(p.get("frame_count", 6), 1, 12) + return + if task_type == "audio.speech": + _keys(inputs, {"prompt"}) + _keys(p, {"voice", "speed", "model"}) + if p.get("model", getattr(settings, "tts_model", "")) != getattr(settings, "tts_model", ""): + raise ProviderError("capability_changed", "配音模型配置已变化,请重新生成执行计划") + _string(inputs.get("prompt"), 2000) + voices = _voices(settings) + if not voices or p.get("voice", voices[0]) not in voices: + raise _invalid("请选择已配置的中文音色。") + _float(p.get("speed", 1), 0.5, 2) + return + if task_type == "video.compose": + if "story_spec" in p: + from app.domain.stories import compile_story_render + + _keys(inputs, {"asset_ids", "audio_asset_id"}) + _keys(p, {"story_spec", "render_inputs", "clips"}) + try: + plan = compile_story_render(p["story_spec"], p["render_inputs"]) + except (ValueError, KeyError, TypeError): + raise _invalid("Invalid frozen story timeline.") from None + if inputs.get("asset_ids") != [c["asset_id"] for c in plan.clips] or p.get("clips") != [ + {"asset_id": c["asset_id"]} for c in plan.clips + ]: + raise _invalid("Story clip order differs.") + audio = plan.spec["render"]["audio"] + if inputs.get("audio_asset_id") != (audio["asset_id"] if audio else None): + raise _invalid("Story audio differs.") + return + if "workflow_spec" in p: + from app.domain.timeline import WorkflowSpec + + _keys(inputs, {"asset_ids", "audio_asset_id"}) + _keys(p, {"workflow_spec", "clips"}) + try: + spec = WorkflowSpec.model_validate(p["workflow_spec"]) + except ValueError: + raise _invalid("Invalid frozen workflow timeline.") from None + clips = p.get("clips") + if not isinstance(clips, list) or len(clips) != len(spec.shots): + raise _invalid("Workflow clips must match the frozen shot count.") + for clip in clips: + _keys(clip, {"asset_id"}) + _string(clip.get("asset_id"), 64) + if inputs.get("asset_ids") != [c["asset_id"] for c in clips]: + raise _invalid("Workflow clip order differs.") + if inputs.get("audio_asset_id") != ( + spec.render.audio.asset_id if spec.render.audio else None + ): + raise _invalid("Workflow audio differs.") + return + _keys(inputs, {"asset_ids", "audio_asset_id"}) + _keys(p, {"clips", "audio_asset_id", "subtitles", "width", "height", "fps"}) + clips = p.get("clips") + if not isinstance(clips, list) or not 1 <= len(clips) <= 1000: + raise _invalid("请选择1至1000个视频片段,并遵守当前配置的资源上限。") + for clip in clips: + _keys(clip, {"asset_id", "start_seconds", "end_seconds"}) + _string(clip.get("asset_id"), 64) + start = _float(clip.get("start_seconds", 0), 0, 86400) + if ( + clip.get("end_seconds") is not None + and _float(clip["end_seconds"], 0, 86400) <= start + ): + raise _invalid("片段结束时间必须大于开始时间。") + if "asset_ids" in inputs and inputs["asset_ids"] != [clip["asset_id"] for clip in clips]: + raise _invalid("素材顺序应与编排片段一致。") + if ( + inputs.get("audio_asset_id") + and p.get("audio_asset_id") + and inputs["audio_asset_id"] != p["audio_asset_id"] + ): + raise _invalid("请只选择一个成片音轨。") + _int(p.get("width", 1280), 256, 3840, 2) + _int(p.get("height", 720), 256, 2160, 2) + if type(p.get("fps", 24)) is not int or p.get("fps", 24) not in {24, 25, 30, 60}: + raise _invalid("不支持此成片帧率。") + cues = p.get("subtitles", []) + if not isinstance(cues, list) or len(cues) > 1000: + raise _invalid("人工字幕数量超出限制。") + for cue in cues: + _keys(cue, {"start", "end", "text"}) + start, end = ( + _float(cue.get("start"), 0, 86400 * 1000), + _float(cue.get("end"), 0, 86400 * 1000), + ) + text = _string(cue.get("text"), 2000) + if end <= start or "\n\n" in text or re.search(r"[\\{}\x00-\x08\x0b-\x1f]", text): + raise _invalid("字幕时间或纯文本内容无效;不支持ASS控制语法。") + return + raise _invalid("不支持此任务类型。") diff --git a/backend/app/adapters/provider/cpu.py b/backend/app/adapters/provider/cpu.py new file mode 100644 index 0000000..c3249de --- /dev/null +++ b/backend/app/adapters/provider/cpu.py @@ -0,0 +1,121 @@ +"""CPU 与共享 HTTP 任务入口和资源阶段切换。""" + +from __future__ import annotations + +import os +import uuid + +from PIL import Image, ImageOps, UnidentifiedImageError + +from app.domain.execution import CpuResult, enter_phase +from app.adapters.storage import file_thread +from app.domain.errors import MediaError as ProviderError +from .contracts import _invalid, _keys, _int, _string +from .contracts import validate_arguments + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +async def run_cpu(provider: Provider, task_type, inputs, parameters, assets, work_dir): + work = provider._work(work_dir) + validate_arguments(task_type, inputs, parameters, provider.settings) + try: + if task_type == "image.prepare_frame": + await enter_phase("prepare_frame", "cpu_media") + source = provider._asset(inputs["image_asset_id"], assets) + width, height = parameters.get("width", 1280), parameters.get("height", 704) + fit = parameters.get("fit", "contain") + target = work / ("frame-" + uuid.uuid4().hex + ".png") + + def normalize(): + temporary = target.with_suffix(".tmp.png") + try: + with Image.open(source) as original: + original.load() + image = ImageOps.exif_transpose(original).convert("RGBA") + background = Image.new("RGBA", image.size, (0, 0, 0, 255)) + background.alpha_composite(image) + image = background.convert("RGB") + if fit == "cover": + image = ImageOps.fit( + image, (width, height), method=Image.Resampling.LANCZOS + ) + else: + image = ImageOps.pad( + image, + (width, height), + method=Image.Resampling.LANCZOS, + color="black", + ) + image.save(temporary, format="PNG") + os.replace(temporary, target) + except (UnidentifiedImageError, Image.DecompressionBombError, ValueError): + raise _invalid("首帧素材必须是可解码的安全图片。") from None + finally: + temporary.unlink(missing_ok=True) + + await file_thread(normalize) + details = { + "width": width, + "height": height, + "fit": fit, + "image_asset_id": inputs["image_asset_id"], + } + return CpuResult( + [target], details, {"provider": "pillow", "stage": "prepare_frame", **details} + ) + if task_type == "math.solve": + await enter_phase("solve", "qwen_http") + _keys(inputs, {"prompt"}) + _keys(parameters, {"max_tokens", "enable_thinking"}) + tokens = _int(parameters.get("max_tokens", 2048), 1, 4096) + thinking = parameters.get("enable_thinking", False) + if type(thinking) is not bool: + raise _invalid("思考开关必须为布尔值。") + text = await provider._chat( + [ + { + "role": "system", + "content": "请给出可复核的数学解题步骤和最终答案;不确定时明确说明。", + }, + {"role": "user", "content": _string(inputs.get("prompt"))}, + ], + max_tokens=tokens, + thinking=thinking, + ) + answer = work / "answer.txt" + answer.write_text(text + "\n", encoding="utf-8") + result = {"text": text} + return CpuResult( + [answer, provider._json_file(work, "answer.json", result)], + result, + { + "provider": "qwen", + "model": provider.settings.qwen_model, + "formal_verification": False, + }, + ) + if task_type == "media.structure": + return await provider._structure(inputs, parameters, assets, work) + if task_type == "text.script.generate": + from .editor_media import script + + await enter_phase("script", "qwen_http") + return await script(provider, inputs, parameters, work) + if task_type == "audio.assemble": + from .editor_media import assemble + + await enter_phase("assemble", "cpu_media") + return await assemble(provider, inputs, parameters, assets, work) + if task_type == "video.compose": + await enter_phase("compose", "cpu_media") + return await provider._compose(inputs, parameters, assets, work) + if task_type == "audio.speech": + await enter_phase("speech", "cpu_media") + return await provider._speech(inputs, parameters, work) + raise _invalid("不支持此CPU任务类型。") + except OSError: + raise ProviderError("output_unavailable", "任务文件处理失败。", True) from None diff --git a/backend/app/adapters/provider/editor_media.py b/backend/app/adapters/provider/editor_media.py new file mode 100644 index 0000000..08c26e8 --- /dev/null +++ b/backend/app/adapters/provider/editor_media.py @@ -0,0 +1,210 @@ +"""自动文案和单音轨装配;模型只通过已有Qwen HTTP边界调用。""" + +from __future__ import annotations + +import json +import os +import re +import uuid +import wave + +from app.adapters.media import input_options, run_process +from app.adapters.storage import file_thread +from app.domain.execution import CpuResult +from app.domain.errors import MediaError +from app.domain.timeline import Subtitle +from .contracts import _invalid, _int, _keys, _string + + +def validate(task_type, inputs, parameters): + if task_type == "text.script.generate": + _keys(inputs, {"shots", "context"}) + _keys(parameters, {"model"}) + if "model" in parameters: + _string(parameters["model"], 256) + shots = inputs.get("shots") + if not isinstance(shots, list) or not 1 <= len(shots) <= 1000: + raise _invalid("文案需要1–1000个镜头") + ids = [] + for shot in shots: + _keys(shot, {"shot_id", "name", "visual_prompt", "motion_prompt", "duration_frames"}) + sid = shot.get("shot_id") + if not isinstance(sid, str) or not re.fullmatch("[a-f0-9]{32}", sid): + raise _invalid("镜头ID无效") + ids.append(sid) + for field in ("name", "visual_prompt", "motion_prompt"): + _string(shot.get(field, ""), 8000, required=False) + _int(shot.get("duration_frames", 120), 24, 360) + if len(ids) != len(set(ids)): + raise _invalid("文案镜头ID不能重复") + if "context" in inputs and not isinstance(inputs["context"], dict): + raise _invalid("故事设定无效") + if len(json.dumps(inputs, ensure_ascii=False)) > 200000: + raise _invalid("文案输入过长,请减少镜头或描述") + elif task_type == "audio.assemble": + _keys(inputs, {"segments", "total_frames"}) + _keys(parameters, {"fps"}) + if parameters.get("fps", 24) != 24: + raise _invalid("音轨装配仅支持24fps") + _int(inputs.get("total_frames"), 1, 360000) + segments = inputs.get("segments") + if not isinstance(segments, list) or not 1 <= len(segments) <= 1000: + raise _invalid("音轨需要1–1000个片段") + for segment in segments: + _keys(segment, {"asset_id", "offset_frame"}) + asset_id = _string(segment.get("asset_id"), 64) + if not re.fullmatch("[A-Za-z0-9_.-]+", asset_id): + raise _invalid("音轨只接受素材编号") + _int(segment.get("offset_frame"), 0, inputs["total_frames"] - 1) + + +async def script(provider, inputs, parameters, work): + validate("text.script.generate", inputs, parameters) + if parameters.get("model", provider.settings.qwen_model) != provider.settings.qwen_model: + raise MediaError("capability_changed", "文案模型配置已变化,请重新生成执行计划") + # 大故事按有界小组调用,避免一次输出截断;已返回组只有在整个步骤成功后发布。 + segments = [] + for index in range(0, len(inputs["shots"]), 8): + shots = inputs["shots"][index : index + 8] + content = await provider._chat( + [ + { + "role": "system", + "content": '根据故事和镜头生成简短中文旁白。只返回JSON对象,格式为{"segments":[{"shot_id":"原ID","text":"旁白"}]}。每镜头恰好一条,ID原样返回。旁白字数必须适合给定duration_frames/24秒,建议每秒不超过3个汉字。不要把运镜、参数或提示词写入旁白,不要输出Markdown。', + }, + { + "role": "user", + "content": json.dumps( + {"context": inputs.get("context", {}), "shots": shots}, ensure_ascii=False + ), + }, + ], + max_tokens=4096, + thinking=False, + ) + try: + text = content.strip() + if text.startswith("```"): + text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text) + value = json.loads(text) + _keys(value, {"segments"}) + rows = value["segments"] + if not isinstance(rows, list) or len(rows) != len(shots): + raise ValueError + by_id = {} + for row in rows: + _keys(row, {"shot_id", "text"}) + if row["shot_id"] in by_id: + raise ValueError + Subtitle(start_frame=0, end_frame=24, text=row["text"]) + if len(row["text"]) > 2000: + raise ValueError + by_id[row["shot_id"]] = row + if set(by_id) != {s["shot_id"] for s in shots}: + raise ValueError + segments.extend(by_id[s["shot_id"]] for s in shots) + except (ValueError, TypeError, KeyError, MediaError) as exc: + raise MediaError( + "invalid_script", "文案服务返回了无效、缺失或不匹配的镜头内容" + ) from exc + result = {"segments": segments} + path = provider._json_file(work, "script.json", result) + return CpuResult( + [path], + result, + {"provider": "qwen", "model": provider.settings.qwen_model, "recipe": "shot-script-v1"}, + ) + + +async def assemble(provider, inputs, parameters, assets, work): + validate("audio.assemble", inputs, parameters) + total_samples = inputs["total_frames"] * 2000 + if total_samples * 4 + 44 > provider.settings.max_output_bytes: + raise MediaError("output_too_large", "装配音轨超出输出大小限制") + normalized, positions = [], [] + target = work / ("narration-" + uuid.uuid4().hex + ".wav") + temporary = target.with_suffix(".part.wav") + try: + for segment in sorted(inputs["segments"], key=lambda s: s["offset_frame"]): + source = provider._asset(segment["asset_id"], assets) + start = segment["offset_frame"] * 2000 + path = work / ("segment-" + uuid.uuid4().hex + ".wav") + normalized.append(path) + await run_process( + [ + provider.settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + *input_options(), + "-i", + str(source), + "-vn", + "-t", + str((total_samples - start + 2000) / 48000), + "-ar", + "48000", + "-ac", + "2", + "-c:a", + "pcm_s16le", + "-y", + str(path), + ], + timeout=300, + ) + with wave.open(str(path), "rb") as audio: + count = audio.getnframes() + if ( + count <= 0 + or start + count > total_samples + or (positions and start < positions[-1]["end_sample"]) + ): + raise MediaError("invalid_timeline", "配音片段重叠或超出成片,原音频已保留") + positions.append( + { + **segment, + "start_sample": start, + "end_sample": start + count, + "sample_count": count, + } + ) + + def write_track(): + cursor = 0 + silence = bytes(65536) + with wave.open(str(temporary), "wb") as output: + output.setparams((2, 2, 48000, 0, "NONE", "not compressed")) + + def pad(count): + remaining = count * 4 + while remaining: + chunk = silence[: min(remaining, len(silence))] + output.writeframesraw(chunk) + remaining -= len(chunk) + + for path, position in zip(normalized, positions, strict=True): + pad(position["start_sample"] - cursor) + with wave.open(str(path), "rb") as source: + while chunk := source.readframes(16384): + output.writeframesraw(chunk) + cursor = position["end_sample"] + pad(total_samples - cursor) + os.replace(temporary, target) + + await file_thread(write_track) + result = { + "segments": positions, + "sample_rate": 48000, + "sample_count": total_samples, + "total_frames": inputs["total_frames"], + } + return CpuResult( + [target, provider._json_file(work, "narration.json", result)], + result, + {"provider": "ffmpeg-cpu", "recipe": "narration-assemble-v1"}, + ) + finally: + temporary.unlink(missing_ok=True) + for path in normalized: + path.unlink(missing_ok=True) diff --git a/backend/app/adapters/provider/files.py b/backend/app/adapters/provider/files.py new file mode 100644 index 0000000..b61d1ee --- /dev/null +++ b/backend/app/adapters/provider/files.py @@ -0,0 +1,227 @@ +"""受限工作目录与远程输入输出字节校验。""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +from pathlib import PurePosixPath +import stat +import uuid + +import httpx + +from app.adapters.media import confined +from app.domain.errors import MediaError as ProviderError +from .contracts import _invalid, _int +from .transport import _url + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +_REMOTE_INPUT_SUFFIXES = { + ".png", + ".jpg", + ".jpeg", + ".webp", + ".bmp", + ".wav", + ".mp3", + ".flac", + ".m4a", + ".ogg", + ".aac", + ".mp4", + ".webm", + ".mov", +} +_REMOTE_INPUT_LIMIT = 512 * 1024 * 1024 + + +def _work(provider: Provider, path): + work = confined(path, provider.settings, exists=False, root=provider.settings.job_work_root) + if not work.is_dir(): + raise _invalid("任务工作目录不可用。") + return work + + +def _asset(provider: Provider, asset_id, assets): + # assets 由上游按用户权限解析;这里只接受映射内 ID,不能把输入当作路径。 + if not isinstance(asset_id, str) or asset_id not in assets: + raise _invalid("请选择可访问的素材。") + return confined(assets[asset_id], provider.settings) + + +async def _upload_input(provider: Provider, source): + source = confined(source, provider.settings) + suffix = source.suffix.lower() + if suffix == ".jfif": + # 参考图已按内容解码校验;JFIF使用JPEG编码,远端沿用标准.jpg名称。 + # 只规范传输文件名,原素材字节、摘要和本地存储位置保持不变。 + suffix = ".jpg" + if suffix not in _REMOTE_INPUT_SUFFIXES: + raise _invalid("模型输入文件类型不受支持。") + limit = min( + _REMOTE_INPUT_LIMIT, + int(getattr(provider.settings, "max_upload_bytes", _REMOTE_INPUT_LIMIT)), + ) + try: + with source.open("rb") as stream: + # 同一描述符完成摘要与上传,回执必须匹配字节数、摘要和目标名。 + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size <= 0: + raise _invalid("模型输入文件为空或不可读取。") + if info.st_size > limit: + raise ProviderError("input_too_large", "模型输入文件超出大小限制。") + digest, size = hashlib.sha256(), 0 + while chunk := await asyncio.to_thread(stream.read, 1024 * 1024): + size += len(chunk) + if size > limit or size > info.st_size: + raise ProviderError("input_too_large", "模型输入文件超出大小限制。") + digest.update(chunk) + if size != info.st_size: + raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True) + digest = digest.hexdigest() + name = digest + suffix + stream.seek(0) + + async def chunks(): + count = 0 + while data := await asyncio.to_thread(stream.read, 1024 * 1024): + count += len(data) + if count > size: + raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True) + yield data + if count != size: + raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True) + + headers = { + **provider._headers(), + "Content-Type": "application/octet-stream", + "Content-Length": str(size), + } + async with asyncio.timeout( + max(30, min(600, float(provider.settings.request_timeout_seconds) * 4)) + ): + async with provider.client.stream( + "POST", + _url(provider.settings.inference_base_url, "/inputs/" + name), + headers=headers, + content=chunks(), + ) as response: + if not 200 <= response.status_code < 300: + raise provider._http_error(response.status_code) + parts, count = [], 0 + async for chunk in response.aiter_bytes(): + count += len(chunk) + if count > 16384: + raise ValueError + parts.append(chunk) + receipt = json.loads(b"".join(parts)) + path = receipt["path"] + candidate = PurePosixPath(path) + if ( + not isinstance(path, str) + or not path.startswith("/") + or path.startswith("//") + or "\\" in path + or ":" in path + or "\x00" in path + or not candidate.is_absolute() + or str(candidate) != path + or any(part in {".", ".."} for part in candidate.parts) + or candidate.name != name + or candidate.parent.parts[-2:] != ("inputs", "llm-services") + or receipt["sha256"] != digest + or type(receipt["size_bytes"]) is not int + or receipt["size_bytes"] != size + ): + raise ValueError + return path + except (httpx.HTTPError, asyncio.TimeoutError): + raise ProviderError( + "upstream_unavailable", "模型输入文件传输失败,请稍后重试。", True + ) from None + except OSError: + raise ProviderError("invalid_asset", "模型输入文件不存在或不可读取。", True) from None + except (ValueError, TypeError, KeyError, UnicodeError, RecursionError): + raise ProviderError( + "invalid_upstream_response", "模型服务返回了无效文件接收结果。", True + ) from None + + +async def _download_url( + provider: Provider, url, destination, headers, *, payload=None, timeout=None, total_timeout=None +): + target = confined(destination, provider.settings, exists=False) + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_name(target.name + ".part-" + uuid.uuid4().hex) + try: + async with asyncio.timeout( + total_timeout + if total_timeout is not None + else max(30, min(600, float(provider.settings.request_timeout_seconds) * 4)) + ): + options = {} if timeout is None else {"timeout": timeout} + async with provider.client.stream( + "POST" if payload is not None else "GET", + url, + headers=headers, + json=payload, + **options, + ) as response: + if not 200 <= response.status_code < 300: + raise provider._http_error(response.status_code) + limit = int(provider.settings.max_output_bytes) + declared = response.headers.get("Content-Length") + if declared is not None and (not declared.isdigit() or int(declared) > limit): + raise ProviderError("output_too_large", "输出文件超出大小限制。") + count = 0 + with temporary.open("xb") as stream: + async for chunk in response.aiter_bytes(): + count += len(chunk) + if count > limit: + raise ProviderError("output_too_large", "输出文件超出大小限制。") + stream.write(chunk) + if not count or (declared is not None and count != int(declared)): + raise ProviderError( + "invalid_upstream_response", "输出文件为空或未传输完整。", True + ) + os.replace(temporary, target) + except (httpx.HTTPError, asyncio.TimeoutError): + raise ProviderError( + "upstream_unavailable", "输出文件传输失败,请稍后重试。", True + ) from None + except OSError: + raise ProviderError("output_unavailable", "无法保存输出文件。", True) from None + finally: + temporary.unlink(missing_ok=True) + + +async def download(provider: Provider, upstream_id, index, destination): + _int(index, 0, 1000) + await provider._download_url( + _url( + provider.settings.inference_base_url, + "/jobs/" + provider._job_id(upstream_id) + "/outputs/" + str(index), + ), + destination, + provider._headers(), + ) + + +def _json_file(work, name, value): + target = work / name + temporary = work / (name + ".part-" + uuid.uuid4().hex) + try: + temporary.write_text( + json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding="utf-8" + ) + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + return target diff --git a/backend/app/adapters/provider/gpu.py b/backend/app/adapters/provider/gpu.py new file mode 100644 index 0000000..3af9a56 --- /dev/null +++ b/backend/app/adapters/provider/gpu.py @@ -0,0 +1,292 @@ +"""GPU 任务准备、幂等提交与远端控制。""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import time +import uuid + +from app.adapters.media import input_options, inspect_media, run_process +from app.domain.execution import enter_phase +from app.domain.errors import MediaError as ProviderError +from .contracts import _invalid, _keys, _int, _float, _string +from .contracts import GPU_TASKS, LANGUAGES, capabilities, validate_arguments +from .transport import _url + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +async def prepare_gpu_payload( + provider: Provider, task_type, inputs, parameters, assets, work_dir, *, analysis_binding=None +): + validate_arguments(task_type, inputs, parameters, provider.settings) + work = provider._work(work_dir) + if task_type not in GPU_TASKS: + raise _invalid("不支持此模型任务类型。") + if task_type in {"video.people.analyze", "video.replace"}: + from .video_editing import prepare_video + + return await prepare_video( + provider, task_type, inputs, parameters, assets, analysis_binding + ) + if task_type == "image.reference.generate": + defaults = next( + item["defaults"] + for item in capabilities(provider.settings) + if item["task_type"] == task_type + ) + upstream = (await provider.upstream_capabilities()).get("reference_generation", {}) + maximum = upstream.get("max_reference_images") + if ( + upstream.get("available") is not True + or upstream.get("profile") != defaults["profile"] + or type(maximum) is not int + or maximum < 1 + ): + raise ProviderError("capability_unavailable", "上游多图生成尚未认证或模型版本不匹配。") + if len(inputs["reference_asset_ids"]) > maximum: + raise _invalid("参考图片数量超出上游已认证范围。") + # 先逐张解码确认全部可用,再上传;不能在中途缺图时退回文生图。 + paths = [] + for asset_id in inputs["reference_asset_ids"]: + source = provider._asset(asset_id, assets) + if (await inspect_media(source, provider.settings))["kind"] != "image": + raise _invalid("全部参考素材必须是有效图片。") + paths.append(str(source)) + if getattr(provider.settings, "inference_remote_files", False): + paths = [await provider._upload_input(Path(path)) for path in paths] + return { + "task_type": task_type, + "input": { + "prompt": inputs["prompt"], + "negative_prompt": inputs.get("negative_prompt", ""), + "image_paths": paths, + }, + "parameters": {**defaults, **parameters}, + "timeout_seconds": 3600, + } + p = dict(parameters) if isinstance(parameters, dict) else parameters + allowed_input = ( + {"audio_asset_id", "asset_id"} + if task_type == "audio.transcribe" + else {"prompt", "negative_prompt"} + ) + if task_type in {"video.generate", "defect.generate"}: + allowed_input.add("image_asset_id") + _keys(inputs, allowed_input) + defaults = next( + item["defaults"] + for item in capabilities(provider.settings) + if item["task_type"] == task_type + ) + _keys(p, set(defaults) | ({"negative_prompt"} if task_type != "audio.transcribe" else set())) + normalized = {**defaults, **p} + out = {} + if task_type == "audio.transcribe": + asset_id = inputs.get("audio_asset_id") or inputs.get("asset_id") + if ( + inputs.get("audio_asset_id") + and inputs.get("asset_id") + and inputs["audio_asset_id"] != inputs["asset_id"] + ): + raise _invalid("请仅选择一个转写素材。") + source = provider._asset(asset_id, assets) + info = await inspect_media(source, provider.settings) + if normalized["language"] not in LANGUAGES: + raise _invalid("不支持此转写语言。") + _int(normalized["max_audio_seconds"], 1, 1800) + if ( + info["kind"] not in {"audio", "video"} + or info["duration_seconds"] > normalized["max_audio_seconds"] + ): + raise _invalid("请选择时长受限的音频或有声视频。") + if info["kind"] == "video": + await enter_phase("extract_audio", "cpu_media") + target = work / "asr-input.wav" + temporary = work / ("asr-" + uuid.uuid4().hex + ".wav") + try: + await run_process( + [ + provider.settings.ffmpeg_bin, + "-v", + "error", + "-nostdin", + *input_options(), + "-i", + str(source), + "-map", + "0:a:0", + "-vn", + "-ac", + "1", + "-ar", + "16000", + "-c:a", + "pcm_s16le", + "-t", + str(normalized["max_audio_seconds"]), + "-threads", + "2", + str(temporary), + ], + timeout=300, + ) + if not temporary.is_file() or not temporary.stat().st_size: + raise _invalid("视频没有可转写的音轨。") + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + source = target + await enter_phase("transcribe", "new_gpu") + out["audio_path"] = str(source) + else: + out["prompt"] = _string(inputs.get("prompt")) + out["negative_prompt"] = _string( + normalized.pop("negative_prompt", inputs.get("negative_prompt", "")), required=False + ) + video = task_type == "video.generate" + for key in ("width", "height"): + _int(normalized[key], 256, 1280 if video else 2048, 32 if video else 16) + if normalized["width"] * normalized["height"] > (1280 * 704 if video else 2048 * 2048): + raise _invalid("画面像素总数超出服务限制。") + _int(normalized["num_inference_steps"], 1, 100) + _int(normalized["seed"], 0, 2**32 - 1) + normalized["guidance_scale"] = _float(normalized["guidance_scale"], 1, 20) + if "image_asset_id" in inputs: + source = provider._asset(inputs["image_asset_id"], assets) + if (await inspect_media(source, provider.settings))["kind"] != "image": + raise _invalid("参考素材必须是图片。") + out["image_path"] = str(source) + if task_type == "defect.generate": + if "image_path" not in out: + raise _invalid("条件样本任务需要参考图片。") + normalized["controlnet_conditioning_scale"] = _float( + normalized["controlnet_conditioning_scale"], 0, 2 + ) + _int(normalized["canny_low"], 0, 255) + _int(normalized["canny_high"], 0, 255) + if normalized["canny_low"] >= normalized["canny_high"]: + raise _invalid("Canny低阈值必须小于高阈值。") + if video: + _int(normalized["num_frames"], 5, 361) + if ( + normalized["num_frames"] % 4 != 1 + or type(normalized["fps"]) is not int + or normalized["fps"] != 24 + ): + raise _invalid("视频仅支持4n+1帧、最多361帧和24fps。") + if type(normalized["upscale"]) is not bool: + raise _invalid("增强开关必须为布尔值。") + _int(normalized["upscale_width"], 256, 3840, 2) + _int(normalized["upscale_height"], 256, 2160, 2) + _int(normalized["tile_size"], 64, 256, 16) + if getattr(provider.settings, "inference_remote_files", False): + for key in ("image_path", "audio_path"): + if key in out: + out[key] = await provider._upload_input(Path(out[key])) + return {"task_type": task_type, "input": out, "parameters": normalized, "timeout_seconds": 3600} + + +async def submit(provider: Provider, payload, idempotency_key): + # 响应丢失后的恢复必须使用相同请求体与幂等键,不能隐式创建第二个模型任务。 + _string(idempotency_key, 128) + if any(not 33 <= ord(char) <= 126 for char in idempotency_key): + raise _invalid("幂等请求标识无效。") + return provider._sanitize_job( + await provider._json( + "POST", + _url(provider.settings.inference_base_url, "/jobs"), + payload=payload, + headers={**provider._headers(), "Idempotency-Key": idempotency_key}, + ) + ) + + +def _job_id(value): + if not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{32}", value) is None: + raise _invalid("模型任务标识无效。") + return value + + +def _sanitize_job(value): + if value.get("error"): + value["error"] = "模型任务执行失败,请检查任务输入或联系管理员。" + if value.get("last_preempted_reason"): + value["last_preempted_reason"] = "GPU资源已让出,任务重新排队。" + return value + + +async def query(provider: Provider, upstream_id): + return provider._sanitize_job( + await provider._json( + "GET", + _url(provider.settings.inference_base_url, "/jobs/" + provider._job_id(upstream_id)), + headers=provider._headers(), + ) + ) + + +async def upstream_capabilities(provider: Provider): + cached = getattr(provider, "_capabilities_cache", None) + if cached and time.monotonic() - cached[0] < 30: + return json.loads(json.dumps(cached[1])) + value = await provider._json( + "GET", + _url(provider.settings.inference_base_url, "/capabilities"), + headers=provider._headers(), + ) + features = value.get("features", {}) + value["admission_policy"] = bool( + value.get("admission_policy") + or (features.get("scheduling") and features.get("admission_pause")) + ) + provider._capabilities_cache = (time.monotonic(), value) + return json.loads(json.dumps(value)) + + +async def control( + provider: Provider, + upstream_id, + desired_state, + command_id, + expected_version=None, + expected_execution_id=None, +): + if desired_state not in {"run", "pause", "cancel"}: + raise _invalid("Invalid control intention.") + _string(command_id, 128) + payload = {"desired_state": desired_state, "command_id": command_id} + if expected_version is not None: + payload["expected_version"] = _int(expected_version, 0, 2**63 - 1) + if expected_execution_id is not None: + payload["expected_execution_id"] = _string(expected_execution_id, 64) + return provider._sanitize_job( + await provider._json( + "PUT", + _url( + provider.settings.inference_base_url, + "/jobs/" + provider._job_id(upstream_id) + "/control", + ), + payload=payload, + headers=provider._headers(), + ) + ) + + +async def cancel(provider: Provider, upstream_id): + return provider._sanitize_job( + await provider._json( + "POST", + _url( + provider.settings.inference_base_url, + "/jobs/" + provider._job_id(upstream_id) + "/cancel", + ), + headers=provider._headers(), + ) + ) diff --git a/backend/app/adapters/provider/qwen.py b/backend/app/adapters/provider/qwen.py new file mode 100644 index 0000000..8e34cfe --- /dev/null +++ b/backend/app/adapters/provider/qwen.py @@ -0,0 +1,199 @@ +"""共享 Qwen 的文本、图片与视频抽帧理解适配。""" + +from __future__ import annotations + +import asyncio +import base64 +from io import BytesIO +import json +import math +import re + +from PIL import Image, ImageOps + +from app.adapters.media import input_options, inspect_media, run_process +from app.domain.execution import CpuResult, enter_phase +from app.domain.errors import MediaError as ProviderError +from .contracts import _invalid, _keys, _int, _string +from .transport import _url + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +async def _chat(provider: Provider, messages, *, max_tokens=2048, thinking=False): + # 取消只影响当前等待;常驻网关负责并发引用计数、排空和模型释放。 + if not provider.settings.qwen_model: + raise ProviderError("capability_unavailable", "文本与视觉服务尚未配置。") + value = await provider._json( + "POST", + _url(provider.settings.qwen_base_url, "/chat/completions"), + headers=provider._headers("qwen"), + timeout=getattr(provider.settings, "qwen_timeout_seconds", 1800.0), + payload={ + "model": provider.settings.qwen_model, + "messages": messages, + "stream": False, + "temperature": 0, + "max_tokens": max_tokens, + "chat_template_kwargs": {"enable_thinking": thinking}, + }, + ) + choices = value.get("choices") + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + raise ProviderError( + "output_truncated", + "模型输出达到长度上限,内容不完整;请提高输出长度或简化要求后重新提交。", + ) + try: + content = value["choices"][0]["message"]["content"] + if isinstance(content, list): + content = "".join(part["text"] for part in content if part.get("type") == "text") + content = _string(content, 200_000) + inline = re.fullmatch(r"\s*.*?\s*(.*)", content, flags=re.DOTALL) + if inline: + content = inline.group(1).strip() + if not content: + raise ValueError + return content + except (ValueError, TypeError, KeyError, IndexError, AttributeError, ProviderError): + raise ProviderError( + "invalid_upstream_response", "文本服务没有返回有效内容。", True + ) from None + + +async def _image_uri(provider: Provider, source): + def encode(): + with Image.open(source) as image: + image = ImageOps.exif_transpose(image).convert("RGB") + image.thumbnail((1280, 1280)) + buffer = BytesIO() + image.save(buffer, format="JPEG", quality=85) + return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode("ascii") + + return await asyncio.to_thread(encode) + + +async def _structure(provider: Provider, inputs, p, assets, work): + _keys(inputs, {"asset_id", "image_asset_id"}) + _keys(p, {"frame_count"}) + asset_id = inputs.get("asset_id") or inputs.get("image_asset_id") + if ( + inputs.get("asset_id") + and inputs.get("image_asset_id") + and inputs["asset_id"] != inputs["image_asset_id"] + ): + raise _invalid("请选择一个待理解素材。") + count = _int(p.get("frame_count", 6), 1, 12) + source = provider._asset(asset_id, assets) + info = await inspect_media(source, provider.settings) + if info["kind"] not in {"image", "video"}: + raise _invalid("素材理解支持图片或视频。") + samples, outputs = [(0.0, source)], [] + if info["kind"] == "video": + await enter_phase("sample_frames", "cpu_media") + samples = [] + for index in range(count): + timestamp = (index + 0.5) * info["duration_seconds"] / count + frame = work / f"frame-{index:03d}.jpg" + # 只使用固定滤镜与数值时间,不允许用户输入 FFmpeg 滤镜或协议。 + _, diagnostics = await run_process( + [ + provider.settings.ffmpeg_bin, + "-v", + "info", + "-nostdin", + "-copyts", + *input_options(), + "-ss", + f"{timestamp:.6f}", + "-i", + str(source), + "-frames:v", + "1", + "-vf", + "scale=1280:1280:force_original_aspect_ratio=decrease,showinfo", + "-threads", + "2", + str(frame), + ], + timeout=90, + return_stderr=True, + ) + if not frame.is_file() or not frame.stat().st_size: + raise ProviderError("frame_extraction_failed", "视频抽帧失败。") + actual_pts = re.search(rb"\bpts_time:([+-]?[0-9]+(?:\.[0-9]+)?)", diagnostics) + if actual_pts is None: + raise ProviderError("frame_extraction_failed", "无法确认抽帧的实际时间。") + actual_time = float(actual_pts.group(1)) - info.get("start_seconds", 0) + if ( + not math.isfinite(actual_time) + or not -0.1 <= actual_time <= info["duration_seconds"] + 0.1 + ): + raise ProviderError("frame_extraction_failed", "抽帧时间超出素材范围。") + samples.append((max(0, actual_time), frame)) + outputs.append(frame) + frames = [] + prompt = ( + "仅根据画面可见内容输出JSON对象,不要Markdown。字段 subjects 为字符串数组,scene 为字符串," + "ocr 为画面实际可见文字的字符串数组,tags 为字符串数组。看不清请写不确定,不要臆测人物身份。" + ) + for index, (timestamp, frame) in enumerate(samples): + image_uri = await provider._image_uri(frame) + await enter_phase(f"describe_frame_{index}", "qwen_http") + text = await provider._chat( + [ + { + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": image_uri}}, + {"type": "text", "text": prompt}, + ], + } + ] + ) + try: + fenced = re.fullmatch( + r"\s*```(?:json)?\s*(.*?)\s*```\s*", text, flags=re.DOTALL | re.IGNORECASE + ) + value = json.loads(fenced.group(1) if fenced else text) + scene = _string(value["scene"], 2000, required=False) + normalized = {} + for key in ("subjects", "ocr", "tags"): + items = value.get(key, []) if key == "tags" else value[key] + if not isinstance(items, list) or len(items) > 100: + raise ValueError + normalized[key] = list( + dict.fromkeys(_string(item, 2000, required=False) for item in items) + ) + frames.append({"timestamp_seconds": round(timestamp, 6), "scene": scene, **normalized}) + except (ValueError, KeyError, TypeError, AttributeError, ProviderError): + raise ProviderError( + "invalid_visual_response", "视觉服务未返回有效的结构化内容。", True + ) from None + result = { + "subjects": list(dict.fromkeys(item for frame in frames for item in frame["subjects"])), + "scene": ";".join(dict.fromkeys(frame["scene"] for frame in frames)), + "ocr": list(dict.fromkeys(item for frame in frames for item in frame["ocr"])), + "tags": list(dict.fromkeys(item for frame in frames for item in frame["tags"])), + "frames": frames, + } + outputs.append(provider._json_file(work, "structure.json", result)) + return CpuResult( + outputs, + result, + { + "provider": "qwen", + "model": provider.settings.qwen_model, + "sampling": "uniform seek" if info["kind"] == "video" else "single image", + "timestamp_precision": "decoded frame PTS relative to source start", + "frame_count": len(frames), + }, + ) diff --git a/backend/app/adapters/provider/runtime.py b/backend/app/adapters/provider/runtime.py new file mode 100644 index 0000000..6c2e058 --- /dev/null +++ b/backend/app/adapters/provider/runtime.py @@ -0,0 +1,313 @@ +"""运行状态白名单、短缓存与远程调度策略镜像。""" + +from __future__ import annotations + +import asyncio +import json +import os +from pathlib import Path +import re +import time +import uuid + +from app.adapters.media import confined +from app.domain.errors import MediaError as ProviderError +from .contracts import _int, _float +from .transport import _url + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +_UUID = re.compile(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z") + + +async def health(provider: Provider): + try: + value = await provider._json( + "GET", + _url(provider.settings.inference_base_url, "/health"), + headers=provider._headers(), + ) + return value.get("status") == "ok" + except ProviderError: + return False + + +def _runtime_value(value): + """Validate and whitelist operator telemetry before retaining it locally.""" + try: + if type(value["schema_version"]) is not int or value["schema_version"] != 1: + raise ValueError + policy = value["runtime_policy"] + if type(policy["batch_window_enabled"]) is not bool: + raise ValueError + shots = _int(policy["workflow_max_shots"], 1, 1000) + error = policy.get("configuration_error") + if error not in {None, "runtime_policy_invalid", "runtime_policy_unavailable"}: + raise ValueError + policy = { + "batch_window_enabled": policy["batch_window_enabled"], + "workflow_max_shots": shots, + "configuration_error": error, + } + monitor = value["monitor"] + if type(monitor["schema_version"]) is not int or monitor["schema_version"] != 1: + raise ValueError + if monitor.get("error") is not None: + monitor = { + "schema_version": 1, + "generated_at": None, + "error": "gpu_monitor_unavailable", + "gpus": [], + } + else: + now = time.time() + stamp = _float(monitor["generated_at"], 0, now + 1) + entries = monitor["gpus"] + if not isinstance(entries, list) or len(entries) > 1024: + raise ValueError + gpus, seen_indexes, seen_uuids = [], set(), set() + for row in entries: + index, gpu_uuid = _int(row["index"], 0, 1024), row["uuid"] + if ( + not isinstance(gpu_uuid, str) + or not _UUID.fullmatch(gpu_uuid) + or index in seen_indexes + or gpu_uuid.lower() in seen_uuids + ): + raise ValueError + seen_indexes.add(index) + seen_uuids.add(gpu_uuid.lower()) + total = _float(row["total_gib"], 0.001, 100000) + free = _float(row["free_gib"], 0, total) + idle = row.get("idle_since") + if idle is not None: + idle = _float(idle, 0, now + 1) + if type(row["external_busy"]) is not bool or type(row["own_busy"]) is not bool: + raise ValueError + gpus.append( + { + "index": index, + "uuid": gpu_uuid, + "total_gib": total, + "free_gib": free, + "idle_since": idle, + "external_busy": row["external_busy"], + "own_busy": row["own_busy"], + } + ) + monitor = {"schema_version": 1, "generated_at": stamp, "error": None, "gpus": gpus} + scheduler = value.get("scheduler") + if scheduler is not None: + if not isinstance(scheduler, dict): + raise ValueError + if type(scheduler.get("schema_version")) is not int or scheduler[ + "schema_version" + ] not in {1, 2}: + raise ValueError + # 只保留摘要所需的租约与计数,不暴露任务 ID、进程或诊断路径。 + clean = { + key: scheduler[key] + for key in ("schema_version", "updated_at", "state", "queued_count") + if key in scheduler + } + if clean.get("state") not in {"idle", "waiting", "running", "blocked", "leased"}: + raise ValueError + clean["updated_at"] = _float(scheduler["updated_at"], 0, time.time() + 1) + if "queued_count" in clean and clean["queued_count"] is not None: + clean["queued_count"] = _int(clean["queued_count"], 0, 10000000) + clean["reason"] = ( + "memory" if "memory" in str(scheduler.get("reason", "")).lower() else None + ) + if scheduler.get("schema_version") == 2: + rows = scheduler.get("active_jobs", []) + if not isinstance(rows, list) or len(rows) > 1024: + raise ValueError + active = [] + for row in rows: + index, gpu_uuid = _int(row["gpu_index"], 0, 1024), row["gpu_uuid"] + if not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid): + raise ValueError + state, stage = row.get("state"), row.get("stage") + if state not in {"running", "launching", "preempting", "blocked"}: + raise ValueError + stage = ( + stage + if stage + in {"launching", "executing", "cleanup", "model", "upscale", "collecting"} + else None + ) + active.append( + {"gpu_index": index, "gpu_uuid": gpu_uuid, "state": state, "stage": stage} + ) + clean["active_jobs"] = active + elif scheduler.get("state") == "leased": + lease = scheduler.get("lease") or {} + index, gpu_uuid = _int(lease["index"], 0, 1024), lease["uuid"] + if not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid): + raise ValueError + clean["lease"] = {"index": index, "uuid": gpu_uuid} + scheduler = clean + return { + "schema_version": 1, + "monitor": monitor, + "scheduler": scheduler, + "runtime_policy": policy, + } + except (ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError): + raise ProviderError( + "invalid_upstream_response", "模型服务返回了无效运行状态。", True + ) from None + + +async def runtime_status(provider: Provider): + cached = getattr(provider, "_runtime_cache", None) + if cached and time.monotonic() - cached[0] < 1: + return json.loads(json.dumps(cached[1])) + async with provider._runtime_lock: + cached = getattr(provider, "_runtime_cache", None) + if cached and time.monotonic() - cached[0] < 1: + return json.loads(json.dumps(cached[1])) + try: + value = await provider._json( + "GET", + _url(provider.settings.inference_base_url, "/runtime/status"), + headers=provider._headers(), + ) + result = provider._runtime_value(value) + provider._mirror_runtime_policy(result["runtime_policy"]) + observed = time.monotonic() + if getattr(provider.settings, "inference_remote_files", False): + provider.settings._remote_policy_error = result["runtime_policy"][ + "configuration_error" + ] + if provider.settings._remote_policy_error is None: + provider.settings._remote_policy_observed_at = observed + provider._runtime_cache = (observed, result) + return json.loads(json.dumps(result)) + except (ProviderError, asyncio.CancelledError) as exc: + if getattr(provider.settings, "inference_remote_files", False): + provider.settings._remote_policy_error = ( + "runtime_policy_invalid" + if isinstance(exc, ProviderError) and exc.code == "invalid_upstream_response" + else "runtime_policy_unavailable" + ) + raise + + +def _mirror_runtime_policy(provider: Provider, policy): + if ( + not getattr(provider.settings, "inference_remote_files", False) + or policy["configuration_error"] is not None + ): + return + path = confined( + getattr(provider.settings, "runtime_policy_file", None), provider.settings, exists=False + ) + payload = { + "schema_version": 1, + "batch_window_enabled": policy["batch_window_enabled"], + "workflow_max_shots": policy["workflow_max_shots"], + } + temporary = path.with_name(path.name + ".part-" + uuid.uuid4().hex) + try: + path.parent.mkdir(parents=True, exist_ok=True) + try: + if path.stat().st_size <= 65536 and json.loads(path.read_bytes()) == payload: + return + except (OSError, ValueError, UnicodeError): + pass + with temporary.open("xb") as handle: + handle.write(json.dumps(payload, allow_nan=False).encode("utf-8")) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + except OSError: + raise ProviderError("provider_not_configured", "无法同步模型服务运行策略。", True) from None + finally: + temporary.unlink(missing_ok=True) + + +async def scheduler_status(provider: Provider): + unavailable = { + "available": False, + "state": "unavailable", + "reason": "GPU状态暂时不可用。", + "gpus": [], + "updated_at": None, + } + try: + remote = bool(getattr(provider.settings, "inference_remote_files", False)) + if remote: + runtime = await provider.runtime_status() + data, scheduler = runtime["monitor"], runtime["scheduler"] + else: + path = Path(provider.settings.gpu_status_path) + if path.stat().st_size > 1024 * 1024: + return unavailable + data = json.loads(path.read_bytes()) + scheduler = None + now = time.time() + generated = _float(data["generated_at"], 0, now + 1) + if data["schema_version"] != 1 or data.get("error") is not None or now - generated > 5: + return unavailable + seen, gpus = set(), [] + for gpu in data["gpus"]: + index = _int(gpu["index"], 0, 1024) + if ( + index in seen + or not isinstance(gpu["uuid"], str) + or not _UUID.fullmatch(gpu["uuid"]) + ): + return unavailable + seen.add(index) + total = _float(gpu["total_gib"], 0.001, 100000) + free = _float(gpu["free_gib"], 0, total) + if remote: + external, own = gpu["external_busy"], gpu["own_busy"] + else: + external, own = gpu["external_pids"], gpu["own_pids"] + if not all( + isinstance(values, list) and all(type(pid) is int and pid > 0 for pid in values) + for values in (external, own) + ): + return unavailable + idle = gpu.get("idle_since") + if idle is not None: + idle = _float(idle, 0, now + 1) + busy = bool(external or own) + eligible = not busy and free >= 76 and idle is not None and now - idle >= 15 + gpus.append( + { + "index": index, + "name": f"GPU {index}", + "busy": busy, + "eligible": eligible, + "free_gib": free, + "_uuid": gpu["uuid"], + "_own": bool(own), + "state": "external" + if external + else "running" + if own + else "ready" + if eligible + else "waiting", + "stage": None, + } + ) + if not remote: + try: + scheduler_path = Path(provider.settings.gpu_scheduler_path) + if scheduler_path.stat().st_size <= 1024 * 1024: + scheduler = json.loads(scheduler_path.read_bytes()) + except (OSError, ValueError, TypeError, AttributeError): + pass + from app.domain.gpu_summary import summarize + + return summarize(gpus, scheduler, now, generated) + except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError): + return unavailable diff --git a/backend/app/adapters/provider/speech.py b/backend/app/adapters/provider/speech.py new file mode 100644 index 0000000..895d9a6 --- /dev/null +++ b/backend/app/adapters/provider/speech.py @@ -0,0 +1,103 @@ +"""已配置真实 TTS 服务的 WAV 输出适配。""" + +from __future__ import annotations + +import math +import wave + +from app.adapters.media import inspect_media +from app.domain.execution import CpuResult +from app.domain.errors import MediaError as ProviderError +from .contracts import _invalid, _keys, _float, _string, _voices +from .transport import _url + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +async def _speech(provider: Provider, inputs, p, work): + if ( + not provider.settings.tts_base_url + or not provider.settings.tts_model + or not _voices(provider.settings) + ): + raise ProviderError("capability_unavailable", "中文配音服务尚未配置。") + _keys(inputs, {"prompt"}) + _keys(p, {"voice", "speed", "model"}) + model = p.get("model", provider.settings.tts_model) + if model != provider.settings.tts_model: + raise ProviderError("capability_changed", "配音模型配置已变化,请重新生成执行计划") + text = _string(inputs.get("prompt"), 2000) + voice = p.get("voice", _voices(provider.settings)[0]) + if voice not in _voices(provider.settings): + raise _invalid("请选择已配置的中文音色。") + speed = _float(p.get("speed", 1.0), 0.5, 2) + target = work / "speech.wav" + await provider._download_url( + _url(provider.settings.tts_base_url, "/audio/speech"), + target, + provider._headers("tts"), + timeout=getattr(provider.settings, "speech_timeout_seconds", 330.0), + total_timeout=getattr(provider.settings, "speech_total_timeout_seconds", 360.0), + payload={ + "model": model, + "input": text, + "voice": voice, + "speed": speed, + "response_format": "wav", + }, + ) + info = await inspect_media(target, provider.settings) + if info["kind"] != "audio" or info["mime_type"] != "audio/wav": + target.unlink(missing_ok=True) + raise ProviderError("invalid_speech_response", "配音服务未返回有效的 WAV 音频。", True) + # 时间线用48kHz整数采样,避免5.02秒被round成5秒后错误准入视频生成。 + try: + with wave.open(str(target), "rb") as source: + samples = ( + source.getnframes() * 48000 + source.getframerate() - 1 + ) // source.getframerate() + except (wave.Error, EOFError): + samples = math.ceil(info["duration_seconds"] * 48000) + return CpuResult( + [target], + { + "text": text, + "voice": voice, + "duration_seconds": info["duration_seconds"], + "sample_count": samples, + "sample_rate": 48000, + }, + {"provider": "openai-compatible-tts", "model": model, "speed": speed}, + ) + + +async def health(provider: Provider): + configured = bool( + provider.settings.tts_base_url + and provider.settings.tts_model + and _voices(provider.settings) + ) + result = { + "configured": configured, + "reachable": False, + "model": provider.settings.tts_model, + "validation": "requires_deployment_acceptance", + } + if not configured: + return result + try: + base = provider.settings.tts_base_url.rstrip("/").removesuffix("/v1") + value = await provider._json( + "GET", _url(base, "/health"), headers=provider._headers("tts"), timeout=5 + ) + result["reachable"] = ( + value.get("status") == "ok" + and value.get("model") == provider.settings.tts_model + and set(_voices(provider.settings)).issubset(value.get("voices", [])) + ) + except (ProviderError, TypeError, ValueError): + pass + return result diff --git a/backend/app/adapters/provider/transport.py b/backend/app/adapters/provider/transport.py new file mode 100644 index 0000000..0011a3e --- /dev/null +++ b/backend/app/adapters/provider/transport.py @@ -0,0 +1,109 @@ +"""受限 HTTP 与按服务隔离的认证。""" + +from __future__ import annotations + +import asyncio +import json +import os +from pathlib import Path +import stat +from urllib.parse import urlsplit + +import httpx + +from app.domain.errors import MediaError as ProviderError + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .client import Provider + + +def _read_key(path): + descriptor = None + try: + path = Path(path) + if not path.is_absolute() or path.is_symlink(): + raise ValueError + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or (os.name == "posix" and info.st_mode & 0o022): + raise ValueError + raw = os.read(descriptor, 4097) + value = raw.decode("utf-8").strip() + if not value or len(raw) > 4096 or "\n" in value or "\r" in value: + raise ValueError + return value + except (OSError, ValueError, UnicodeError): + raise ProviderError("provider_not_configured", "模型服务认证配置不可用。", True) from None + finally: + if descriptor is not None: + os.close(descriptor) + + +def _url(base, suffix): + if not isinstance(base, str) or not base: + raise ProviderError("capability_unavailable", "此能力尚未配置。") + parsed = urlsplit(base) + if ( + parsed.scheme not in {"http", "https"} + or not parsed.hostname + or parsed.username + or parsed.password + or parsed.query + or parsed.fragment + ): + raise ProviderError("provider_not_configured", "模型服务地址配置无效。", True) + return base.rstrip("/") + suffix + + +def _headers(provider: Provider, family="inference"): + # 各服务只读自己的认证信息,Qwen/TTS 不继承 GPU 推理服务的密钥。 + key = getattr(provider.settings, family + "_api_key", "") or "" + if family == "inference" and getattr(provider.settings, "inference_api_key_file", None): + key = _read_key(provider.settings.inference_api_key_file) + if ( + not isinstance(key, str) + or len(key) > 4096 + or any(not 32 <= ord(char) <= 126 for char in key) + ): + raise ProviderError("provider_not_configured", "模型服务认证配置不可用。", True) + return {"Authorization": "Bearer " + key} if key else {} + + +def _http_error(status): + if status in {400, 413, 415, 422}: + return ProviderError("upstream_rejected", "模型服务拒绝了任务输入或参数。") + if status == 404: + return ProviderError("upstream_not_found", "模型服务未找到请求的任务或结果。", True) + if status == 409: + return ProviderError("upstream_conflict", "模型任务或幂等请求发生冲突。") + return ProviderError("upstream_unavailable", "模型服务暂时不可用。", True) + + +async def _json(provider: Provider, method, url, *, payload=None, headers=None, timeout=None): + seconds = float(provider.settings.request_timeout_seconds if timeout is None else timeout) + options = {} if timeout is None else {"timeout": httpx.Timeout(seconds)} + try: + async with asyncio.timeout(seconds + 1): + async with provider.client.stream( + method, url, json=payload, headers=headers, **options + ) as response: + if not 200 <= response.status_code < 300: + raise provider._http_error(response.status_code) + data, size = [], 0 + async for chunk in response.aiter_bytes(): + size += len(chunk) + if size > 2 * 1024 * 1024: + raise ProviderError( + "invalid_upstream_response", "模型服务响应超出限制。", True + ) + data.append(chunk) + value = json.loads(b"".join(data)) + if not isinstance(value, dict): + raise ValueError + return value + except (httpx.HTTPError, asyncio.TimeoutError): + raise ProviderError("upstream_unavailable", "模型服务连接失败或响应超时。", True) from None + except (ValueError, UnicodeError, RecursionError): + raise ProviderError("invalid_upstream_response", "模型服务返回了无效响应。", True) from None diff --git a/backend/app/adapters/provider/video_editing.py b/backend/app/adapters/provider/video_editing.py new file mode 100644 index 0000000..812aac1 --- /dev/null +++ b/backend/app/adapters/provider/video_editing.py @@ -0,0 +1,74 @@ +"""可信分析绑定到真实输入字节,再送入现有监管队列。""" + +import asyncio +from app.adapters.media import inspect_media, inspect_video_timeline +from app.services.artifacts import digest_file +from app.domain.errors import MediaError +from app.domain.video_editing import video_capability, video_defaults + + +async def prepare_video(provider, task, inputs, parameters, assets, binding): + local = video_capability(provider.settings) + remote = (await provider.upstream_capabilities()).get("video_edit", {}) + p = video_defaults(task, provider.settings) | parameters + if ( + remote.get("available") is not True + or remote.get("profile") != p["profile"] + or remote.get("fps") != 24 + ): + raise MediaError("capability_unavailable", "上游视频编辑未认证或模型版本不匹配。") + source = provider._asset(inputs["video_asset_id"], assets) + info = await inspect_media(source, provider.settings) + duration = await inspect_video_timeline(source, provider.settings) + if ( + info["kind"] != "video" + or duration > min(local["max_seconds"], remote.get("max_seconds", 0)) + 0.001 + or p["max_pixels"] > remote.get("max_pixels", 0) + ): + raise MediaError("invalid_input", "视频类型、时长或规格超出已认证范围。") + digest = await asyncio.to_thread(digest_file, source) + paths = [] + if task == "video.replace": + if ( + not isinstance(binding, dict) + or binding.get("source_sha256") != digest + or binding.get("profile") != p["profile"] + ): + raise MediaError("analysis_source_mismatch", "源视频字节与冻结分析不匹配。") + if len(inputs["replacements"]) > remote.get("max_people", 0): + raise MediaError("invalid_input", "人物数量超出上游范围。") + for row in inputs["replacements"]: + image = provider._asset(row["reference_asset_id"], assets) + if (await inspect_media(image, provider.settings))["kind"] != "image": + raise MediaError("invalid_input", "人物参考素材必须是有效图片。") + if await asyncio.to_thread(digest_file, image) != binding.get( + "reference_sha256", {} + ).get(row["reference_asset_id"]): + raise MediaError("invalid_asset", "参考图片字节与冻结映射不一致。") + paths.append(image) + + # 全部输入完成校验后才上传;原片不改写,映射保序且包含所有所选人物。 + async def path(value): + return ( + await provider._upload_input(value) + if provider.settings.inference_remote_files + else str(value) + ) + + out = {"video_path": await path(source)} + if task == "video.replace": + out.update( + analysis_id=binding["analysis_id"], + analysis_token=binding["analysis_token"], + prompt=inputs.get("prompt", ""), + negative_prompt=inputs.get("negative_prompt", ""), + replacements=[ + { + "person_id": row["person_id"], + "image_path": await path(image), + "prompt": row.get("prompt", ""), + } + for row, image in zip(inputs["replacements"], paths, strict=True) + ], + ) + return {"task_type": task, "input": out, "parameters": p, "timeout_seconds": 86400} diff --git a/backend/app/adapters/storage.py b/backend/app/adapters/storage.py new file mode 100644 index 0000000..efab498 --- /dev/null +++ b/backend/app/adapters/storage.py @@ -0,0 +1,45 @@ +import asyncio +import os, stat +from pathlib import Path + + +async def file_thread(operation, *args, **kwargs): + """取消等待不会停止系统线程;真实文件操作结束后才能释放执行/上传保护。""" + worker = asyncio.create_task(asyncio.to_thread(operation, *args, **kwargs)) + try: + return await asyncio.shield(worker) + except asyncio.CancelledError: + # 多次cancel也不能让底层线程失去跟踪;只等待本次本地文件操作。 + while not worker.done(): + try: + await asyncio.shield(worker) + except asyncio.CancelledError: + continue + except Exception: + break + if not worker.cancelled(): + worker.exception() + raise + + +def confined(root, value, *, exists=False): + root = Path(root).resolve() + path = Path(value) + path = (path if path.is_absolute() else root / path).resolve(strict=exists) + if not path.is_relative_to(root): + raise ValueError("File is outside its permitted directory") + return path + + +def safe_file(root, value): + path = confined(root, value, exists=True) + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise ValueError("Regular file required") + if os.name == "posix": + confined(root, os.readlink(f"/proc/self/fd/{fd}"), exists=True) + return os.fdopen(fd, "rb") + except BaseException: + os.close(fd) + raise diff --git a/backend/app/admission_clock.py b/backend/app/admission_clock.py deleted file mode 100644 index c4bb707..0000000 --- a/backend/app/admission_clock.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Durable clock-anomaly gate, applied only to new batch phases.""" -from datetime import datetime, timezone, timedelta -import json -import math -import os -from pathlib import Path -import time -import uuid - -SHANGHAI=timezone(timedelta(hours=8)) - -class AdmissionClock: - def __init__(self,path): - self.path=Path(path) - self.watermark=0.0 - self.closed_through='' - self.reason=None - self.valid=True - if self.path.exists(): - try: - data=json.loads(self.path.read_text(encoding='utf-8')) - self.watermark=float(data['max_seen']) - self.closed_through=data['closed_through'] - if not math.isfinite(self.watermark) or not 0<=self.watermark<=253402300799: - raise ValueError('Invalid timestamp') - datetime.fromisoformat(self.closed_through) - except (ValueError,KeyError,TypeError,OSError): - self.valid=False - - def observe(self,now=None): - if not self.valid: - self.reason='clock_state_invalid' - return False - try: - now=time.time() if now is None else float(now) - if not math.isfinite(now):raise ValueError() - local=datetime.fromtimestamp(now,timezone.utc).astimezone(SHANGHAI) - except (ValueError,TypeError,OverflowError,OSError): - self.reason='clock_invalid' - return False - closed=(local.date() if local.hour>=8 else local.date()-timedelta(days=1)).isoformat() - next_closed=max(self.closed_through,closed) - next_watermark=max(self.watermark,now) - if int(next_watermark)>int(self.watermark) or next_closed!=self.closed_through: - temporary=self.path.with_name(self.path.name+'.'+uuid.uuid4().hex+'.tmp') - try: - self.path.parent.mkdir(parents=True,exist_ok=True) - with temporary.open('x',encoding='utf-8') as stream: - json.dump({'max_seen':next_watermark,'closed_through':next_closed},stream) - stream.flush();os.fsync(stream.fileno()) - os.replace(temporary,self.path) - self.watermark,self.closed_through=next_watermark,next_closed - except OSError: - self.reason='clock_state_unwritable' - return False - finally: - try:temporary.unlink(missing_ok=True) - except OSError:pass - if now=21 or local.hour<8: - window_end=local.date()+timedelta(days=1) if local.hour>=21 else local.date() - if window_end.isoformat()<=self.closed_through: - self.reason='window_already_closed' - return False - self.reason=None - return True diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/api/dependencies.py b/backend/app/api/dependencies.py new file mode 100644 index 0000000..a37d4b3 --- /dev/null +++ b/backend/app/api/dependencies.py @@ -0,0 +1,100 @@ +import hmac +from fastapi import Depends, Request +from sqlalchemy import select +from app.models import Session, User, utcnow, ApiToken +from app.core.errors import fail +from app.core.security import Actor, COOKIE, token_hash + + +async def current_actor(request: Request): + authorization = request.headers.get("Authorization", "") + if authorization.startswith("Bearer "): + return await bearer_actor(request, authorization[7:]) + token = request.cookies.get(COOKIE) + if not token or len(token) > 512: + fail(401, "not_authenticated", "请先登录") + async with request.app.state.db.session() as session: + row = ( + await session.execute( + select(Session, User) + .join(User, User.id == Session.user_id) + .where( + Session.token_hash == token_hash(token), + Session.expires_at > utcnow(), + User.disabled.is_(False), + ) + ) + ).first() + if row is None: + fail(401, "session_expired", "登录已失效,请重新登录") + saved, user = row + return Actor( + user.id, + user.username, + user.display_name, + user.role, + saved.csrf_token, + saved.token_hash, + must_change_password=user.must_change_password, + ) + + +async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)): + if actor.auth_kind == "bearer": + if request.headers.get("sec-fetch-site") or request.cookies.get(COOKIE): + fail(403, "machine_token_only", "Use session authentication in browsers") + return actor + supplied = request.headers.get("X-CSRF-Token", "") + if not hmac.compare_digest(supplied.encode("utf-8"), actor.csrf_token.encode("utf-8")): + fail(403, "csrf_failed", "请求校验失败,请刷新登录状态") + # Same-origin proxy is the deployment default; reject explicitly cross-site writes. + if request.headers.get("sec-fetch-site") == "cross-site": + fail(403, "cross_site_request", "不允许跨站写入") + return actor + + +async def bearer_actor(request, token): + async with request.app.state.db.session() as session: + row = await session.scalar( + select(ApiToken).where( + ApiToken.token_hash == token_hash(token), ApiToken.revoked_at.is_(None) + ) + ) + if not row or (row.expires_at and row.expires_at <= utcnow()): + fail(401, "token_expired", "Token unavailable") + user = await session.get(User, row.owner_id) + if not user or user.disabled: + fail(401, "token_expired", "Token unavailable") + path = request.url.path.removeprefix("/api/").split("/")[0] + if path == "submissions": + operation = request.query_params.get("operation", "") + path = ( + "assets" + if operation in {"assets.publish", "shared.import"} + else "workflows" + if operation.startswith("workflow") + or operation.startswith("story.") + or operation.startswith("editor.") + else "batches" + if operation.startswith("batch") + else "jobs" + ) + scope = { + "workflow-runs": "workflows", + "stories": "workflows", + "editors": "workflows", + "shared-assets": "assets", + }.get(path, path) + (":read" if request.method in {"GET", "HEAD"} else ":write") + if scope not in row.scopes: + fail(403, "scope_required", "Token scope required: " + scope) + return Actor( + user.id, + user.username, + user.display_name, + "user", + "", + row.token_hash, + "bearer", + row.scopes, + user.must_change_password, + ) diff --git a/backend/app/api/middleware/__init__.py b/backend/app/api/middleware/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/api/middleware/upload_guard.py b/backend/app/api/middleware/upload_guard.py new file mode 100644 index 0000000..3dfd998 --- /dev/null +++ b/backend/app/api/middleware/upload_guard.py @@ -0,0 +1,116 @@ +"""Authenticate and bound uploads before multipart parsing creates spool files.""" + +import asyncio +import tempfile +from fastapi import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse +from app.api.dependencies import current_actor, csrf_actor +from app.services.quotas import check_storage_budget + + +class UploadGuard: + def __init__(self, app): + self.app = app + self.slots = asyncio.Semaphore(2) + self.lock = asyncio.Lock() + self.reserved = {} + self.global_reserved = 0 + + async def __call__(self, scope, receive, send): + if ( + scope["type"] != "http" + or scope["method"] != "POST" + or scope["path"].rstrip("/") != "/api/assets" + ): + return await self.app(scope, receive, send) + request = Request(scope) + settings = request.app.state.settings + + async def reject(status, code, message): + await JSONResponse({"detail": {"code": code, "message": message}}, status_code=status)( + scope, receive, send + ) + + try: + actor = await current_actor(request) + await csrf_actor(request, actor) + except HTTPException as exc: + return await JSONResponse({"detail": exc.detail}, status_code=exc.status_code)( + scope, receive, send + ) + limit = settings.max_upload_bytes + 1024 * 1024 # bounded multipart overhead + length = request.headers.get("content-length") + try: + expected = int(length) if length is not None else limit + if expected < 0: + raise ValueError() + except ValueError: + return await reject(400, "invalid_content_length", "上传长度无效") + if expected > limit: + return await reject(413, "upload_too_large", "上传超过文件大小限制") + if self.slots.locked(): + return await reject(429, "upload_busy", "同时上传数量已满,请稍后重试") + await self.slots.acquire() + reservation = expected * 2 # raw body plus multipart spool during parsing + reserved = False + try: + async with self.lock: + async with request.app.state.db.session() as session: + await check_storage_budget( + session, + settings, + actor.id, + incoming_bytes=self.reserved.get(actor.id, 0) + expected, + global_incoming_bytes=self.global_reserved + reservation, + ) + self.reserved[actor.id] = self.reserved.get(actor.id, 0) + expected + self.global_reserved += reservation + reserved = True + temporary = (settings.asset_root.parent / "tmp").resolve() + if not temporary.is_relative_to(settings.workspace_root): + return await reject(503, "upload_storage_unavailable", "上传暂存目录不可用") + temporary.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryFile(dir=temporary) as body: + total = 0 + while True: + message = await receive() + if message["type"] == "http.disconnect": + return await reject(499, "upload_disconnected", "上传连接已断开") + if message["type"] != "http.request": + continue + chunk = message.get("body", b"") + total += len(chunk) + if total > limit or (length is not None and total > expected): + return await reject(413, "upload_too_large", "上传超过文件大小限制") + await asyncio.to_thread(body.write, chunk) + if not message.get("more_body", False): + break + if length is not None and total != expected: + return await reject(400, "invalid_content_length", "上传数据长度不匹配") + await asyncio.to_thread(body.seek, 0) + remaining = total + completed = False + + async def replay(): + nonlocal remaining, completed + if completed: + return await receive() + chunk = await asyncio.to_thread(body.read, min(1024 * 1024, remaining)) + remaining -= len(chunk) + completed = remaining == 0 + return {"type": "http.request", "body": chunk, "more_body": not completed} + + await self.app(scope, replay, send) + except HTTPException as exc: + await JSONResponse({"detail": exc.detail}, status_code=exc.status_code)( + scope, receive, send + ) + finally: + if reserved: + async with self.lock: + self.reserved[actor.id] -= expected + self.global_reserved -= reservation + if self.reserved[actor.id] == 0: + self.reserved.pop(actor.id) + self.slots.release() diff --git a/backend/app/api/responses.py b/backend/app/api/responses.py new file mode 100644 index 0000000..fd588dd --- /dev/null +++ b/backend/app/api/responses.py @@ -0,0 +1,64 @@ +import os, re +from urllib.parse import quote +from fastapi import Response +from fastapi.responses import StreamingResponse +from starlette.background import BackgroundTask +from app.adapters.storage import safe_file +from app.core.errors import fail + + +def file_response(settings, asset, key, range_header, download): + try: + handle = safe_file(settings.asset_root, key) + except (ValueError, OSError): + fail(404, "file_unavailable", "素材文件不可用") + size = os.fstat(handle.fileno()).st_size + start, end, code = 0, size - 1, 200 + if range_header: + match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip()) + try: + if not match or not any(match.groups()): + raise ValueError + a, b = match.groups() + if a: + start, end = int(a), min(int(b), size - 1) if b else size - 1 + else: + start, end = max(0, size - int(b)), size - 1 + if start > end or start >= size or start < 0: + raise ValueError + code = 206 + except ValueError: + handle.close() + return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"}) + handle.seek(start) + + def chunks(): + remaining = end - start + 1 + try: + while remaining > 0: + data = handle.read(min(1024 * 1024, remaining)) + if not data: + break + remaining -= len(data) + yield data + finally: + handle.close() + + headers = { + "Accept-Ranges": "bytes", + "Content-Length": str(max(0, end - start + 1)), + "X-Content-Type-Options": "nosniff", + "Cache-Control": "private, no-store", + "Content-Disposition": ("attachment" if download else "inline") + + "; filename*=UTF-8''" + + quote(asset.name, safe=""), + } + if code == 206: + headers["Content-Range"] = f"bytes {start}-{end}/{size}" + return StreamingResponse( + chunks(), + status_code=code, + media_type="image/jpeg" if key != asset.storage_key else asset.mime_type, + headers=headers, + background=BackgroundTask(handle.close), + ) diff --git a/backend/app/api/router.py b/backend/app/api/router.py new file mode 100644 index 0000000..1b7c087 --- /dev/null +++ b/backend/app/api/router.py @@ -0,0 +1,38 @@ +"""统一挂载 /api,子路由保留原有路径与注册顺序。""" + +from fastapi import APIRouter +from app.api.routes import ( + editors, + folders, + auth, + assets, + shared_assets, + jobs, + events, + submissions, + tokens, + workflows, + batches, + system, + stories, +) + +router = APIRouter() +for child in ( + editors.router, + folders.router, + auth.router, + assets.router, + shared_assets.router, + shared_assets.publish_router, + jobs.router, + events.router, + submissions.router, + tokens.router, + workflows.router, + workflows.runs_router, + batches.router, + system.router, + stories.router, +): + router.include_router(child) diff --git a/backend/app/api/routes/__init__.py b/backend/app/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/api/routes/assets.py b/backend/app/api/routes/assets.py new file mode 100644 index 0000000..90bca0c --- /dev/null +++ b/backend/app/api/routes/assets.py @@ -0,0 +1,104 @@ +from app.services.assets import owned_asset + + +from fastapi import APIRouter, Depends, File, Form, Request, UploadFile + + +from app.core.security import Actor +from app.api.dependencies import csrf_actor, current_actor + + +from app.core.errors import fail + + +from app.schemas.assets import AssetPatch +from app.services import assets as service +from app.api.responses import file_response + +router = APIRouter(prefix="/assets", tags=["assets"]) + + +@router.post("", status_code=201) +async def upload( + request: Request, + file: UploadFile = File(), + name: str | None = Form(default=None), + folder_id: str | None = Form(default=None), + actor: Actor = Depends(csrf_actor), +): + return await service.upload( + runtime=request.app.state, + file=file, + name=name, + folder_id=folder_id, + actor=actor, + content_length=request.headers.get("content-length", "0"), + ) + + +@router.get("") +async def list_assets( + request: Request, + page: int = 1, + page_size: int = 24, + folder_id: str = "", + kind: str = "", + q: str = "", + tag: str = "", + favorite: bool | None = None, + origin: str = "", + actor: Actor = Depends(current_actor), +): + return await service.list_assets( + runtime=request.app.state, + page=page, + page_size=page_size, + folder_id=folder_id, + kind=kind, + q=q, + tag=tag, + favorite=favorite, + origin=origin, + actor=actor, + ) + + +@router.get("/{asset_id}") +async def get_asset(asset_id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_asset(asset_id=asset_id, runtime=request.app.state, actor=actor) + + +@router.patch("/{asset_id}") +async def patch_asset( + asset_id: str, body: AssetPatch, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.patch_asset( + asset_id=asset_id, body=body, runtime=request.app.state, actor=actor + ) + + +@router.delete("/{asset_id}", status_code=204) +async def delete_asset(asset_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.delete_asset(asset_id=asset_id, runtime=request.app.state, actor=actor) + + +@router.get("/{asset_id}/content") +async def content( + asset_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor) +): + async with request.app.state.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + return file_response( + request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download + ) + + +@router.get("/{asset_id}/thumbnail") +async def thumbnail(asset_id: str, request: Request, actor: Actor = Depends(current_actor)): + async with request.app.state.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + if not asset.thumbnail_key and asset.kind != "image": + fail(404, "thumbnail_unavailable", "预览图暂不可用") + return file_response( + request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False + ) diff --git a/backend/app/api/routes/auth.py b/backend/app/api/routes/auth.py new file mode 100644 index 0000000..09cca7b --- /dev/null +++ b/backend/app/api/routes/auth.py @@ -0,0 +1,81 @@ +from fastapi import APIRouter, Depends, Request, Response +from app.schemas.auth import Login, CreateUser, UserPatch, PasswordChange, UsernameChange +from app.api.dependencies import current_actor, csrf_actor +from app.core.security import Actor, COOKIE +from app.services import auth as service + +router = APIRouter(prefix="/auth", tags=["auth"]) + + +@router.post("/login") +async def login(body: Login, request: Request, response: Response): + result, token = await service.login(body=body, runtime=request.app.state) + settings = request.app.state.settings + response.set_cookie( + COOKIE, + token, + httponly=True, + secure=settings.cookie_secure, + samesite="lax", + max_age=settings.session_hours * 3600, + path="/", + ) + return result + + +@router.get("/me") +async def me(actor: Actor = Depends(current_actor)): + return await service.me(actor=actor) + + +@router.post("/logout", status_code=204) +async def logout(request: Request, actor: Actor = Depends(csrf_actor)): + await service.logout(runtime=request.app.state, actor=actor) + response = Response(status_code=204) + response.delete_cookie(COOKIE, path="/") + return response + + +@router.post("/users", status_code=201) +async def create_user(body: CreateUser, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.create_user(body=body, runtime=request.app.state, actor=actor) + + +@router.get("/users") +async def list_users( + request: Request, page: int = 1, page_size: int = 24, actor: Actor = Depends(current_actor) +): + return await service.list_users( + runtime=request.app.state, page=page, page_size=page_size, actor=actor + ) + + +@router.patch("/users/{user_id}") +async def patch_user( + user_id: str, body: UserPatch, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.patch_user( + user_id=user_id, body=body, runtime=request.app.state, actor=actor + ) + + +@router.post("/password") +async def change_password( + body: PasswordChange, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.change_password(body=body, runtime=request.app.state, actor=actor) + + +@router.post("/username") +async def change_username( + body: UsernameChange, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.change_username(body=body, runtime=request.app.state, actor=actor) + + +@router.delete("/users/{user_id}", status_code=204) +async def delete_user(user_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + from app.services.user_deletion import delete_user as delete_account + + await delete_account(user_id=user_id, runtime=request.app.state, actor=actor) + return Response(status_code=204) diff --git a/backend/app/api/routes/batches.py b/backend/app/api/routes/batches.py new file mode 100644 index 0000000..2622680 --- /dev/null +++ b/backend/app/api/routes/batches.py @@ -0,0 +1,62 @@ +from fastapi import APIRouter, Depends, Header, Request + + +from app.core.security import Actor +from app.api.dependencies import csrf_actor, current_actor + + +from app.schemas.batches import BatchCreate, BatchControl +from app.services import batches as service + +router = APIRouter(prefix="/batches", tags=["batches"]) + + +@router.post("", status_code=202) +async def post_batch( + body: BatchCreate, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.post_batch( + body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) + + +@router.get("") +async def list_batches( + request: Request, page: int = 1, page_size: int = 24, actor: Actor = Depends(current_actor) +): + return await service.list_batches( + runtime=request.app.state, page=page, page_size=page_size, actor=actor + ) + + +@router.get("/{id}") +async def get_batch(id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_batch(id=id, runtime=request.app.state, actor=actor) + + +@router.delete("/{id}") +async def delete_batch( + id: str, + request: Request, + if_match: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.delete_batch( + id=id, runtime=request.app.state, if_match=if_match, actor=actor + ) + + +@router.post("/{id}/control") +async def batch_control( + id: str, + body: BatchControl, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.batch_control( + id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) diff --git a/backend/app/api/routes/editors.py b/backend/app/api/routes/editors.py new file mode 100644 index 0000000..101871e --- /dev/null +++ b/backend/app/api/routes/editors.py @@ -0,0 +1,78 @@ +from fastapi import APIRouter, Depends, Header, Request +from app.api.dependencies import csrf_actor, current_actor +from app.core.security import Actor +from app.schemas.editors import SaveEditor, RestoreEditor, PlanEditor, StartEditor, EditorMode +from app.services import editors as service + +router = APIRouter(prefix="/editors", tags=["editors"]) + + +@router.get("/{draft_id}") +async def get(draft_id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_editor(request.app.state, actor, draft_id) + + +@router.post("/{draft_id}/save") +async def save( + draft_id: str, + body: SaveEditor, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.save_editor(request.app.state, actor, draft_id, body, idempotency_key) + + +@router.post("/{draft_id}/from-run") +async def restore( + draft_id: str, + body: RestoreEditor, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.from_run(request.app.state, actor, draft_id, body, idempotency_key) + + +@router.post("/{draft_id}/plan") +async def plan( + draft_id: str, body: PlanEditor, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.plan_editor_request(request.app.state, actor, draft_id, body) + + +@router.post("/{draft_id}/runs", status_code=202) +async def start( + draft_id: str, + body: StartEditor, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.start_editor_request( + request.app.state, actor, draft_id, body, idempotency_key + ) + + +@router.post("/{draft_id}/apply") +async def apply( + draft_id: str, + body: RestoreEditor, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.apply_editor(request.app.state, actor, draft_id, body, idempotency_key) + + +@router.post("/{draft_id}/mode") +async def change_mode( + draft_id: str, + body: EditorMode, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + from app.services.editor_modes import change_mode + + return await change_mode(request.app.state, actor, draft_id, body, idempotency_key) diff --git a/backend/app/api/routes/events.py b/backend/app/api/routes/events.py new file mode 100644 index 0000000..d8142eb --- /dev/null +++ b/backend/app/api/routes/events.py @@ -0,0 +1,78 @@ +import asyncio + +import json + +import time + +from fastapi import APIRouter, Depends, Request + +from fastapi.responses import StreamingResponse + +from sqlalchemy import func, select + +from app.core.security import Actor, COOKIE +from app.api.dependencies import current_actor + + +from app.core.errors import fail + +from app.models import Event + +from app.services.events import event_batch, session_is_active + +router = APIRouter(tags=["events"]) + + +async def event_stream(request, owner_id, token, after): + # Authentication was checked by the endpoint. Flush a body immediately so + # EventSource/proxies need not wait for the first durable event or heartbeat. + yield ": connected\n\n" + db = request.app.state.db + heartbeat = request.app.state.settings.event_heartbeat_seconds + last_heartbeat = time.monotonic() + async with db.session() as session: + maximum = ( + await session.scalar(select(func.max(Event.id)).where(Event.owner_id == owner_id)) or 0 + ) + minimum = ( + await session.scalar(select(func.min(Event.id)).where(Event.owner_id == owner_id)) or 0 + ) + if after > maximum or (after > 0 and minimum > 0 and after < minimum - 1): + yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n" + after = maximum + while not await request.is_disconnected(): + if getattr(request.app.state, "draining", False): + return + if not await session_is_active(db, token): + return + rows = await event_batch(db, owner_id, after) + for event in rows: + after = event["id"] + yield f"id: {after}\nevent: {event['event']}\ndata: {json.dumps(event['data'], ensure_ascii=False, separators=(',', ':'))}\n\n" + if time.monotonic() - last_heartbeat >= heartbeat: + yield ": heartbeat\n\n" + last_heartbeat = time.monotonic() + if not rows: + await asyncio.sleep(min(0.5, heartbeat)) + + +@router.get("/events") +async def events(request: Request, after: int = 0, actor: Actor = Depends(current_actor)): + try: + cursor = int(request.headers.get("Last-Event-ID", after)) + if cursor < 0: + raise ValueError + except ValueError: + fail(422, "invalid_cursor", "事件游标必须为非负整数") + return StreamingResponse( + event_stream( + request, + actor.id, + request.headers.get("Authorization") + if actor.auth_kind == "bearer" + else request.cookies.get(COOKIE), + cursor, + ), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"}, + ) diff --git a/backend/app/api/routes/folders.py b/backend/app/api/routes/folders.py new file mode 100644 index 0000000..da03112 --- /dev/null +++ b/backend/app/api/routes/folders.py @@ -0,0 +1,37 @@ +from fastapi import APIRouter, Depends, Request, Response +from app.api.dependencies import current_actor, csrf_actor +from app.core.security import Actor +from app.schemas.folders import FolderCreate, FolderPatch, FolderAssign +from app.services import folders as service + +router = APIRouter(prefix="/folders", tags=["folders"]) + + +@router.get("") +async def list_folders(request: Request, actor: Actor = Depends(current_actor)): + return await service.list_folders(runtime=request.app.state, actor=actor) + + +@router.post("", status_code=201) +async def create(body: FolderCreate, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.create(runtime=request.app.state, actor=actor, body=body) + + +@router.post("/assign") +async def assign(body: FolderAssign, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.assign(runtime=request.app.state, actor=actor, body=body) + + +@router.patch("/{folder_id}") +async def patch( + folder_id: str, body: FolderPatch, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.patch( + runtime=request.app.state, actor=actor, folder_id=folder_id, body=body + ) + + +@router.delete("/{folder_id}", status_code=204) +async def remove(folder_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + await service.remove(runtime=request.app.state, actor=actor, folder_id=folder_id) + return Response(status_code=204) diff --git a/backend/app/api/routes/jobs.py b/backend/app/api/routes/jobs.py new file mode 100644 index 0000000..b620386 --- /dev/null +++ b/backend/app/api/routes/jobs.py @@ -0,0 +1,80 @@ +from fastapi import APIRouter, Depends, Header, Request + + +from app.core.security import Actor +from app.api.dependencies import csrf_actor, current_actor + + +from app.schemas.jobs import Submit +from app.services import jobs as service + +router = APIRouter(prefix="/jobs", tags=["jobs"]) + + +@router.post("", status_code=202) +async def submit( + body: Submit, + request: Request, + idempotency_key: str | None = Header(default=None), + actor: Actor = Depends(csrf_actor), +): + return await service.submit( + body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) + + +@router.get("") +async def list_jobs( + request: Request, + page: int = 1, + page_size: int = 24, + folder_id: str = "", + task_type: str = "", + state: str = "", + root_only: bool = False, + actor: Actor = Depends(current_actor), +): + return await service.list_jobs( + runtime=request.app.state, + page=page, + page_size=page_size, + folder_id=folder_id, + task_type=task_type, + state=state, + root_only=root_only, + actor=actor, + ) + + +@router.get("/{job_id}") +async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_job(job_id=job_id, runtime=request.app.state, actor=actor) + + +@router.delete("/{job_id}") +async def delete_job( + job_id: str, + request: Request, + if_match: str | None = Header(default=None), + actor: Actor = Depends(csrf_actor), +): + return await service.delete_job( + job_id=job_id, runtime=request.app.state, if_match=if_match, actor=actor + ) + + +@router.post("/{job_id}/cancel") +async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.cancel(job_id=job_id, runtime=request.app.state, actor=actor) + + +@router.post("/{job_id}/retry", status_code=202) +async def retry( + job_id: str, + request: Request, + idempotency_key: str | None = Header(default=None), + actor: Actor = Depends(csrf_actor), +): + return await service.retry( + job_id=job_id, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) diff --git a/backend/app/api/routes/shared_assets.py b/backend/app/api/routes/shared_assets.py new file mode 100644 index 0000000..79f8d69 --- /dev/null +++ b/backend/app/api/routes/shared_assets.py @@ -0,0 +1,121 @@ +from app.services.shared_assets import available_shared + + +from fastapi import APIRouter, Body, Depends, Header, Request + + +from app.api.responses import file_response +from app.core.security import Actor +from app.api.dependencies import csrf_actor, current_actor + + +from app.core.errors import fail + + +from app.schemas.shared_assets import EmptyPayload +from app.schemas.assets import SharedImport +from app.services import shared_assets as service + +router = APIRouter(prefix="/shared-assets", tags=["shared-assets"]) + + +publish_router = APIRouter(prefix="/assets", tags=["shared-assets"]) + + +@publish_router.post("/{asset_id}/publish", status_code=201) +async def publish_asset( + asset_id: str, + request: Request, + body: EmptyPayload | None = Body(default=None), + idempotency_key: str | None = Header(default=None), + actor: Actor = Depends(csrf_actor), +): + return await service.publish_asset( + asset_id=asset_id, + runtime=request.app.state, + body=body, + idempotency_key=idempotency_key, + actor=actor, + ) + + +@router.get("") +async def list_shared_assets( + request: Request, + q: str = "", + kind: str = "", + tag: str = "", + mine: bool = False, + page: int = 1, + page_size: int = 24, + actor: Actor = Depends(current_actor), +): + return await service.list_shared_assets( + runtime=request.app.state, + q=q, + kind=kind, + tag=tag, + mine=mine, + page=page, + page_size=page_size, + actor=actor, + ) + + +@router.get("/{shared_id}") +async def get_shared_asset(shared_id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_shared_asset( + shared_id=shared_id, runtime=request.app.state, actor=actor + ) + + +@router.get("/{shared_id}/content") +async def shared_content( + shared_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor) +): + async with request.app.state.db.session() as session: + _, asset, _ = await available_shared(session, shared_id) + return file_response( + request.app.state.settings, + asset, + asset.storage_key, + request.headers.get("range"), + download, + ) + + +@router.get("/{shared_id}/thumbnail") +async def shared_thumbnail(shared_id: str, request: Request, actor: Actor = Depends(current_actor)): + async with request.app.state.db.session() as session: + _, asset, _ = await available_shared(session, shared_id) + if not asset.thumbnail_key and asset.kind != "image": + fail(404, "thumbnail_unavailable", "预览图暂不可用") + return file_response( + request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False + ) + + +@router.post("/{shared_id}/import", status_code=201) +async def import_shared_asset( + shared_id: str, + request: Request, + body: SharedImport | None = Body(default=None), + idempotency_key: str | None = Header(default=None), + actor: Actor = Depends(csrf_actor), +): + return await service.import_shared_asset( + shared_id=shared_id, + runtime=request.app.state, + body=body, + idempotency_key=idempotency_key, + actor=actor, + ) + + +@router.delete("/{shared_id}", status_code=204) +async def withdraw_shared_asset( + shared_id: str, request: Request, actor: Actor = Depends(csrf_actor) +): + return await service.withdraw_shared_asset( + shared_id=shared_id, runtime=request.app.state, actor=actor + ) diff --git a/backend/app/api/routes/stories.py b/backend/app/api/routes/stories.py new file mode 100644 index 0000000..8e4dc12 --- /dev/null +++ b/backend/app/api/routes/stories.py @@ -0,0 +1,180 @@ +from fastapi import APIRouter, Depends, Header, Request +from app.api.dependencies import csrf_actor, current_actor +from app.schemas.stories import ( + StoryCreate, + StoryPatch, + CandidateCreate, + CandidateBatch, + SelectionCreate, + SelectionClear, + RenderCreate, + Version, +) +from app.services.stories import api as service +from app.services.stories.candidates import capabilities + +router = APIRouter(prefix="/stories", tags=["stories"]) + + +@router.get("/capabilities") +async def get_capabilities(request: Request, actor=Depends(current_actor)): + return await capabilities(request.app.state) + + +@router.get("") +async def listing( + request: Request, + page: int = 1, + page_size: int = 24, + folder_id: str = "", + actor=Depends(current_actor), +): + return await service.listing(request.app.state, actor, page, page_size, folder_id) + + +@router.post("", status_code=201) +async def create(body: StoryCreate, request: Request, actor=Depends(csrf_actor)): + return await service.create(request.app.state, actor, body) + + +@router.get("/{id}") +async def get(id: str, request: Request, actor=Depends(current_actor)): + return await service.get(request.app.state, actor, id) + + +@router.patch("/{id}") +async def patch( + id: str, + body: StoryPatch, + request: Request, + if_match: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.patch(request.app.state, actor, id, body, if_match) + + +@router.delete("/{id}") +async def delete_story( + id: str, request: Request, if_match: str | None = Header(None), actor=Depends(csrf_actor) +): + from app.services.stories.deletion import delete_story as remove + + return await remove(request.app.state, actor, id, if_match) + + +@router.get("/{id}/preview") +async def preview(id: str, request: Request, actor=Depends(current_actor)): + return await service.get(request.app.state, actor, id, "preview") + + +@router.get("/{id}/readiness") +async def readiness(id: str, request: Request, actor=Depends(current_actor)): + return await service.get(request.app.state, actor, id, "readiness") + + +@router.get("/{id}/candidates") +async def candidates( + id: str, + request: Request, + shot_id: str | None = None, + kind: str | None = None, + page: int = 1, + page_size: int = 24, + actor=Depends(current_actor), +): + return await service.candidates_list( + request.app.state, actor, id, shot_id, kind, page, page_size + ) + + +@router.post("/{id}/candidates", status_code=202) +async def create_candidates( + id: str, + body: CandidateCreate, + request: Request, + idempotency_key: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.create_candidates(request.app.state, actor, id, body, idempotency_key) + + +@router.post("/{id}/candidate-batches", status_code=202) +async def create_batch( + id: str, + body: CandidateBatch, + request: Request, + idempotency_key: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.create_candidates( + request.app.state, actor, id, body, idempotency_key, batch=True + ) + + +@router.post("/{id}/candidates/{candidate_id}/retry", status_code=202) +async def retry( + id: str, + candidate_id: str, + body: Version, + request: Request, + idempotency_key: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.create_candidates( + request.app.state, actor, id, body, idempotency_key, retry_id=candidate_id + ) + + +@router.delete("/{id}/candidates/{candidate_id}") +async def delete_candidate( + id: str, + candidate_id: str, + request: Request, + if_match: str | None = Header(None), + actor=Depends(csrf_actor), +): + from app.services.stories.deletion import delete_candidate as remove + + return await remove(request.app.state, actor, id, candidate_id, if_match) + + +@router.post("/{id}/selections") +async def selection( + id: str, + body: SelectionCreate, + request: Request, + idempotency_key: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.select_candidate(request.app.state, actor, id, body, idempotency_key) + + +@router.post("/{id}/selections/clear") +async def clear( + id: str, + body: SelectionClear, + request: Request, + idempotency_key: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.select_candidate( + request.app.state, actor, id, body, idempotency_key, clear=True + ) + + +@router.post("/{id}/renders", status_code=202) +async def render( + id: str, + body: RenderCreate, + request: Request, + idempotency_key: str | None = Header(None), + actor=Depends(csrf_actor), +): + return await service.render(request.app.state, actor, id, body, idempotency_key) + + +@router.get("/{id}/runs") +async def runs( + id: str, request: Request, page: int = 1, page_size: int = 24, actor=Depends(current_actor) +): + return await service.runs(request.app.state, actor, id, page, page_size) diff --git a/backend/app/api/routes/submissions.py b/backend/app/api/routes/submissions.py new file mode 100644 index 0000000..93f3496 --- /dev/null +++ b/backend/app/api/routes/submissions.py @@ -0,0 +1,19 @@ +from fastapi import APIRouter, Depends, Request + + +from app.core.security import Actor +from app.api.dependencies import current_actor + + +from app.services import submissions as service + +router = APIRouter(prefix="/submissions", tags=["submissions"]) + + +@router.get("/{key}") +async def recover( + key: str, request: Request, operation: str, actor: Actor = Depends(current_actor) +): + return await service.recover( + key=key, runtime=request.app.state, operation=operation, actor=actor + ) diff --git a/backend/app/api/routes/system.py b/backend/app/api/routes/system.py new file mode 100644 index 0000000..a30142c --- /dev/null +++ b/backend/app/api/routes/system.py @@ -0,0 +1,36 @@ +from fastapi import APIRouter, Depends, Request +from fastapi.responses import JSONResponse +from app.api.dependencies import current_actor +from app.services import system as service + +router = APIRouter() + + +@router.get("/health") +async def health(request: Request): + return await service.health(request.app.state) + + +@router.get("/live") +async def live(): + return {"status": "ok"} + + +@router.get("/ready") +async def ready(request: Request): + checks = await service.readiness(request.app.state) + healthy = all(checks.values()) + return JSONResponse( + status_code=200 if healthy else 503, + content={"status": "ready" if healthy else "not_ready", "checks": checks}, + ) + + +@router.get("/capabilities", dependencies=[Depends(current_actor)]) +async def capabilities(request: Request): + return await service.capabilities(request.app.state) + + +@router.get("/system/status", dependencies=[Depends(current_actor)]) +async def status(request: Request): + return await service.status(request.app.state) diff --git a/backend/app/api/routes/tokens.py b/backend/app/api/routes/tokens.py new file mode 100644 index 0000000..62231ee --- /dev/null +++ b/backend/app/api/routes/tokens.py @@ -0,0 +1,26 @@ +from fastapi import APIRouter, Depends, Request + + +from app.core.security import Actor +from app.api.dependencies import current_actor, csrf_actor + + +from app.schemas.tokens import TokenInput +from app.services import tokens as service + +router = APIRouter(prefix="/auth/tokens", tags=["tokens"]) + + +@router.get("") +async def list_tokens(request: Request, actor: Actor = Depends(current_actor)): + return await service.list_tokens(runtime=request.app.state, actor=actor) + + +@router.post("", status_code=201) +async def create_token(body: TokenInput, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.create_token(body=body, runtime=request.app.state, actor=actor) + + +@router.delete("/{token_id}", status_code=204) +async def revoke(token_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.revoke(token_id=token_id, runtime=request.app.state, actor=actor) diff --git a/backend/app/api/routes/workflows.py b/backend/app/api/routes/workflows.py new file mode 100644 index 0000000..8d17eda --- /dev/null +++ b/backend/app/api/routes/workflows.py @@ -0,0 +1,163 @@ +from fastapi import APIRouter, Depends, Header, Request + + +from app.core.security import Actor +from app.api.dependencies import csrf_actor, current_actor + + +from app.schemas.workflows import DraftCreate, DraftPatch, RunCreate, Control, Retry +from app.services import workflows as service + +router = APIRouter(prefix="/workflows", tags=["workflows"]) + + +runs_router = APIRouter(prefix="/workflow-runs", tags=["workflows"]) + + +@router.post("", status_code=201) +async def post_draft(body: DraftCreate, request: Request, actor: Actor = Depends(csrf_actor)): + return await service.post_draft(body=body, runtime=request.app.state, actor=actor) + + +@router.get("") +async def list_drafts( + request: Request, + page: int = 1, + page_size: int = 24, + folder_id: str = "", + actor: Actor = Depends(current_actor), +): + return await service.list_drafts( + runtime=request.app.state, page=page, page_size=page_size, actor=actor, folder_id=folder_id + ) + + +@router.get("/{id}") +async def get_draft(id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_draft(id=id, runtime=request.app.state, actor=actor) + + +@router.delete("/{id}") +async def delete_draft( + id: str, + request: Request, + if_match: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.delete_draft( + id=id, runtime=request.app.state, if_match=if_match, actor=actor + ) + + +@router.patch("/{id}") +async def patch_draft( + id: str, + body: DraftPatch, + request: Request, + if_match: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.patch_draft( + id=id, body=body, runtime=request.app.state, if_match=if_match, actor=actor + ) + + +@router.post("/{id}/runs", status_code=202) +async def post_run( + id: str, + body: RunCreate, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.post_run( + id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) + + +@runs_router.get("") +async def list_runs( + request: Request, + page: int = 1, + page_size: int = 24, + folder_id: str = "", + actor: Actor = Depends(current_actor), +): + return await service.list_runs( + runtime=request.app.state, page=page, page_size=page_size, actor=actor, folder_id=folder_id + ) + + +@runs_router.get("/{id}") +async def get_run(id: str, request: Request, actor: Actor = Depends(current_actor)): + return await service.get_run(id=id, runtime=request.app.state, actor=actor) + + +@runs_router.delete("/{id}") +async def delete_run( + id: str, + request: Request, + if_match: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.delete_run( + id=id, runtime=request.app.state, if_match=if_match, actor=actor + ) + + +@runs_router.post("/{id}/steps/{key}/retry", status_code=202) +async def retry_step( + id: str, + key: str, + body: Retry, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.retry_step( + id=id, + key=key, + body=body, + runtime=request.app.state, + idempotency_key=idempotency_key, + actor=actor, + ) + + +@runs_router.post("/{id}/cancel") +async def cancel_run( + id: str, + body: Control, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.cancel_run( + id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) + + +@runs_router.post("/{id}/pause") +async def pause_run( + id: str, + body: Control, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.pause_run( + id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) + + +@runs_router.post("/{id}/resume") +async def resume_run( + id: str, + body: Control, + request: Request, + idempotency_key: str | None = Header(None), + actor: Actor = Depends(csrf_actor), +): + return await service.resume_run( + id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor + ) diff --git a/backend/app/artifacts.py b/backend/app/artifacts.py deleted file mode 100644 index 98a68b8..0000000 --- a/backend/app/artifacts.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Atomic durable manifests. Paths and bytes are validated before result recovery.""" -import hashlib,json,os -from pathlib import Path -from .assets import confined,safe_file - -def digest_file(path): - digest=hashlib.sha256() - with Path(path).open("rb") as stream: - while chunk:=stream.read(1024*1024):digest.update(chunk) - return digest.hexdigest() - -def write_manifest(root,directory,execution_id,fence_token,outputs,result,metadata): - directory=confined(root,directory,exists=True) - entries=[] - for output in outputs: - path=confined(root,output,exists=True) - with safe_file(root,path): pass - entries.append({"path":path.relative_to(root).as_posix(),"size":path.stat().st_size,"sha256":digest_file(path)}) - manifest={"schema":1,"execution_id":execution_id,"fence_token":fence_token,"outputs":entries,"result":result,"metadata":metadata} - target=directory/"result-manifest.json" - temporary=target.with_suffix(".tmp") - with temporary.open("w",encoding="utf-8") as stream: - json.dump(manifest,stream,ensure_ascii=False,allow_nan=False);stream.flush();os.fsync(stream.fileno()) - os.replace(temporary,target) - return manifest - -def verify_manifest(root,manifest): - if manifest.get("schema")!=1 or not manifest.get("outputs"):raise ValueError("Invalid manifest") - paths=[] - for entry in manifest["outputs"]: - if Path(entry["path"]).is_absolute():raise ValueError("Manifest path must be relative") - path=confined(root,entry["path"],exists=True) - with safe_file(root,path):pass - if path.stat().st_size!=entry["size"] or digest_file(path)!=entry["sha256"]:raise ValueError("Artifact hash mismatch") - paths.append(str(path)) - return paths - -def reconcile_artifacts(root): - verified=[];invalid=[] - for path in Path(root).rglob("result-manifest.json"): - try: verify_manifest(root,json.loads(path.read_text(encoding="utf-8")));verified.append(str(path)) - except (OSError,ValueError,KeyError):invalid.append(str(path)) - return {"verified":verified,"invalid":invalid,"deleted":[]} diff --git a/backend/app/assets.py b/backend/app/assets.py deleted file mode 100644 index 1fe5366..0000000 --- a/backend/app/assets.py +++ /dev/null @@ -1,338 +0,0 @@ -import asyncio -import hashlib -import os -from pathlib import Path -import re -import shutil -import stat -from urllib.parse import quote -from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile -from fastapi.responses import StreamingResponse -from pydantic import BaseModel, Field -from sqlalchemy import delete, func, select, update -from starlette.background import BackgroundTask -from .auth import Actor, csrf_actor, current_actor -from .dto import asset_dto -from .errors import fail -from .events import emit_asset, emit_job -from .models import Asset, Job, JobAsset, new_id, utcnow - -router = APIRouter(prefix="/assets", tags=["assets"]) - - -def confined(root, value, *, exists=False): - root = Path(root).resolve() - path = Path(value) - path = (path if path.is_absolute() else root / path).resolve(strict=exists) - if not path.is_relative_to(root): - raise ValueError("File is outside its permitted directory") - return path - - -def safe_file(root, value): - path = confined(root, value, exists=True) - fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) - try: - if not stat.S_ISREG(os.fstat(fd).st_mode): - raise ValueError("Regular file required") - if os.name == "posix": - confined(root, os.readlink(f"/proc/self/fd/{fd}"), exists=True) - return os.fdopen(fd, "rb") - except BaseException: - os.close(fd) - raise - - -async def owned_asset(session, asset_id, owner_id, *, include_deleted=False): - query = select(Asset).where(Asset.id == asset_id, Asset.owner_id == owner_id, - Asset.library_scope == "private", Asset.ready.is_(True)) - if not include_deleted: - query = query.where(Asset.deleted_at.is_(None)) - asset = await session.scalar(query.with_for_update()) - if asset is None: - fail(404, "asset_not_found", "素材不存在") - return asset - - -async def touch_source_job(session, asset): - if asset.source_job_id: - source = await session.scalar(select(Job).where(Job.id == asset.source_job_id, Job.owner_id == asset.owner_id, - Job.deleted_at.is_(None))) - if source is not None: - await emit_job(session, source) - - -async def build_asset(settings, owner_id, asset_id, path, name, **fields): - from .media import inspect_media, make_thumbnail - path = confined(settings.asset_root, path, exists=True) - metadata = await inspect_media(path, settings) - def hash_file(): - digest = hashlib.sha256() - with safe_file(settings.asset_root, path) as source: - while chunk := source.read(1024 * 1024): - digest.update(chunk) - return digest.hexdigest() - digest = await asyncio.to_thread(hash_file) - thumbnail = await make_thumbnail(path, path.with_name("thumbnail.jpg"), settings) - return Asset(id=asset_id, owner_id=owner_id, name=name[:255], - storage_key=path.relative_to(settings.asset_root).as_posix(), - thumbnail_key=Path(thumbnail).relative_to(settings.asset_root).as_posix() if thumbnail else None, - kind=metadata["kind"], mime_type=metadata["mime_type"], size_bytes=path.stat().st_size, - sha256=digest, width=metadata.get("width"), height=metadata.get("height"), - duration_seconds=metadata.get("duration_seconds"), tags=[], favorite=False, **fields) - - -async def validate_workflow_output(job, source, settings): - if job.run_id and job.step_key != "compose" and job.task_type == "video.generate": - from .media import inspect_video_track - source_frames = job.parameters.get('num_frames',121) - if not isinstance(source_frames,int) or isinstance(source_frames,bool): - raise ValueError("Workflow shot does not meet frozen decoded video specification") - required = max(120,source_frames-1) - track = await inspect_video_track(source,settings) - if track['frames']settings.max_output_bytes: - raise ValueError("Output exceeds reserved asset limit; retained for operator reconciliation") - await validate_workflow_output(job,source,settings) - directory = confined(settings.asset_root, Path(job.owner_id) / asset_id) - directory.mkdir(parents=True) - suffix = source.suffix.lower() if re.fullmatch(r"\.[a-z0-9]{1,10}", source.suffix.lower()) else ".bin" - destination = directory / ("original" + suffix) - def copy(): - with safe_file(settings.job_work_root, source) as src, destination.open("xb") as dst: - shutil.copyfileobj(src, dst, 1024 * 1024) - try: - await asyncio.to_thread(copy) - asset = await build_asset(settings, job.owner_id, asset_id, destination, source.name, - origin="generated", source_job_id=job.id, source_upstream_id=job.upstream_id, - source_output_index=index, ready=False) - async with db.session() as session: - current = await session.scalar(select(Job).where(Job.id == job.id, Job.owner_id == job.owner_id, - Job.deleted_at.is_(None))) - if current is None: - raise ValueError("Archived job cannot import output") - if execution_fence: - from .executions import gpu_publication_matches - current=await session.get(Job,job.id) - if not await gpu_publication_matches(session,current,execution_fence):raise ValueError("Stale GPU result import") - from .quotas import enforce_owner_asset_budget - await enforce_owner_asset_budget(session,settings,job.owner_id,asset.size_bytes) - session.add(asset) - await session.flush() - if execution_fence: - from .v2_models import AssetReference - session.add(AssetReference(owner_id=job.owner_id,asset_id=asset.id,ref_kind="execution",ref_id=execution_fence["execution_id"])) - await session.commit() - return asset - except BaseException: - # Commit may have succeeded despite lost ACK; retain for reconciliation. - raise - - -@router.post("", status_code=201) -async def upload(request: Request, file: UploadFile = File(), name: str | None = Form(default=None), - actor: Actor = Depends(csrf_actor)): - settings = request.app.state.settings - from .maintenance import require_writable - from .quotas import check_storage_budget - require_writable(settings) - async with request.app.state.db.session() as session: - await check_storage_budget(session,settings,actor.id,min(max(0,int(request.headers.get("content-length","0"))) if request.headers.get("content-length","0").isdigit() else settings.max_upload_bytes,settings.max_upload_bytes)) - asset_id = new_id() - directory = confined(settings.asset_root, Path(actor.id) / asset_id) - directory.mkdir(parents=True) - original_name = (file.filename or "素材").replace("\\", "/").rsplit("/", 1)[-1] - suffix = Path(original_name).suffix.lower() - if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix): - suffix = ".bin" - path, size = directory / ("original" + suffix), 0 - commit_started = False - try: - with path.open("xb") as output: - while chunk := await file.read(1024 * 1024): - size += len(chunk) - if size > settings.max_upload_bytes: - fail(413, "upload_too_large", "文件超过上传大小限制") - output.write(chunk) - if not size: - fail(422, "empty_upload", "文件不能为空") - asset = await build_asset(settings, actor.id, asset_id, path, name or original_name or "素材", origin="upload") - if asset.kind not in {"image", "video", "audio"}: - fail(422, "unsupported_upload", "上传仅支持图片、视频或音频") - async with request.app.state.db.session() as session: - from .quotas import enforce_owner_asset_budget - await enforce_owner_asset_budget(session,settings,actor.id,asset.size_bytes) - session.add(asset) - await session.flush() - commit_started = True - emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)}) - await session.commit() - return asset_dto(asset) - except BaseException as exc: - if not commit_started: - shutil.rmtree(directory, ignore_errors=True) - if hasattr(exc, "code") and hasattr(exc, "message"): - fail(422, exc.code, exc.message) - raise - finally: - await file.close() - - -@router.get("") -async def list_assets(request: Request, page: int = 1, page_size: int = 24, kind: str = "", q: str = "", tag: str = "", favorite: bool | None = None, origin: str = "", - actor: Actor = Depends(current_actor)): - if page < 1 or not 1 <= page_size <= 100: - fail(422, "invalid_page", "分页参数无效") - async with request.app.state.db.session() as session: - query = select(Asset).where(Asset.owner_id == actor.id, Asset.library_scope == "private", - Asset.deleted_at.is_(None), Asset.ready.is_(True)) - if kind: - query = query.where(Asset.kind == kind) - if q: - query = query.where(Asset.name.contains(q[:255], autoescape=True)) - from .v2_models import AssetTag - if favorite is not None:query=query.where(Asset.favorite==favorite) - if origin:query=query.where(Asset.origin==origin) - if tag:query=query.where(Asset.id.in_(select(AssetTag.asset_id).where(AssetTag.owner_id==actor.id,AssetTag.tag==tag))) - total=await session.scalar(select(func.count()).select_from(query.subquery())) - rows=(await session.scalars(query.order_by(Asset.created_at.desc(),Asset.id.desc()).offset((page-1)*page_size).limit(page_size))).all() - return {"items":[asset_dto(a) for a in rows],"total":total,"page":page,"page_size":page_size} - - - -@router.get("/{asset_id}") -async def get_asset(asset_id: str, request: Request, actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - return asset_dto(await owned_asset(session, asset_id, actor.id)) - - -class AssetPatch(BaseModel): - name: str | None = Field(default=None, min_length=1, max_length=255) - tags: list[str] | None = Field(default=None, max_length=30) - favorite: bool | None = None - - -@router.patch("/{asset_id}") -async def patch_asset(asset_id: str, body: AssetPatch, request: Request, actor: Actor = Depends(csrf_actor)): - async with request.app.state.db.session() as session: - asset = await owned_asset(session, asset_id, actor.id) - if body.name is not None: - asset.name = body.name.strip() or asset.name - if body.tags is not None: - if any(not tag.strip() or len(tag) > 64 for tag in body.tags): - fail(422, "invalid_tag", "标签须为 1–64 个字符") - asset.tags = list(dict.fromkeys(tag.strip() for tag in body.tags)) - from .v2_models import AssetTag - await session.execute(delete(AssetTag).where(AssetTag.asset_id==asset.id)) - session.add_all(AssetTag(owner_id=actor.id,asset_id=asset.id,tag=tag) for tag in asset.tags) - if body.favorite is not None: - asset.favorite = body.favorite - emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)}) - await touch_source_job(session, asset) - await session.commit() - return asset_dto(asset) - - -@router.delete("/{asset_id}", status_code=204) -async def delete_asset(asset_id: str, request: Request, actor: Actor = Depends(csrf_actor)): - async with request.app.state.db.session() as session: - asset = await owned_asset(session, asset_id, actor.id, include_deleted=True) - from .asset_deletion import remove_asset - from .v2_models import Submission - await remove_asset(session, request.app.state.settings, asset) - # Match the deleted result only: a publication's private source may be - # deleted while its independent shared snapshot remains available. - await session.execute(update(Submission).where( - Submission.owner_id == actor.id, Submission.status != "purged", - Submission.resource_json["asset_id"].as_string() == asset.id).values(status="purged")) - emit_asset(session, actor.id, "asset.deleted", {"id": asset.id}) - await touch_source_job(session, asset) - await session.commit() - return Response(status_code=204) - - -def file_response(settings, asset, key, range_header, download): - try: - handle = safe_file(settings.asset_root, key) - except (ValueError, OSError): - fail(404, "file_unavailable", "素材文件不可用") - size = os.fstat(handle.fileno()).st_size - start, end, code = 0, size - 1, 200 - if range_header: - match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip()) - try: - if not match or not any(match.groups()): - raise ValueError - a, b = match.groups() - if a: - start, end = int(a), min(int(b), size - 1) if b else size - 1 - else: - start, end = max(0, size - int(b)), size - 1 - if start > end or start >= size or start < 0: - raise ValueError - code = 206 - except ValueError: - handle.close() - return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"}) - handle.seek(start) - def chunks(): - remaining = end - start + 1 - try: - while remaining > 0: - data = handle.read(min(1024 * 1024, remaining)) - if not data: - break - remaining -= len(data) - yield data - finally: - handle.close() - headers = {"Accept-Ranges": "bytes", "Content-Length": str(max(0, end - start + 1)), - "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store", - "Content-Disposition": ("attachment" if download else "inline") + "; filename*=UTF-8''" + quote(asset.name, safe="")} - if code == 206: - headers["Content-Range"] = f"bytes {start}-{end}/{size}" - return StreamingResponse(chunks(), status_code=code, media_type="image/jpeg" if key != asset.storage_key else asset.mime_type, - headers=headers, background=BackgroundTask(handle.close)) - - -@router.get("/{asset_id}/content") -async def content(asset_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - asset = await owned_asset(session, asset_id, actor.id) - return file_response(request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download) - - -@router.get("/{asset_id}/thumbnail") -async def thumbnail(asset_id: str, request: Request, actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - asset = await owned_asset(session, asset_id, actor.id) - if not asset.thumbnail_key and asset.kind != "image": - fail(404, "thumbnail_unavailable", "预览图暂不可用") - return file_response(request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False) diff --git a/backend/app/auth.py b/backend/app/auth.py deleted file mode 100644 index ddb2a6f..0000000 --- a/backend/app/auth.py +++ /dev/null @@ -1,239 +0,0 @@ -import asyncio -from dataclasses import dataclass, field -from datetime import timedelta -import hashlib -import hmac -import re -import secrets -from fastapi import APIRouter, Depends, Request, Response -from pydantic import BaseModel, Field -from sqlalchemy import delete, select, func -from sqlalchemy.exc import IntegrityError -from .errors import fail -from .models import Session, User, utcnow - -router = APIRouter(prefix="/auth", tags=["auth"]) -COOKIE = "cmvr_session" - - -def token_hash(token): - return hashlib.sha256(token.encode()).hexdigest() - - -def hash_password(password): - salt = secrets.token_bytes(16) - key = hashlib.scrypt(password.encode(), salt=salt, n=32768, r=8, p=1, dklen=64, maxmem=128 * 1024 * 1024) - return f"scrypt$32768$8$1${salt.hex()}${key.hex()}" - - -def verify_password(password, encoded): - try: - _, n, r, p, salt, expected = encoded.split("$") - key = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p), - dklen=64, maxmem=128 * 1024 * 1024) - return hmac.compare_digest(key.hex(), expected) - except (ValueError, TypeError): - hashlib.scrypt(password.encode(), salt=b"\0" * 16, n=32768, r=8, p=1, maxmem=128 * 1024 * 1024) - return False - - -def validate_password(password, *, minimum=12): - if not minimum <= len(password) <= 256: - fail(422, "weak_password", f"密码长度须为 {minimum}–256 个字符") - - -def user_dto(user): - return {"id": user.id, "username": user.username, "display_name": user.display_name, "role": user.role, "disabled": user.disabled, "must_change_password": user.must_change_password} - - -@dataclass -class Actor: - id: str - username: str - display_name: str - role: str - csrf_token: str - token_hash: str - auth_kind: str = "session" - scopes: list[str] = field(default_factory=list) - must_change_password: bool = False - - -async def current_actor(request: Request): - authorization = request.headers.get("Authorization", "") - if authorization.startswith("Bearer "): - from .tokens import bearer_actor - return await bearer_actor(request, authorization[7:]) - token = request.cookies.get(COOKIE) - if not token or len(token) > 512: - fail(401, "not_authenticated", "请先登录") - async with request.app.state.db.session() as session: - row = (await session.execute(select(Session, User).join(User, User.id == Session.user_id) - .where(Session.token_hash == token_hash(token), Session.expires_at > utcnow(), - User.disabled.is_(False)))).first() - if row is None: - fail(401, "session_expired", "登录已失效,请重新登录") - saved, user = row - return Actor(user.id, user.username, user.display_name, user.role, saved.csrf_token, saved.token_hash, must_change_password=user.must_change_password) - - -async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)): - if actor.auth_kind == "bearer": - if request.headers.get("sec-fetch-site") or request.cookies.get(COOKIE): - fail(403, "machine_token_only", "Use session authentication in browsers") - return actor - supplied = request.headers.get("X-CSRF-Token", "") - if not hmac.compare_digest(supplied.encode("utf-8"), actor.csrf_token.encode("utf-8")): - fail(403, "csrf_failed", "请求校验失败,请刷新登录状态") - # Same-origin proxy is the deployment default; reject explicitly cross-site writes. - if request.headers.get("sec-fetch-site") == "cross-site": - fail(403, "cross_site_request", "不允许跨站写入") - return actor - - -class Login(BaseModel): - username: str = Field(min_length=1, max_length=64) - password: str = Field(min_length=1, max_length=256) - - -class CreateUser(Login): - display_name: str = Field(default="", max_length=80) - - -async def bootstrap_admin(db, settings): - if not settings.admin_username and not settings.admin_password: - return - if not settings.admin_username or not settings.admin_password: - raise ValueError("Both ADMIN_USERNAME and ADMIN_PASSWORD are required for bootstrap") - # The initial account may use the operator's explicitly chosen six-character - # password. Ordinary user creation keeps the 12-character minimum. - validate_password(settings.admin_password, minimum=6) - async with db.session() as session: - exists = await session.scalar(select(User).where(User.username == settings.admin_username.strip().lower())) - if exists is not None: - return - session.add(User(username=settings.admin_username.strip().lower(), display_name=settings.admin_display_name, - role="admin", must_change_password=True, password_hash=await asyncio.to_thread(hash_password, settings.admin_password))) - await session.commit() - - -@router.post("/login") -async def login(body: Login, request: Request, response: Response): - async with request.app.state.db.session() as session: - user = await session.scalar(select(User).where(User.username == body.username.strip().lower())) - valid = await asyncio.to_thread(verify_password, body.password, user.password_hash if user else "") - if not valid or user is None or user.disabled: - fail(401, "invalid_credentials", "用户名或密码不正确") - token, csrf = secrets.token_urlsafe(32), secrets.token_urlsafe(32) - settings = request.app.state.settings - session.add(Session(token_hash=token_hash(token), user_id=user.id, csrf_token=csrf, - expires_at=utcnow() + timedelta(hours=settings.session_hours))) - await session.commit() - response.set_cookie(COOKIE, token, httponly=True, secure=settings.cookie_secure, samesite="lax", - max_age=settings.session_hours * 3600, path="/") - return {"user": user_dto(user), "csrf_token": csrf} - - -@router.get("/me") -async def me(actor: Actor = Depends(current_actor)): - return {"user": {"id": actor.id, "username": actor.username, "display_name": actor.display_name, "role": actor.role, "must_change_password": actor.must_change_password}, - "csrf_token": actor.csrf_token} - - -@router.post("/logout", status_code=204) -async def logout(request: Request, actor: Actor = Depends(csrf_actor)): - async with request.app.state.db.session() as session: - await session.execute(delete(Session).where(Session.token_hash == actor.token_hash)) - await session.commit() - response = Response(status_code=204) - response.delete_cookie(COOKIE, path="/") - return response - - -@router.post("/users", status_code=201) -async def create_user(body: CreateUser, request: Request, actor: Actor = Depends(csrf_actor)): - if actor.role != "admin" or actor.auth_kind != "session": - fail(403, "admin_required", "此操作仅限管理员") - username = body.username.strip().lower() - if not re.fullmatch(r"[a-z0-9_.-]{3,64}", username): - fail(422, "invalid_username", "用户名须为 3–64 位字母、数字、点、横线或下划线") - validate_password(body.password) - async with request.app.state.db.session() as session: - user = User(username=username, display_name=body.display_name.strip() or username, - password_hash=await asyncio.to_thread(hash_password, body.password)) - session.add(user) - try: - await session.commit() - except IntegrityError: - fail(409, "username_exists", "用户名已存在") - return user_dto(user) - - -class UserPatch(BaseModel): - display_name: str | None = Field(default=None,min_length=1,max_length=80) - disabled: bool | None = None - -class PasswordChange(BaseModel): - current_password: str = Field(max_length=256) - new_password: str = Field(max_length=256) - -@router.get("/users") -async def list_users(request:Request,page:int=1,page_size:int=24,actor:Actor=Depends(current_actor)): - if actor.role!="admin" or actor.auth_kind!="session": fail(403,"admin_required","Administrator session required") - if page<1 or not 1<=page_size<=100: fail(422,"invalid_page","Invalid page") - async with request.app.state.db.session() as session: - total=await session.scalar(select(func.count()).select_from(User)) - rows=(await session.scalars(select(User).order_by(User.created_at,User.id).offset((page-1)*page_size).limit(page_size))).all() - return {"items":[user_dto(u) for u in rows],"total":total,"page":page,"page_size":page_size} - -@router.patch("/users/{user_id}") -async def patch_user(user_id:str,body:UserPatch,request:Request,actor:Actor=Depends(csrf_actor)): - if actor.role!="admin" or actor.auth_kind!="session": fail(403,"admin_required","Administrator session required") - from .models import Job - from .events import emit_job - async with request.app.state.db.session() as session: - user=await session.get(User,user_id) - if not user: fail(404,"user_not_found","User not found") - if body.disabled and user.role=="admin" and not user.disabled: - count=await session.scalar(select(func.count()).select_from(User).where(User.role=="admin",User.disabled.is_(False))) - if count<=1: fail(409,"last_admin","Cannot disable the last administrator") - if body.display_name is not None: user.display_name=body.display_name.strip() or user.display_name - if body.disabled is not None: - user.disabled=body.disabled - if body.disabled: - await session.execute(delete(Session).where(Session.user_id==user_id)) - from .v2_models import ApiToken - from sqlalchemy import update - await session.execute(update(ApiToken).where(ApiToken.owner_id==user_id,ApiToken.revoked_at.is_(None)).values(revoked_at=utcnow())) - from .v2_models import WorkflowRun,Batch - runs=(await session.scalars(select(WorkflowRun).where(WorkflowRun.owner_id==user_id,WorkflowRun.state.notin_(["succeeded","failed","cancelled"])))).all() - from .workflows import emit_run - from .batches import emit_batch - for run in runs: - if "admin_suspend" not in (run.hold_reasons or []): - run.hold_reasons=list(set((run.hold_reasons or [])+["admin_suspend"])) - await emit_run(session,run) - batches=(await session.scalars(select(Batch).where(Batch.owner_id==user_id,Batch.state.notin_(["succeeded","cancelled","completed_with_errors"])))).all() - for batch in batches: - if "admin_suspend" not in (batch.hold_reasons or []): - batch.hold_reasons=list(set((batch.hold_reasons or [])+["admin_suspend"])) - await emit_batch(session,batch) - rows=(await session.scalars(select(Job).where(Job.owner_id==user_id,Job.state.notin_(["succeeded","failed","cancelled","timed_out"])))).all() - for job in rows: - job.hold_reasons=list(set((job.hold_reasons or [])+["admin_suspend"])) - await emit_job(session,job) - await session.commit() - return user_dto(user) - -@router.post("/password") -async def change_password(body:PasswordChange,request:Request,actor:Actor=Depends(csrf_actor)): - if actor.auth_kind!="session": fail(403,"session_required","Session required") - validate_password(body.new_password) - async with request.app.state.db.session() as session: - user=await session.get(User,actor.id) - if not await asyncio.to_thread(verify_password,body.current_password,user.password_hash): fail(403,"invalid_password","Current password is incorrect") - user.password_hash=await asyncio.to_thread(hash_password,body.new_password) - user.must_change_password=False - await session.execute(delete(Session).where(Session.user_id==actor.id)) - await session.commit() - return {"requires_relogin":True} diff --git a/backend/app/batches.py b/backend/app/batches.py deleted file mode 100644 index a33d015..0000000 --- a/backend/app/batches.py +++ /dev/null @@ -1,202 +0,0 @@ -"""Persistent mixed workflow/job batches with independently eligible members.""" -from typing import Literal -from fastapi import APIRouter, Depends, Header, Request, HTTPException -from pydantic import Field -from sqlalchemy import select -from .auth import Actor, csrf_actor, current_actor -from .dto import iso -from .errors import fail -from .events import emit_asset, emit_job -from .jobs import Submit, create_jobs, validate_submission, TERMINAL -from .models import Job, utcnow -from .submissions import accept_submission -from .timeline import Strict -from .v2_models import Batch, BatchItem, WorkflowDraft, WorkflowRun, Execution -from .workflows import owned, cursor, create_run, control_run, page_rows, wake, RUN_TERMINAL, check_batch_capability, emit_run - -router=APIRouter(prefix='/batches',tags=['batches']) -class BatchWorkflow(Strict): - kind:Literal['workflow'] - draft_id:str - draft_revision:int=Field(ge=1) - expected_version:int=Field(ge=1) -class BatchJob(Strict): - kind:Literal['job'] - task_type:str - input:dict=Field(default_factory=dict) - parameters:dict=Field(default_factory=dict) - count:int=Field(default=1,ge=1,le=4) -class BatchCreate(Strict): - name:str=Field(default='夜间批次',min_length=1,max_length=255) - items:list[BatchWorkflow|BatchJob]=Field(min_length=1,max_length=100) -class BatchControl(Strict): - desired_state:Literal['run','pause','cancel'] - expected_version:int|None=Field(default=None,ge=1) - -def batch_dto(b,items): - return dict(id=b.id,name=b.name,state=b.state,desired_state=b.desired_state,hold_reasons=b.hold_reasons or [],version=b.version,created_at=iso(b.created_at),finished_at=iso(b.finished_at),total_items=len(items),completed_items=sum(i.state=='succeeded' for i in items),current_item_index=next((i.item_index for i in items if i.state=='running'),None),active_item_indices=[i.item_index for i in items if i.state in {'running','cleanup_pending'}],active_item_count=sum(i.state in {'running','cleanup_pending'} for i in items)) -async def snapshot_batch(s,owner,id): - b=await owned(s,Batch,id,owner) - items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all() - return {'batch':batch_dto(b,items),'items':[{k:getattr(i,k) for k in ('id','batch_id','item_index','target_kind','target_id','state','spec_json')} for i in items],'cursor':await cursor(s,owner)} -async def emit_batch(s,b): - if b.deleted_at is not None:return - b.version+=1;snap=await snapshot_batch(s,b.owner_id,b.id);emit_asset(s,b.owner_id,'batch.updated',{'batch':snap['batch'],'items':snap['items']}) - -async def active_member(s,items): - eligible=[i for i in items if i.state not in {'succeeded','cancelled','failed','timed_out','blocked'}] - # A retry joins behind the member already admitted. Its batch_wait hold - # survives ticks until that member drains, including a queued child. - for item in eligible: - if item.target_kind=='run': - target=await s.get(WorkflowRun,item.target_id) - if target and target.deleted_at is None and 'batch_wait' not in (target.hold_reasons or []):return item - else: - # target_id is only the group's representative. It may already - # be cancelled while a different job in the member is draining. - jobs=(await s.scalars(select(Job).where(Job.batch_id==item.batch_id,Job.batch_item_index==item.item_index,Job.state.not_in(TERMINAL)))).all() - if any('batch_wait' not in (j.hold_reasons or []) for j in jobs):return item - return eligible[0] if eligible else None - -def member_holds(holds,b,waiting): - holds=set(holds or [])|set(b.hold_reasons or []) - if b.desired_state=='pause':holds.add('batch_pause') - else:holds.discard('batch_pause') - if waiting:holds.add('batch_wait') - else:holds.discard('batch_wait') - return holds - -async def run_member_holds(s,r): - b=await s.get(Batch,r.batch_id) - if b is None or b.deleted_at is not None:return set(r.hold_reasons or [])|{'batch_wait'} - return member_holds(r.hold_reasons,b,False) - -async def advance_batches(s,settings): - batches=(await s.scalars(select(Batch).where(Batch.deleted_at.is_(None),Batch.state.not_in({'succeeded','cancelled','completed_with_errors'})).order_by(Batch.created_at,Batch.id).with_for_update())).all() - for b in batches: - items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all() - before=(b.state,tuple(i.state for i in items)) - for item in items: - if item.target_kind=='run': - target=await s.get(WorkflowRun,item.target_id);item.state=target.state - else: - jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index))).all() - if all(j.state in TERMINAL for j in jobs):item.state='succeeded' if all(j.state=='succeeded' for j in jobs) else 'cancelled' if all(j.state=='cancelled' for j in jobs) else 'failed' - elif any(j.state in {'running','collecting','cancelling'} for j in jobs):item.state='running' - else:item.state='queued' - if item.state in {'failed','cancelled','timed_out','blocked'}: - target_jobs=select(Job.id).where(Job.run_id==item.target_id) if item.target_kind=='run' else select(Job.id).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index) - pending=await s.scalar(select(Execution.id).where(Execution.job_id.in_(target_jobs),Execution.state.not_in({'exited','results_ready'}))) - if pending:item.state='cleanup_pending' - active=await active_member(s,items) - for item in items: - if item.target_kind=='run': - target=await s.get(WorkflowRun,item.target_id) - holds=sorted(member_holds(target.hold_reasons,b,False)) - if target.hold_reasons!=holds: - target.hold_reasons=holds;await emit_run(s,target) - jobs=(await s.scalars(select(Job).where(Job.run_id==item.target_id,Job.state.not_in(TERMINAL)))).all() - else: - jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index,Job.state.not_in(TERMINAL)))).all() - for j in jobs: - holds=member_holds(j.hold_reasons,b,False) - if item.target_kind=='run': - # Parent admission pressure must not stop accepted children - # from completing and freeing the very quota it waits for. - holds-= {'quota','storage'} - holds|=set(target.hold_reasons or [])-{'quota','storage'} - holds=sorted(holds) - if j.hold_reasons!=holds: - j.hold_reasons=holds;await emit_job(s,j) - if all(i.state in RUN_TERMINAL|{'timed_out'} for i in items): - b.state='cancelled' if b.desired_state=='cancel' else 'succeeded' if all(i.state=='succeeded' for i in items) else 'completed_with_errors';b.finished_at=utcnow() - elif b.desired_state=='cancel':b.state='cancelling' - elif b.desired_state=='pause' or b.hold_reasons:b.state='paused' - elif not active:b.state='blocked' - else:b.state='running' - if before!=(b.state,tuple(i.state for i in items)):await emit_batch(s,b) - -@router.post('',status_code=202) -async def post_batch(body:BatchCreate,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - from .maintenance import require_writable - require_writable(request.app.state.settings) - capability_error=None - try:await check_batch_capability(request,[i.task_type if i.kind=='job' else 'video.generate' for i in body.items]) - except HTTPException as exc:capability_error=exc - async with request.app.state.db.session() as s: - sub=await accept_submission(s,actor.id,'batch.create',idempotency_key,2,body.model_dump(mode='json')) - if sub.resource_json:b=await owned(s,Batch,sub.resource_json['batch_id'],actor.id) - else: - if capability_error:raise capability_error - from .quotas import reserve_budget,check_parent_capacity - await reserve_budget(s,actor.id,'batch.create',units=0,settings=request.app.state.settings) - await check_parent_capacity(s,request.app.state.settings,actor.id,'batch') - b=Batch(owner_id=actor.id,name=body.name,spec_snapshot=body.model_dump(mode='json'));s.add(b);await s.flush() - frozen_drafts={} - for item in body.items: - if item.kind=='workflow': - d=await owned(s,WorkflowDraft,item.draft_id,actor.id) - if d.version!=item.expected_version or d.revision!=item.draft_revision:fail(409,'draft_version_conflict','Draft version conflict.') - frozen_drafts[d.id]=d - for idx,item in enumerate(body.items): - if item.kind=='workflow': - r=await create_run(s,actor.id,item.draft_id,frozen_drafts[item.draft_id].version,item.draft_revision,'batch',batch_id=b.id,batch_item_index=idx,settings=request.app.state.settings) - kind,target='run',r.id - else: - jobs=await create_jobs(s,Submit(task_type=item.task_type,input=item.input,parameters=item.parameters,count=item.count,execution_mode='batch'),actor,request.app.state.settings,key=f'batch:{b.id}:{idx}',internal=True) - for j in jobs: - j.batch_id=b.id;j.batch_item_index=idx - await emit_job(s,j) - kind,target='job',jobs[0].id - s.add(BatchItem(batch_id=b.id,item_index=idx,target_kind=kind,target_id=target,spec_json=item.model_dump(mode='json'))) - sub.resource_json={'batch_id':b.id};await emit_batch(s,b) - await s.commit();snap=await snapshot_batch(s,actor.id,b.id) - wake(request);return snap - -@router.get('') -async def list_batches(request:Request,page:int=1,page_size:int=24,actor:Actor=Depends(current_actor)): - async with request.app.state.db.session() as s: - rows,data=await page_rows(s,Batch,actor,page,page_size);return {**data,'items':[(await snapshot_batch(s,actor.id,b.id))['batch'] for b in rows]} -@router.get('/{id}') -async def get_batch(id:str,request:Request,actor:Actor=Depends(current_actor)): - async with request.app.state.db.session() as s:return await snapshot_batch(s,actor.id,id) -@router.delete('/{id}') -async def delete_batch(id:str,request:Request,if_match:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - from .deletions import archive_records - async with request.app.state.db.session() as s: - result=await archive_records(s,Batch,id,actor.id,if_match) - await s.commit() - return result -@router.post('/{id}/control') -async def batch_control(id:str,body:BatchControl,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - async with request.app.state.db.session() as s: - sub=await accept_submission(s,actor.id,'batch.control',idempotency_key,2,{'batch_id':id,**body.model_dump()}) - b=await owned(s,Batch,id,actor.id) - if not sub.resource_json: - if body.expected_version is not None and b.version!=body.expected_version:fail(409,'batch_version_conflict','批次版本冲突') - if b.state not in {'succeeded','cancelled','completed_with_errors'}: - if b.desired_state=='cancel' and body.desired_state!='cancel':fail(409,'batch_cancelled','取消不可逆') - b.desired_state=body.desired_state - runs=(await s.scalars(select(WorkflowRun).where(WorkflowRun.batch_id==b.id))).all() - for r in runs: - if body.desired_state=='cancel':await control_run(s,r,'cancel') - else: - holds=set(r.hold_reasons or []) - if body.desired_state=='pause':holds.add('batch_pause') - else:holds.discard('batch_pause') - r.hold_reasons=sorted(holds) - jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.state.not_in(TERMINAL)))).all() - for j in jobs: - holds=set(j.hold_reasons or []) - if body.desired_state=='pause':holds.add('batch_pause') - else:holds.discard('batch_pause') - j.hold_reasons=sorted(holds) - if body.desired_state=='cancel': - j.desired_state='cancel';j.cancel_requested=True - if not j.upstream_id and not j.upstream_payload and j.phase not in {'cpu_running','preparing'}:j.state='cancelled';j.phase='cancelled';j.finished_at=utcnow() - elif j.state!='collecting':j.state='cancelling';j.phase='cancellation_pending' - await emit_job(s,j) - await advance_batches(s,request.app.state.settings);await emit_batch(s,b) - sub.resource_json={'batch_id':id} - await s.commit();snap=await snapshot_batch(s,actor.id,id) - wake(request);return snap diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py new file mode 100644 index 0000000..012adae --- /dev/null +++ b/backend/app/bootstrap.py @@ -0,0 +1,106 @@ +"""应用组装边界:仅在 lifespan 中创建外部资源,退出时按顺序回收。""" + +from contextlib import asynccontextmanager +import logging +from fastapi import FastAPI +from fastapi.responses import JSONResponse +from sqlalchemy.exc import SQLAlchemyError +from app.api.router import router as api_router +from app.core.config import Settings +from app.core.database import Database +from app.services.auth import bootstrap_admin +from app.services.orchestration.coordinator import Coordinator + + +def create_app(settings=None, *, provider=None): + + @asynccontextmanager + async def lifespan(app): + configuration = settings or Settings.from_env() + for root in ( + configuration.asset_root, + configuration.job_work_root, + configuration.state_root, + ): + root.mkdir(parents=True, exist_ok=True) + db = Database(configuration) + app.state.settings, app.state.db = (configuration, db) + live_provider = provider + if live_provider is None: + from app.adapters.provider.client import Provider + + live_provider = Provider(configuration) + app.state.provider = live_provider + coordinator = Coordinator(configuration, db, live_provider) + app.state.coordinator = coordinator + app.state.draining = False + + async def after_tick(): + from app.services.orchestration.workflow_engine import advance_workflows + + await advance_workflows(db, configuration, live_provider) + + coordinator.after_tick = after_tick + try: + await db.initialize() + await bootstrap_admin(db, configuration) + from app.core.public_preflight import require_public_ready + + await require_public_ready(db, configuration) + if configuration.run_coordinator: + await coordinator.start() + yield + finally: + app.state.draining = True + await coordinator.close() + await live_provider.aclose() + await db.close() + + app = FastAPI(title="CMVR Visual", lifespan=lifespan) + from app.api.middleware.upload_guard import UploadGuard + + app.add_middleware(UploadGuard) + + @app.middleware("http") + async def maintenance_writes(request, call_next): + from app.core.maintenance import maintenance_active + + configuration = getattr(request.app.state, "settings", None) + if ( + configuration + and request.method in {"POST", "PUT", "PATCH", "DELETE"} + and request.url.path.startswith("/api/") + and (request.url.path not in {"/api/auth/login", "/api/auth/logout"}) + and maintenance_active(configuration) + ): + return JSONResponse( + status_code=503, + content={ + "detail": { + "code": "maintenance", + "message": "系统维护中,任务和草稿已保留,请稍后重试", + } + }, + ) + return await call_next(request) + + @app.exception_handler(SQLAlchemyError) + async def database_failure(request, exc): + logging.getLogger(__name__).error("Database request failed: %s", type(exc).__name__) + return JSONResponse( + status_code=503, + content={ + "detail": {"code": "database_unavailable", "message": "数据库暂不可用,请稍后重试"} + }, + ) + + @app.exception_handler(Exception) + async def internal_failure(request, exc): + logging.getLogger(__name__).exception("Unhandled application error") + return JSONResponse( + status_code=500, + content={"detail": {"code": "internal_error", "message": "服务处理失败,请联系管理员"}}, + ) + + app.include_router(api_router, prefix="/api") + return app diff --git a/backend/app/config.py b/backend/app/config.py deleted file mode 100644 index 76b4784..0000000 --- a/backend/app/config.py +++ /dev/null @@ -1,127 +0,0 @@ -from dataclasses import dataclass -import os -from pathlib import Path -from sqlalchemy.engine import URL, make_url - - -def boolean(value): - return str(value).lower() in {"1", "true", "yes", "on"} - - -@dataclass -class Settings: - mode: str = "production" - database_url: str | None = None - mysql_host: str = "192.168.28.10" - mysql_port: int = 3306 - mysql_database: str = "cmvr-visual" - mysql_user: str = "" - mysql_password: str = "" - workspace_root: Path = Path("/workspace") - asset_root: Path | None = None - job_work_root: Path | None = None - state_root: Path | None = None - admin_username: str = "" - admin_password: str = "" - admin_display_name: str = "管理员" - cookie_secure: bool = True - session_hours: int = 12 - public_access: bool = False - # Zero disables this optional per-owner unfinished interactive GPU job cap. - max_interactive_gpu_jobs: int = 0 - max_creation_commands_per_minute: int = 6 - max_owner_asset_bytes: int = 100 * 1024**3 - max_data_bytes: int = 2 * 1024**4 - min_free_bytes: int = 50 * 1024**3 - max_owner_jobs: int = 500 - max_global_jobs: int = 2000 - max_owner_runs: int = 100 - max_global_runs: int = 1000 - max_owner_batches: int = 20 - max_global_batches: int = 200 - run_coordinator: bool = True - poll_seconds: float = 1.0 - event_heartbeat_seconds: float = 15.0 - max_upload_bytes: int = 512 * 1024 * 1024 - max_output_bytes: int = 2 * 1024 * 1024 * 1024 - request_timeout_seconds: float = 30.0 - inference_base_url: str = "http://llmuser-workspace:18190" - inference_api_key: str = "" - inference_api_key_file: Path | None = Path("/workspace/projects/llm-services/config/api_key") - gpu_status_path: Path | None = Path("/run/llm-gpu-policy/status.json") - gpu_scheduler_path: Path | None = Path("/workspace/projects/llm-services/state/gpu-scheduler.json") - runtime_policy_file: Path | None = Path("/workspace/projects/llm-services/config/runtime-policy.json") - qwen_base_url: str = "http://192.168.28.10:14081/v1" - qwen_model: str = "Qwen/Qwen3.8-27B-FP8" - qwen_api_key: str = "" - ffmpeg_bin: str = "ffmpeg" - ffprobe_bin: str = "ffprobe" - tts_base_url: str = "" - tts_model: str = "kokoro-82m" - tts_api_key: str = "" - tts_voices: tuple[str, ...] = ("zf_xiaobei", "zm_yunxi") - - def __post_init__(self): - if self.mode not in {"production", "preview", "test"}: - raise ValueError("CMVR_MODE must be production, preview or test") - if self.max_interactive_gpu_jobs < 0: - raise ValueError("MAX_INTERACTIVE_GPU_JOBS must be non-negative; 0 disables the limit") - self.workspace_root = Path(self.workspace_root).resolve() - for field, leaf in (("asset_root", "assets"), ("job_work_root", "jobs"), ("state_root", "state")): - value = Path(getattr(self, field) or self.workspace_root / "cmvr-visual" / leaf).resolve() - if not value.is_relative_to(self.workspace_root): - raise ValueError(field + " must stay inside WORKSPACE_ROOT") - setattr(self, field, value) - for field in ("inference_api_key_file", "gpu_status_path", "gpu_scheduler_path", "runtime_policy_file"): - if getattr(self, field): - setattr(self, field, Path(getattr(self, field))) - if self.database_url: - url = make_url(self.database_url) - if url.drivername.startswith("sqlite"): - if self.mode not in {"preview", "test"} or url.drivername != "sqlite+aiosqlite": - raise ValueError("SQLite requires explicit test/preview mode and the aiosqlite driver") - elif url.drivername != "mysql+aiomysql": - raise ValueError("Production database must use mysql+aiomysql") - elif self.mode != "production": - raise ValueError("Test/preview mode requires an explicit DATABASE_URL") - elif not self.mysql_user or not self.mysql_password: - raise ValueError("Production MySQL credentials must be configured") - - @property - def sqlalchemy_url(self): - if self.database_url: - return make_url(self.database_url) - return URL.create("mysql+aiomysql", username=self.mysql_user, password=self.mysql_password, - host=self.mysql_host, port=self.mysql_port, database=self.mysql_database, - query={"charset": "utf8mb4"}) - - @classmethod - def from_env(cls): - env = os.environ - values = {} - strings = ("database_url", "mysql_host", "mysql_database", "mysql_user", "mysql_password", - "admin_username", "admin_password", "admin_display_name", "inference_base_url", - "inference_api_key", "qwen_base_url", "qwen_model", "qwen_api_key", "ffmpeg_bin", "ffprobe_bin", - "tts_base_url", "tts_model", "tts_api_key") - for field in strings: - if field.upper() in env: - values[field] = env[field.upper()] - for field in ("workspace_root", "asset_root", "job_work_root", "state_root", "inference_api_key_file", - "gpu_status_path", "gpu_scheduler_path"): - if field.upper() in env: - values[field] = Path(env[field.upper()]) if env[field.upper()] else None - if env.get("RUNTIME_POLICY_FILE"): - values["runtime_policy_file"] = Path(env["RUNTIME_POLICY_FILE"]) - for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes", "max_owner_jobs", "max_global_jobs", "max_interactive_gpu_jobs", "max_creation_commands_per_minute", "max_owner_asset_bytes", "max_data_bytes", "min_free_bytes", "max_owner_runs", "max_global_runs", "max_owner_batches", "max_global_batches"): - if field.upper() in env: - values[field] = int(env[field.upper()]) - for field in ("poll_seconds", "event_heartbeat_seconds", "request_timeout_seconds"): - if field.upper() in env: - values[field] = float(env[field.upper()]) - for field in ("cookie_secure", "run_coordinator", "public_access"): - if field.upper() in env: - values[field] = boolean(env[field.upper()]) - values["mode"] = env.get("CMVR_MODE", "production") - if "TTS_VOICES" in env: - values["tts_voices"] = tuple(v.strip() for v in env["TTS_VOICES"].split(",") if v.strip()) - return cls(**values) diff --git a/backend/app/coordinator.py b/backend/app/coordinator.py deleted file mode 100644 index ea1cc5f..0000000 --- a/backend/app/coordinator.py +++ /dev/null @@ -1,703 +0,0 @@ -import asyncio -from datetime import timedelta -import json -import logging -import time -from pathlib import Path -import re -from filelock import FileLock -from sqlalchemy import case, or_, select -from .assets import confined, import_output, safe_file, validate_workflow_output -from .dto import asset_dto, public_value -from .events import emit_asset, emit_job -from .jobs import GPU_TYPES, TERMINAL -from .models import Asset, Job, JobAsset, User, utcnow - -LOG = logging.getLogger(__name__) -GPU_FENCE_UNSET = object() - - -class PhaseDeferred(Exception): - pass - - -class Coordinator: - def __init__(self, settings, db, provider): - self.settings, self.db, self.provider = settings, db, provider - self._task = None - self._cpu = {} - self._preparing = {} - self._collecting = {} - # Bound pending coroutines independently of their current phase/slot. - # A Qwen quarantine must leave capacity for unrelated media work. - self._cpu_initial_pool = {} - self._pools = {name:asyncio.Semaphore(1) for name in ("new_gpu","cpu_media","qwen_http")} - self._held_pool = {} - self._blocked_pools = set() - from .admission_clock import AdmissionClock - self._admission_clock=AdmissionClock(settings.state_root / "admission-clock.json") - self._control_sent = {} - self._run_lock = asyncio.Lock() - self._wake = asyncio.Event() - self._file_lock = FileLock(str(settings.state_root / "coordinator.lock")) - self._closing = False - self.after_tick = None - self.last_tick_success = None - self._cancel_sent = set() - self._uncertain_cpu = set() - - def wake(self): - self._wake.set() - - async def start(self): - self._file_lock.acquire(timeout=0) - try: - # CPU calls cannot be replayed after an unknown crash. GPU IDs and - # persisted submit payload/key are resumed by their normal branches. - async with self.db.session() as session: - rows = (await session.scalars(select(Job).where(Job.deleted_at.is_(None), Job.state.notin_(TERMINAL), - Job.task_type.notin_(GPU_TYPES), Job.state.in_(["running","cancelling"])))).all() - from .v2_models import Execution - from .artifacts import verify_manifest - for job in rows: - execution = await session.get(Execution,job.current_execution_id) if job.current_execution_id else None - manifest = execution.manifest_json if execution else None - if not manifest: - candidates = sorted((self.settings.job_work_root / job.id).glob("attempt-*/result-manifest.json")) - for candidate in reversed(candidates): - try: - found=json.loads(candidate.read_text(encoding="utf-8")) - if found.get("execution_id")==job.current_execution_id: - manifest=found;break - except (ValueError,OSError):pass - if manifest and execution: - try: - paths=verify_manifest(self.settings.job_work_root,manifest) - if manifest.get("fence_token")!=execution.fence_token:raise ValueError("Fence mismatch") - job.upstream_result={"cpu_outputs":paths,"cpu_result":manifest["result"],"metadata":manifest["metadata"]} - job.state,job.phase="collecting","importing_outputs" - execution.manifest_json=manifest;execution.state="results_ready" - await emit_job(session,job) - continue - except (ValueError,OSError,KeyError):pass - if execution and (execution.resource_pool == "qwen_http" or job.task_type=="audio.speech"): - self._blocked_pools.add(execution.resource_pool) - execution.state="unknown" - job.state = "cancelled" if job.cancel_requested else "needs_attention" - job.phase, job.finished_at = job.state, utcnow() - job.error_json = {"code": "worker_interrupted", "message": "服务重启中断了此任务,可手动重试", "retriable": True} - await emit_job(session, job) - blocked=(await session.scalars(select(Execution).where(Execution.resource_pool.in_(["qwen_http","cpu_media"]),Execution.state=="unknown"))).all() - self._blocked_pools.update(execution.resource_pool for execution in blocked) - await session.commit() - self._task = asyncio.create_task(self._loop(), name="cmvr-coordinator") - except BaseException: - self._file_lock.release() - raise - - async def close(self): - self._closing = True - if self._task: - self._task.cancel() - await asyncio.gather(self._task, return_exceptions=True) - background=[*self._cpu.values(),*self._preparing.values(),*self._collecting.values()] - for task in background:task.cancel() - await asyncio.gather(*background, return_exceptions=True) - if self._file_lock.is_locked: - self._file_lock.release() - - async def _loop(self): - while True: - try: - await self.run_once() - self.last_tick_success=time.monotonic() - except asyncio.CancelledError: - raise - except Exception: - LOG.exception("Coordinator tick failed; persisted work remains recoverable") - self._wake.clear() - try: - await asyncio.wait_for(self._wake.wait(), timeout=self.settings.poll_seconds) - except asyncio.TimeoutError: - pass - - async def _job(self, job_id): - async with self.db.session() as session: - return await session.get(Job, job_id) - - async def _update(self, job_id, *, fresh_dispatch=False, remote_observation=None, **changes): - async with self.db.session() as session: - job = await session.get(Job, job_id) - if job is None or job.deleted_at is not None or job.state in TERMINAL: - return job - execution_changed=False - if remote_observation is not None: - from .executions import observe_gpu_execution,gpu_result_fence - from .v2_models import Execution - previous_execution_id=job.current_execution_id - accepted,execution=await observe_gpu_execution(session,job,remote_observation) - if not accepted:return job - execution_changed=job.current_execution_id!=previous_execution_id or any(isinstance(row,Execution) and session.is_modified(row) for row in session.dirty) - if remote_observation["state"]=="succeeded" and execution: - changes["upstream_result"]={**(changes.get("upstream_result") or {}),"_visual_execution":gpu_result_fence(execution)} - if job.cancel_requested: - if fresh_dispatch or changes.get("state") in {"collecting", "succeeded", "failed", "timed_out", "cancelled"}: - # Cancellation is arbitrated against the authoritative row - # in the same transaction as any outcome/publication phase. - changes = {"state": "cancelled", "phase": "cancelled", "finished_at": utcnow(), - "result_json": None, "error_json": None, "sync_warning": None} - elif changes.get("state") in {"queued", "running", "submitting"}: - changes["state"], changes["phase"] = "cancelling", "cancellation_pending" - changed = execution_changed - for key, value in changes.items(): - if getattr(job, key) != value: - setattr(job, key, value) - if key not in {"next_action_at", "sync_failures"}: - changed = True - if changed: - await emit_job(session, job) - await session.commit() - return job - - async def _assets(self, job): - async with self.db.session() as session: - assets = (await session.scalars(select(Asset).join(JobAsset, JobAsset.asset_id == Asset.id) - .where(JobAsset.job_id == job.id, Asset.owner_id == job.owner_id, - Asset.library_scope == 'private', Asset.ready.is_(True), Asset.deleted_at.is_(None)))).all() - return {asset.id: confined(self.settings.asset_root, asset.storage_key, exists=True) for asset in assets} - - async def _workdir(self, job): - job = await self._update(job.id, work_attempt=job.work_attempt + 1) - path = confined(self.settings.job_work_root, Path(job.id) / f"attempt-{job.work_attempt:04d}") - path.mkdir(parents=True, exist_ok=False) - return job, path - - async def _warning(self, job_id, error): - job = await self._job(job_id) - await self._update(job_id, sync_warning="上游连接或结果导入暂不可用,正在恢复同步", - sync_failures=job.sync_failures + 1, - next_action_at=utcnow() + timedelta(seconds=min(30, 2 ** min(job.sync_failures, 5)))) - LOG.warning("Job %s external boundary unavailable: %s", job_id, type(error).__name__) - - async def _failure(self, job_id, exc): - job = await self._job(job_id) - if job is None or job.deleted_at is not None:return - from .v2_models import Execution - async with self.db.session() as session: - job = await session.get(Job, job_id) - if job is None or job.deleted_at is not None:return - execution=await session.get(Execution,job.current_execution_id) if job.current_execution_id else None - if execution: - unknown=(execution.resource_pool=="qwen_http" or job.task_type=="audio.speech") and getattr(exc,"retriable",False) - execution.state="unknown" if unknown else "exited" - execution.finished_at=utcnow() - if unknown:self._blocked_pools.add(execution.resource_pool) - await session.commit() - if execution and execution.state=="unknown": - await self._update(job_id,state="needs_attention",phase="remote_outcome_unknown",error_json={"code":"remote_outcome_unknown","message":"Remote request completion is unconfirmed","retriable":False}) - return - code = getattr(exc, "code", "processing_failed") - message = getattr(exc, "message", "任务处理失败,请联系管理员查看服务日志") - await self._update(job_id, state="cancelled" if job.cancel_requested else "failed", - phase="cancelled" if job.cancel_requested else "failed", finished_at=utcnow(), - error_json={"code": code, "message": message, "retriable": bool(getattr(exc, "retriable", False))}) - - async def _complete(self, job_id, result, *, gpu_fence=GPU_FENCE_UNSET): - async with self.db.session() as session: - job = await session.get(Job, job_id) - if job is None or job.deleted_at is not None or job.state in TERMINAL: - return - if gpu_fence is not GPU_FENCE_UNSET: - from .executions import gpu_publication_matches - if not await gpu_publication_matches(session,job,gpu_fence):return - if job.cancel_requested: - job.state, job.phase = "cancelled", "cancelled" - job.result_json, job.error_json, job.sync_warning = None, None, None - job.finished_at = utcnow() - await emit_job(session, job) - await session.commit() - return - outputs = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id, - Asset.owner_id == job.owner_id, Asset.library_scope == 'private', Asset.deleted_at.is_(None)) - .order_by(Asset.source_output_index))).all() - if not outputs: - raise ValueError("Completed job has no imported artifacts") - for asset in outputs: - if gpu_fence is not GPU_FENCE_UNSET and gpu_fence: - from .v2_models import AssetReference - binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==asset.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==gpu_fence["execution_id"])) - if not binding:raise ValueError("Output belongs to a different execution") - if not asset.ready: - asset.ready = True - emit_asset(session, job.owner_id, "asset.created", {"asset": asset_dto(asset)}) - job.state, job.phase = "succeeded", "completed" - job.result_json, job.finished_at, job.sync_warning = result, utcnow(), None - await emit_job(session, job) - await session.commit() - - def _clock_allows(self,job): - if job.execution_mode!="batch":return True - return self._batch_clock_allows() - - def _batch_clock_allows(self): - from .runtime_policy import read_runtime_policy - from .resource_policy import execution_policy - policy=read_runtime_policy(self.settings) - if policy["configuration_error"]:return False - if not policy["batch_window_enabled"]:return True - return execution_policy()["batch_open"] and self._admission_clock.observe() - - async def run_once(self, *, force=False): - from .runtime_policy import read_runtime_policy - policy=read_runtime_policy(self.settings) - if policy["batch_window_enabled"] and not policy["configuration_error"]: - self._admission_clock.observe() - async with self._run_lock: - for job_id, task in list(self._cpu.items()): - if task.done(): - self._cpu.pop(job_id) - self._cpu_initial_pool.pop(job_id, None) - await asyncio.gather(task, return_exceptions=True) - for pending in (self._preparing,self._collecting): - for jid,task in list(pending.items()): - if task.done(): - pending.pop(jid) - await asyncio.gather(task,return_exceptions=True) - async with self.db.session() as session: - query = select(Job).where(Job.deleted_at.is_(None), Job.state.notin_(TERMINAL)) - if not force: - query = query.where(Job.next_action_at <= utcnow()) - ordering = (case((Job.cancel_requested.is_(True), 0), else_=1), - Job.next_action_at, Job.created_at, Job.batch_index, Job.id) - jobs = list((await session.scalars(query.order_by(*ordering).limit(50))).all()) - # New dispatch FIFO is separate from observation/retry backoff. - fresh=select(Job).join(User,User.id==Job.owner_id).where(User.disabled.is_(False),Job.deleted_at.is_(None),Job.state.notin_(TERMINAL), - Job.task_type.in_(GPU_TYPES),Job.upstream_id.is_(None), - Job.desired_state=="run",or_(Job.hold_reasons==[],Job.hold_reasons==["window"]), - Job.state.in_(["submitting","queued","scheduled"]), - (or_(Job.sync_failures==0,Job.next_action_at<=utcnow()) if not force else True), - or_(Job.scheduled_at.is_(None),Job.scheduled_at<=utcnow())) - if not self._batch_clock_allows():fresh=fresh.where(Job.execution_mode!="batch") - ready=list((await session.scalars(fresh.order_by(Job.created_at,Job.batch_index,Job.id).limit(25))).all()) - ready_ids={j.id for j in ready} - jobs=ready+[j for j in jobs if j.id not in ready_ids] - # Reserve one CPU candidate independently of a large GPU or - # cancellation backlog; network/GPU waiting cannot consume its slot. - cpu = await session.scalar(query.where(Job.task_type.notin_(GPU_TYPES), - or_(Job.scheduled_at.is_(None), Job.scheduled_at <= utcnow())).order_by(*ordering).limit(1)) - if cpu is not None: - # Start/cancel the independent CPU task before potentially - # slow GPU HTTP calls, rather than merely adding a tail slot. - jobs = [cpu] + [job for job in jobs if job.id != cpu.id] - from .resource_policy import admits - # Media preparation is bounded independently of the dispatch loop. - for job in jobs: - if job.task_type not in GPU_TYPES or job.upstream_id or job.upstream_payload is not None or job.state in {"collecting","needs_attention","paused","pausing"} or job.cancel_requested:continue - if job.scheduled_at and job.scheduled_at>utcnow():continue - if not admits(job,settings=self.settings) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id):continue - from .maintenance import maintenance_active - if maintenance_active(self.settings):continue - if job.id not in self._preparing and len(self._preparing)<4: - self._preparing[job.id]=asyncio.create_task(self._gpu(job,prepare_only=True),name=f"prepare-{job.id}") - if self._preparing: - await asyncio.wait(list(self._preparing.values()),timeout=.1) - # Preparation candidates are not the submission queue. Re-read - # persisted ready payloads after bounded preparation, including - # payloads beyond a prefix of unfinished media jobs. - async with self.db.session() as session: - ready=list((await session.scalars(fresh.where(Job.upstream_payload.is_not(None)).order_by(Job.created_at,Job.batch_index,Job.id).limit(25))).all()) - ready=[j for j in ready if j.id not in self._preparing or self._preparing[j.id].done()] - ready_ids={j.id for j in ready} - jobs=ready+[j for j in jobs if j.id not in ready_ids] - if cpu is not None:jobs=[cpu]+[j for j in jobs if j.id!=cpu.id] - for job in jobs: - job=await self._job(job.id) - if job.scheduled_at and job.scheduled_at > utcnow(): - continue - # Every inspected candidate moves forward, even when CPU is - # busy. This durable timestamp rotates bounded batches fairly. - job = await self._update(job.id, next_action_at=utcnow() + timedelta(seconds=self.settings.poll_seconds)) - if job.state in TERMINAL: - continue - from .maintenance import maintenance_active - holds=set(job.hold_reasons or []) - if maintenance_active(self.settings):holds.add('maintenance') - else:holds.discard('maintenance') - if holds!=set(job.hold_reasons or []): - job=await self._update(job.id,hold_reasons=sorted(holds)) - if job.id in self._cpu: - if job.cancel_requested and job.state != "collecting": - held=self._held_pool.get(job.id) - draining_http=held=="qwen_http" or (job.task_type=="audio.speech" and held=="cpu_media") - if not draining_http:self._cpu[job.id].cancel() - continue - if job.id in self._uncertain_cpu: - await self._update(job.id,state="needs_attention",phase="outcome_unknown") - continue - if job.state == "needs_attention" or (job.state in {"paused","pausing"} and not job.upstream_id):continue - # Query existing upstream IDs and collect artifacts at all hours. - # Admission only protects NEW computational phases. - from .maintenance import maintenance_active - if job.state != "collecting" and not job.upstream_id and not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id)): - continue - if job.id in self._collecting:continue - # A persisted payload is not dispatchable until preparation's - # final cancellation check has finished. Otherwise it could - # locally cancel while a concurrent POST loses its remote ID. - if job.id in self._preparing and not self._preparing[job.id].done():continue - if job.task_type in GPU_TYPES: - if job.state=="collecting": - if len(self._collecting)<2:self._collecting[job.id]=asyncio.create_task(self._gpu(job),name=f"collect-{job.id}") - elif job.upstream_id or job.upstream_payload is not None or job.cancel_requested: - # Observation overflow is a polling cursor, never a - # second submit queue. Only the FIFO prefix dispatches. - if not job.upstream_id and not job.cancel_requested and job.id not in ready_ids:continue - await self._gpu(job) - elif job.state == "collecting": - if len(self._collecting)<2: - self._collecting[job.id]=asyncio.create_task(self._collect_cpu_background(job),name=f"collect-{job.id}") - elif job.state in {"submitting","queued","scheduled","cancelling"}: - from .resource_policy import resource_plan - initial_pool = resource_plan(job.task_type)[0][1] - if sum(pool == initial_pool for pool in self._cpu_initial_pool.values()) < 25: - # This membership stays fixed when the provider moves - # phases; only _held_pool follows active resource slots. - self._cpu_initial_pool[job.id] = initial_pool - self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{job.id}") - - if self._collecting: - await asyncio.wait(list(self._collecting.values()),timeout=.1) - if self.after_tick is not None: - await self.after_tick() - - async def _collect_cpu_background(self,job): - try:await self._collect_cpu(job) - except Exception as exc:await self._warning(job.id,exc) - - async def _gpu(self, job, *, prepare_only=False): - try: - job = await self._job(job.id) - if job is None or job.deleted_at is not None or job.state in TERMINAL:return - if job.state == "collecting": - await self._collect_gpu(job) - return - if not job.upstream_id: - if job.cancel_requested and job.upstream_payload is None: - await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) - return - if job.upstream_payload is None: - job = await self._update(job.id, phase="preparing", state="submitting") - job, work = await self._workdir(job) - from .providers import current_phase_callback - async def prepare_phase(key,pool): - from .resource_policy import admits - current=await self._job(job.id) - if not admits(current,settings=self.settings):raise PhaseDeferred() - await self._enter_phase(job.id,key,pool,nonblocking=True) - token=current_phase_callback.set(prepare_phase) - try: - payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters, - await self._assets(job), work) - finally: - current_phase_callback.reset(token) - held=self._held_pool.pop(job.id,None) - if held:self._pools[held].release() - payload["scheduling"] = {"execution_mode": job.execution_mode, "principal_id": job.owner_id, - "policy_version": job.policy_version, - **{key:getattr(job,key) for key in ("batch_id","run_id","step_key") if getattr(job,key)}} - # This commit precedes POST; retries must reuse both values. - job = await self._update(job.id, upstream_payload=payload, phase="dispatching", fresh_dispatch=True) - if job.state in TERMINAL: - return - # This invocation knows no POST has started yet. An existing - # persisted payload on restart is instead ambiguous and must - # still recover its upstream ID using the same key below. - job = await self._job(job.id) - if job.cancel_requested: - await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) - return - if prepare_only:return - from .resource_policy import admits - if not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id)):return - if job.execution_mode == "batch": - capabilities = await self.provider.upstream_capabilities() if hasattr(self.provider,"upstream_capabilities") else {} - if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False): - await self._update(job.id,sync_warning="Batch requires upstream scheduling protocol v2") - return - remote = await self.provider.submit(job.upstream_payload, job.upstream_key) - remote_id = remote.get("id") - if not isinstance(remote_id, str) or not remote_id: - raise ValueError("Upstream omitted its job ID") - job = await self._update(job.id, upstream_id=remote_id) - else: - controls = {"manual","batch_pause","admin_suspend","batch_wait","maintenance"} - desired = "pause" if job.desired_state == "pause" or controls.intersection(job.hold_reasons or []) else "run" - if job.cancel_requested and job.id not in self._cancel_sent: - remote = await self.provider.cancel(job.upstream_id) - self._cancel_sent.add(job.id) - elif not job.cancel_requested and hasattr(self.provider,"control") and self._control_sent.get(job.id)!=desired: - remote = await self.provider.control(job.upstream_id,desired,"cmvr:"+job.id+":"+str(job.version)+":"+desired) - self._control_sent[job.id]=desired - else: - remote = await self.provider.query(job.upstream_id) - # A cancellation arriving while POST was in flight is persisted and - # sent against the same recovered ID on the next tick. - await self._apply_remote(job.id, remote, defer_collection=True) - except PhaseDeferred: - await self._update(job.id,state="submitting",phase="waiting_phase") - except asyncio.CancelledError: - raise - except Exception as exc: - if getattr(exc,"code",None) in {"quota_exceeded","storage_insufficient"}: - await self._failure(job.id,exc) - elif not job.upstream_id and getattr(exc, "code", None) == "upstream_rejected": - await self._failure(job.id, exc) - elif getattr(exc, "retriable", False) or job.upstream_payload is not None or job.upstream_id: - await self._warning(job.id, exc) - else: - LOG.exception("Job %s preparation failed", job.id) - await self._failure(job.id, exc) - - async def _apply_remote(self, job_id, remote, *, defer_collection=False): - state = remote.get("state") - if state not in {"queued", "running", "paused", "pausing", "succeeded", "failed", "cancelled", "timed_out"}: - raise ValueError("Invalid upstream job state") - job = await self._job(job_id) - changes = {"state": state, "phase": remote.get("stage") or state, - "attempt_count": int(remote.get("attempt_count", job.attempt_count)), - "preemptions": int(remote.get("preemptions", job.preemptions)), - "last_preempted_reason": public_value(remote.get("last_preempted_reason")), - "sync_warning": None, "sync_failures": 0, - "next_action_at": utcnow() + timedelta(seconds=self.settings.poll_seconds)} - if state == "running" and not job.started_at: - changes["started_at"] = utcnow() - if state == "succeeded": - changes.update(state="collecting", phase="importing_outputs", upstream_result=remote.get("result") or {}) - elif state in TERMINAL: - changes["finished_at"] = utcnow() - if state in {"failed", "timed_out"}: - changes["error_json"] = {"code": "upstream_" + state, "message": "模型任务未完成,请检查参数或重试", "retriable": True} - job = await self._update(job_id, remote_observation=remote, **changes) - if job.state == "collecting": - if defer_collection: - if job.id not in self._collecting and len(self._collecting)<2: - self._collecting[job.id]=asyncio.create_task(self._gpu(job),name=f"collect-{job.id}") - else: - await self._collect_gpu(job) - - async def _collect_gpu(self, job): - fence=(job.upstream_result or {}).get("_visual_execution") - from .executions import gpu_publication_matches - async with self.db.session() as session: - current=await session.get(Job,job.id) - if not await gpu_publication_matches(session,current,fence):raise ValueError("Stale GPU execution result") - outputs = (job.upstream_result or {}).get("outputs") - if not isinstance(outputs, list) or not outputs: - raise ValueError("Succeeded upstream job has no outputs") - directory = confined(self.settings.job_work_root, Path(job.id) / "imports") - directory.mkdir(parents=True, exist_ok=True) - assets = [] - selected_indices = None - if job.run_id and job.task_type == "video.generate" and job.step_key != "compose": - selected_indices = (job.upstream_result.get("metadata") or {}).get("final_output_indices") - if (not isinstance(selected_indices, list) or not selected_indices or - any(type(i) is not int or i < 0 or i >= len(outputs) for i in selected_indices)): - raise ValueError("Workflow requires explicit final enhanced output indices from upstream") - for index, output in enumerate(outputs): - if selected_indices is not None and index not in selected_indices: - continue - async with self.db.session() as session: - existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id, - Asset.owner_id == job.owner_id, - Asset.library_scope == 'private', - Asset.source_output_index == index)) - if existing: - if fence: - from .v2_models import AssetReference - async with self.db.session() as session: - binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==existing.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==fence["execution_id"])) - if not binding:raise ValueError("Output belongs to a different execution") - from .artifacts import digest_file - path=confined(self.settings.asset_root,existing.storage_key,exists=True) - if path.stat().st_size!=existing.size_bytes or digest_file(path)!=existing.sha256: - raise ValueError("Imported artifact is missing or corrupt") - await validate_workflow_output(job,path,self.settings) - assets.append(existing) - continue - raw = output.get("path", "") if isinstance(output, dict) else str(output) - suffix = Path(raw).suffix.lower() - if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix): - suffix = ".bin" - destination = directory / f"output-{index:04d}{suffix}" - await self.provider.download(job.upstream_id, index, destination) - assets.append(await import_output(self.db, self.settings, job, destination, index, execution_fence=fence)) - result = public_value((job.upstream_result or {}).get("metadata", {})) - if job.task_type == "audio.transcribe": - for asset in assets: - if asset.kind == "json" and asset.size_bytes <= 5 * 1024 * 1024: - with safe_file(self.settings.asset_root, asset.storage_key) as stream: - transcript = json.load(stream) - result = {"text": transcript.get("text", ""), "segments": transcript.get("segments", [])} - break - await self._complete(job.id, result, gpu_fence=fence) - - async def _owner_enabled(self,owner_id): - async with self.db.session() as session: - owner=await session.get(User,owner_id) - return owner is not None and not owner.disabled - - async def _enter_phase(self, job_id, phase_key, pool, *, nonblocking=False): - previous=self._held_pool.pop(job_id,None) - if previous:self._pools[previous].release() - from .resource_policy import admits - from .maintenance import maintenance_active - while True: - job=await self._job(job_id) - if job is None or job.deleted_at is not None or job.state in TERMINAL:raise asyncio.CancelledError() - if job.cancel_requested:raise asyncio.CancelledError() - if admits(job,settings=self.settings) and self._clock_allows(job) and pool not in self._blocked_pools and not maintenance_active(self.settings) and await self._owner_enabled(job.owner_id):break - if nonblocking:raise PhaseDeferred() - await self._update(job_id,phase="waiting_phase:"+phase_key) - await asyncio.sleep(min(1,self.settings.poll_seconds)) - if nonblocking and self._pools[pool].locked():raise PhaseDeferred() - await self._pools[pool].acquire() - # Recheck after waiting for the slot; no closed-window compute starts. - job=await self._job(job_id) - if job.deleted_at is not None or job.state in TERMINAL or job.cancel_requested or not admits(job,settings=self.settings) or not self._clock_allows(job) or pool in self._blocked_pools or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id): - self._pools[pool].release() - if nonblocking:raise PhaseDeferred() - return await self._enter_phase(job_id,phase_key,pool) - self._held_pool[job_id]=pool - async with self.db.session() as session: - current=await session.get(Job,job_id) - if current.current_execution_id: - from .v2_models import Execution - from .executions import begin_execution - active=await session.get(Execution,current.current_execution_id) - if active and (active.phase_key!=phase_key or active.resource_pool!=pool): - active.state="exited";active.finished_at=utcnow() - await begin_execution(session,job_id,phase_key,pool) - await session.commit() - await self._update(job_id,phase="cpu_running") - - async def _run_cpu(self, job): - phase_token=None - try: - job = await self._job(job.id) - if job is None or job.deleted_at is not None:return - if job.cancel_requested: - await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) - return - if job.state in TERMINAL or job.cancel_requested: - if job.state not in TERMINAL: - await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) - return - job, work = await self._workdir(job) - from .executions import begin_execution - from .resource_policy import resource_plan - from .providers import current_phase_callback - phase_token=current_phase_callback.set(lambda phase,pool:self._enter_phase(job.id,phase,pool)) - initial_pool=resource_plan(job.task_type)[0][1] - await self._enter_phase(job.id,"execute",initial_pool) - job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(), - attempt_count=job.attempt_count + 1) - if job.cancel_requested or job.state in TERMINAL: - if job.state not in TERMINAL: - await self._update(job.id,state="cancelled",phase="cancelled",finished_at=utcnow()) - return - async with self.db.session() as session: - execution = await begin_execution(session,job.id,resource_pool=resource_plan(job.task_type)[0][1]) - await session.commit() - result = await self.provider.run_cpu(job.task_type, job.input_json, job.parameters, await self._assets(job), work) - # A successful HTTP response proves this request ended. Explicit - # cancellation drains shared calls, then discards their response. - from .v2_models import Execution - async with self.db.session() as session: - current=await session.get(Job,job.id) - if current.cancel_requested: - execution=await session.get(Execution,current.current_execution_id) - if execution:execution.state="exited";execution.finished_at=utcnow() - current.state,current.phase,current.finished_at="cancelled","cancelled",utcnow() - current.result_json=None;current.error_json=None - await emit_job(session,current) - await session.commit() - return - from .artifacts import write_manifest - from .v2_models import Execution - async with self.db.session() as session: - current=await session.get(Job,job.id) - execution=await session.get(Execution,current.current_execution_id) - manifest=write_manifest(self.settings.job_work_root,work,execution.id,execution.fence_token,result.outputs,result.result,result.metadata) - from .executions import accept_manifest - async with self.db.session() as session: - if not await accept_manifest(session,execution.id,execution.fence_token,manifest): - current=await session.get(Job,job.id) - if current.cancel_requested: - execution.state="exited";execution.finished_at=utcnow() - current.state,current.phase,current.finished_at="cancelled","cancelled",utcnow() - current.result_json=None;current.error_json=None - await emit_job(session,current) - await session.commit() - return - await session.commit() - job = await self._job(job.id) - if job.cancel_requested: - await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) - return - if not isinstance(result.outputs, list) or not result.outputs: - raise ValueError("CPU provider returned no artifacts") - private = {"cpu_outputs": [str(confined(self.settings.job_work_root, p, exists=True)) for p in result.outputs], - "cpu_result": result.result, "metadata": result.metadata} - job = await self._update(job.id, state="collecting", phase="importing_outputs", upstream_result=private) - if job.state not in TERMINAL: - await self._collect_cpu(job) - except asyncio.CancelledError: - held=self._held_pool.get(job.id) - current=await self._job(job.id) - if self._closing and not current.cancel_requested and current.current_execution_id is None: - # A pool/window waiter never allocated a provider execution. - # Keep its accepted identity queued across an API restart. - await self._update(job.id,state='queued',phase='waiting_for_resource', - started_at=None,finished_at=None,error_json=None) - return - unknown=held=="qwen_http" or (job.task_type=="audio.speech" and held=="cpu_media") - if unknown:self._blocked_pools.add(held) - from .v2_models import Execution - async with self.db.session() as session: - current=await session.get(Job,job.id) - active=await session.get(Execution,current.current_execution_id) if current.current_execution_id else None - if active and active.state not in {"results_ready","exited"}: - active.state="unknown" if unknown else "exited" - active.finished_at=utcnow() - await session.commit() - job = await self._job(job.id) - if job.state != "collecting": - await self._update(job.id, state="cancelled" if job.cancel_requested else "failed", - phase="cancelled" if job.cancel_requested else "interrupted", finished_at=utcnow(), - error_json=None if job.cancel_requested else {"code": "worker_interrupted", "message": "任务因服务停止而中断", "retriable": True}) - except Exception as exc: - job = await self._job(job.id) - if job.state == "collecting" and getattr(exc,"code",None) not in {"quota_exceeded","storage_insufficient"}: - await self._warning(job.id, exc) - else: - LOG.exception("CPU job %s failed", job.id) - try: - await self._failure(job.id, exc) - except Exception: - self._uncertain_cpu.add(job.id) - LOG.exception("CPU outcome uncertain; execution is quarantined") - - finally: - previous=self._held_pool.pop(job.id,None) - if previous:self._pools[previous].release() - if phase_token is not None: - from .providers import current_phase_callback - current_phase_callback.reset(phase_token) - - async def _collect_cpu(self, job): - job = await self._job(job.id) - if job is None or job.deleted_at is not None or job.state in TERMINAL:return - private = job.upstream_result or {} - for index, source in enumerate(private.get("cpu_outputs", [])): - await import_output(self.db, self.settings, job, Path(source), index) - await self._complete(job.id, public_value(private.get("cpu_result", {}))) diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/core/config.py b/backend/app/core/config.py new file mode 100644 index 0000000..09a947e --- /dev/null +++ b/backend/app/core/config.py @@ -0,0 +1,269 @@ +from dataclasses import dataclass +import os +from pathlib import Path +from sqlalchemy.engine import URL, make_url + + +def boolean(value): + return str(value).lower() in {"1", "true", "yes", "on"} + + +@dataclass +class Settings: + mode: str = "production" + database_url: str | None = None + mysql_host: str = "192.168.28.10" + mysql_port: int = 3306 + mysql_database: str = "cmvr-visual" + mysql_user: str = "" + mysql_password: str = "" + workspace_root: Path = Path("/workspace") + asset_root: Path | None = None + job_work_root: Path | None = None + state_root: Path | None = None + admin_username: str = "" + admin_password: str = "" + admin_display_name: str = "管理员" + cookie_secure: bool = True + session_hours: int = 12 + public_access: bool = False + # Zero disables this optional per-owner unfinished interactive GPU job cap. + max_interactive_gpu_jobs: int = 0 + max_creation_commands_per_minute: int = 6 + max_owner_asset_bytes: int = 100 * 1024**3 + max_data_bytes: int = 2 * 1024**4 + min_free_bytes: int = 50 * 1024**3 + max_owner_jobs: int = 500 + max_global_jobs: int = 2000 + # 等待补队的持久候选与活动Job独立限额,默认容纳1000镜头各4个候选。 + max_owner_story_candidates: int = 4000 + max_global_story_candidates: int = 16000 + max_owner_runs: int = 100 + max_global_runs: int = 1000 + max_owner_batches: int = 20 + max_global_batches: int = 200 + run_coordinator: bool = True + poll_seconds: float = 1.0 + event_heartbeat_seconds: float = 15.0 + max_upload_bytes: int = 512 * 1024 * 1024 + max_output_bytes: int = 2 * 1024 * 1024 * 1024 + request_timeout_seconds: float = 30.0 + inference_base_url: str = "http://llmuser-workspace:18190" + inference_remote_files: bool = False + # 真实多图通道尚未完成资源、抢占及质量认证,默认关闭。 + reference_generation_enabled: bool = False + reference_generation_profile: str = "qwen-image-edit-2511-v1" + reference_max_images: int = 3 + video_edit_enabled: bool = False + video_edit_profile: str = "wan-animate-replace-v1" + video_edit_max_seconds: int = 120 + video_edit_max_people: int = 12 + video_edit_max_pixels: int = 399360 + inference_api_key: str = "" + inference_api_key_file: Path | None = Path("/workspace/projects/llm-services/config/api_key") + gpu_status_path: Path | None = Path("/run/llm-gpu-policy/status.json") + gpu_scheduler_path: Path | None = Path( + "/workspace/projects/llm-services/state/gpu-scheduler.json" + ) + runtime_policy_file: Path | None = Path( + "/workspace/projects/llm-services/config/runtime-policy.json" + ) + qwen_base_url: str = "http://192.168.28.10:14081/v1" + qwen_model: str = "Qwen/Qwen3.8-27B-FP8" + qwen_api_key: str = "" + # 包含 GPU 交接和冷加载;普通模型控制接口仍使用原来的短超时。 + qwen_timeout_seconds: float = 1800.0 + ffmpeg_bin: str = "ffmpeg" + ffprobe_bin: str = "ffprobe" + tts_base_url: str = "" + tts_model: str = "kokoro-82m" + tts_api_key: str = "" + tts_voices: tuple[str, ...] = ("zf_xiaobei", "zm_yunxi") + speech_timeout_seconds: float = 330.0 + speech_total_timeout_seconds: float = 360.0 + + def __post_init__(self): + import math + + if ( + not math.isfinite(self.speech_timeout_seconds) + or not math.isfinite(self.speech_total_timeout_seconds) + or self.speech_timeout_seconds <= 0 + or self.speech_total_timeout_seconds < self.speech_timeout_seconds + ): + raise ValueError("Speech timeouts must be finite, positive and ordered") + if self.mode not in {"production", "preview", "test"}: + raise ValueError("CMVR_MODE must be production, preview or test") + if self.max_interactive_gpu_jobs < 0: + raise ValueError("MAX_INTERACTIVE_GPU_JOBS must be non-negative; 0 disables the limit") + if any( + type(value) is not int or value < 0 + for value in (self.max_owner_story_candidates, self.max_global_story_candidates) + ): + raise ValueError("Story candidate plan limits must be non-negative integers") + if self.video_edit_profile != "wan-animate-replace-v1": + raise ValueError("Unsupported VIDEO_EDIT_PROFILE") + if any( + type(v) is not int or v < 1 + for v in (self.video_edit_max_seconds, self.video_edit_max_people) + ): + raise ValueError("Video edit limits must be positive integers") + if type(self.video_edit_max_pixels) is not int or self.video_edit_max_pixels not in { + 399360, + 921600, + }: + raise ValueError("VIDEO_EDIT_MAX_PIXELS must be a certified 480p/720p budget") + profiles = { + "qwen-image-edit-2511-v1", + "qwen-image-edit-2509-v1", + "qwen-image-edit-2511-experimental-4-v1", + } + if self.reference_generation_profile not in profiles: + raise ValueError("Unsupported REFERENCE_GENERATION_PROFILE") + maximum = 4 if "experimental-4" in self.reference_generation_profile else 3 + if ( + type(self.reference_max_images) is not int + or not 1 <= self.reference_max_images <= maximum + ): + raise ValueError("REFERENCE_MAX_IMAGES exceeds the selected profile") + self.workspace_root = Path(self.workspace_root).resolve() + for field, leaf in ( + ("asset_root", "assets"), + ("job_work_root", "jobs"), + ("state_root", "state"), + ): + value = Path( + getattr(self, field) or self.workspace_root / "cmvr-visual" / leaf + ).resolve() + if not value.is_relative_to(self.workspace_root): + raise ValueError(field + " must stay inside WORKSPACE_ROOT") + setattr(self, field, value) + for field in ( + "inference_api_key_file", + "gpu_status_path", + "gpu_scheduler_path", + "runtime_policy_file", + ): + if getattr(self, field): + setattr(self, field, Path(getattr(self, field))) + if self.database_url: + url = make_url(self.database_url) + if url.drivername.startswith("sqlite"): + if self.mode not in {"preview", "test"} or url.drivername != "sqlite+aiosqlite": + raise ValueError( + "SQLite requires explicit test/preview mode and the aiosqlite driver" + ) + elif url.drivername != "mysql+aiomysql": + raise ValueError("Production database must use mysql+aiomysql") + elif self.mode != "production": + raise ValueError("Test/preview mode requires an explicit DATABASE_URL") + elif not self.mysql_user or not self.mysql_password: + raise ValueError("Production MySQL credentials must be configured") + + @property + def sqlalchemy_url(self): + if self.database_url: + return make_url(self.database_url) + return URL.create( + "mysql+aiomysql", + username=self.mysql_user, + password=self.mysql_password, + host=self.mysql_host, + port=self.mysql_port, + database=self.mysql_database, + query={"charset": "utf8mb4"}, + ) + + @classmethod + def from_env(cls): + env = os.environ + values = {} + strings = ( + "database_url", + "mysql_host", + "mysql_database", + "mysql_user", + "mysql_password", + "admin_username", + "admin_password", + "admin_display_name", + "inference_base_url", + "inference_api_key", + "reference_generation_profile", + "video_edit_profile", + "qwen_base_url", + "qwen_model", + "qwen_api_key", + "ffmpeg_bin", + "ffprobe_bin", + "tts_base_url", + "tts_model", + "tts_api_key", + ) + for field in strings: + if field.upper() in env: + values[field] = env[field.upper()] + for field in ( + "workspace_root", + "asset_root", + "job_work_root", + "state_root", + "inference_api_key_file", + "gpu_status_path", + "gpu_scheduler_path", + ): + if field.upper() in env: + values[field] = Path(env[field.upper()]) if env[field.upper()] else None + if env.get("RUNTIME_POLICY_FILE"): + values["runtime_policy_file"] = Path(env["RUNTIME_POLICY_FILE"]) + for field in ( + "mysql_port", + "session_hours", + "max_upload_bytes", + "max_output_bytes", + "max_owner_jobs", + "max_global_jobs", + "max_owner_story_candidates", + "max_global_story_candidates", + "max_interactive_gpu_jobs", + "reference_max_images", + "video_edit_max_seconds", + "video_edit_max_people", + "video_edit_max_pixels", + "max_creation_commands_per_minute", + "max_owner_asset_bytes", + "max_data_bytes", + "min_free_bytes", + "max_owner_runs", + "max_global_runs", + "max_owner_batches", + "max_global_batches", + ): + if field.upper() in env: + values[field] = int(env[field.upper()]) + for field in ( + "poll_seconds", + "event_heartbeat_seconds", + "request_timeout_seconds", + "qwen_timeout_seconds", + "speech_timeout_seconds", + "speech_total_timeout_seconds", + ): + if field.upper() in env: + values[field] = float(env[field.upper()]) + for field in ( + "cookie_secure", + "run_coordinator", + "public_access", + "inference_remote_files", + "reference_generation_enabled", + "video_edit_enabled", + ): + if field.upper() in env: + values[field] = boolean(env[field.upper()]) + values["mode"] = env.get("CMVR_MODE", "production") + if "TTS_VOICES" in env: + values["tts_voices"] = tuple( + v.strip() for v in env["TTS_VOICES"].split(",") if v.strip() + ) + return cls(**values) diff --git a/backend/app/database.py b/backend/app/core/database.py similarity index 82% rename from backend/app/database.py rename to backend/app/core/database.py index dcad684..e2f4aa8 100644 --- a/backend/app/database.py +++ b/backend/app/core/database.py @@ -2,8 +2,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy import event import asyncio from contextlib import asynccontextmanager -from .models import Base -from . import v2_models +from app.models import Base class Database: @@ -11,15 +10,16 @@ class Database: self.mode = settings.mode self.engine = create_async_engine(settings.sqlalchemy_url, pool_pre_ping=True) if settings.sqlalchemy_url.drivername.startswith("sqlite"): + @event.listens_for(self.engine.sync_engine, "connect") def sqlite_options(connection, _): cursor = connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.execute("PRAGMA busy_timeout=10000") cursor.close() + self._sessions = async_sessionmaker(self.engine, expire_on_commit=False) - # One API process by deployment contract. Short DB units are serialized - # so durable SSE IDs are observed in commit order, including CPU imports. + # 单 API 进程内串行提交短事务,确保 SSE 游标顺序与提交顺序一致;GPU 并行不等于增加 API workers。 self._unit_lock = asyncio.Lock() @asynccontextmanager @@ -33,8 +33,9 @@ class Database: if self.mode in {"test", "preview"}: await connection.run_sync(Base.metadata.create_all) else: - from .schema import check_schema_revision - await connection.run_sync(check_schema_revision, {"004"}) + from app.core.schema import check_schema_revision + + await connection.run_sync(check_schema_revision, {"007"}) async def close(self): await self.engine.dispose() diff --git a/backend/app/errors.py b/backend/app/core/errors.py similarity index 100% rename from backend/app/errors.py rename to backend/app/core/errors.py diff --git a/backend/app/core/maintenance.py b/backend/app/core/maintenance.py new file mode 100644 index 0000000..3697925 --- /dev/null +++ b/backend/app/core/maintenance.py @@ -0,0 +1,13 @@ +"""Server-owned admission switch. Reads, synchronization and archival continue.""" + +from pathlib import Path +from app.core.errors import fail + + +def maintenance_active(settings): + return (Path(settings.state_root) / "maintenance").exists() + + +def require_writable(settings): + if maintenance_active(settings): + fail(503, "maintenance", "Service is in maintenance mode") diff --git a/backend/app/public_preflight.py b/backend/app/core/public_preflight.py similarity index 66% rename from backend/app/public_preflight.py rename to backend/app/core/public_preflight.py index 0632029..7b8a6ac 100644 --- a/backend/app/public_preflight.py +++ b/backend/app/core/public_preflight.py @@ -1,8 +1,9 @@ """Fail closed when the operator explicitly enables Internet access.""" + import asyncio from sqlalchemy import select -from .auth import verify_password -from .models import User +from app.core.security import verify_password +from app.models import User async def require_public_ready(db, settings): @@ -10,11 +11,14 @@ async def require_public_ready(db, settings): return if not settings.cookie_secure: raise ValueError("PUBLIC_ACCESS requires COOKIE_SECURE and HTTPS") - if (settings.sqlalchemy_url.username or '').lower()=='root': + if (settings.sqlalchemy_url.username or "").lower() == "root": raise ValueError("PUBLIC_ACCESS requires a dedicated MySQL application user") async with db.session() as session: - admins = (await session.scalars(select(User).where( - User.role == "admin", User.disabled.is_(False)))).all() + admins = ( + await session.scalars( + select(User).where(User.role == "admin", User.disabled.is_(False)) + ) + ).all() if not admins: raise ValueError("Public access requires an enabled administrator") initial_passwords = {"123456"} @@ -25,4 +29,6 @@ async def require_public_ready(db, settings): for password in initial_passwords: unchanged |= await asyncio.to_thread(verify_password, password, user.password_hash) if unchanged: - raise ValueError("Change the initial administrator password in private mode before PUBLIC_ACCESS") + raise ValueError( + "Change the initial administrator password in private mode before PUBLIC_ACCESS" + ) diff --git a/backend/app/runtime_policy.py b/backend/app/core/runtime_policy.py similarity index 55% rename from backend/app/runtime_policy.py rename to backend/app/core/runtime_policy.py index fcf8cbd..a3278fc 100644 --- a/backend/app/runtime_policy.py +++ b/backend/app/core/runtime_policy.py @@ -1,11 +1,13 @@ """Hot-read, operator-owned policy. Client job data never selects this file.""" + import json +import math from pathlib import Path +import time -def read_runtime_policy(settings=None): - result = {"batch_window_enabled": True, "workflow_max_shots": 120, - "configuration_error": None} +def _read_file_policy(settings=None): + result = {"batch_window_enabled": True, "workflow_max_shots": 120, "configuration_error": None} path = getattr(settings, "runtime_policy_file", None) if path is None: return result @@ -21,7 +23,10 @@ def read_runtime_policy(settings=None): raise ValueError("Policy too large") value = json.loads(raw.decode("utf-8")) if not isinstance(value, dict) or set(value) - { - "schema_version", "batch_window_enabled", "workflow_max_shots"}: + "schema_version", + "batch_window_enabled", + "workflow_max_shots", + }: raise ValueError("Unknown policy fields") if type(value.get("schema_version")) is not int or value["schema_version"] != 1: raise ValueError("Unsupported schema") @@ -32,5 +37,31 @@ def read_runtime_policy(settings=None): raise ValueError("Invalid shot limit") except (ValueError, TypeError, UnicodeError): return {**result, "configuration_error": "runtime_policy_invalid"} - return {"batch_window_enabled": value["batch_window_enabled"], - "workflow_max_shots": max_shots, "configuration_error": None} + return { + "batch_window_enabled": value["batch_window_enabled"], + "workflow_max_shots": max_shots, + "configuration_error": None, + } + + +def read_runtime_policy(settings=None): + policy = _read_file_policy(settings) + if not getattr(settings, "inference_remote_files", False): + return policy + error = getattr(settings, "_remote_policy_error", None) + observed = getattr(settings, "_remote_policy_observed_at", None) + if error is not None: + error = ( + "runtime_policy_invalid" + if error == "runtime_policy_invalid" + else "runtime_policy_unavailable" + ) + elif ( + type(observed) not in (int, float) + or not math.isfinite(observed) + or not 0 <= time.monotonic() - observed <= 5 + ): + error = "runtime_policy_unavailable" + if error: + return {**policy, "configuration_error": error} + return policy diff --git a/backend/app/core/schema.py b/backend/app/core/schema.py new file mode 100644 index 0000000..c466c01 --- /dev/null +++ b/backend/app/core/schema.py @@ -0,0 +1,119 @@ +from dataclasses import dataclass, field +from sqlalchemy import inspect, text, Boolean, String, Text +from sqlalchemy.dialects.mysql import TINYINT + + +@dataclass +class SchemaDiff: + differences: list[str] = field(default_factory=list) + + @property + def matches(self): + return not self.differences + + +def compatible_type(expected, observed, dialect): + # Reflection includes inherited database collation; generic VARCHAR does not + # assert one. Explicit model collation/charset still remains a hard contract. + if isinstance(expected, Boolean) and dialect.name == "mysql": + return ( + isinstance(observed, Boolean) + or isinstance(observed, TINYINT) + and observed.display_width == 1 + ) + if isinstance(expected, String) and isinstance(observed, String): + if isinstance(expected, Text) != isinstance(observed, Text): + return False + if expected.length != observed.length: + return False + for option in ("collation", "charset"): + desired = getattr(expected, option, None) + if desired is not None and desired != getattr(observed, option, None): + return False + return True + return expected.compile(dialect=dialect).upper() == observed.compile(dialect=dialect).upper() + + +def schema_preflight(connection, metadata): + inspector = inspect(connection) + diff = SchemaDiff() + tables = set(inspector.get_table_names()) + for table in metadata.sorted_tables: + if table.name not in tables: + diff.differences.append("Missing table: " + table.name) + continue + if connection.dialect.name == "mysql": + options = inspector.get_table_options(table.name) + charset = ( + options.get("mysql_default charset") + or options.get("mysql_default_charset") + or options.get("mysql_charset") + ) + if charset and charset != "utf8mb4": + diff.differences.append("Unexpected charset: " + table.name) + actual = {c["name"]: c for c in inspector.get_columns(table.name)} + if set(actual) != set(table.columns.keys()): + diff.differences.append("Unexpected/missing columns: " + table.name) + if tuple(inspector.get_pk_constraint(table.name)["constrained_columns"]) != tuple( + c.name for c in table.primary_key.columns + ): + diff.differences.append("Primary key: " + table.name) + for col in table.columns: + current = actual.get(col.name) + if not current: + diff.differences.append(f"Missing column: {table.name}.{col.name}") + continue + expected = col.type.compile(dialect=connection.dialect) + observed = current["type"].compile(dialect=connection.dialect) + if not compatible_type(col.type, current["type"], connection.dialect): + diff.differences.append( + f"Column type: {table.name}.{col.name}: {observed} != {expected}" + ) + if not col.primary_key and col.nullable != current["nullable"]: + diff.differences.append(f"Nullability: {table.name}.{col.name}") + expected_fks = { + ( + tuple(fk.parent.name for fk in constraint.elements), + constraint.elements[0].column.table.name, + tuple(fk.column.name for fk in constraint.elements), + ) + for constraint in table.foreign_key_constraints + } + actual_fks = { + (tuple(fk["constrained_columns"]), fk["referred_table"], tuple(fk["referred_columns"])) + for fk in inspector.get_foreign_keys(table.name) + } + if not expected_fks <= actual_fks: + diff.differences.append("Missing foreign key: " + table.name) + expected_unique = { + tuple(c.name for c in constraint.columns) + for constraint in table.constraints + if constraint.__class__.__name__ == "UniqueConstraint" + } + observed_unique = { + tuple(c["column_names"]) for c in inspector.get_unique_constraints(table.name) + } + observed_unique |= { + tuple(c["column_names"]) for c in inspector.get_indexes(table.name) if c.get("unique") + } + if not expected_unique <= observed_unique: + diff.differences.append("Missing unique constraint: " + table.name) + expected_indexes = {tuple(c.name for c in index.columns) for index in table.indexes} + observed_indexes = {tuple(c["column_names"]) for c in inspector.get_indexes(table.name)} + if not expected_indexes <= observed_indexes: + diff.differences.append("Missing index: " + table.name) + return diff + + +def check_schema_revision(connection, supported): + inspector = inspect(connection) + if "alembic_version" not in inspector.get_table_names(): + raise RuntimeError("Schema is unversioned; preflight and explicit migration required") + revisions = set(connection.execute(text("SELECT version_num FROM alembic_version")).scalars()) + if len(revisions) != 1 or not revisions <= supported: + raise RuntimeError("Unsupported schema revision") + from app.models import Base + + diff = schema_preflight(connection, Base.metadata) + if not diff.matches: + raise RuntimeError("Schema drift: " + "; ".join(diff.differences)) diff --git a/backend/app/core/security.py b/backend/app/core/security.py new file mode 100644 index 0000000..b5d96cf --- /dev/null +++ b/backend/app/core/security.py @@ -0,0 +1,55 @@ +from dataclasses import dataclass, field +import hashlib, hmac, secrets +from app.core.errors import fail + +COOKIE = "cmvr_session" + + +def token_hash(token): + return hashlib.sha256(token.encode()).hexdigest() + + +def hash_password(password): + salt = secrets.token_bytes(16) + key = hashlib.scrypt( + password.encode(), salt=salt, n=32768, r=8, p=1, dklen=64, maxmem=128 * 1024 * 1024 + ) + return f"scrypt$32768$8$1${salt.hex()}${key.hex()}" + + +def verify_password(password, encoded): + try: + _, n, r, p, salt, expected = encoded.split("$") + key = hashlib.scrypt( + password.encode(), + salt=bytes.fromhex(salt), + n=int(n), + r=int(r), + p=int(p), + dklen=64, + maxmem=128 * 1024 * 1024, + ) + return hmac.compare_digest(key.hex(), expected) + except (ValueError, TypeError): + hashlib.scrypt( + password.encode(), salt=b"\0" * 16, n=32768, r=8, p=1, maxmem=128 * 1024 * 1024 + ) + return False + + +def validate_password(password, *, minimum=12): + if not minimum <= len(password) <= 256: + fail(422, "weak_password", f"密码长度须为 {minimum}–256 个字符") + + +@dataclass +class Actor: + id: str + username: str + display_name: str + role: str + csrf_token: str + token_hash: str + auth_kind: str = "session" + scopes: list[str] = field(default_factory=list) + must_change_password: bool = False diff --git a/backend/app/deletions.py b/backend/app/deletions.py deleted file mode 100644 index cf795ca..0000000 --- a/backend/app/deletions.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Transactional archival of owner records; execution and asset audit rows survive.""" -from sqlalchemy import delete, or_, select - -from .errors import fail -from .events import emit_asset -from .models import Job, JobAsset, utcnow -from .v2_models import AssetReference, Batch, Execution, Submission, WorkflowDraft, WorkflowRun, WorkflowStep - -JOB_TERMINAL = {'succeeded', 'failed', 'cancelled', 'timed_out'} -RUN_TERMINAL = {'succeeded', 'failed', 'cancelled'} -BATCH_TERMINAL = {'succeeded', 'cancelled', 'completed_with_errors'} -MODEL_KEYS = {Job: 'job_ids', WorkflowRun: 'run_ids', WorkflowDraft: 'draft_ids', Batch: 'batch_ids'} -EVENT_NAMES = {Job: 'job.deleted', WorkflowRun: 'workflow.deleted', WorkflowDraft: 'draft.deleted', Batch: 'batch.deleted'} - - -async def archive_records(session, model, record_id, owner_id, if_match=None): - """Validate the complete tree before changing anything in the caller's unit.""" - root = await session.scalar(select(model).where(model.id == record_id, - model.owner_id == owner_id).with_for_update()) - if root is None: - fail(404, 'resource_not_found', '记录不存在') - groups = {Job: [], WorkflowRun: [], WorkflowDraft: [], Batch: []} - groups[model] = [root] - if model is WorkflowDraft: - groups[WorkflowRun] = list((await session.scalars(select(WorkflowRun).where( - WorkflowRun.owner_id == owner_id, WorkflowRun.draft_id == root.id) - .order_by(WorkflowRun.created_at, WorkflowRun.id).with_for_update())).all()) - elif model is Batch: - groups[WorkflowRun] = list((await session.scalars(select(WorkflowRun).where( - WorkflowRun.owner_id == owner_id, WorkflowRun.batch_id == root.id) - .order_by(WorkflowRun.created_at, WorkflowRun.id).with_for_update())).all()) - run_ids = [run.id for run in groups[WorkflowRun]] - if model is not Job: - child_filter = Job.run_id.in_(run_ids) - if model is Batch: - child_filter = or_(child_filter, Job.batch_id == root.id) - groups[Job] = list((await session.scalars(select(Job).where(Job.owner_id == owner_id, - child_filter).order_by(Job.created_at, Job.id).with_for_update())).all()) - result = {'deleted': {MODEL_KEYS[kind]: [row.id for row in rows] for kind, rows in groups.items()}} - if root.deleted_at is not None: - return result - if if_match is not None and if_match.strip('"') != str(root.version): - fail(409, 'version_conflict', '记录已更新,请刷新后重试删除') - if model is Job and (root.run_id or root.batch_id): - fail(409, 'parent_control_required', '请在所属工作流或批次中删除此任务') - if model is WorkflowRun and root.batch_id: - fail(409, 'parent_control_required', '请删除所属批次') - if model is WorkflowDraft: - batch_ids = {run.batch_id for run in groups[WorkflowRun] if run.batch_id and run.deleted_at is None} - if batch_ids and await session.scalar(select(Batch.id).where(Batch.id.in_(batch_ids), - Batch.owner_id == owner_id, Batch.deleted_at.is_(None)).limit(1)): - fail(409, 'parent_control_required', '草稿仍有关联批次,请先删除所属批次') - for kind, terminal in ((Job, JOB_TERMINAL), (WorkflowRun, RUN_TERMINAL), (Batch, BATCH_TERMINAL)): - if any(row.deleted_at is None and row.state not in terminal for row in groups[kind]): - fail(409, 'deletion_requires_terminal', '请先取消活动任务,等待执行结束后再删除') - job_ids = [job.id for job in groups[Job]] - executions = list((await session.scalars(select(Execution).where(Execution.job_id.in_(job_ids)) - .with_for_update())).all()) if job_ids else [] - if any(execution.state not in {'exited', 'results_ready'} for execution in executions): - fail(409, 'cleanup_pending', '执行尚未确认清理,请等待清理完成后再删除') - if job_ids: - in_use = await session.scalar(select(WorkflowRun.id).join(WorkflowStep, - WorkflowStep.run_id == WorkflowRun.id).where(WorkflowRun.deleted_at.is_(None), - WorkflowRun.id.not_in(run_ids), WorkflowStep.selected_job_id.in_(job_ids)).limit(1)) - if in_use: - fail(409, 'resource_in_use', '任务产物仍被其他工作流运行复用,请先删除该运行') - now = utcnow() - for kind in (Job, WorkflowRun, WorkflowDraft, Batch): - for row in groups[kind]: - if row.deleted_at is not None: - continue - row.deleted_at = now - row.version += 1 - emit_asset(session, owner_id, EVENT_NAMES[kind], {'id': row.id, 'version': row.version}) - # A draft survives deletion of its last/current run or enclosing batch. - if run_ids: - drafts = (await session.scalars(select(WorkflowDraft).where(WorkflowDraft.owner_id == owner_id, - WorkflowDraft.current_run_id.in_(run_ids), WorkflowDraft.deleted_at.is_(None)).with_for_update())).all() - from .workflows import draft_dto - for draft in drafts: - draft.current_run_id = None - draft.version += 1 - draft.updated_at = now - emit_asset(session, owner_id, 'draft.updated', {'draft': draft_dto(draft)}) - for draft in groups[WorkflowDraft]: - draft.current_run_id = None - draft.updated_at = now - if job_ids: - await session.execute(delete(JobAsset).where(JobAsset.job_id.in_(job_ids))) - refs = [] - if run_ids: - refs.append((AssetReference.ref_kind == 'run') & AssetReference.ref_id.in_(run_ids)) - if groups[WorkflowDraft]: - refs.append((AssetReference.ref_kind == 'draft') & AssetReference.ref_id.in_([d.id for d in groups[WorkflowDraft]])) - if executions: - refs.append((AssetReference.ref_kind == 'execution') & AssetReference.ref_id.in_([e.id for e in executions])) - if refs: - await session.execute(delete(AssetReference).where(AssetReference.owner_id == owner_id, or_(*refs))) - archived_ids = {row.id for rows in groups.values() for row in rows} - submissions = (await session.scalars(select(Submission).where(Submission.owner_id == owner_id, - Submission.status != 'purged').with_for_update())).all() - for submission in submissions: - if references_any(submission.resource_json, archived_ids): - submission.status = 'purged' - await session.flush() - return result - - -def references_any(value, ids): - if isinstance(value, str): - return value in ids - if isinstance(value, dict): - return any(references_any(item, ids) for item in value.values()) - if isinstance(value, list): - return any(references_any(item, ids) for item in value) - return False diff --git a/backend/app/domain/__init__.py b/backend/app/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/domain/editors.py b/backend/app/domain/editors.py new file mode 100644 index 0000000..decae2d --- /dev/null +++ b/backend/app/domain/editors.py @@ -0,0 +1,165 @@ +"""编辑真源转换和时间冲突报告,不访问数据库。""" + +from copy import deepcopy +import re +import uuid +from pydantic import ValidationError +from app.schemas.editors import EditorManifest +from app.domain.timeline import WorkflowSpec +from app.domain.stories import StorySpecV3 +from app.core.errors import fail + + +def validate_manifest(manifest): + try: + m = EditorManifest.model_validate(manifest).model_dump(mode="json") + raw = deepcopy(m["spec"]) + raw.pop("compiled", None) + raw.setdefault("render", {}).update(audio=None, subtitles=[], total_frames=None) + model = StorySpecV3 if m["source_kind"] == "story" else WorkflowSpec + m["spec"] = model.model_validate(raw).model_dump(mode="json") + ids = m["shot_ids"] + if ( + len(ids) != len(m["spec"]["shots"]) + or len(set(ids)) != len(ids) + or any(not re.fullmatch("[0-9a-f]{32}", i) for i in ids) + ): + raise ValueError("shot_ids must match ordered shots") + if m["source_kind"] == "story" and ids != [s["id"] for s in m["spec"]["shots"]]: + raise ValueError("story shot_ids mismatch") + for group in (m["audio"]["segments"], m["captions"]["cues"]): + if len({x["id"] for x in group}) != len(group): + raise ValueError("duplicate stable id") + valid_keys = {f"{kind}:{id}" for kind in ("frame", "video") for id in ids} + valid_keys.update("audio:" + x["id"] for x in m["audio"]["segments"]) + if set(m["bindings"]) - valid_keys: + raise ValueError("unknown binding key") + for key, b in m["bindings"].items(): + if ( + b["kind"] + != {"frame": "image", "video": "video", "audio": "audio"}[key.split(":")[0]] + ): + raise ValueError("wrong binding kind") + return m + except (ValidationError, ValueError, TypeError, KeyError) as exc: + fail(422, "invalid_editor_manifest", str(exc)) + + +def manifest_from_draft(draft): + if draft.editor_manifest: + return deepcopy(draft.editor_manifest) + spec = deepcopy(draft.spec) + spec.pop("compiled", None) + spec.pop("render_inputs", None) + story = draft.kind == "story_v3" + ids = [ + s["id"] if story else uuid.uuid5(uuid.NAMESPACE_URL, f"editor:{draft.id}:{s['key']}").hex + for s in spec["shots"] + ] + old = spec.get("render", {}) + audio = { + "mode": "manual_track" if old.get("audio") else "silent", + "voice": "", + "speed": 1.0, + "track": old.get("audio"), + "segments": [ + { + "id": uuid.uuid5(uuid.NAMESPACE_URL, f"segment:{draft.id}:{id}").hex, + "shot_id": id, + "text": "", + } + for id in ids + ], + } + cues = [ + dict( + id=uuid.uuid5(uuid.NAMESPACE_URL, f"cue:{draft.id}:{i}").hex, + anchor="absolute", + text_override=True, + timing_override=True, + **c, + ) + for i, c in enumerate(old.get("subtitles", [])) + ] + return validate_manifest( + dict( + schema_version=1, + source_kind="story" if story else "workflow", + spec=spec, + shot_ids=ids, + bindings={}, + audio=audio, + captions={"mode": "manual" if cues else "none", "cues": cues}, + ) + ) + + +def editor_issues(manifest): + m = manifest + shots = { + id: s.get("edit", {}).get("duration_frames", s.get("duration_frames", 120)) + for id, s in zip(m["shot_ids"], m["spec"]["shots"]) + } + total = sum(shots.values()) + segments = {s["id"]: s for s in m["audio"]["segments"]} + issues = [] + + def issue(code, id, message): + issues.append(dict(code=code, unit_id=id, message=message)) + + for s in segments.values(): + if s["shot_id"] not in shots: + issue("orphan_audio_segment", s["id"], "配音段引用的镜头不存在") + for c in m["captions"]["cues"]: + limit = total + if c["anchor"] == "shot": + limit = shots.get(c["shot_id"]) + elif c["anchor"] == "audio_segment": + segment = segments.get(c["segment_id"]) + limit = shots.get(segment["shot_id"]) if segment else None + if limit is None: + issue("orphan_caption_anchor", c["id"], "字幕锚点不存在") + elif c["start_frame"] < 0 or c["end_frame"] <= c["start_frame"] or c["end_frame"] > limit: + issue("invalid_timeline", c["id"], "字幕时间超出锚点范围") + a = m["audio"].get("track") + if m["audio"]["mode"] == "manual_track": + if not a: + issue("missing_audio_track", "audio", "请选择音轨") + elif a["offset_frame"] + (a["source_end_ms"] - a["source_start_ms"]) * 24 / 1000 > total: + issue("invalid_timeline", "audio", "音轨超出成片范围") + return issues + + +def collect_manifest_asset_ids(manifest): + result = set() + + def visit(value): + if isinstance(value, dict): + for k, v in value.items(): + if k.endswith("asset_id") and isinstance(v, str): + result.add(v) + elif k.endswith("asset_ids") and isinstance(v, list): + result.update(v) + else: + visit(v) + elif isinstance(value, list): + for item in value: + visit(item) + + visit(manifest) + return result + + +def editing_mode(draft): + return ( + (draft.editor_manifest or {}).get("editing_mode", "auto") + if draft.editor_manifest + else "manual" + ) + + +def is_editor_auto(draft): + return bool(draft.editor_manifest) and editing_mode(draft) == "auto" + + +MODE_CAPABILITIES = {"mode_switch": True, "manual": True, "auto": True, "name_edit": True} diff --git a/backend/app/domain/errors.py b/backend/app/domain/errors.py new file mode 100644 index 0000000..428e0ac --- /dev/null +++ b/backend/app/domain/errors.py @@ -0,0 +1,7 @@ +"""领域任务错误,不依赖 HTTP、数据库或具体模型。""" + + +class MediaError(RuntimeError): + def __init__(self, code: str, message: str, retriable: bool = False): + super().__init__(message) + self.code, self.message, self.retriable = code, message, retriable diff --git a/backend/app/domain/execution.py b/backend/app/domain/execution.py new file mode 100644 index 0000000..db4c0ad --- /dev/null +++ b/backend/app/domain/execution.py @@ -0,0 +1,27 @@ +"""执行结果与任务阶段上下文,不引入 HTTP、数据库或适配器。""" + +from __future__ import annotations + +from contextvars import ContextVar +from dataclasses import dataclass +from pathlib import Path +from typing import Awaitable, Callable + +PhaseCallback = Callable[[str, str], Awaitable[None]] +# ContextVar 按 asyncio 任务隔离;共享同一对象让媒体与 HTTP 阶段使用同一准入边界。 +current_phase_callback: ContextVar[PhaseCallback | None] = ContextVar( + "current_phase_callback", default=None +) + + +async def enter_phase(phase_key: str, resource_pool: str) -> None: + callback = current_phase_callback.get() + if callback is not None: + await callback(phase_key, resource_pool) + + +@dataclass +class CpuResult: + outputs: list[Path] + result: dict + metadata: dict diff --git a/backend/app/domain/gpu_summary.py b/backend/app/domain/gpu_summary.py new file mode 100644 index 0000000..3b4e435 --- /dev/null +++ b/backend/app/domain/gpu_summary.py @@ -0,0 +1,102 @@ +"""Public GPU summary. Never expose scheduler job IDs or host PID details.""" + +import math +from datetime import datetime, timezone + + +def summarize(gpus, scheduler, now, generated): + active, queued = [], None + try: + stamp = scheduler["updated_at"] + if ( + type(stamp) not in (int, float) + or not math.isfinite(stamp) + or not now - 5 <= stamp <= now + 1 + ): + raise ValueError("Stale scheduler") + if scheduler.get("schema_version") == 2: + entries = scheduler.get("active_jobs", []) + if not isinstance(entries, list) or len(entries) > len(gpus): + raise ValueError("Invalid active list") + indexes = set() + for entry in entries: + index = entry["gpu_index"] + if ( + type(index) is not int + or index in indexes + or not any( + row["index"] == index and row["_uuid"] == entry["gpu_uuid"] for row in gpus + ) + ): + raise ValueError("Invalid lease") + indexes.add(index) + count = scheduler.get("queued_count") + if count is not None and (type(count) is not int or not 0 <= count <= 10000000): + raise ValueError("Invalid queue count") + active, queued = entries, count + elif scheduler.get("state") == "leased": + lease = scheduler.get("lease") or {} + active = [ + {"gpu_index": lease.get("index"), "gpu_uuid": lease.get("uuid"), "state": "running"} + ] + except (KeyError, TypeError, ValueError): + scheduler, active, queued = None, [], None + active_indexes = set() + for entry in active: + gpu = next( + ( + row + for row in gpus + if row["index"] == entry.get("gpu_index") and row["_uuid"] == entry.get("gpu_uuid") + ), + None, + ) + if gpu is None: + continue + active_indexes.add(gpu["index"]) + state = entry.get("state") + gpu.update( + busy=True, + eligible=False, + state=state if state in {"preempting", "blocked", "launching"} else "running", + stage=entry.get("stage") + if entry.get("stage") + in {"launching", "executing", "cleanup", "model", "upscale", "collecting"} + else None, + ) + running = sum(row["index"] in active_indexes or row["_own"] for row in gpus) + available = sum(row["eligible"] for row in gpus) + state = "running" if running else "ready" if available else "waiting" + reason = ( + f"正在运行{running}个GPU任务,{available}张卡可接新任务。" + if running + else None + if available + else "等待可用GPU,外部任务优先。" + ) + dispatch_blocked = bool(scheduler and scheduler.get("state") == "blocked") + if dispatch_blocked: + reason = "执行器需要管理员检查,新任务暂停派发。" + if not running: + state = "blocked" + available = 0 + for gpu in gpus: + gpu["eligible"] = False + if gpu["state"] == "ready": + gpu["state"] = "waiting" + elif scheduler and "memory" in str(scheduler.get("reason", "")).lower(): + reason = "共享内存不足,任务按入队顺序等待资源。" + for gpu in gpus: + gpu.pop("_uuid") + gpu.pop("_own") + return { + "available": True, + "state": state, + "reason": reason, + "gpus": gpus, + "running_count": running, + "available_count": available, + "queued_count": queued, + "dispatch_blocked": dispatch_blocked, + "updated_at": datetime.fromtimestamp(generated, timezone.utc).isoformat(), + } diff --git a/backend/app/domain/stories.py b/backend/app/domain/stories.py new file mode 100644 index 0000000..ce497e0 --- /dev/null +++ b/backend/app/domain/stories.py @@ -0,0 +1,341 @@ +"""独立 v3 故事模型及确定性编译,不读数据库或调用语言模型。""" + +from dataclasses import dataclass +import hashlib +import json +from typing import Literal + +from pydantic import Field, model_validator +from app.domain.timeline import Strict, Render, MAX_WORKFLOW_SHOTS + +ID = r"^[0-9a-f]{32}$" + + +def digest(value): + return hashlib.sha256( + json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False + ).encode() + ).hexdigest() + + +class Context(Strict): + era: str = "" + style: str = "" + palette: str = "" + lighting: str = "" + negative_prompt: str = "" + + +class Variant(Strict): + id: str = Field(pattern=ID) + name: str = "" + description: str = "" + reference_asset_ids: list[str] = Field(default_factory=list) + + +class Entity(Variant): + kind: Literal["person", "creature", "prop"] = "person" + forms: list[Variant] = Field(default_factory=list) + appearances: list[Variant] = Field(default_factory=list) + + +class Scene(Variant): + location: str = "" + time: str = "" + weather: str = "" + lighting: str = "" + + +class Cast(Strict): + id: str = Field(pattern=ID) + entity_id: str = Field(pattern=ID) + form_id: str | None = Field(default=None, pattern=ID) + appearance_id: str | None = Field(default=None, pattern=ID) + position: str = "" + action: str = "" + + +class Overrides(Strict): + time: str | None = None + weather: str | None = None + lighting: str | None = None + palette: str | None = None + + @model_validator(mode="before") + @classmethod + def no_null(cls, value): + if isinstance(value, dict) and any(v is None for v in value.values()): + raise ValueError("override must be a string; remove key to inherit") + return value + + def model_dump(self, **kwargs): + return super().model_dump(exclude_unset=True, **kwargs) + + +class FrameParameters(Strict): + seed: int = Field(default=42, ge=0, le=2**32 - 1) + + +class VideoParameters(FrameParameters): + source_seconds: int = Field(default=5, ge=1, le=15) + num_inference_steps: int = Field(default=50, ge=1, le=100) + guidance_scale: float = Field(default=5.0, ge=1, le=20, allow_inf_nan=False) + upscale: bool = True + + +class Edit(Strict): + start_frame: int = Field(default=0, ge=0) + duration_frames: int = Field(default=120, ge=24, le=360) + + +class StoryShot(Strict): + id: str = Field(pattern=ID) + name: str = "" + scene_id: str | None = Field(default=None, pattern=ID) + cast: list[Cast] = Field(default_factory=list) + visual_prompt: str = Field(default="", max_length=8000) + motion_prompt: str = Field(default="", max_length=8000) + overrides: Overrides = Field(default_factory=Overrides) + frame_parameters: FrameParameters = Field(default_factory=FrameParameters) + video_parameters: VideoParameters = Field(default_factory=VideoParameters) + edit: Edit = Field(default_factory=Edit) + + +class StorySpecV3(Strict): + schema_version: Literal[3] = 3 + profile: Literal["landscape_1080_v1", "portrait_1080_v1"] = "landscape_1080_v1" + context: Context = Field(default_factory=Context) + scenes: list[Scene] = Field(default_factory=list) + entities: list[Entity] = Field(default_factory=list) + shots: list[StoryShot] = Field(min_length=1, max_length=MAX_WORKFLOW_SHOTS) + render: Render = Field(default_factory=Render) + + @model_validator(mode="after") + def consistent(self): + all_ids = [] + for collection in (self.scenes, self.entities, self.shots): + all_ids.extend(x.id for x in collection) + for entity in self.entities: + all_ids.extend(x.id for x in entity.forms + entity.appearances) + for shot in self.shots: + all_ids.extend(x.id for x in shot.cast) + if len(set(all_ids)) != len(all_ids): + raise ValueError("duplicate stable id") + scenes = {x.id for x in self.scenes} + entities = {x.id: x for x in self.entities} + for shot in self.shots: + if shot.scene_id and shot.scene_id not in scenes: + raise ValueError("scene reference missing") + for cast in shot.cast: + entity = entities.get(cast.entity_id) + if ( + entity is None + or (cast.form_id and cast.form_id not in {x.id for x in entity.forms}) + or ( + cast.appearance_id + and cast.appearance_id not in {x.id for x in entity.appearances} + ) + ): + raise ValueError("entity/form/appearance reference missing") + # 生成源长度不代表人工素材长度;实际选用范围由候选来源与媒体帧数校验。 + frames = sum(s.edit.duration_frames for s in self.shots) + if self.render.total_frames is not None and self.render.total_frames != frames: + raise ValueError("total_frames differs from edits") + self.render.total_frames = frames + if any(s.end_frame > frames for s in self.render.subtitles): + raise ValueError("subtitle exceeds canvas") + audio = self.render.audio + if audio and ( + audio.offset_frame >= frames + or (audio.source_end_ms - audio.source_start_ms) * 24 + > (frames - audio.offset_frame) * 1000 + ): + raise ValueError("audio exceeds canvas") + return self + + def model_dump(self, **kwargs): + data = super().model_dump(**kwargs) + for shot, model in zip(data["shots"], self.shots): + shot["overrides"] = model.overrides.model_dump() + return data + + +def ordered_reference_ids(references): + """编号与模型输入共享同一首次去重顺序,角色清单自身不去重。""" + return list(dict.fromkeys(ref["asset_id"] for ref in references)) + + +def reference_binding_suffix(references): + if not references: + return "" + lines = [] + for index, asset_id in enumerate(ordered_reference_ids(references), 1): + labels = list( + dict.fromkeys( + (ref["role"], ref["label"]) for ref in references if ref["asset_id"] == asset_id + ) + ) + bindings = "; ".join( + f"{role} {json.dumps(label, ensure_ascii=False)}" for role, label in labels + ) + lines.append(f"Picture {index}: {bindings}.") + return ( + "\n\nReference image bindings (Picture numbers follow the attached image order):\n" + + "\n".join(lines) + + "\nUse scene references for the setting and background. Use entity, form and appearance references only for their named subject; preserve its identity, selected form and costume. Compose one frame according to the shot description; do not draw the Picture labels." + ) + + +def text_frame_prompt(compiled_shot): + """显式文生图不声称已附图,只移除编译器确定追加的映射后缀。""" + return compiled_shot["frame_prompt"].removesuffix( + reference_binding_suffix(compiled_shot["references"]) + ) + + +def compile_story(spec, assets): + spec = spec if isinstance(spec, StorySpecV3) else StorySpecV3.model_validate(spec) + scenes, entities = {s.id: s for s in spec.scenes}, {e.id: e for e in spec.entities} + results = [] + for shot in spec.shots: + scene = scenes.get(shot.scene_id) + effective = spec.context.model_dump() + if scene: + effective.update( + {k: getattr(scene, k) for k in ("time", "weather", "lighting") if getattr(scene, k)} + ) + effective.update(shot.overrides.model_dump()) + parts = [f"{k}: {v}" for k, v in effective.items() if v and k != "negative_prompt"] + bound_parts = list(parts) + aliases = {} + for cast in shot.cast: + if cast.entity_id not in aliases: + entity = entities[cast.entity_id] + kind = {"person": "Character", "creature": "Creature", "prop": "Prop"}[entity.kind] + aliases[entity.id] = f"{kind} {len(aliases) + 1} / {entity.name or entity.kind}" + bound_items = set() + refs = [] + errors = [] + + def include(item, role, label): + parts.extend(v for v in (item.name, item.description) if v) + if (role, item.id) not in bound_items: + bound_items.add((role, item.id)) + description = f": {item.description}" if item.description else "" + bound_parts.append(f"{role} {json.dumps(label, ensure_ascii=False)}{description}") + for asset_id in item.reference_asset_ids: + asset = assets.get(asset_id) + sha = ( + asset.get("sha256") + if isinstance(asset, dict) + else getattr(asset, "sha256", None) + ) + refs.append({"asset_id": asset_id, "sha256": sha, "role": role, "label": label}) + if not sha: + errors.append( + { + "code": "reference_unavailable", + "message": "参考素材不存在或不可访问", + "asset_id": asset_id, + } + ) + + if scene: + scene_alias = f"Scene 1 / {scene.name or 'unnamed scene'}" + include(scene, "scene", scene_alias) + if scene.location: + parts.append(scene.location) + bound_parts.append( + f"{json.dumps(scene_alias, ensure_ascii=False)} location: {scene.location}" + ) + for cast in shot.cast: + entity = entities[cast.entity_id] + alias = aliases[entity.id] + include(entity, "entity", alias) + for key, role in (("form_id", "form"), ("appearance_id", "appearance")): + selected = getattr(cast, key) + if selected: + variant = next( + v + for v in getattr(entity, "forms" if role == "form" else "appearances") + if v.id == selected + ) + include( + variant, + role, + f"{alias} / {variant.name or role}", + ) + parts.extend(v for v in (cast.position, cast.action) if v) + for key in ("position", "action"): + if value := getattr(cast, key): + bound_parts.append(f"{json.dumps(alias, ensure_ascii=False)} {key}: {value}") + parts.append(shot.visual_prompt) + bound_parts.append(shot.visual_prompt) + if refs: + bound_parts.insert( + 0, + "Use the following subject aliases to bind descriptions and spatial relations; do not draw these alias labels or numbers as text.", + ) + prompt = "\n".join( + p for p in (bound_parts if refs else parts) if p + ) + reference_binding_suffix(refs) + if not prompt.strip(): + errors.append({"code": "prompt_required", "message": "请输入镜头画面描述"}) + if len(prompt) > 8000: + errors.append({"code": "prompt_too_long", "message": "编译提示词超过8000字符"}) + visual = { + "prompt": prompt, + "settings": effective, + "references": refs, + "profile": spec.profile, + } + results.append( + { + "shot_id": shot.id, + "context_hash": digest(visual), + "frame_prompt": prompt, + "motion_prompt": shot.motion_prompt, + "references": refs, + "effective_settings": effective, + "errors": errors, + } + ) + return {"shots": results, "errors": []} + + +def canvas(profile): + return (1080, 1920) if profile == "portrait_1080_v1" else (1920, 1080) + + +@dataclass(frozen=True) +class StoryRenderPlan: + spec: dict + canvas: tuple + frames: int + clips: tuple + fps: int = 24 + + +def compile_story_render(spec, render_inputs): + model = StorySpecV3.model_validate(spec) + clips = render_inputs["clips"] + if ( + len(clips) != len(model.shots) + or render_inputs.get("fps") != 24 + or render_inputs.get("canvas") != list(canvas(model.profile)) + ): + raise ValueError("invalid story render inputs") + for shot, clip in zip(model.shots, clips): + if ( + shot.id != clip["shot_id"] + or shot.edit.start_frame != clip["start_frame"] + or shot.edit.duration_frames != clip["duration_frames"] + ): + raise ValueError("frozen trim differs from spec") + return StoryRenderPlan( + model.model_dump(mode="json"), + canvas(model.profile), + model.render.total_frames, + tuple(clips), + ) diff --git a/backend/app/domain/tasks.py b/backend/app/domain/tasks.py new file mode 100644 index 0000000..3934733 --- /dev/null +++ b/backend/app/domain/tasks.py @@ -0,0 +1,22 @@ +"""任务分类与完成态;不读取配置、不访问数据库或模型。""" + +GPU_TYPES = { + "image.generate", + "image.reference.generate", + "video.generate", + "video.people.analyze", + "video.replace", + "defect.generate", + "audio.transcribe", +} +CPU_TYPES = { + "image.prepare_frame", + "math.solve", + "media.structure", + "video.compose", + "audio.speech", + "text.script.generate", + "audio.assemble", +} +TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"} +RUN_TERMINAL = {"succeeded", "cancelled", "failed"} diff --git a/backend/app/domain/timeline.py b/backend/app/domain/timeline.py new file mode 100644 index 0000000..4d38817 --- /dev/null +++ b/backend/app/domain/timeline.py @@ -0,0 +1,196 @@ +"""Versioned short-clip story contract. Public fields contain no executable paths.""" + +from dataclasses import dataclass, field +from typing import Literal +import re +from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator + +DEFAULT_CLIP_FRAMES = 120 +MAX_CLIP_FRAMES = 360 +DEFAULT_SOURCE_FRAMES = 121 +MAX_SOURCE_FRAMES = 361 +MAX_WORKFLOW_SHOTS = 1000 +MAX_TIMELINE_FRAMES = MAX_WORKFLOW_SHOTS * MAX_CLIP_FRAMES + + +class Strict(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +class ShotParameters(Strict): + seed: int = Field(default=42, ge=0, le=2**32 - 1) + + +class Shot(Strict): + key: str = Field(pattern=r"^shot_[1-9][0-9]{0,3}$") + prompt: str = Field(min_length=1, max_length=8000) + duration_frames: int = Field(default=DEFAULT_CLIP_FRAMES, ge=24, le=MAX_CLIP_FRAMES) + image_asset_id: str | None = Field(default=None, min_length=1, max_length=64) + parameters: ShotParameters = Field(default_factory=ShotParameters) + + @model_validator(mode="after") + def prompt_required(self): + if not self.prompt.strip(): + raise ValueError("prompt_required") + return self + + +class Subtitle(Strict): + start_frame: int = Field(ge=0) + end_frame: int = Field(gt=0) + text: str = Field(min_length=1, max_length=2000) + + @model_validator(mode="after") + def safe(self): + if ( + self.end_frame <= self.start_frame + or not self.text.strip() + or re.search(r"[\\{}\x00-\x1f\x7f]", self.text) + ): + raise ValueError("invalid_timeline: subtitle") + return self + + +class Audio(Strict): + asset_id: str = Field(min_length=1, max_length=64) + source_start_ms: int = Field(ge=0) + source_end_ms: int = Field(gt=0) + offset_frame: int = Field(default=0, ge=0) + short_policy: Literal["silence"] = "silence" + + @model_validator(mode="after") + def fits(self): + if self.source_end_ms <= self.source_start_ms: + raise ValueError("invalid_timeline: invalid audio selection") + return self + + +class Render(Strict): + fps: Literal[24] = 24 + total_frames: int | None = Field(default=None, ge=1, le=MAX_TIMELINE_FRAMES) + fit: Literal["contain", "cover"] = "contain" + audio: Audio | None = None + subtitles: list[Subtitle] = Field(default_factory=list, max_length=1000) + template_version: Literal["plain-v1"] = "plain-v1" + + +class WorkflowSpec(Strict): + schema_version: Literal[1, 2] = 1 + shots: list[Shot] = Field(min_length=1, max_length=MAX_WORKFLOW_SHOTS) + profile: Literal["landscape_1080_v1", "portrait_1080_v1"] = "landscape_1080_v1" + render: Render = Field(default_factory=Render) + + @model_validator(mode="after") + def ordered_timeline(self): + if self.schema_version == 1 and ( + len(self.shots) != 3 or any("duration_frames" in s.model_fields_set for s in self.shots) + ): + raise ValueError("schema_version 1 requires three full-length shots") + if [s.key for s in self.shots] != [f"shot_{i}" for i in range(1, len(self.shots) + 1)]: + raise ValueError("exact ordered sequential shot keys required") + frames = sum(s.duration_frames for s in self.shots) + if frames > MAX_TIMELINE_FRAMES: + raise ValueError("invalid_timeline: total frames exceed maximum story length") + if self.render.total_frames is not None and self.render.total_frames != frames: + raise ValueError("invalid_timeline: total_frames differs from shots") + self.render.total_frames = frames + if any(c.end_frame > frames for c in self.render.subtitles): + raise ValueError("invalid_timeline: subtitle exceeds canvas") + audio = self.render.audio + if audio and ( + audio.offset_frame >= frames + or (audio.source_end_ms - audio.source_start_ms) * 24 + > (frames - audio.offset_frame) * 1000 + ): + raise ValueError("invalid_timeline: audio exceeds canvas") + return self + + @model_serializer(mode="wrap") + def legacy_compatible_dump(self, handler): + data = handler(self) + if self.schema_version == 1: + for shot in data["shots"]: + shot.pop("duration_frames", None) + return data + + +@dataclass(frozen=True) +class TimelinePlan: + spec: dict + generation_parameters: dict + canvas: tuple[int, int] + frames: int = 360 + clip_frames: int = 120 + fps: int = 24 + shot_frames: tuple[int, ...] = () + shot_generation_parameters: dict[str, dict] = field(default_factory=dict) + + +def ordered_step_keys(snapshot): + """The frozen shot array is authoritative, including shot_10 and later.""" + if snapshot.get("schema_version") == 3: + return ["compose"] + return [shot["key"] for shot in snapshot["shots"]] + ["compose"] + + +def generation_parameters_for_shot(snapshot, key): + """只读取已冻结源参数;仅旧快照完全缺少 map 时回退,不能从当前草稿重算。""" + compiled = snapshot["compiled"] + if "shot_generation_parameters" not in compiled: + return compiled["generation_parameters"] + parameters = compiled["shot_generation_parameters"] + if ( + not isinstance(parameters, dict) + or key not in parameters + or not isinstance(parameters[key], dict) + or "num_frames" not in parameters[key] + ): + raise ValueError("Frozen shot generation parameters are incomplete") + return parameters[key] + + +def compile_timeline(spec, owned_assets) -> TimelinePlan: + spec = spec if isinstance(spec, WorkflowSpec) else WorkflowSpec.model_validate(spec) + audio = spec.render.audio + if audio: + asset = owned_assets.get(audio.asset_id) + + def field(name): + return asset.get(name) if isinstance(asset, dict) else getattr(asset, name, None) + + if ( + asset is None + or field("kind") != "audio" + or field("duration_seconds") is None + or audio.source_end_ms > round(field("duration_seconds") * 1000) + ): + raise ValueError("invalid_timeline: audio source cut exceeds source") + portrait = spec.profile == "portrait_1080_v1" + parameters = dict( + width=704 if portrait else 1280, + height=1280 if portrait else 704, + num_frames=DEFAULT_SOURCE_FRAMES, + fps=24, + upscale=True, + upscale_width=1056 if portrait else 1920, + upscale_height=1920 if portrait else 1056, + num_inference_steps=50, + guidance_scale=5.0, + tile_size=128, + ) + # 原生源长按每个镜头独立取 4n+1;短片保持 121 帧,使旧的 trim-only 复用哈希不变。 + per_shot = { + shot.key: { + **parameters, + "num_frames": max(DEFAULT_SOURCE_FRAMES, 4 * ((shot.duration_frames + 3) // 4) + 1), + } + for shot in spec.shots + } + return TimelinePlan( + spec.model_dump(mode="json"), + parameters, + (1080, 1920) if portrait else (1920, 1080), + frames=spec.render.total_frames, + shot_frames=tuple(s.duration_frames for s in spec.shots), + shot_generation_parameters=per_shot, + ) diff --git a/backend/app/domain/video_editing.py b/backend/app/domain/video_editing.py new file mode 100644 index 0000000..e371586 --- /dev/null +++ b/backend/app/domain/video_editing.py @@ -0,0 +1,188 @@ +"""视频编辑的纯参数与公开分析合同;不接受客户端路径或遮罩。""" + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator +from app.domain.errors import MediaError + +PROFILE = "wan-animate-replace-v1" +TASKS = {"video.people.analyze", "video.replace"} + + +def video_capability(settings): + available = bool(getattr(settings, "video_edit_enabled", False) and settings.inference_base_url) + return { + "available": available, + "profile": getattr(settings, "video_edit_profile", PROFILE), + "model": "Wan2.2-Animate-14B", + "max_seconds": getattr(settings, "video_edit_max_seconds", 120), + "max_people": getattr(settings, "video_edit_max_people", 12), + "max_pixels": getattr(settings, "video_edit_max_pixels", 399360), + "fps": 24, + "reason": None if available else "视频编辑尚未启用或未完成模型认证。", + } + + +def video_defaults(task, settings): + value = { + "profile": getattr(settings, "video_edit_profile", PROFILE), + "max_pixels": 399360, + "fps": 24, + } + if task == "video.replace": + value.update( + num_inference_steps=20, + guidance_scale=1.0, + seed=42, + preserve_audio=True, + mask_expand_pixels=8, + mask_feather_pixels=4, + ) + return value + + +def invalid(message="视频编辑输入或参数无效。"): + return MediaError("invalid_input", message) + + +def validate_video_arguments(task, inputs, parameters, settings): + # 参数校验也用于Provider;服务器绑定通过单独参数传递,不能混入浏览器input。 + if not video_capability(settings)["available"]: + raise MediaError("capability_unavailable", "视频编辑尚未启用或未认证。") + allowed = {"video_asset_id"} + if task == "video.replace": + allowed |= {"analysis_job_id", "prompt", "negative_prompt", "replacements"} + if not isinstance(inputs, dict) or set(inputs) - allowed: + raise invalid() + for key in ("video_asset_id", "analysis_job_id"): + if (key == "video_asset_id" or task == "video.replace") and ( + not isinstance(inputs.get(key), str) or not 1 <= len(inputs[key]) <= 64 + ): + raise invalid() + defaults = video_defaults(task, settings) + if not isinstance(parameters, dict) or set(parameters) - set(defaults): + raise invalid() + p = defaults | parameters + if ( + p["profile"] != getattr(settings, "video_edit_profile", PROFILE) + or type(p["fps"]) is not int + or p["fps"] != 24 + or type(p["max_pixels"]) is not int + or p["max_pixels"] not in {399360, 921600} + or p["max_pixels"] > video_capability(settings)["max_pixels"] + ): + raise invalid() + if task == "video.people.analyze": + return p + for key in ("prompt", "negative_prompt"): + if not isinstance(inputs.get(key, ""), str) or len(inputs.get(key, "")) > 8000: + raise invalid() + if not inputs.get("prompt", "").strip(): + raise invalid("请输入全局提示词。") + rows = inputs.get("replacements") + if not isinstance(rows, list) or not 1 <= len(rows) <= getattr( + settings, "video_edit_max_people", 12 + ): + raise invalid("请选择预算范围内的人物。") + seen = set() + for row in rows: + if not isinstance(row, dict) or set(row) - {"person_id", "reference_asset_id", "prompt"}: + raise invalid() + for key in ("person_id", "reference_asset_id"): + if not isinstance(row.get(key), str) or not 1 <= len(row[key]) <= 64: + raise invalid() + if row["person_id"] in seen: + raise invalid("同一人物不能重复替换。") + seen.add(row["person_id"]) + if not isinstance(row.get("prompt", ""), str) or len(row.get("prompt", "")) > 8000: + raise invalid() + for key, low, high in ( + ("num_inference_steps", 1, 100), + ("seed", 0, 2**32 - 1), + ("mask_expand_pixels", 0, 64), + ("mask_feather_pixels", 0, 64), + ): + if type(p[key]) is not int or not low <= p[key] <= high: + raise invalid() + if ( + type(p["preserve_audio"]) is not bool + or type(p["guidance_scale"]) not in {int, float} + or not 1 <= p["guidance_scale"] <= 20 + ): + raise invalid() + return p + + +class SafeModel(BaseModel): + model_config = ConfigDict(extra="ignore", strict=True, allow_inf_nan=False) + + +class Video(SafeModel): + width: int = Field(gt=0, le=16384) + height: int = Field(gt=0, le=16384) + fps: int = Field(ge=24, le=24) + frames: int = Field(gt=0) + duration_seconds: float = Field(gt=0) + + +class Sample(SafeModel): + frame: int = Field(ge=0) + bbox: list[float] = Field(min_length=4, max_length=4) + + @model_validator(mode="after") + def valid_box(self): + x1, y1, x2, y2 = self.bbox + if not 0 <= x1 < x2 <= 1 or not 0 <= y1 < y2 <= 1: + raise ValueError("Invalid normalized bbox") + return self + + +class Person(SafeModel): + id: str = Field(pattern=r"^person_[0-9]{4,}$", max_length=64) + label: str = Field(min_length=1, max_length=128) + thumbnail_output_index: int = Field(ge=0) + first_frame: int = Field(ge=0) + last_frame: int = Field(ge=0) + confidence: float = Field(ge=0, le=1) + samples: list[Sample] = Field(min_length=1, max_length=128) + + +class Analysis(SafeModel): + profile: str + analysis_token: str = Field(min_length=1, max_length=512) + source_sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + video: Video + poster_output_index: int = Field(ge=0) + people: list[Person] = Field(max_length=1000) + warnings: list[str] = Field(max_length=128) + + +def safe_analysis(value, settings, *, output_count=None): + try: + data = Analysis.model_validate(value) + if ( + data.profile != getattr(settings, "video_edit_profile", PROFILE) + or data.video.duration_seconds > getattr(settings, "video_edit_max_seconds", 120) + or len(data.people) > getattr(settings, "video_edit_max_people", 12) + ): + raise ValueError("Analysis exceeds profile limits") + indexes = [data.poster_output_index] + [p.thumbnail_output_index for p in data.people] + if len(set(indexes)) != len(indexes) or len({p.id for p in data.people}) != len( + data.people + ): + raise ValueError("Duplicate analysis index or person") + if output_count is not None and any(i >= output_count for i in indexes): + raise ValueError("Missing preview output") + if abs(data.video.frames - round(data.video.duration_seconds * 24)) > 1: + raise ValueError("Analysis timeline duration differs") + for p in data.people: + frames = {s.frame for s in p.samples} + if not {p.first_frame, p.last_frame} <= frames or len(frames) < min( + 3, p.last_frame - p.first_frame + 1 + ): + raise ValueError("Analysis needs visible start/middle/end samples") + if not p.first_frame <= p.last_frame < data.video.frames or any( + not p.first_frame <= s.frame <= p.last_frame for s in p.samples + ): + raise ValueError("Invalid person timing") + return data.model_dump() + except (ValidationError, ValueError, TypeError): + raise MediaError("invalid_analysis", "人物分析结果无效或已过期。") from None diff --git a/backend/app/dto.py b/backend/app/dto.py deleted file mode 100644 index 51e144e..0000000 --- a/backend/app/dto.py +++ /dev/null @@ -1,45 +0,0 @@ -import re -from sqlalchemy import select -from .models import Asset, JobAsset - - -def iso(value): - return value.isoformat(timespec="milliseconds") + "Z" if value is not None else None - - -def public_value(value): - if isinstance(value, dict): - return {k: public_value(v) for k, v in value.items() - if k not in {"path", "output_dir", "storage_key", "api_key", "token", "request_path"}} - if isinstance(value, list): - return [public_value(v) for v in value] - if isinstance(value, str): - value = re.sub(r"/(?:workspace|run|data|home|var|tmp|srv)/[^\s,;]+", "[server file]", value) - return re.sub(r"[A-Za-z]:[\\/][^\s,;]+", "[server file]", value) - return value - - -def asset_dto(asset): - return {"id": asset.id, "name": asset.name, "kind": asset.kind, "mime_type": asset.mime_type, - "size_bytes": asset.size_bytes, "width": asset.width, "height": asset.height, - "duration_seconds": asset.duration_seconds, - "preview_url": f"/api/assets/{asset.id}/content", - "thumbnail_url": f"/api/assets/{asset.id}/thumbnail" if asset.kind in {"image", "video"} else None, - "download_url": f"/api/assets/{asset.id}/content?download=1", "source_job_id": asset.source_job_id, - "origin": asset.origin, "tags": asset.tags or [], "favorite": asset.favorite, - "created_at": iso(asset.created_at)} - - -async def job_dto(session, job): - assets = (await session.scalars(select(Asset).where(Asset.source_job_id == job.id, - Asset.owner_id == job.owner_id, Asset.library_scope == 'private', Asset.deleted_at.is_(None), Asset.ready.is_(True)) - .order_by(Asset.source_output_index))).all() - inputs = (await session.scalars(select(JobAsset.asset_id).where(JobAsset.job_id == job.id))).all() - return {"id": job.id, "task_type": job.task_type, "state": job.state, "phase": job.phase, - "version": job.version, "execution_mode": job.execution_mode, "desired_state": job.desired_state, "hold_reasons": job.hold_reasons or [], "run_id": job.run_id, "step_key": job.step_key, "batch_id": job.batch_id, "current_execution_id": job.current_execution_id, "explicit_attempt": job.explicit_attempt, "prompt": job.input_json.get("prompt", ""), "parameters": job.parameters, - "input_asset_ids": list(inputs), "result_assets": [asset_dto(a) for a in assets], - "result": public_value(job.result_json), "progress": None, "queue_position": None, - "upstream_id": job.upstream_id, "attempt_count": job.attempt_count, "preemptions": job.preemptions, - "last_preempted_reason": job.last_preempted_reason, "cancel_requested": job.cancel_requested, - "error": job.error_json, "sync_warning": job.sync_warning, "created_at": iso(job.created_at), - "scheduled_at": iso(job.scheduled_at), "started_at": iso(job.started_at), "finished_at": iso(job.finished_at)} diff --git a/backend/app/events.py b/backend/app/events.py deleted file mode 100644 index 640462d..0000000 --- a/backend/app/events.py +++ /dev/null @@ -1,86 +0,0 @@ -import asyncio -import json -import time -from fastapi import APIRouter, Depends, Request -from fastapi.responses import StreamingResponse -from sqlalchemy import func, select -from .auth import Actor, COOKIE, current_actor, token_hash -from .dto import job_dto -from .errors import fail -from .models import Event, Session, User, utcnow - -router = APIRouter(tags=["events"]) - - -async def emit_job(session, job, *, increment=True): - if increment: - job.version += 1 - await session.flush() - session.add(Event(owner_id=job.owner_id, job_id=job.id, event_type="job.updated", - data={"job": await job_dto(session, job)})) - - -def emit_asset(session, owner_id, event_type, data): - session.add(Event(owner_id=owner_id, event_type=event_type, data=data)) - - -async def event_batch(db, owner_id, after, limit=100): - async with db.session() as session: - events = (await session.scalars(select(Event).where(Event.owner_id == owner_id, Event.id > after) - .order_by(Event.id).limit(limit))).all() - return [{"id": event.id, "event": event.event_type, "data": event.data} for event in events] - - -async def session_is_active(db, token): - if not token: - return False - if token.startswith("Bearer "): - from .v2_models import ApiToken - async with db.session() as session: - return (await session.scalar(select(ApiToken.id).join(User,User.id==ApiToken.owner_id).where(ApiToken.token_hash==token_hash(token[7:]),ApiToken.revoked_at.is_(None),User.disabled.is_(False), (ApiToken.expires_at.is_(None) | (ApiToken.expires_at>utcnow()))))) is not None - async with db.session() as session: - return (await session.scalar(select(Session.token_hash).join(User, User.id == Session.user_id) - .where(Session.token_hash == token_hash(token), Session.expires_at > utcnow(), User.disabled.is_(False)))) is not None - - -async def event_stream(request, owner_id, token, after): - # Authentication was checked by the endpoint. Flush a body immediately so - # EventSource/proxies need not wait for the first durable event or heartbeat. - yield ": connected\n\n" - db = request.app.state.db - heartbeat = request.app.state.settings.event_heartbeat_seconds - last_heartbeat = time.monotonic() - async with db.session() as session: - maximum = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == owner_id)) or 0 - minimum = await session.scalar(select(func.min(Event.id)).where(Event.owner_id == owner_id)) or 0 - if after > maximum or (after > 0 and minimum > 0 and after < minimum - 1): - yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n" - after = maximum - while not await request.is_disconnected(): - if getattr(request.app.state,"draining",False):return - if not await session_is_active(db, token): - return - rows = await event_batch(db, owner_id, after) - for event in rows: - after = event["id"] - yield f"id: {after}\nevent: {event['event']}\ndata: {json.dumps(event['data'], ensure_ascii=False, separators=(',', ':'))}\n\n" - if time.monotonic() - last_heartbeat >= heartbeat: - yield ": heartbeat\n\n" - last_heartbeat = time.monotonic() - if not rows: - await asyncio.sleep(min(.5, heartbeat)) - - -@router.get("/events") -async def events(request: Request, after: int = 0, actor: Actor = Depends(current_actor)): - try: - cursor = int(request.headers.get("Last-Event-ID", after)) - if cursor < 0: - raise ValueError - except ValueError: - fail(422, "invalid_cursor", "事件游标必须为非负整数") - return StreamingResponse(event_stream(request, actor.id, request.headers.get("Authorization") if actor.auth_kind=="bearer" else request.cookies.get(COOKIE), cursor), - media_type="text/event-stream", headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"}) - -# Domain events share the existing owner stream and caller transaction. -emit_event = emit_asset diff --git a/backend/app/executions.py b/backend/app/executions.py deleted file mode 100644 index 1f06ace..0000000 --- a/backend/app/executions.py +++ /dev/null @@ -1,103 +0,0 @@ -import secrets -from sqlalchemy import select,func -from .models import Job,utcnow -from .v2_models import Execution - -async def begin_execution(session,job_id,phase_key="execute",resource_pool="cpu_media"): - job=await session.get(Job,job_id) - if not job or job.deleted_at is not None:raise ValueError("Job is unavailable") - ordinal=(await session.scalar(select(func.max(Execution.ordinal)).where(Execution.job_id==job_id)) or 0)+1 - row=Execution(job_id=job_id,ordinal=ordinal,phase_key=phase_key,resource_pool=resource_pool,fence_token=secrets.token_hex(24),state="running",started_at=utcnow()) - session.add(row);await session.flush();job.current_execution_id=row.id - return row - -async def accept_manifest(session,execution_id,fence_token,manifest): - row=await session.get(Execution,execution_id) - if not row or row.fence_token!=fence_token:return False - job=await session.get(Job,row.job_id) - if not job or job.deleted_at is not None or job.current_execution_id!=execution_id or job.cancel_requested:return False - row.manifest_json=manifest;row.state="results_ready";row.finished_at=utcnow() - return True - -async def request_control(session,job_id,desired_state,expected_execution_id=None): - job=await session.get(Job,job_id) - if not job or job.deleted_at is not None or (expected_execution_id and job.current_execution_id!=expected_execution_id):return {"accepted":False} - if job.state in {"succeeded","failed","cancelled","timed_out"}:return {"accepted":False,"state":job.state} - if job.desired_state!="cancel":job.desired_state=desired_state - if desired_state=="cancel":job.cancel_requested=True - return {"accepted":True,"execution_id":job.current_execution_id,"desired_state":job.desired_state} - - -async def observe_gpu_execution(session,job,remote): - """Observe real upstream attempts without fabricating missed/queued claims. - - Return (accepted_snapshot, current_observed_execution). This runs inside the - same transaction as the Job update/event, under the database unit lock. - """ - import hashlib,json - if not job or job.deleted_at is not None:return False,None - if remote.get("id") and remote["id"]!=job.upstream_id:return False,None - attempt=int(remote.get("attempt_count",job.attempt_count)) - if attempt<0:raise ValueError("Invalid upstream attempt") - rows=list((await session.scalars(select(Execution).where(Execution.job_id==job.id,Execution.phase_key.like("gpu:%")).order_by(Execution.ordinal))).all()) - highest=max([job.attempt_count]+[(row.manifest_json or {}).get("upstream_attempt",0) for row in rows]) - if attempt0 and (state=="running" and not unlaunched or state in {"succeeded","failed","timed_out","cancelled"} and (not unlaunched or execution is not None)) - if execution is None and actual: - previous=await session.get(Execution,job.current_execution_id) if job.current_execution_id else None - if previous and previous.state=="running": - previous.state="exited";previous.finished_at=utcnow() - previous.manifest_json={**(previous.manifest_json or {}),"superseded_by":identity} - execution=await begin_execution(session,job.id,f"gpu:{attempt}","new_gpu") - execution.manifest_json={"schema":1,"kind":"upstream_gpu","upstream_id":job.upstream_id,"upstream_execution_id":identity,"upstream_attempt":attempt,"upstream_fence":remote.get("fence_token") or identity,"local_fence":execution.fence_token} - if execution is None: - no_runner=("runner_pid" in remote and remote["runner_pid"] is None) or remote.get("cleanup_ack") is True - if no_runner and state in {"queued","paused","cancelled"} and job.current_execution_id: - previous=await session.get(Execution,job.current_execution_id) - if previous and previous.phase_key.startswith("gpu:") and previous.state=="running": - previous.state="exited";previous.finished_at=utcnow() - previous.manifest_json={**(previous.manifest_json or {}),"cleanup_ack":True,"ack_observed_attempt":attempt} - return True,None - manifest=dict(execution.manifest_json or {}) - manifest["observed_state"]=state - if state=="succeeded": - result=remote.get("result") or {} - digest=hashlib.sha256(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).encode()).hexdigest() - if execution.state=="results_ready" and manifest.get("result_hash")!=digest:return False,None - manifest["result_hash"]=digest - execution.state="results_ready";execution.finished_at=utcnow() - elif state in {"failed","cancelled","timed_out"}: - execution.state="exited";execution.finished_at=utcnow() - elif state in {"queued","paused"}: - no_runner=("runner_pid" in remote and remote["runner_pid"] is None) or remote.get("cleanup_ack") is True - if no_runner: - execution.state="exited";execution.finished_at=utcnow();manifest["cleanup_ack"]=True - execution.manifest_json=manifest - return True,execution - - -def gpu_result_fence(execution): - manifest=execution.manifest_json or {} - return {"execution_id":execution.id,"fence_token":execution.fence_token,"upstream_execution_id":manifest.get("upstream_execution_id"),"upstream_attempt":manifest.get("upstream_attempt"),"result_hash":manifest.get("result_hash")} - - -async def gpu_publication_matches(session,job,fence): - import hashlib,json - if not job or job.deleted_at is not None:return False - if not fence:return job.current_execution_id is None - if job.current_execution_id!=fence.get("execution_id"):return False - execution=await session.get(Execution,job.current_execution_id) - if not execution or execution.job_id!=job.id or execution.state!="results_ready" or execution.fence_token!=fence.get("fence_token"):return False - manifest=execution.manifest_json or {} - result={key:value for key,value in (job.upstream_result or {}).items() if key!="_visual_execution"} - digest=hashlib.sha256(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).encode()).hexdigest() - return manifest.get("upstream_execution_id")==fence.get("upstream_execution_id") and manifest.get("upstream_attempt")==job.attempt_count==fence.get("upstream_attempt") and manifest.get("result_hash")==digest==fence.get("result_hash") diff --git a/backend/app/gpu_summary.py b/backend/app/gpu_summary.py deleted file mode 100644 index c296d25..0000000 --- a/backend/app/gpu_summary.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Public GPU summary. Never expose scheduler job IDs or host PID details.""" -import math -from datetime import datetime, timezone - - -def summarize(gpus, scheduler, now, generated): - active, queued = [], None - try: - stamp = scheduler['updated_at'] - if type(stamp) not in (int, float) or not math.isfinite(stamp) or not now - 5 <= stamp <= now + 1: - raise ValueError('Stale scheduler') - if scheduler.get('schema_version') == 2: - entries = scheduler.get('active_jobs', []) - if not isinstance(entries, list) or len(entries) > len(gpus): - raise ValueError('Invalid active list') - indexes = set() - for entry in entries: - index = entry['gpu_index'] - if type(index) is not int or index in indexes or not any( - row['index'] == index and row['_uuid'] == entry['gpu_uuid'] for row in gpus - ): - raise ValueError('Invalid lease') - indexes.add(index) - count = scheduler.get('queued_count') - if count is not None and (type(count) is not int or not 0 <= count <= 10000000): - raise ValueError('Invalid queue count') - active, queued = entries, count - elif scheduler.get('state') == 'leased': - lease = scheduler.get('lease') or {} - active = [{'gpu_index': lease.get('index'), 'gpu_uuid': lease.get('uuid'), 'state': 'running'}] - except (KeyError, TypeError, ValueError): - scheduler, active, queued = None, [], None - active_indexes = set() - for entry in active: - gpu = next((row for row in gpus if row['index'] == entry.get('gpu_index') - and row['_uuid'] == entry.get('gpu_uuid')), None) - if gpu is None: - continue - active_indexes.add(gpu['index']) - state = entry.get('state') - gpu.update(busy=True, eligible=False, - state=state if state in {'preempting', 'blocked', 'launching'} else 'running', - stage=entry.get('stage') if entry.get('stage') in - {'launching', 'executing', 'cleanup', 'model', 'upscale', 'collecting'} else None) - running = sum(row['index'] in active_indexes or row['_own'] for row in gpus) - available = sum(row['eligible'] for row in gpus) - state = 'running' if running else 'ready' if available else 'waiting' - reason = (f'正在运行{running}个GPU任务,{available}张卡可接新任务。' if running - else None if available else '等待可用GPU,外部任务优先。') - dispatch_blocked = bool(scheduler and scheduler.get('state') == 'blocked') - if dispatch_blocked: - reason = '执行器需要管理员检查,新任务暂停派发。' - if not running: - state = 'blocked' - available = 0 - for gpu in gpus: - gpu['eligible'] = False - if gpu['state'] == 'ready': - gpu['state'] = 'waiting' - elif scheduler and 'memory' in str(scheduler.get('reason', '')).lower(): - reason = '共享内存不足,任务按入队顺序等待资源。' - for gpu in gpus: - gpu.pop('_uuid') - gpu.pop('_own') - return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus, - 'running_count': running, 'available_count': available, 'queued_count': queued, - 'dispatch_blocked': dispatch_blocked, - 'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()} diff --git a/backend/app/jobs.py b/backend/app/jobs.py deleted file mode 100644 index 42b8bcf..0000000 --- a/backend/app/jobs.py +++ /dev/null @@ -1,290 +0,0 @@ -from datetime import datetime, timezone -import hashlib -import json -from fastapi import APIRouter, Depends, Header, Request -from pydantic import BaseModel, Field, ConfigDict -from typing import Literal -from sqlalchemy import func, select -from sqlalchemy.exc import IntegrityError -from .assets import owned_asset -from .auth import Actor, csrf_actor, current_actor -from .dto import job_dto -from .errors import fail -from .events import emit_job -from .models import Event, Job, JobAsset, new_id, utcnow - -router = APIRouter(prefix="/jobs", tags=["jobs"]) -GPU_TYPES = {"image.generate", "video.generate", "defect.generate", "audio.transcribe"} -CPU_TYPES = {"math.solve", "media.structure", "video.compose", "audio.speech"} -TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"} - - -class Submit(BaseModel): - model_config = ConfigDict(extra="forbid") - execution_mode: Literal["interactive", "batch"] = "interactive" - task_type: str - input: dict = Field(default_factory=dict) - parameters: dict = Field(default_factory=dict) - count: int = Field(default=1, ge=1, le=4) - scheduled_at: datetime | None = None - - -async def owned_job(session, job_id, owner_id): - job = await session.scalar(select(Job).where(Job.id == job_id, Job.owner_id == owner_id, - Job.deleted_at.is_(None)).with_for_update()) - if job is None: - fail(404, "job_not_found", "任务不存在") - return job - - -def input_ids(inputs, parameters): - result = [] - for field in ("image_asset_id", "audio_asset_id", "asset_id"): - if inputs.get(field): - result.append(inputs[field]) - if inputs.get("asset_ids"): - if not isinstance(inputs["asset_ids"], list): - fail(422, "invalid_assets", "asset_ids 必须为素材编号列表") - result.extend(inputs["asset_ids"]) - for clip in parameters.get("clips", []): - if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str): - fail(422, "invalid_clip", "每个片段需要素材编号") - result.append(clip["asset_id"]) - if parameters.get("audio_asset_id"): - result.append(parameters["audio_asset_id"]) - if any(not isinstance(value, str) or len(value) > 64 for value in result): - fail(422, "invalid_assets", "素材编号格式不正确") - return list(dict.fromkeys(result)) - - -async def validate_submission(session, body, owner_id, settings, *, frozen_workflow=False): - if body.task_type not in GPU_TYPES | CPU_TYPES: - fail(422, "unsupported_task", "不支持此任务类型") - allowed = {"prompt", "negative_prompt", "image_asset_id", "audio_asset_id", "asset_id", "asset_ids"} - if set(body.input) - allowed: - fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL") - if body.count > 1 and body.task_type not in {"image.generate", "defect.generate"}: - fail(422, "batch_not_supported", "此任务类型不支持批量生成") - if body.task_type == "audio.speech" and not settings.tts_base_url: - fail(422, "speech_unavailable", "尚未配置真实配音服务") - from .providers import ProviderError, validate_arguments - try: - validate_arguments(body.task_type, body.input, body.parameters, settings) - except ProviderError as exc: - fail(400, exc.code, exc.message) - prompt = body.input.get("prompt", "") - if not isinstance(prompt, str) or len(prompt) > 8000: - fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本") - if body.task_type in {"image.generate", "video.generate", "defect.generate", "math.solve", "audio.speech"} and not prompt.strip(): - fail(422, "prompt_required", "请输入提示词或文本") - ids = input_ids(body.input, body.parameters) - assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids} - required = {"defect.generate": "image_asset_id", "audio.transcribe": "audio_asset_id", "media.structure": "asset_id"} - if body.task_type in required: - key = required[body.task_type] - value = body.input.get(key) or (body.input.get("asset_id") if key == "audio_asset_id" else None) - if not value: - fail(422, "asset_required", "此任务需要输入素材") - for key, kinds in (("image_asset_id", {"image"}), ("audio_asset_id", {"audio", "video"})): - if body.input.get(key) and assets[body.input[key]].kind not in kinds: - fail(422, "wrong_asset_kind", "输入素材类型不正确") - if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in {"image", "video"}: - fail(422, "wrong_asset_kind", "素材理解需要图片或视频") - if body.task_type == "audio.transcribe": - source_id = body.input.get("audio_asset_id") or body.input.get("asset_id") - if assets[source_id].kind not in {"audio", "video"}: - fail(422, "wrong_asset_kind", "转写需要音频或视频素材") - if body.task_type == "video.compose" and not ids: - fail(422, "clips_required", "请添加待合成片段") - if body.task_type == "video.compose": - if not frozen_workflow: - from .runtime_policy import read_runtime_policy - policy=read_runtime_policy(settings) - if policy.get('configuration_error'):fail(503,'runtime_policy_unavailable','运行配置无效,请联系管理员') - if len(body.parameters.get('clips',[]))>policy['workflow_max_shots']: - fail(422,'workflow_shot_limit',f"当前配置最多允许{policy['workflow_max_shots']}个视频片段") - if any(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])): - fail(422, "wrong_asset_kind", "编排片段必须为视频素材") - audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id") - if audio_id and assets[audio_id].kind != "audio": - fail(422, "wrong_asset_kind", "成片音轨必须为音频素材") - if body.scheduled_at is not None and body.scheduled_at.tzinfo is None: - fail(422, "timezone_required", "定时任务时间须包含时区") - return ids - - -async def create_jobs(session, body, actor, settings, key=None, internal=False, *, frozen_workflow=False): - if key is not None and not 1 <= len(key) <= 128: - fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128") - payload = body.model_dump(mode="json") - if body.execution_mode == "interactive": - payload.pop("execution_mode", None) - try: - fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False, - allow_nan=False).encode()).hexdigest() - except (ValueError, TypeError): - fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON") - if key: - existing = (await session.scalars(select(Job).where(Job.owner_id == actor.id, Job.request_key == key) - .order_by(Job.batch_index))).all() - if existing: - if existing[0].request_hash != fingerprint: - fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数") - if any(job.deleted_at is not None for job in existing): - fail(410, "resource_purged", "此幂等键对应的任务已删除") - from .submissions import accept_submission - saved=await accept_submission(session,actor.id,"jobs.create",key,2,body.model_dump(mode="json")) - saved.resource_json={"job_ids":[job.id for job in existing]} - return existing - from .submissions import accept_submission - record = await accept_submission(session, actor.id, "jobs.create", key, 2, body.model_dump(mode="json")) if key else None - from .quotas import reserve_budget - await reserve_budget(session, actor.id, "workflow.child" if internal else "jobs.create", units=body.count, settings=settings) - from .maintenance import require_writable - require_writable(settings) - if actor.auth_kind == "bearer" and body.execution_mode == "interactive" and "interactive:write" not in actor.scopes: - fail(403,"scope_required","Machine tokens require interactive:write for interactive jobs") - from .quotas import check_storage_budget - await check_storage_budget(session,settings,actor.id,new_jobs=body.count) - if settings.max_interactive_gpu_jobs>0 and body.execution_mode=="interactive" and body.task_type in GPU_TYPES: - active=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==actor.id,Job.execution_mode=="interactive",Job.task_type.in_(GPU_TYPES),Job.state.notin_(TERMINAL))) - if active+body.count>settings.max_interactive_gpu_jobs:fail(429,"quota_exceeded","Interactive GPU queue limit reached") - # Internal quota accounting also covers newly submitted batch members. - # Only children of an already accepted, frozen workflow bypass a new cap. - ids = await validate_submission(session, body, actor.id, settings, frozen_workflow=frozen_workflow) - scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None - jobs = [] - for index in range(body.count): - job_id = new_id() - future = scheduled and scheduled > utcnow() - parameters = dict(body.parameters) - if body.count > 1: - parameters["seed"] = (parameters.get("seed", 42) + index) % (2 ** 32) - job = Job(id=job_id, owner_id=actor.id, task_type=body.task_type, - state="scheduled" if future else "submitting", phase="scheduled" if future else "waiting_dispatch", - execution_mode=body.execution_mode, version=1, input_json=body.input, parameters=parameters, request_key=key, - request_hash=fingerprint, batch_index=index, upstream_key="cmvr-visual:" + job_id, - scheduled_at=scheduled, next_action_at=scheduled if future else utcnow(), - attempt_count=0, work_attempt=0, preemptions=0, cancel_requested=False) - session.add(job) - await session.flush() - session.add_all(JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids) - await emit_job(session, job, increment=False) - jobs.append(job) - if record is not None: - record.resource_json = {"job_ids": [job.id for job in jobs]} - return jobs - - -def wake(request): - request.app.state.coordinator.wake() - - -@router.post("", status_code=202) -async def submit(body: Submit, request: Request, idempotency_key: str | None = Header(default=None), - actor: Actor = Depends(csrf_actor)): - recovering=False - if idempotency_key: - async with request.app.state.db.session() as session: - recovering=bool(await session.scalar(select(Job.id).where(Job.owner_id==actor.id,Job.request_key==idempotency_key).limit(1))) - if body.execution_mode=="batch" and body.task_type in GPU_TYPES and not recovering: - provider=request.app.state.provider - capabilities=await provider.upstream_capabilities() if hasattr(provider,"upstream_capabilities") else {} - if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False): - fail(503,"upstream_protocol_incompatible","Batch requires scheduling protocol v2") - async with request.app.state.db.session() as session: - try: - jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key) - await session.commit() - except IntegrityError: - await session.rollback() - jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key) - await session.commit() - result = {"jobs": [await job_dto(session, job) for job in jobs]} - wake(request) - return result - - -@router.get("") -async def list_jobs(request: Request, page: int = 1, page_size: int = 24, task_type: str = "", state: str = "", root_only: bool = False, - actor: Actor = Depends(current_actor)): - if page < 1 or not 1 <= page_size <= 100: - fail(422, "invalid_page", "分页参数无效") - async with request.app.state.db.session() as session: - query = select(Job).where(Job.owner_id == actor.id, Job.deleted_at.is_(None)) - if root_only: - query = query.where(Job.run_id.is_(None)) - if task_type: - query = query.where(Job.task_type == task_type) - if state: - query = query.where(Job.state == state) - total = await session.scalar(select(func.count()).select_from(query.subquery())) - jobs = (await session.scalars(query.order_by(Job.created_at.desc(), Job.id.desc()) - .offset((page - 1) * page_size).limit(page_size))).all() - cursor = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0 - return {"items": [await job_dto(session, job) for job in jobs], "total": total, - "page": page, "page_size": page_size, "cursor": cursor} - - -@router.get("/{job_id}") -async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - return await job_dto(session, await owned_job(session, job_id, actor.id)) - - -@router.delete("/{job_id}") -async def delete_job(job_id: str, request: Request, if_match: str | None = Header(default=None), - actor: Actor = Depends(csrf_actor)): - from .deletions import archive_records - async with request.app.state.db.session() as session: - result = await archive_records(session, Job, job_id, actor.id, if_match) - await session.commit() - return result - - -@router.post("/{job_id}/cancel") -async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)): - async with request.app.state.db.session() as session: - job = await owned_job(session, job_id, actor.id) - if job.state not in TERMINAL and job.state != "collecting": - job.cancel_requested = True - if job.upstream_id is None and job.upstream_payload is None and job.phase not in {"cpu_running", "preparing"}: - job.state, job.phase, job.finished_at = "cancelled", "cancelled", utcnow() - else: - job.state, job.phase = "cancelling", "cancellation_pending" - await emit_job(session, job) - await session.commit() - result = await job_dto(session, job) - wake(request) - return result - - -@router.post("/{job_id}/retry", status_code=202) -async def retry(job_id: str, request: Request, idempotency_key: str | None = Header(default=None), actor: Actor = Depends(csrf_actor)): - async with request.app.state.db.session() as session: - old = await owned_job(session, job_id, actor.id) - if old.state not in TERMINAL: - fail(409, "job_not_finished", "请先等待或取消当前任务") - if old.run_id: - fail(409, "workflow_child", "Use workflow step retry") - if old.batch_id: - fail(409,"parent_control_required","Batch members require parent control") - from .submissions import accept_submission - record = await accept_submission(session, actor.id, "jobs.retry", idempotency_key, 2, {"job_id":job_id}) if idempotency_key else None - if record and record.resource_json.get("job_ids"): - jobs = list((await session.scalars(select(Job).where(Job.owner_id == actor.id, - Job.id.in_(record.resource_json["job_ids"]), Job.deleted_at.is_(None)))).all()) - if len(jobs) != len(record.resource_json["job_ids"]): - fail(410, "resource_purged", "重试任务已删除") - return {"jobs": [await job_dto(session, job) for job in jobs]} - from .v2_models import Execution - unsafe=await session.scalar(select(Execution.id).where(Execution.job_id==old.id,Execution.state.in_(["allocated","running","stopping","unknown"])).limit(1)) - if unsafe:fail(409,"cleanup_pending","Previous execution has not confirmed cleanup") - body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters, execution_mode=old.execution_mode) - jobs = await create_jobs(session, body, actor, request.app.state.settings) - if record: - record.resource_json = {"job_ids":[j.id for j in jobs]} - await session.commit() - result = {"jobs": [await job_dto(session, job) for job in jobs]} - wake(request) - return result diff --git a/backend/app/main.py b/backend/app/main.py index f38f4d3..7e46e8f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,146 +1,6 @@ -from contextlib import asynccontextmanager -import asyncio -import logging -import time -from fastapi import Depends, FastAPI -from fastapi.responses import JSONResponse -from sqlalchemy import text -from sqlalchemy.exc import SQLAlchemyError -from . import assets, auth, events, jobs, submissions, tokens, workflows, batches, shared_assets -from .config import Settings -from .coordinator import Coordinator -from .database import Database -from .timeline import DEFAULT_SOURCE_FRAMES, MAX_SOURCE_FRAMES, DEFAULT_CLIP_FRAMES, MAX_CLIP_FRAMES - - -def workflow_limits(policy): - return {"max_shots":policy["workflow_max_shots"],"source_frames":DEFAULT_SOURCE_FRAMES, - "default_source_frames":DEFAULT_SOURCE_FRAMES,"max_source_frames":MAX_SOURCE_FRAMES, - "default_clip_frames":DEFAULT_CLIP_FRAMES,"max_clip_frames":MAX_CLIP_FRAMES,"fps":24} - - -def create_app(settings=None, *, provider=None): - @asynccontextmanager - async def lifespan(app): - configuration = settings or Settings.from_env() - for root in (configuration.asset_root, configuration.job_work_root, configuration.state_root): - root.mkdir(parents=True, exist_ok=True) - db = Database(configuration) - app.state.settings, app.state.db = configuration, db - live_provider = provider - if live_provider is None: - from .providers import Provider - live_provider = Provider(configuration) - app.state.provider = live_provider - coordinator = Coordinator(configuration, db, live_provider) - app.state.coordinator = coordinator - app.state.draining = False - async def after_tick(): - from .workflow_engine import advance_workflows - await advance_workflows(db, configuration, live_provider) - coordinator.after_tick = after_tick - try: - await db.initialize() - await auth.bootstrap_admin(db, configuration) - from .public_preflight import require_public_ready - await require_public_ready(db, configuration) - if configuration.run_coordinator: - await coordinator.start() - yield - finally: - app.state.draining = True - await coordinator.close() - await live_provider.aclose() - await db.close() - - app = FastAPI(title="CMVR Visual", lifespan=lifespan) - from .upload_guard import UploadGuard - app.add_middleware(UploadGuard) - @app.middleware("http") - async def maintenance_writes(request, call_next): - from .maintenance import maintenance_active - configuration = getattr(request.app.state, "settings", None) - if (configuration and request.method in {"POST", "PUT", "PATCH", "DELETE"} - and request.url.path.startswith("/api/") - and request.url.path not in {"/api/auth/login", "/api/auth/logout"} - and maintenance_active(configuration)): - return JSONResponse(status_code=503, content={"detail":{ - "code":"maintenance", "message":"系统维护中,任务和草稿已保留,请稍后重试"}}) - return await call_next(request) - @app.exception_handler(SQLAlchemyError) - async def database_failure(request, exc): - logging.getLogger(__name__).error("Database request failed: %s", type(exc).__name__) - return JSONResponse(status_code=503, content={"detail": {"code": "database_unavailable", "message": "数据库暂不可用,请稍后重试"}}) - - @app.exception_handler(Exception) - async def internal_failure(request, exc): - logging.getLogger(__name__).exception("Unhandled application error") - return JSONResponse(status_code=500, content={"detail": {"code": "internal_error", "message": "服务处理失败,请联系管理员"}}) - for router in (auth.router, assets.router, shared_assets.router, shared_assets.publish_router, - jobs.router, events.router, submissions.router, tokens.router, - workflows.router, workflows.runs_router, batches.router): - app.include_router(router, prefix="/api") - - @app.get("/api/health") - async def health(): - async with app.state.db.session() as session: - await session.execute(text("SELECT 1")) - return {"status": "ok", "database": app.state.settings.sqlalchemy_url.get_backend_name()} - - @app.get("/api/live") - async def live(): - return {"status": "ok"} - - @app.get("/api/ready") - async def ready(): - from .maintenance import maintenance_active - checks = {"database": False, "coordinator": True, "upstream_protocol": False, - "accepting": not app.state.draining and not maintenance_active(app.state.settings)} - try: - async with app.state.db.session() as session: - await session.execute(text("SELECT 1")) - checks["database"] = True # Schema was verified before coordinator startup. - except SQLAlchemyError: - pass - coordinator = app.state.coordinator - if app.state.settings.run_coordinator: - heartbeat = getattr(coordinator, "last_tick_success", None) - checks["coordinator"] = bool(coordinator._task and not coordinator._task.done() - and heartbeat is not None and time.monotonic() - heartbeat < 90) - try: - caps = await asyncio.wait_for(app.state.provider.upstream_capabilities(), 3) - checks["upstream_protocol"] = caps.get("protocol_version", 0) >= 2 and bool(caps.get("admission_policy")) - except (Exception, asyncio.TimeoutError): - pass - healthy = all(checks.values()) - return JSONResponse(status_code=200 if healthy else 503, - content={"status": "ready" if healthy else "not_ready", "checks": checks}) - - @app.get("/api/capabilities", dependencies=[Depends(auth.current_actor)]) - async def capabilities(): - from .providers import capabilities as provider_capabilities - from .resource_policy import execution_policy - from .runtime_policy import read_runtime_policy - policy=read_runtime_policy(app.state.settings) - return {"items": provider_capabilities(app.state.settings), - "scheduler": await app.state.provider.scheduler_status(), "execution_policy": execution_policy(settings=app.state.settings), - "workflow_limits":workflow_limits(policy)} - - @app.get("/api/system/status", dependencies=[Depends(auth.current_actor)]) - async def status(): - from .providers import capabilities as provider_capabilities - from .resource_policy import execution_policy - from .runtime_policy import read_runtime_policy - policy=read_runtime_policy(app.state.settings) - online, scheduler = await asyncio.gather(app.state.provider.health(), app.state.provider.scheduler_status()) - return {"inference_online": online, "scheduler": scheduler, "models": provider_capabilities(app.state.settings), - "environment": app.state.settings.mode, - "database_backend": app.state.settings.sqlalchemy_url.get_backend_name(), - "execution_policy": execution_policy(settings=app.state.settings), - "workflow_limits":workflow_limits(policy), - "public_access": getattr(app.state.settings, "public_access", False)} - - return app +"""稳定的 ASGI 入口;Docker、本地启动和测试均从这里加载。""" +from app.bootstrap import create_app app = create_app() +__all__ = ["app", "create_app"] diff --git a/backend/app/maintenance.py b/backend/app/maintenance.py deleted file mode 100644 index 6a048ab..0000000 --- a/backend/app/maintenance.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Server-owned admission switch. Reads, synchronization and archival continue.""" -from pathlib import Path -from .errors import fail - -def maintenance_active(settings):return (Path(settings.state_root)/"maintenance").exists() - -def require_writable(settings): - if maintenance_active(settings):fail(503,"maintenance","Service is in maintenance mode") diff --git a/backend/app/media.py b/backend/app/media.py deleted file mode 100644 index 772b151..0000000 --- a/backend/app/media.py +++ /dev/null @@ -1,310 +0,0 @@ -"""Bounded CPU media operations. No shell, CUDA, external URLs or user filters.""" -from __future__ import annotations - -import asyncio -import json -import math -import os -from pathlib import Path -import uuid - -from PIL import Image, ImageOps, UnidentifiedImageError - - -class MediaError(RuntimeError): - def __init__(self, code: str, message: str, retriable: bool = False): - super().__init__(message) - self.code, self.message, self.retriable = code, message, retriable - - -def confined(path: Path, settings, *, exists: bool = True, root: Path | None = None) -> Path: - try: - candidate = Path(path) - boundary = Path(root or settings.workspace_root).resolve() - if not candidate.is_absolute(): - raise ValueError - resolved = candidate.resolve() - if not resolved.is_relative_to(boundary) or (exists and not resolved.is_file()): - raise ValueError - return resolved - except (OSError, ValueError, TypeError): - raise MediaError('invalid_asset', '素材文件不存在或不可访问。') from None - - -async def _stop(process): - if process.returncode is None: - try: - process.terminate() - except ProcessLookupError: - pass - try: - await asyncio.wait_for(process.wait(), 2) - except asyncio.TimeoutError: - try: - process.kill() - except ProcessLookupError: - pass - await asyncio.wait_for(process.wait(), 5) - - -async def _cleanup(process, readers): - for task in readers: - if not task.done(): - task.cancel() - await asyncio.gather(*readers, return_exceptions=True) - - async def discard(stream): - while await stream.read(65536): - pass - - # Drain after a size rejection/cancel too. Otherwise a full paused pipe - # can keep asyncio's process transport alive even after the child exited. - drains = [asyncio.create_task(discard(process.stdout)), asyncio.create_task(discard(process.stderr))] - try: - await _stop(process) - await asyncio.wait_for(asyncio.gather(*drains), 5) - finally: - for task in drains: - if not task.done(): - task.cancel() - await asyncio.gather(*drains, return_exceptions=True) - - -async def run_process(argv: list[str], *, timeout: float = 120, max_output: int = 1024 * 1024, - cwd: Path | None = None, return_stderr: bool = False) -> bytes | tuple[bytes, bytes]: - """Own one executable; cancellation does TERM/KILL/wait only on that child. - - FFmpeg/ffprobe do not launch child programs. Pipe readers enforce their - bounds while the child runs, rather than buffering arbitrary diagnostics. - """ - process = None - readers = [] - - async def read_bounded(stream): - chunks, count = [], 0 - while chunk := await stream.read(65536): - count += len(chunk) - if count > max_output: - raise MediaError('media_output_limit', '媒体处理诊断超出限制。') - chunks.append(chunk) - return b''.join(chunks) - - try: - process = await asyncio.create_subprocess_exec(*[str(value) for value in argv], - stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, cwd=str(cwd) if cwd else None, - start_new_session=(os.name == 'posix')) - readers = [asyncio.create_task(read_bounded(process.stdout)), - asyncio.create_task(read_bounded(process.stderr))] - async with asyncio.timeout(timeout): - stdout, stderr = await asyncio.gather(*readers) - await process.wait() - if process.returncode != 0: - raise MediaError('media_processing_failed', '媒体解码或处理失败,请检查素材格式。') - return (stdout, stderr) if return_stderr else stdout - except asyncio.CancelledError: - raise - except asyncio.TimeoutError: - raise MediaError('media_timeout', '媒体处理超时,请缩短素材后重试。', True) from None - except (OSError, ValueError): - raise MediaError('media_unavailable', '媒体处理程序不可用。', True) from None - finally: - if process is not None: - cleanup = asyncio.create_task(_cleanup(process, readers)) - recancelled = False - while not cleanup.done(): - try: - await asyncio.shield(cleanup) - except asyncio.CancelledError: - recancelled = True - await cleanup - if recancelled: - raise asyncio.CancelledError - - -def input_options() -> list[str]: - # Exclude playlists, concat input, network protocols and nested file lists. - return ['-protocol_whitelist', 'file,pipe', '-format_whitelist', - 'mov,matroska,webm,avi,wav,mp3,flac,ogg,aac,mpeg,mpegts'] - - -def _image_info(path): - try: - with Image.open(path) as image: - mime = {'PNG': 'image/png', 'JPEG': 'image/jpeg', 'WEBP': 'image/webp'}.get(image.format) - if mime is None or image.width * image.height > 40_000_000: - raise MediaError('invalid_image', '仅支持像素数受限的 PNG、JPEG、WebP 图片。') - image.load() - return {'kind': 'image', 'mime_type': mime, 'width': image.width, - 'height': image.height, 'duration_seconds': None} - except UnidentifiedImageError: - return None - except (OSError, ValueError, Image.DecompressionBombError): - raise MediaError('invalid_image', '图片文件无法解码。') from None - - -def _text_info(path): - if path.suffix.lower() not in {'.json', '.txt', '.md', '.srt', '.vtt'}: - return None - try: - if path.stat().st_size > 4 * 1024 * 1024: - raise ValueError - text = path.read_text(encoding='utf-8-sig') - if '\x00' in text or not text.strip(): - raise ValueError - is_json = path.suffix.lower() == '.json' - if is_json: - json.loads(text, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) - return {'kind': 'json' if is_json else 'text', - 'mime_type': 'application/json' if is_json else 'text/plain', - 'width': None, 'height': None, 'duration_seconds': None} - except (OSError, UnicodeError, ValueError, RecursionError): - raise MediaError('invalid_text', '文本或 JSON 文件格式无效。') from None - - -async def inspect_media(path: Path, settings) -> dict: - source = confined(path, settings) - if source.stat().st_size <= 0: - raise MediaError('invalid_asset', '素材文件为空。') - text = await asyncio.to_thread(_text_info, source) - if text is not None: - return text - image = await asyncio.to_thread(_image_info, source) - if image is not None: - return image - if source.suffix.lower() in {'.png', '.jpg', '.jpeg', '.webp'}: - raise MediaError('invalid_image', '图片文件无法解码。') - raw = await run_process([settings.ffprobe_bin, '-v', 'error', *input_options(), - '-show_entries', 'format=format_name,duration,start_time:stream=codec_type,codec_name,width,height,duration:stream_disposition=attached_pic', - '-of', 'json', str(source)], timeout=30, max_output=256 * 1024) - try: - data = json.loads(raw) - streams = data['streams'] - videos = [item for item in streams if item.get('codec_type') == 'video' - and not item.get('disposition', {}).get('attached_pic')] - audios = [item for item in streams if item.get('codec_type') == 'audio'] - if not videos and not audios: - raise ValueError - stream = videos[0] if videos else audios[0] - duration = float(data.get('format', {}).get('duration', stream.get('duration', 0))) - start_time = float(data.get('format', {}).get('start_time', 0)) - if not math.isfinite(start_time): - raise ValueError - if not math.isfinite(duration) or not 0 < duration <= 86400: - raise ValueError - width, height = stream.get('width'), stream.get('height') - if videos and (type(width) is not int or type(height) is not int or width <= 0 or height <= 0 - or width * height > 40_000_000): - raise ValueError - formats = str(data.get('format', {}).get('format_name', '')).split(',') - if videos: - mime = 'video/webm' if 'webm' in formats and source.suffix.lower() == '.webm' else 'video/mp4' if 'mov' in formats else 'video/x-matroska' if 'matroska' in formats else 'video/mp2t' if 'mpegts' in formats else 'video/mpeg' if 'mpeg' in formats else 'video/x-msvideo' - else: - mime = 'audio/wav' if 'wav' in formats else 'audio/mpeg' if 'mp3' in formats else 'audio/flac' if 'flac' in formats else 'audio/ogg' if 'ogg' in formats else 'audio/aac' if 'aac' in formats else 'audio/mp4' - return {'kind': 'video' if videos else 'audio', 'mime_type': mime, 'has_audio': bool(audios), - 'width': width if videos else None, 'height': height if videos else None, - 'duration_seconds': duration, 'start_seconds': start_time} - except (ValueError, TypeError, KeyError, AttributeError): - raise MediaError('invalid_media', '媒体文件信息无效。') from None - - -async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None: - source, target = confined(path, settings), confined(destination, settings, exists=False) - info = await inspect_media(source, settings) - if info['kind'] not in {'image', 'video'}: - return None - target.parent.mkdir(parents=True, exist_ok=True) - temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex + '.jpg') - try: - if info['kind'] == 'image': - def convert(): - with Image.open(source) as image: - image = ImageOps.exif_transpose(image).convert('RGB') - image.thumbnail((512, 512)) - image.save(temporary, format='JPEG', quality=85) - await asyncio.to_thread(convert) - else: - await run_process([settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), - '-i', str(source), '-frames:v', '1', '-vf', 'scale=512:512:force_original_aspect_ratio=decrease', - '-threads', '2', '-f', 'image2', '-update', '1', str(temporary)], timeout=60) - if not temporary.is_file() or temporary.stat().st_size == 0: - raise MediaError('thumbnail_failed', '预览图生成失败。') - os.replace(temporary, target) - return target - finally: - temporary.unlink(missing_ok=True) - -async def inspect_video_track(path: Path, settings) -> dict: - """Count decoded video frames; container or audio duration cannot mask a short source.""" - from fractions import Fraction - source=confined(path,settings) - raw=await run_process([settings.ffprobe_bin,'-v','error',*input_options(),'-select_streams','v:0','-count_frames','-show_entries','stream=width,height,avg_frame_rate,nb_read_frames,duration,time_base:format=duration','-of','json',str(source)],timeout=120,max_output=256*1024) - try: - data=json.loads(raw);stream=data['streams'][0] - frames=int(stream['nb_read_frames']);fps=Fraction(stream['avg_frame_rate']) - width,height=int(stream['width']),int(stream['height']) - if frames<=0 or fps<=0 or width<=0 or height<=0 or width*height>40000000:raise ValueError - return {'frames':frames,'fps':float(fps),'width':width,'height':height,'duration':float(data['format']['duration']),'time_base':stream.get('time_base')} - except (KeyError,IndexError,TypeError,ValueError,ZeroDivisionError): - raise MediaError('invalid_media','Video frame decoding failed.') from None - - -async def compose_workflow(plan,work_dir,control=None,*,settings,sources,audio=None): - """Render a frozen multi-shot timeline from internal resolved asset paths.""" - from .providers import CpuResult - if len(sources)!=len(plan.spec['shots']):raise MediaError('invalid_timeline','Source videos differ from the frozen shot count.') - shot_frames=plan.shot_frames or (plan.clip_frames,)*len(sources) - duration=plan.frames/plan.fps - duration_text=f'{duration:.9f}'.rstrip('0').rstrip('.') - sources=[confined(p,settings) for p in sources] - work=Path(work_dir).resolve() - if not work.is_relative_to(Path(settings.workspace_root).resolve()):raise MediaError('invalid_asset','Invalid work directory.') - width,height=plan.canvas - expected=(plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height']) - for source,frames in zip(sources,shot_frames): - info=await inspect_video_track(source,settings) - if info['frames']round(info['duration_seconds']*1000):raise MediaError('invalid_timeline','Audio cut exceeds decoded source.') - work.mkdir(parents=True,exist_ok=True) - async def checkpoint(): - if control is not None: - result=control() if callable(control) else control.checkpoint() - if hasattr(result,'__await__'):await result - parts=[] - for index,(source,frames) in enumerate(zip(sources,shot_frames)): - await checkpoint();target=work/f'shot-{index}.mp4' - fit=plan.spec['render']['fit'] - canvas=f'scale={width}:{height}:force_original_aspect_ratio=' + ('decrease' if fit=='contain' else 'increase') - canvas+=f',pad={width}:{height}:(ow-iw)/2:(oh-ih)/2' if fit=='contain' else f',crop={width}:{height}' - vf=f'trim=start_frame=0:end_frame={frames},setpts=PTS-STARTPTS,'+canvas+',setsar=1' - await run_process([settings.ffmpeg_bin,'-v','error','-nostdin',*input_options(),'-i',str(source),'-map','0:v:0','-an','-vf',vf,'-r','24','-frames:v',str(frames),'-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-threads','2','-fs',str(settings.max_output_bytes),str(target)],timeout=600) - parts.append(target) - if sum(p.stat().st_size for p in parts)>=settings.max_output_bytes:raise MediaError('output_too_large','Intermediate media exceeds size budget.') - listing=work/'concat.txt';listing.write_text(''.join(f"file '{p.name}'\n" for p in parts),encoding='utf-8') - target=work/'workflow.mp4' - command=[settings.ffmpeg_bin,'-v','error','-nostdin','-f','concat','-safe','1','-i',listing.name] - if audio:command += [*input_options(),'-i',str(audio)] - else:command += ['-f','lavfi','-i','anullsrc=channel_layout=stereo:sample_rate=48000'] - filters=[] - for index,cue in enumerate(plan.spec['render']['subtitles']): - name=f'cue-{index:04d}.txt';(work/name).write_text(cue['text'],encoding='utf-8') - filters.append(f"drawtext=font='Noto Sans CJK SC':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'") - if audio: - start,end=audio_spec['source_start_ms']/1000,audio_spec['source_end_ms']/1000 - delay=audio_spec['offset_frame']*1000/24 - af=f'atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}' - else:af=f'atrim=duration={duration_text}' - command+=['-map','0:v:0','-map','1:a:0'] - if filters:command+=['-vf',','.join(filters)] - command+=['-af',af,'-frames:v',str(plan.frames),'-r','24','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-c:a','aac','-ar','48000','-ac','2','-threads','2','-movflags','+faststart','-fs',str(settings.max_output_bytes),str(target)] - await checkpoint();await run_process(command,timeout=min(3600,max(600,duration*5)),cwd=work) - info=await inspect_video_track(target,settings) - if info['frames']!=plan.frames or info['fps']!=24 or (info['width'],info['height'])!=plan.canvas or abs(info['duration']-duration)>.10 or target.stat().st_size>=settings.max_output_bytes: - raise MediaError('composition_incomplete','Final video differs from the frozen frame count, profile or duration.') - result={'frames':plan.frames,'fps':24,'duration_seconds':duration,'width':width,'height':height,'clip_count':len(sources),'subtitle_count':len(filters)} - return CpuResult([target],result,{'provider':'ffmpeg-cpu','profile':plan.spec['profile'],'template_version':'plain-v1'}) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py new file mode 100644 index 0000000..375c575 --- /dev/null +++ b/backend/app/models/__init__.py @@ -0,0 +1,38 @@ +# 统一注册18张业务表,迁移与运行时共享同一个 metadata。 +from .folders import Folder, AssetFolder +from .base import Base, Timestamp, new_id, utcnow +from .accounts import User, Session, ApiToken +from .assets import Asset, AssetReference, AssetTag, SharedAsset +from .jobs import Job, JobAsset, Event, Execution +from .workflows import WorkflowDraft, WorkflowRun, WorkflowStep, Batch, BatchItem +from .operations import Submission, QuotaReservation +from .stories import ShotCandidate, ShotSelection + +__all__ = [ + "Folder", + "AssetFolder", + "Base", + "Timestamp", + "new_id", + "utcnow", + "User", + "Session", + "ApiToken", + "Asset", + "AssetReference", + "AssetTag", + "SharedAsset", + "Job", + "JobAsset", + "Event", + "Execution", + "WorkflowDraft", + "WorkflowRun", + "WorkflowStep", + "Batch", + "BatchItem", + "Submission", + "QuotaReservation", + "ShotCandidate", + "ShotSelection", +] diff --git a/backend/app/models/accounts.py b/backend/app/models/accounts.py new file mode 100644 index 0000000..1c30f2e --- /dev/null +++ b/backend/app/models/accounts.py @@ -0,0 +1,43 @@ +from datetime import datetime + + +from sqlalchemy import Boolean, ForeignKey, JSON, String, UniqueConstraint + +from sqlalchemy.orm import Mapped, mapped_column + + +from app.models.base import Base, Timestamp, new_id, utcnow + + +class User(Base): + __tablename__ = "visual_users" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + username: Mapped[str] = mapped_column(String(64), unique=True) + display_name: Mapped[str] = mapped_column(String(80)) + password_hash: Mapped[str] = mapped_column(String(512)) + role: Mapped[str] = mapped_column(String(16), default="user") + disabled: Mapped[bool] = mapped_column(Boolean, default=False) + must_change_password: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class Session(Base): + __tablename__ = "visual_sessions" + token_hash: Mapped[str] = mapped_column(String(64), primary_key=True) + user_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) + csrf_token: Mapped[str] = mapped_column(String(128)) + expires_at: Mapped[datetime] = mapped_column(Timestamp, index=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class ApiToken(Base): + __tablename__ = "visual_api_tokens" + __table_args__ = (UniqueConstraint("token_hash"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + name: Mapped[str] = mapped_column(String(128)) + token_hash: Mapped[str] = mapped_column(String(64)) + scopes: Mapped[list] = mapped_column(JSON, default=list) + expires_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + revoked_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) diff --git a/backend/app/models/assets.py b/backend/app/models/assets.py new file mode 100644 index 0000000..03e6186 --- /dev/null +++ b/backend/app/models/assets.py @@ -0,0 +1,91 @@ +from datetime import datetime +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from app.models.folders import AssetFolder + + +from sqlalchemy import BigInteger, Boolean, ForeignKey, Integer, JSON, String, UniqueConstraint + +from sqlalchemy.orm import Mapped, mapped_column, relationship + + +from app.models.base import Base, Timestamp, new_id, utcnow + + +class Asset(Base): + __tablename__ = "visual_assets" + __table_args__ = ( + UniqueConstraint("source_job_id", "source_output_index"), + UniqueConstraint("source_upstream_id", "source_output_index"), + ) + folder_links: Mapped[list["AssetFolder"]] = relationship( + "AssetFolder", lazy="selectin", cascade="all, delete-orphan", passive_deletes=True + ) + + def __init__(self, **kwargs): + kwargs.setdefault("folder_links", []) + super().__init__(**kwargs) + + @property + def folder_ids(self): + return [link.folder_id for link in self.folder_links] + + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) + name: Mapped[str] = mapped_column(String(255)) + storage_key: Mapped[str] = mapped_column(String(512), unique=True) + thumbnail_key: Mapped[str | None] = mapped_column(String(512), nullable=True) + kind: Mapped[str] = mapped_column(String(16)) + mime_type: Mapped[str] = mapped_column(String(128)) + size_bytes: Mapped[int] = mapped_column(BigInteger) + sha256: Mapped[str] = mapped_column(String(64)) + width: Mapped[int | None] = mapped_column(Integer, nullable=True) + height: Mapped[int | None] = mapped_column(Integer, nullable=True) + duration_seconds: Mapped[float | None] = mapped_column(nullable=True) + tags: Mapped[list] = mapped_column(JSON, default=list) + favorite: Mapped[bool] = mapped_column(Boolean, default=False) + origin: Mapped[str] = mapped_column(String(16), default="upload") + library_scope: Mapped[str] = mapped_column( + String(16), default="private", server_default="private", index=True + ) + ready: Mapped[bool] = mapped_column(Boolean, default=True) + source_job_id: Mapped[str | None] = mapped_column( + ForeignKey("visual_jobs.id"), nullable=True, index=True + ) + source_upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True) + source_output_index: Mapped[int | None] = mapped_column(Integer, nullable=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True) + deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class AssetReference(Base): + __tablename__ = "visual_asset_refs" + __table_args__ = (UniqueConstraint("asset_id", "ref_kind", "ref_id"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + asset_id: Mapped[str] = mapped_column(String(32)) + ref_kind: Mapped[str] = mapped_column(String(32)) + ref_id: Mapped[str] = mapped_column(String(32)) + + +class AssetTag(Base): + __tablename__ = "visual_asset_tags" + __table_args__ = (UniqueConstraint("asset_id", "tag"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + asset_id: Mapped[str] = mapped_column(String(32)) + tag: Mapped[str] = mapped_column(String(128)) + + +class SharedAsset(Base): + __tablename__ = "visual_shared_assets" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + publisher_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + asset_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_assets.id"), unique=True) + source_asset_id: Mapped[str | None] = mapped_column( + String(32), ForeignKey("visual_assets.id"), nullable=True, index=True + ) + version: Mapped[int] = mapped_column(Integer, default=1, server_default="1") + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True) + withdrawn_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) diff --git a/backend/app/models/base.py b/backend/app/models/base.py new file mode 100644 index 0000000..079133a --- /dev/null +++ b/backend/app/models/base.py @@ -0,0 +1,25 @@ +from datetime import datetime, timezone + +import uuid + +from sqlalchemy import DateTime + +from sqlalchemy.orm import DeclarativeBase + +from sqlalchemy.dialects.mysql import DATETIME + + +# MySQL 保留微秒,防止同秒创建的任务丢失 FIFO 顺序;不能退回普通 DATETIME。 +Timestamp = DateTime().with_variant(DATETIME(fsp=6), "mysql") + + +def utcnow(): + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def new_id(): + return uuid.uuid4().hex + + +class Base(DeclarativeBase): + pass diff --git a/backend/app/models/folders.py b/backend/app/models/folders.py new file mode 100644 index 0000000..4648863 --- /dev/null +++ b/backend/app/models/folders.py @@ -0,0 +1,31 @@ +from datetime import datetime +from sqlalchemy import ForeignKey, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column +from app.models.base import Base, Timestamp, new_id, utcnow + + +class Folder(Base): + __tablename__ = "visual_folders" + __table_args__ = ( + UniqueConstraint("owner_id", "parent_key", "name", name="uq_visual_folders_sibling"), + ) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) + name: Mapped[str] = mapped_column(String(255)) + parent_id: Mapped[str | None] = mapped_column( + ForeignKey("visual_folders.id", ondelete="CASCADE"), nullable=True, index=True + ) + # 根目录使用空字符串,避免 MySQL 唯一键对 NULL 允许重复。 + parent_key: Mapped[str] = mapped_column(String(32), default="", server_default="") + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + updated_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class AssetFolder(Base): + __tablename__ = "visual_asset_folders" + asset_id: Mapped[str] = mapped_column( + ForeignKey("visual_assets.id", ondelete="CASCADE"), primary_key=True + ) + folder_id: Mapped[str] = mapped_column( + ForeignKey("visual_folders.id", ondelete="CASCADE"), primary_key=True, index=True + ) diff --git a/backend/app/models.py b/backend/app/models/jobs.py similarity index 51% rename from backend/app/models.py rename to backend/app/models/jobs.py index bc9a0b8..60e7279 100644 --- a/backend/app/models.py +++ b/backend/app/models/jobs.py @@ -1,80 +1,33 @@ -from datetime import datetime, timezone -import uuid -from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint -from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column -from sqlalchemy.dialects.mysql import DATETIME - -# MySQL's plain DATETIME truncates fractions, scrambling FIFO for jobs created -# within one second. Keep the same microsecond precision as SQLite/Python UTC. -Timestamp = DateTime().with_variant(DATETIME(fsp=6), "mysql") +from datetime import datetime -def utcnow(): - return datetime.now(timezone.utc).replace(tzinfo=None) +from sqlalchemy import ( + BigInteger, + Boolean, + ForeignKey, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, +) + +from sqlalchemy.orm import Mapped, mapped_column -def new_id(): - return uuid.uuid4().hex - - -class Base(DeclarativeBase): - pass - - -class User(Base): - __tablename__ = "visual_users" - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - username: Mapped[str] = mapped_column(String(64), unique=True) - display_name: Mapped[str] = mapped_column(String(80)) - password_hash: Mapped[str] = mapped_column(String(512)) - role: Mapped[str] = mapped_column(String(16), default="user") - disabled: Mapped[bool] = mapped_column(Boolean, default=False) - must_change_password: Mapped[bool] = mapped_column(Boolean, default=False) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - - -class Session(Base): - __tablename__ = "visual_sessions" - token_hash: Mapped[str] = mapped_column(String(64), primary_key=True) - user_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) - csrf_token: Mapped[str] = mapped_column(String(128)) - expires_at: Mapped[datetime] = mapped_column(Timestamp, index=True) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - - -class Asset(Base): - __tablename__ = "visual_assets" - __table_args__ = (UniqueConstraint("source_job_id", "source_output_index"), - UniqueConstraint("source_upstream_id", "source_output_index")) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) - name: Mapped[str] = mapped_column(String(255)) - storage_key: Mapped[str] = mapped_column(String(512), unique=True) - thumbnail_key: Mapped[str | None] = mapped_column(String(512), nullable=True) - kind: Mapped[str] = mapped_column(String(16)) - mime_type: Mapped[str] = mapped_column(String(128)) - size_bytes: Mapped[int] = mapped_column(BigInteger) - sha256: Mapped[str] = mapped_column(String(64)) - width: Mapped[int | None] = mapped_column(Integer, nullable=True) - height: Mapped[int | None] = mapped_column(Integer, nullable=True) - duration_seconds: Mapped[float | None] = mapped_column(nullable=True) - tags: Mapped[list] = mapped_column(JSON, default=list) - favorite: Mapped[bool] = mapped_column(Boolean, default=False) - origin: Mapped[str] = mapped_column(String(16), default="upload") - library_scope: Mapped[str] = mapped_column(String(16), default="private", server_default="private", index=True) - ready: Mapped[bool] = mapped_column(Boolean, default=True) - source_job_id: Mapped[str | None] = mapped_column(ForeignKey("visual_jobs.id"), nullable=True, index=True) - source_upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True) - source_output_index: Mapped[int | None] = mapped_column(Integer, nullable=True) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True) - deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) +from app.models.base import Base, Timestamp, new_id, utcnow class Job(Base): __tablename__ = "visual_jobs" - __table_args__ = (UniqueConstraint("owner_id", "request_key", "batch_index"), - Index("visual_jobs_dispatch", "state", "next_action_at")) + __table_args__ = ( + UniqueConstraint("owner_id", "request_key", "batch_index"), + Index("visual_jobs_dispatch", "state", "next_action_at"), + ) id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + folder_id: Mapped[str | None] = mapped_column(ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True) + output_folder_id: Mapped[str | None] = mapped_column(ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True) owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) task_type: Mapped[str] = mapped_column(String(48)) execution_mode: Mapped[str] = mapped_column(String(16), default="interactive") @@ -126,9 +79,27 @@ class JobAsset(Base): class Event(Base): __tablename__ = "visual_job_events" __table_args__ = (Index("visual_events_owner_cursor", "owner_id", "id"),) - id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True) + id: Mapped[int] = mapped_column( + BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True + ) owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id")) job_id: Mapped[str | None] = mapped_column(String(32), nullable=True) event_type: Mapped[str] = mapped_column(String(48)) data: Mapped[dict] = mapped_column(JSON) created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class Execution(Base): + __tablename__ = "visual_job_executions" + __table_args__ = (UniqueConstraint("job_id", "ordinal"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + job_id: Mapped[str] = mapped_column(String(32)) + ordinal: Mapped[int] = mapped_column(Integer) + phase_key: Mapped[str] = mapped_column(String(48)) + resource_pool: Mapped[str] = mapped_column(String(32)) + fence_token: Mapped[str] = mapped_column(String(64)) + state: Mapped[str] = mapped_column(String(32), default="allocated") + manifest_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) diff --git a/backend/app/models/operations.py b/backend/app/models/operations.py new file mode 100644 index 0000000..bc83a54 --- /dev/null +++ b/backend/app/models/operations.py @@ -0,0 +1,35 @@ +from datetime import datetime + + +from sqlalchemy import ForeignKey, Integer, JSON, String, UniqueConstraint + +from sqlalchemy.orm import Mapped, mapped_column + + +from app.models.base import Base, Timestamp, new_id, utcnow + + +class Submission(Base): + __tablename__ = "visual_submissions" + __table_args__ = (UniqueConstraint("owner_id", "operation", "key"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + operation: Mapped[str] = mapped_column(String(128)) + key: Mapped[str] = mapped_column(String(128)) + payload_schema: Mapped[int] = mapped_column(Integer, default=2) + body_hash: Mapped[str] = mapped_column(String(64)) + request_json: Mapped[dict] = mapped_column(JSON, default=dict) + resource_json: Mapped[dict] = mapped_column(JSON, default=dict) + status: Mapped[str] = mapped_column(String(32), default="accepted") + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class QuotaReservation(Base): + __tablename__ = "visual_quota_reservations" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + operation: Mapped[str] = mapped_column(String(128)) + units: Mapped[int] = mapped_column(Integer, default=1) + bytes_reserved: Mapped[int] = mapped_column(Integer, default=0) + released_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) diff --git a/backend/app/models/stories.py b/backend/app/models/stories.py new file mode 100644 index 0000000..e8e9abc --- /dev/null +++ b/backend/app/models/stories.py @@ -0,0 +1,45 @@ +"""候选保留冻结输入,选择追加记录;普通草稿 JSON 无法伪造批准。""" + +from datetime import datetime +from sqlalchemy import ForeignKey, Integer, JSON, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column +from app.models.base import Base, Timestamp, new_id, utcnow + + +class ShotCandidate(Base): + __tablename__ = "visual_shot_candidates" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + draft_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_drafts.id"), index=True) + shot_id: Mapped[str] = mapped_column(String(32), index=True) + kind: Mapped[str] = mapped_column(String(16)) + source_kind: Mapped[str] = mapped_column(String(16)) + job_id: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True) + asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + asset_sha256: Mapped[str | None] = mapped_column(String(64), nullable=True) + context_hash: Mapped[str] = mapped_column(String(64)) + generation_hash: Mapped[str] = mapped_column(String(64)) + created_revision: Mapped[int] = mapped_column(Integer) + version: Mapped[int] = mapped_column(Integer, default=1) + state: Mapped[str] = mapped_column(String(32), default="queued") + plan_json: Mapped[dict] = mapped_column(JSON, default=dict) + error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class ShotSelection(Base): + __tablename__ = "visual_shot_selections" + __table_args__ = (UniqueConstraint("draft_id", "shot_id", "kind", "version"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + draft_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_drafts.id"), index=True) + shot_id: Mapped[str] = mapped_column(String(32), index=True) + kind: Mapped[str] = mapped_column(String(16)) + candidate_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + decision_json: Mapped[dict] = mapped_column(JSON, default=dict) + context_hash: Mapped[str] = mapped_column(String(64)) + version: Mapped[int] = mapped_column(Integer, default=1) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) diff --git a/backend/app/models/workflows.py b/backend/app/models/workflows.py new file mode 100644 index 0000000..e7c90f3 --- /dev/null +++ b/backend/app/models/workflows.py @@ -0,0 +1,109 @@ +from datetime import datetime + + +from sqlalchemy import ForeignKey, Integer, JSON, String, UniqueConstraint + +from sqlalchemy.orm import Mapped, mapped_column + + +from app.models.base import Base, Timestamp, new_id, utcnow + + +class WorkflowDraft(Base): + __tablename__ = "visual_drafts" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + folder_id: Mapped[str | None] = mapped_column( + ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True + ) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + name: Mapped[str] = mapped_column(String(255)) + kind: Mapped[str] = mapped_column(String(48), default="three_shot") + spec: Mapped[dict] = mapped_column(JSON, default=dict) + editor_manifest: Mapped[dict | None] = mapped_column(JSON, nullable=True) + revision: Mapped[int] = mapped_column(Integer, default=1) + version: Mapped[int] = mapped_column(Integer, default=1) + current_run_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + updated_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class WorkflowRun(Base): + __tablename__ = "visual_workflow_runs" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + folder_id: Mapped[str | None] = mapped_column( + ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True + ) + output_folder_id: Mapped[str | None] = mapped_column( + ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True + ) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + draft_id: Mapped[str] = mapped_column(String(32)) + draft_revision: Mapped[int] = mapped_column(Integer) + spec_snapshot: Mapped[dict] = mapped_column(JSON, default=dict) + spec_hash: Mapped[str] = mapped_column(String(64)) + run_kind: Mapped[str] = mapped_column(String(32), default="legacy", server_default="legacy") + output_goal: Mapped[str] = mapped_column(String(16), default="film", server_default="film") + base_run_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + source_draft_version: Mapped[int | None] = mapped_column(Integer, nullable=True) + plan_snapshot: Mapped[dict | None] = mapped_column(JSON, nullable=True) + result_manifest: Mapped[dict | None] = mapped_column(JSON, nullable=True) + apply_state: Mapped[str | None] = mapped_column(String(16), nullable=True) + execution_mode: Mapped[str] = mapped_column(String(16), default="interactive") + state: Mapped[str] = mapped_column(String(32), default="queued") + desired_state: Mapped[str] = mapped_column(String(16), default="run") + hold_reasons: Mapped[list] = mapped_column(JSON, default=list) + version: Mapped[int] = mapped_column(Integer, default=1) + batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + batch_item_index: Mapped[int | None] = mapped_column(Integer, nullable=True) + current_output_asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class WorkflowStep(Base): + __tablename__ = "visual_workflow_steps" + __table_args__ = (UniqueConstraint("run_id", "step_key"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + run_id: Mapped[str] = mapped_column(String(32)) + step_key: Mapped[str] = mapped_column(String(32)) + kind: Mapped[str] = mapped_column(String(48)) + dependencies: Mapped[list] = mapped_column(JSON, default=list) + semantic_input_hash: Mapped[str] = mapped_column(String(64)) + selected_job_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + state: Mapped[str] = mapped_column(String(32), default="waiting") + recipe_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + resolved_input_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + explicit_attempt: Mapped[int] = mapped_column(Integer, default=0) + version: Mapped[int] = mapped_column(Integer, default=1) + + +class Batch(Base): + __tablename__ = "visual_batches" + hold_reasons: Mapped[list] = mapped_column(JSON, default=list) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) + name: Mapped[str] = mapped_column(String(255)) + spec_snapshot: Mapped[dict] = mapped_column(JSON, default=dict) + state: Mapped[str] = mapped_column(String(32), default="queued") + desired_state: Mapped[str] = mapped_column(String(16), default="run") + version: Mapped[int] = mapped_column(Integer, default=1) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class BatchItem(Base): + __tablename__ = "visual_batch_items" + __table_args__ = (UniqueConstraint("batch_id", "item_index"),) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + batch_id: Mapped[str] = mapped_column(String(32)) + item_index: Mapped[int] = mapped_column(Integer) + target_kind: Mapped[str] = mapped_column(String(16)) + target_id: Mapped[str] = mapped_column(String(32)) + spec_json: Mapped[dict] = mapped_column(JSON, default=dict) + state: Mapped[str] = mapped_column(String(32), default="queued") diff --git a/backend/app/providers.py b/backend/app/providers.py deleted file mode 100644 index a5717fb..0000000 --- a/backend/app/providers.py +++ /dev/null @@ -1,843 +0,0 @@ -"""Database-independent adapters for deployed GPU jobs, text/vision and CPU media.""" -from __future__ import annotations - -import asyncio -from contextvars import ContextVar -import base64 -from dataclasses import dataclass -from datetime import datetime, timezone -import html -from io import BytesIO -import json -import math -import os -from pathlib import Path -import re -import stat -import time -from urllib.parse import urlsplit -import uuid - -import httpx -from PIL import Image, ImageOps - -from .media import MediaError as ProviderError, confined, input_options, inspect_media, run_process - - -current_phase_callback = ContextVar('current_phase_callback', default=None) - - -async def enter_phase(phase_key, resource_pool): - callback = current_phase_callback.get() - if callback is not None: - await callback(phase_key, resource_pool) - - -GPU_TASKS = {'image.generate', 'video.generate', 'defect.generate', 'audio.transcribe'} -LANGUAGES = ['zh', 'en', 'ja', 'ko', 'de', 'fr', 'es', 'ru', 'ar', 'pt', 'it', 'auto'] -_UUID = re.compile(r'GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z') - - -@dataclass -class CpuResult: - outputs: list[Path] - result: dict - metadata: dict - - -def _invalid(message='任务输入或参数无效。'): - return ProviderError('invalid_input', message) - - -def _keys(value, allowed): - if not isinstance(value, dict) or set(value) - set(allowed): - raise _invalid('包含不支持的输入或参数。') - - -def _int(value, low, high, step=1): - if type(value) is not int or not low <= value <= high or value % step: - raise _invalid('整数参数超出范围或步长不正确。') - return value - - -def _float(value, low, high): - if isinstance(value, bool) or not isinstance(value, (float, int)): - raise _invalid('数值参数无效。') - try: - normalized = float(value) - except (ValueError, OverflowError): - raise _invalid('数值参数无效。') from None - if not math.isfinite(normalized) or not low <= normalized <= high: - raise _invalid('数值参数超出范围。') - return normalized - - -def _string(value, maximum=8000, *, required=True): - if not isinstance(value, str) or len(value) > maximum or (required and not value.strip()): - raise _invalid('文字内容为空或超出长度限制。') - return value - - -def _voices(settings): - values = getattr(settings, 'tts_voices', ['zf_xiaobei', 'zm_yunxi']) - if isinstance(values, str): - values = [item.strip() for item in values.split(',') if item.strip()] - return [value for value in values if isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9_-]{1,64}', value)] - - -def capabilities(settings) -> list[dict]: - from .runtime_policy import read_runtime_policy - compose_limit=read_runtime_policy(settings)['workflow_max_shots'] - image_defaults = {'width': 1024, 'height': 1024, 'num_inference_steps': 50, 'seed': 42, 'guidance_scale': 4.0} - image_limits = {'width': {'min': 256, 'max': 2048, 'step': 16}, - 'height': {'min': 256, 'max': 2048, 'step': 16}, - 'num_inference_steps': {'min': 1, 'max': 100}, - 'guidance_scale': {'min': 1, 'max': 20}, 'seed': {'min': 0, 'max': 2**32 - 1}, - 'count': {'min': 1, 'max': 4}, 'max_pixels': 2048 * 2048} - video_defaults = dict(image_defaults, width=1280, height=704, guidance_scale=5.0, - num_frames=121, fps=24, upscale=True, upscale_width=1920, upscale_height=1080, tile_size=128) - video_limits = {**image_limits, 'width': {'min': 256, 'max': 1280, 'step': 32}, - 'height': {'min': 256, 'max': 1280, 'step': 32}, 'max_pixels': 1280 * 704, - 'count': {'min': 1, 'max': 1}, 'num_frames': {'min': 5, 'max': 361, 'step': 4}, - 'fps': {'values': [24]}, 'upscale': {'values': [True, False]}, - 'upscale_width': {'min': 256, 'max': 3840, 'step': 2}, - 'upscale_height': {'min': 256, 'max': 2160, 'step': 2}, 'tile_size': {'min': 64, 'max': 256, 'step': 16}} - configured = bool(getattr(settings, 'inference_base_url', '')) - qwen = bool(getattr(settings, 'qwen_base_url', '') and getattr(settings, 'qwen_model', '')) - speech = bool(getattr(settings, 'tts_base_url', '') and getattr(settings, 'tts_model', '') and _voices(settings)) - def item(task_type, label, model, available, types, defaults, constraints, description): - return dict(task_type=task_type, label=label, model=model, available=available, - input_types=types, defaults=defaults, constraints=constraints, description=description) - return [ - item('image.generate', '图像生成', 'Qwen-Image', configured, ['text'], image_defaults, image_limits, - '文字生成图片;不包含图像编辑或风格 LoRA 管理。'), - item('video.generate', '视频生成', 'Wan2.2-TI2V-5B + Real-ESRGAN', configured, ['text', 'image'], - video_defaults, video_limits, '单镜头最多361帧、24fps,约15秒无声视频;默认约5秒,可选1080p增强。'), - item('defect.generate', '条件样本生成', 'SDXL + Canny ControlNet', configured, ['text', 'image'], - dict(image_defaults, guidance_scale=7.5, controlnet_conditioning_scale=.8, canny_low=100, canny_high=200), - {**image_limits, 'controlnet_conditioning_scale': {'min': 0, 'max': 2}, - 'canny_low': {'min': 0, 'max': 255}, 'canny_high': {'min': 0, 'max': 255}}, - '参考图片提供边缘结构;输出控制图不是缺陷真值掩膜。'), - item('audio.transcribe', '语音转写', 'Whisper-large-v3-turbo', configured, ['audio', 'video'], - {'language': 'zh', 'max_audio_seconds': 1800}, - {'language': {'values': LANGUAGES}, 'max_audio_seconds': {'min': 1, 'max': 1800}}, - '支持音频和有声视频;时间戳为30秒块边界,不是字词对齐。'), - item('math.solve', '数学推演', getattr(settings, 'qwen_model', ''), qwen, ['text'], - {'max_tokens': 2048, 'enable_thinking': False}, {'max_tokens': {'min': 1, 'max': 4096}}, - '调用现有文本服务给出解答,未集成形式化证明或准确率评测。'), - item('media.structure', '素材理解', getattr(settings, 'qwen_model', ''), qwen, ['image', 'video'], - {'frame_count': 6}, {'frame_count': {'min': 1, 'max': 12}}, - '视频均匀抽帧后理解画面、文字和标签;不承诺镜头切分准确率。'), - item('video.compose', '成片编排', 'FFmpeg CPU', True, ['video', 'audio'], - {'width': 1280, 'height': 720, 'fps': 24}, - {'width': {'min': 256, 'max': 3840, 'step': 2}, 'height': {'min': 256, 'max': 2160, 'step': 2}, - 'fps': {'values': [24, 25, 30, 60]}, 'clips': {'min': 1, 'max': compose_limit}, - 'source_duration_seconds': {'min': .05, 'max': 86400}}, - '按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。'), - item('audio.speech', '中文配音', getattr(settings, 'tts_model', '') or '尚未配置', speech, ['text'], - {'voice': (_voices(settings) or [''])[0], 'speed': 1.0}, - {'voice': {'values': _voices(settings)}, 'speed': {'min': .5, 'max': 2}, 'text': {'max': 2000}}, - '仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。'), - ] - - -def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=None) -> None: - """Pure submission validation: no HTTP, file decoding, mkdir or model work.""" - p = parameters - if task_type in GPU_TASKS: - allowed = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'} - if task_type in {'video.generate', 'defect.generate'}: - allowed.add('image_asset_id') - _keys(inputs, allowed) - defaults = next(item['defaults'] for item in capabilities(settings) if item['task_type'] == task_type) - _keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set())) - p = {**defaults, **p} - if task_type == 'audio.transcribe': - if not (inputs.get('audio_asset_id') or inputs.get('asset_id')): - raise _invalid('请选择转写素材。') - if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']: - raise _invalid('请仅选择一个转写素材。') - if p['language'] not in LANGUAGES: - raise _invalid('不支持此转写语言。') - _int(p['max_audio_seconds'], 1, 1800) - return - _string(inputs.get('prompt')) - _string(inputs.get('negative_prompt', ''), required=False) - if 'negative_prompt' in p: - _string(p['negative_prompt'], required=False) - video = task_type == 'video.generate' - for key in ('width', 'height'): - _int(p[key], 256, 1280 if video else 2048, 32 if video else 16) - if p['width'] * p['height'] > (1280 * 704 if video else 2048 * 2048): - raise _invalid('画面像素总数超出服务限制。') - _int(p['num_inference_steps'], 1, 100) - _int(p['seed'], 0, 2**32 - 1) - _float(p['guidance_scale'], 1, 20) - if task_type == 'defect.generate': - if not inputs.get('image_asset_id'): - raise _invalid('条件样本任务需要参考图片。') - _float(p['controlnet_conditioning_scale'], 0, 2) - _int(p['canny_low'], 0, 255) - _int(p['canny_high'], 0, 255) - if p['canny_low'] >= p['canny_high']: - raise _invalid('Canny低阈值必须小于高阈值。') - if video: - _int(p['num_frames'], 5, 361) - if p['num_frames'] % 4 != 1 or type(p['fps']) is not int or p['fps'] != 24 or type(p['upscale']) is not bool: - raise _invalid('视频帧数、帧率或增强开关无效。') - _int(p['upscale_width'], 256, 3840, 2) - _int(p['upscale_height'], 256, 2160, 2) - _int(p['tile_size'], 64, 256, 16) - return - if task_type == 'math.solve': - _keys(inputs, {'prompt'}) - _keys(p, {'max_tokens', 'enable_thinking'}) - _string(inputs.get('prompt')) - _int(p.get('max_tokens', 2048), 1, 4096) - if type(p.get('enable_thinking', False)) is not bool: - raise _invalid('思考开关必须为布尔值。') - return - if task_type == 'media.structure': - _keys(inputs, {'asset_id', 'image_asset_id'}) - _keys(p, {'frame_count'}) - if not (inputs.get('asset_id') or inputs.get('image_asset_id')): - raise _invalid('请选择待理解素材。') - if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']: - raise _invalid('请选择一个待理解素材。') - _int(p.get('frame_count', 6), 1, 12) - return - if task_type == 'audio.speech': - _keys(inputs, {'prompt'}) - _keys(p, {'voice', 'speed'}) - _string(inputs.get('prompt'), 2000) - voices = _voices(settings) - if not voices or p.get('voice', voices[0]) not in voices: - raise _invalid('请选择已配置的中文音色。') - _float(p.get('speed', 1), .5, 2) - return - if task_type == 'video.compose': - if 'workflow_spec' in p: - from .timeline import WorkflowSpec - _keys(inputs, {'asset_ids', 'audio_asset_id'}) - _keys(p, {'workflow_spec', 'clips'}) - try: - spec = WorkflowSpec.model_validate(p['workflow_spec']) - except ValueError: - raise _invalid('Invalid frozen workflow timeline.') from None - clips = p.get('clips') - if not isinstance(clips, list) or len(clips) != len(spec.shots): - raise _invalid('Workflow clips must match the frozen shot count.') - for clip in clips: - _keys(clip, {'asset_id'}) - _string(clip.get('asset_id'), 64) - if inputs.get('asset_ids') != [c['asset_id'] for c in clips]: - raise _invalid('Workflow clip order differs.') - if inputs.get('audio_asset_id') != (spec.render.audio.asset_id if spec.render.audio else None): - raise _invalid('Workflow audio differs.') - return - _keys(inputs, {'asset_ids', 'audio_asset_id'}) - _keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'}) - clips = p.get('clips') - if not isinstance(clips, list) or not 1 <= len(clips) <= 1000: - raise _invalid('请选择1至1000个视频片段,并遵守当前配置的资源上限。') - for clip in clips: - _keys(clip, {'asset_id', 'start_seconds', 'end_seconds'}) - _string(clip.get('asset_id'), 64) - start = _float(clip.get('start_seconds', 0), 0, 86400) - if clip.get('end_seconds') is not None and _float(clip['end_seconds'], 0, 86400) <= start: - raise _invalid('片段结束时间必须大于开始时间。') - if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]: - raise _invalid('素材顺序应与编排片段一致。') - if inputs.get('audio_asset_id') and p.get('audio_asset_id') and inputs['audio_asset_id'] != p['audio_asset_id']: - raise _invalid('请只选择一个成片音轨。') - _int(p.get('width', 1280), 256, 3840, 2) - _int(p.get('height', 720), 256, 2160, 2) - if type(p.get('fps', 24)) is not int or p.get('fps', 24) not in {24, 25, 30, 60}: - raise _invalid('不支持此成片帧率。') - cues = p.get('subtitles', []) - if not isinstance(cues, list) or len(cues) > 1000: - raise _invalid('人工字幕数量超出限制。') - for cue in cues: - _keys(cue, {'start', 'end', 'text'}) - start, end = _float(cue.get('start'), 0, 86400*1000), _float(cue.get('end'), 0, 86400*1000) - text = _string(cue.get('text'), 2000) - if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text): - raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。') - return - raise _invalid('不支持此任务类型。') - - -def _read_key(path): - descriptor = None - try: - path = Path(path) - if not path.is_absolute() or path.is_symlink(): - raise ValueError - descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) - info = os.fstat(descriptor) - if not stat.S_ISREG(info.st_mode) or (os.name == 'posix' and info.st_mode & 0o022): - raise ValueError - raw = os.read(descriptor, 4097) - value = raw.decode('utf-8').strip() - if not value or len(raw) > 4096 or '\n' in value or '\r' in value: - raise ValueError - return value - except (OSError, ValueError, UnicodeError): - raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True) from None - finally: - if descriptor is not None: - os.close(descriptor) - - -def _url(base, suffix): - if not isinstance(base, str) or not base: - raise ProviderError('capability_unavailable', '此能力尚未配置。') - parsed = urlsplit(base) - if parsed.scheme not in {'http', 'https'} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: - raise ProviderError('provider_not_configured', '模型服务地址配置无效。', True) - return base.rstrip('/') + suffix - - -class Provider: - def __init__(self, settings): - self.settings = settings - self.client = httpx.AsyncClient(trust_env=False, follow_redirects=False, - timeout=httpx.Timeout(float(settings.request_timeout_seconds)), - limits=httpx.Limits(max_connections=4, max_keepalive_connections=2)) - - async def aclose(self): - await self.client.aclose() - - def _headers(self, family='inference'): - key = getattr(self.settings, family + '_api_key', '') or '' - if family == 'inference' and getattr(self.settings, 'inference_api_key_file', None): - key = _read_key(self.settings.inference_api_key_file) - if not isinstance(key, str) or len(key) > 4096 or any(not 32 <= ord(char) <= 126 for char in key): - raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True) - return {'Authorization': 'Bearer ' + key} if key else {} - - @staticmethod - def _http_error(status): - if status in {400, 413, 415, 422}: - return ProviderError('upstream_rejected', '模型服务拒绝了任务输入或参数。') - if status == 404: - return ProviderError('upstream_not_found', '模型服务未找到请求的任务或结果。', True) - if status == 409: - return ProviderError('upstream_conflict', '模型任务或幂等请求发生冲突。') - return ProviderError('upstream_unavailable', '模型服务暂时不可用。', True) - - async def _json(self, method, url, *, payload=None, headers=None): - try: - async with asyncio.timeout(float(self.settings.request_timeout_seconds) + 1): - async with self.client.stream(method, url, json=payload, headers=headers) as response: - if not 200 <= response.status_code < 300: - raise self._http_error(response.status_code) - data, size = [], 0 - async for chunk in response.aiter_bytes(): - size += len(chunk) - if size > 2 * 1024 * 1024: - raise ProviderError('invalid_upstream_response', '模型服务响应超出限制。', True) - data.append(chunk) - value = json.loads(b''.join(data)) - if not isinstance(value, dict): - raise ValueError - return value - except (httpx.HTTPError, asyncio.TimeoutError): - raise ProviderError('upstream_unavailable', '模型服务连接失败或响应超时。', True) from None - except (ValueError, UnicodeError, RecursionError): - raise ProviderError('invalid_upstream_response', '模型服务返回了无效响应。', True) from None - - async def health(self): - try: - value = await self._json('GET', _url(self.settings.inference_base_url, '/health'), headers=self._headers()) - return value.get('status') == 'ok' - except ProviderError: - return False - - async def scheduler_status(self): - unavailable = {'available': False, 'state': 'unavailable', 'reason': 'GPU状态暂时不可用。', 'gpus': [], 'updated_at': None} - try: - path = Path(self.settings.gpu_status_path) - if path.stat().st_size > 1024 * 1024: - return unavailable - data = json.loads(path.read_bytes()) - now = time.time() - generated = _float(data['generated_at'], 0, now + 1) - if data['schema_version'] != 1 or data.get('error') is not None or now - generated > 5: - return unavailable - seen, gpus = set(), [] - for gpu in data['gpus']: - index = _int(gpu['index'], 0, 1024) - if index in seen or not isinstance(gpu['uuid'], str) or not _UUID.fullmatch(gpu['uuid']): - return unavailable - seen.add(index) - total = _float(gpu['total_gib'], .001, 100000) - free = _float(gpu['free_gib'], 0, total) - external, own = gpu['external_pids'], gpu['own_pids'] - if not all(isinstance(values, list) and all(type(pid) is int and pid > 0 for pid in values) - for values in (external, own)): - return unavailable - idle = gpu.get('idle_since') - if idle is not None: - idle = _float(idle, 0, now + 1) - busy = bool(external or own) - eligible = not busy and free >= 76 and idle is not None and now - idle >= 15 - gpus.append({'index': index, 'name': f'GPU {index}', 'busy': busy, - 'eligible': eligible, 'free_gib': free, '_uuid': gpu['uuid'], '_own': bool(own), - 'state': 'external' if external else 'running' if own else 'ready' if eligible else 'waiting', - 'stage': None}) - scheduler = None - try: - scheduler_path = Path(self.settings.gpu_scheduler_path) - if scheduler_path.stat().st_size <= 1024 * 1024: - scheduler = json.loads(scheduler_path.read_bytes()) - except (OSError, ValueError, TypeError, AttributeError): - pass - from .gpu_summary import summarize - return summarize(gpus, scheduler, now, generated) - except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError): - return unavailable - - def _work(self, path): - work = confined(path, self.settings, exists=False, root=self.settings.job_work_root) - if not work.is_dir(): - raise _invalid('任务工作目录不可用。') - return work - - def _asset(self, asset_id, assets): - if not isinstance(asset_id, str) or asset_id not in assets: - raise _invalid('请选择可访问的素材。') - return confined(assets[asset_id], self.settings) - - async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir): - validate_arguments(task_type, inputs, parameters, self.settings) - work = self._work(work_dir) - if task_type not in GPU_TASKS: - raise _invalid('不支持此模型任务类型。') - p = dict(parameters) if isinstance(parameters, dict) else parameters - allowed_input = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'} - if task_type in {'video.generate', 'defect.generate'}: - allowed_input.add('image_asset_id') - _keys(inputs, allowed_input) - defaults = next(item['defaults'] for item in capabilities(self.settings) if item['task_type'] == task_type) - _keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set())) - normalized = {**defaults, **p} - out = {} - if task_type == 'audio.transcribe': - asset_id = inputs.get('audio_asset_id') or inputs.get('asset_id') - if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']: - raise _invalid('请仅选择一个转写素材。') - source = self._asset(asset_id, assets) - info = await inspect_media(source, self.settings) - if normalized['language'] not in LANGUAGES: - raise _invalid('不支持此转写语言。') - _int(normalized['max_audio_seconds'], 1, 1800) - if info['kind'] not in {'audio', 'video'} or info['duration_seconds'] > normalized['max_audio_seconds']: - raise _invalid('请选择时长受限的音频或有声视频。') - if info['kind'] == 'video': - await enter_phase('extract_audio', 'cpu_media') - target = work / 'asr-input.wav' - temporary = work / ('asr-' + uuid.uuid4().hex + '.wav') - try: - await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), - '-i', str(source), '-map', '0:a:0', '-vn', '-ac', '1', '-ar', '16000', - '-c:a', 'pcm_s16le', '-t', str(normalized['max_audio_seconds']), '-threads', '2', str(temporary)], timeout=300) - if not temporary.is_file() or not temporary.stat().st_size: - raise _invalid('视频没有可转写的音轨。') - os.replace(temporary, target) - finally: - temporary.unlink(missing_ok=True) - source = target - await enter_phase('transcribe', 'new_gpu') - out['audio_path'] = str(source) - else: - out['prompt'] = _string(inputs.get('prompt')) - out['negative_prompt'] = _string(normalized.pop('negative_prompt', inputs.get('negative_prompt', '')), required=False) - video = task_type == 'video.generate' - for key in ('width', 'height'): - _int(normalized[key], 256, 1280 if video else 2048, 32 if video else 16) - if normalized['width'] * normalized['height'] > (1280 * 704 if video else 2048 * 2048): - raise _invalid('画面像素总数超出服务限制。') - _int(normalized['num_inference_steps'], 1, 100) - _int(normalized['seed'], 0, 2**32 - 1) - normalized['guidance_scale'] = _float(normalized['guidance_scale'], 1, 20) - if 'image_asset_id' in inputs: - source = self._asset(inputs['image_asset_id'], assets) - if (await inspect_media(source, self.settings))['kind'] != 'image': - raise _invalid('参考素材必须是图片。') - out['image_path'] = str(source) - if task_type == 'defect.generate': - if 'image_path' not in out: - raise _invalid('条件样本任务需要参考图片。') - normalized['controlnet_conditioning_scale'] = _float(normalized['controlnet_conditioning_scale'], 0, 2) - _int(normalized['canny_low'], 0, 255) - _int(normalized['canny_high'], 0, 255) - if normalized['canny_low'] >= normalized['canny_high']: - raise _invalid('Canny低阈值必须小于高阈值。') - if video: - _int(normalized['num_frames'], 5, 361) - if normalized['num_frames'] % 4 != 1 or type(normalized['fps']) is not int or normalized['fps'] != 24: - raise _invalid('视频仅支持4n+1帧、最多361帧和24fps。') - if type(normalized['upscale']) is not bool: - raise _invalid('增强开关必须为布尔值。') - _int(normalized['upscale_width'], 256, 3840, 2) - _int(normalized['upscale_height'], 256, 2160, 2) - _int(normalized['tile_size'], 64, 256, 16) - return {'task_type': task_type, 'input': out, 'parameters': normalized, 'timeout_seconds': 3600} - - async def submit(self, payload, idempotency_key): - _string(idempotency_key, 128) - if any(not 33 <= ord(char) <= 126 for char in idempotency_key): - raise _invalid('幂等请求标识无效。') - return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url, '/jobs'), payload=payload, - headers={**self._headers(), 'Idempotency-Key': idempotency_key})) - - @staticmethod - def _job_id(value): - if not isinstance(value, str) or re.fullmatch(r'[0-9a-f]{32}', value) is None: - raise _invalid('模型任务标识无效。') - return value - - @staticmethod - def _sanitize_job(value): - if value.get('error'): - value['error'] = '模型任务执行失败,请检查任务输入或联系管理员。' - if value.get('last_preempted_reason'): - value['last_preempted_reason'] = 'GPU资源已让出,任务重新排队。' - return value - - async def query(self, upstream_id): - return self._sanitize_job(await self._json('GET', _url(self.settings.inference_base_url, - '/jobs/' + self._job_id(upstream_id)), headers=self._headers())) - - async def upstream_capabilities(self): - cached = getattr(self, '_capabilities_cache', None) - if cached and time.monotonic() - cached[0] < 30: - return json.loads(json.dumps(cached[1])) - value = await self._json('GET', _url(self.settings.inference_base_url, '/capabilities'), headers=self._headers()) - features = value.get('features', {}) - value['admission_policy'] = bool(value.get('admission_policy') or (features.get('scheduling') and features.get('admission_pause'))) - self._capabilities_cache = (time.monotonic(), value) - return json.loads(json.dumps(value)) - - async def control(self, upstream_id, desired_state, command_id, expected_version=None, expected_execution_id=None): - if desired_state not in {'run', 'pause', 'cancel'}: - raise _invalid('Invalid control intention.') - _string(command_id, 128) - payload = {'desired_state': desired_state, 'command_id': command_id} - if expected_version is not None: - payload['expected_version'] = _int(expected_version, 0, 2**63-1) - if expected_execution_id is not None: - payload['expected_execution_id'] = _string(expected_execution_id, 64) - return self._sanitize_job(await self._json('PUT', _url(self.settings.inference_base_url, - '/jobs/' + self._job_id(upstream_id) + '/control'), payload=payload, headers=self._headers())) - - async def cancel(self, upstream_id): - return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url, - '/jobs/' + self._job_id(upstream_id) + '/cancel'), headers=self._headers())) - - async def _download_url(self, url, destination, headers, *, payload=None): - target = confined(destination, self.settings, exists=False) - target.parent.mkdir(parents=True, exist_ok=True) - temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex) - try: - async with asyncio.timeout(max(30, min(600, float(self.settings.request_timeout_seconds) * 4))): - async with self.client.stream('POST' if payload is not None else 'GET', url, - headers=headers, json=payload) as response: - if not 200 <= response.status_code < 300: - raise self._http_error(response.status_code) - limit = int(self.settings.max_output_bytes) - declared = response.headers.get('Content-Length') - if declared is not None and (not declared.isdigit() or int(declared) > limit): - raise ProviderError('output_too_large', '输出文件超出大小限制。') - count = 0 - with temporary.open('xb') as stream: - async for chunk in response.aiter_bytes(): - count += len(chunk) - if count > limit: - raise ProviderError('output_too_large', '输出文件超出大小限制。') - stream.write(chunk) - if not count or (declared is not None and count != int(declared)): - raise ProviderError('invalid_upstream_response', '输出文件为空或未传输完整。', True) - os.replace(temporary, target) - except (httpx.HTTPError, asyncio.TimeoutError): - raise ProviderError('upstream_unavailable', '输出文件传输失败,请稍后重试。', True) from None - except OSError: - raise ProviderError('output_unavailable', '无法保存输出文件。', True) from None - finally: - temporary.unlink(missing_ok=True) - - async def download(self, upstream_id, index, destination): - _int(index, 0, 1000) - await self._download_url(_url(self.settings.inference_base_url, - '/jobs/' + self._job_id(upstream_id) + '/outputs/' + str(index)), destination, self._headers()) - - async def _chat(self, messages, *, max_tokens=2048, thinking=False): - if not self.settings.qwen_model: - raise ProviderError('capability_unavailable', '文本与视觉服务尚未配置。') - value = await self._json('POST', _url(self.settings.qwen_base_url, '/chat/completions'), - headers=self._headers('qwen'), payload={'model': self.settings.qwen_model, 'messages': messages, - 'stream': False, 'temperature': 0, 'max_tokens': max_tokens, - 'chat_template_kwargs': {'enable_thinking': thinking}}) - choices = value.get('choices') - if (isinstance(choices, list) and choices and isinstance(choices[0], dict) - and choices[0].get('finish_reason') == 'length'): - raise ProviderError('output_truncated', '模型输出达到长度上限,内容不完整;请提高输出长度或简化要求后重新提交。') - try: - content = value['choices'][0]['message']['content'] - if isinstance(content, list): - content = ''.join(part['text'] for part in content if part.get('type') == 'text') - content = _string(content, 200_000) - inline = re.fullmatch(r'\s*.*?\s*(.*)', content, flags=re.DOTALL) - if inline: - content = inline.group(1).strip() - if not content: - raise ValueError - return content - except (ValueError, TypeError, KeyError, IndexError, AttributeError, ProviderError): - raise ProviderError('invalid_upstream_response', '文本服务没有返回有效内容。', True) from None - - @staticmethod - def _json_file(work, name, value): - target = work / name - temporary = work / (name + '.part-' + uuid.uuid4().hex) - try: - temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8') - os.replace(temporary, target) - finally: - temporary.unlink(missing_ok=True) - return target - - async def run_cpu(self, task_type, inputs, parameters, assets, work_dir): - work = self._work(work_dir) - validate_arguments(task_type, inputs, parameters, self.settings) - try: - if task_type == 'math.solve': - await enter_phase('solve', 'qwen_http') - _keys(inputs, {'prompt'}) - _keys(parameters, {'max_tokens', 'enable_thinking'}) - tokens = _int(parameters.get('max_tokens', 2048), 1, 4096) - thinking = parameters.get('enable_thinking', False) - if type(thinking) is not bool: - raise _invalid('思考开关必须为布尔值。') - text = await self._chat([{'role': 'system', 'content': '请给出可复核的数学解题步骤和最终答案;不确定时明确说明。'}, - {'role': 'user', 'content': _string(inputs.get('prompt'))}], max_tokens=tokens, thinking=thinking) - answer = work / 'answer.txt' - answer.write_text(text + '\n', encoding='utf-8') - result = {'text': text} - return CpuResult([answer, self._json_file(work, 'answer.json', result)], result, - {'provider': 'qwen', 'model': self.settings.qwen_model, 'formal_verification': False}) - if task_type == 'media.structure': - return await self._structure(inputs, parameters, assets, work) - if task_type == 'video.compose': - await enter_phase('compose', 'cpu_media') - return await self._compose(inputs, parameters, assets, work) - if task_type == 'audio.speech': - await enter_phase('speech', 'cpu_media') - return await self._speech(inputs, parameters, work) - raise _invalid('不支持此CPU任务类型。') - except OSError: - raise ProviderError('output_unavailable', '任务文件处理失败。', True) from None - - async def _image_uri(self, source): - def encode(): - with Image.open(source) as image: - image = ImageOps.exif_transpose(image).convert('RGB') - image.thumbnail((1280, 1280)) - buffer = BytesIO() - image.save(buffer, format='JPEG', quality=85) - return 'data:image/jpeg;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii') - return await asyncio.to_thread(encode) - - async def _structure(self, inputs, p, assets, work): - _keys(inputs, {'asset_id', 'image_asset_id'}) - _keys(p, {'frame_count'}) - asset_id = inputs.get('asset_id') or inputs.get('image_asset_id') - if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']: - raise _invalid('请选择一个待理解素材。') - count = _int(p.get('frame_count', 6), 1, 12) - source = self._asset(asset_id, assets) - info = await inspect_media(source, self.settings) - if info['kind'] not in {'image', 'video'}: - raise _invalid('素材理解支持图片或视频。') - samples, outputs = [(0.0, source)], [] - if info['kind'] == 'video': - await enter_phase('sample_frames', 'cpu_media') - samples = [] - for index in range(count): - timestamp = (index + .5) * info['duration_seconds'] / count - frame = work / f'frame-{index:03d}.jpg' - # Fixed filters and numeric seek only; never accept a filter from input. - _, diagnostics = await run_process([self.settings.ffmpeg_bin, '-v', 'info', '-nostdin', '-copyts', *input_options(), - '-ss', f'{timestamp:.6f}', '-i', str(source), '-frames:v', '1', '-vf', - 'scale=1280:1280:force_original_aspect_ratio=decrease,showinfo', '-threads', '2', str(frame)], - timeout=90, return_stderr=True) - if not frame.is_file() or not frame.stat().st_size: - raise ProviderError('frame_extraction_failed', '视频抽帧失败。') - actual_pts = re.search(rb'\bpts_time:([+-]?[0-9]+(?:\.[0-9]+)?)', diagnostics) - if actual_pts is None: - raise ProviderError('frame_extraction_failed', '无法确认抽帧的实际时间。') - actual_time = float(actual_pts.group(1)) - info.get('start_seconds', 0) - if not math.isfinite(actual_time) or not -.1 <= actual_time <= info['duration_seconds'] + .1: - raise ProviderError('frame_extraction_failed', '抽帧时间超出素材范围。') - samples.append((max(0, actual_time), frame)) - outputs.append(frame) - frames = [] - prompt = ('仅根据画面可见内容输出JSON对象,不要Markdown。字段 subjects 为字符串数组,scene 为字符串,' - 'ocr 为画面实际可见文字的字符串数组,tags 为字符串数组。看不清请写不确定,不要臆测人物身份。') - for index, (timestamp, frame) in enumerate(samples): - image_uri = await self._image_uri(frame) - await enter_phase(f'describe_frame_{index}', 'qwen_http') - text = await self._chat([{'role': 'user', 'content': [ - {'type': 'image_url', 'image_url': {'url': image_uri}}, - {'type': 'text', 'text': prompt}]}]) - try: - fenced = re.fullmatch(r'\s*```(?:json)?\s*(.*?)\s*```\s*', text, flags=re.DOTALL | re.IGNORECASE) - value = json.loads(fenced.group(1) if fenced else text) - scene = _string(value['scene'], 2000, required=False) - normalized = {} - for key in ('subjects', 'ocr', 'tags'): - items = value.get(key, []) if key == 'tags' else value[key] - if not isinstance(items, list) or len(items) > 100: - raise ValueError - normalized[key] = list(dict.fromkeys(_string(item, 2000, required=False) for item in items)) - frames.append({'timestamp_seconds': round(timestamp, 6), 'scene': scene, **normalized}) - except (ValueError, KeyError, TypeError, AttributeError, ProviderError): - raise ProviderError('invalid_visual_response', '视觉服务未返回有效的结构化内容。', True) from None - result = {'subjects': list(dict.fromkeys(item for frame in frames for item in frame['subjects'])), - 'scene': ';'.join(dict.fromkeys(frame['scene'] for frame in frames)), - 'ocr': list(dict.fromkeys(item for frame in frames for item in frame['ocr'])), - 'tags': list(dict.fromkeys(item for frame in frames for item in frame['tags'])), 'frames': frames} - outputs.append(self._json_file(work, 'structure.json', result)) - return CpuResult(outputs, result, {'provider': 'qwen', 'model': self.settings.qwen_model, - 'sampling': 'uniform seek' if info['kind'] == 'video' else 'single image', - 'timestamp_precision': 'decoded frame PTS relative to source start', 'frame_count': len(frames)}) - - async def _speech(self, inputs, p, work): - if not self.settings.tts_base_url or not self.settings.tts_model or not _voices(self.settings): - raise ProviderError('capability_unavailable', '中文配音服务尚未配置。') - _keys(inputs, {'prompt'}) - _keys(p, {'voice', 'speed'}) - text = _string(inputs.get('prompt'), 2000) - voice = p.get('voice', _voices(self.settings)[0]) - if voice not in _voices(self.settings): - raise _invalid('请选择已配置的中文音色。') - speed = _float(p.get('speed', 1.0), .5, 2) - target = work / 'speech.wav' - await self._download_url(_url(self.settings.tts_base_url, '/audio/speech'), target, self._headers('tts'), - payload={'model': self.settings.tts_model, 'input': text, 'voice': voice, 'speed': speed, 'response_format': 'wav'}) - info = await inspect_media(target, self.settings) - if info['kind'] != 'audio' or info['mime_type'] != 'audio/wav': - target.unlink(missing_ok=True) - raise ProviderError('invalid_speech_response', '配音服务未返回有效的 WAV 音频。', True) - return CpuResult([target], {'text': text, 'voice': voice, 'duration_seconds': info['duration_seconds']}, - {'provider': 'openai-compatible-tts', 'model': self.settings.tts_model, 'speed': speed}) - - async def _compose(self, inputs, p, assets, work): - if 'workflow_spec' in p: - from .timeline import compile_timeline - from .media import compose_workflow - validate_arguments('video.compose', inputs, p, self.settings) - audio_id = inputs.get('audio_asset_id') - audio = self._asset(audio_id, assets) if audio_id else None - owned = {audio_id: await inspect_media(audio, self.settings)} if audio else {} - try: - plan = compile_timeline(p['workflow_spec'], owned) - except ValueError: - raise _invalid('Invalid workflow audio timeline.') from None - return await compose_workflow(plan, work, settings=self.settings, sources=[self._asset(c['asset_id'], assets) for c in p['clips']], audio=audio) - _keys(inputs, {'asset_ids', 'audio_asset_id'}) - _keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'}) - clips = p.get('clips') - if not isinstance(clips, list) or not 1 <= len(clips) <= 1000: - raise _invalid('请选择1至1000个视频片段。') - width, height, fps = p.get('width', 1280), p.get('height', 720), p.get('fps', 24) - _int(width, 256, 3840, 2) - _int(height, 256, 2160, 2) - if type(fps) is not int or fps not in {24, 25, 30, 60}: - raise _invalid('不支持此成片帧率。') - normalized = [] - for clip in clips: - _keys(clip, {'asset_id', 'start_seconds', 'end_seconds'}) - start = _float(clip.get('start_seconds', 0), 0, 86400) - end = clip.get('end_seconds') - if end is not None and _float(end, 0, 86400) <= start: - raise _invalid('片段结束时间必须大于开始时间。') - normalized.append((self._asset(clip.get('asset_id'), assets), start, end)) - if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]: - raise _invalid('素材顺序应与编排片段一致。') - a, b = inputs.get('audio_asset_id'), p.get('audio_asset_id') - if a and b and a != b: - raise _invalid('请只选择一个成片音轨。') - audio = self._asset(a or b, assets) if a or b else None - subtitles = p.get('subtitles', []) - if not isinstance(subtitles, list) or len(subtitles) > 1000: - raise _invalid('人工字幕数量超出限制。') - cues = [] - for cue in subtitles: - _keys(cue, {'start', 'end', 'text'}) - start, end = _float(cue.get('start'), 0, 86400*1000), _float(cue.get('end'), 0, 86400*1000) - text = _string(cue.get('text'), 2000) - if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text): - raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。') - cues.append((start, end, html.escape(text, quote=False))) - parts, total = [], 0.0 - for source, start, end in normalized: - info = await inspect_media(source, self.settings) - if info['kind'] != 'video': - raise _invalid('编排片段必须是视频素材。') - end = info['duration_seconds'] if end is None else end - if start >= end or end > info['duration_seconds'] + .05 or end - start < .05: - raise _invalid('裁剪范围超出视频实际时长。') - total += end - start - parts.append((source, start, end - start, info.get('has_audio', False))) - if any(end > total + .05 for _, end, _ in cues): - raise _invalid('字幕超出成片时长。') - if audio and (await inspect_media(audio, self.settings))['kind'] != 'audio': - raise _invalid('成片音轨必须为音频素材。') - files = [] - async with asyncio.timeout(900): - for index, (source, start, duration, has_audio) in enumerate(parts): - target = work / f'clip-{index:03d}.mp4' - command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), '-i', str(source)] - if not has_audio: - command += ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000'] - command += ['-ss', f'{start:.6f}', '-t', f'{duration:.6f}', '-map', '0:v:0', '-map', - '0:a:0' if has_audio else '1:a:0', '-vf', - f'scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}', - '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p', - '-c:a', 'aac', '-ar', '48000', '-ac', '2', '-threads', '2', '-fs', str(self.settings.max_output_bytes), str(target)] - await run_process(command, timeout=min(600, max(60, duration * 5))) - files.append(target) - if sum(path.stat().st_size for path in files) >= self.settings.max_output_bytes: - raise ProviderError('output_too_large', '成片中间文件超出大小限制。') - listing = work / 'concat.txt' - listing.write_text(''.join(f"file '{path.name}'\n" for path in files), encoding='utf-8') - if cues: - def stamp(value): - milliseconds = round(value * 1000) - hours, milliseconds = divmod(milliseconds, 3600000) - minutes, milliseconds = divmod(milliseconds, 60000) - seconds, milliseconds = divmod(milliseconds, 1000) - return f'{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}' - (work / 'subtitles.srt').write_text(''.join(f'{index}\n{stamp(start)} --> {stamp(end)}\n{text}\n\n' - for index, (start, end, text) in enumerate(cues, 1)), encoding='utf-8') - target = work / 'composition.mp4' - command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', '-f', 'concat', '-safe', '1', '-i', listing.name] - if audio: - command += [*input_options(), '-i', str(audio)] - command += ['-map', '0:v:0', '-map', '1:a:0' if audio else '0:a:0'] - if cues: - command += ['-vf', 'subtitles=filename=subtitles.srt', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p'] - else: - command += ['-c:v', 'copy'] - command += ['-af', 'apad', '-t', f'{total:.6f}', '-c:a', 'aac', '-threads', '2', - '-movflags', '+faststart', '-fs', str(self.settings.max_output_bytes), str(target)] - await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work) - info = await inspect_media(target, self.settings) - if abs(info['duration_seconds'] - total) > max(.2, 2 / fps) or target.stat().st_size >= self.settings.max_output_bytes: - raise ProviderError('composition_incomplete', '成片未完整输出或超出大小限制。') - result = {'duration_seconds': info['duration_seconds'], 'width': width, 'height': height, - 'fps': fps, 'clip_count': len(parts), 'subtitle_count': len(cues)} - manifest = self._json_file(work, 'composition.json', result) - return CpuResult([target, manifest], result, {'provider': 'ffmpeg-cpu', 'audio': 'uploaded' if audio else 'original-or-silence'}) diff --git a/backend/app/quotas.py b/backend/app/quotas.py deleted file mode 100644 index f0a91de..0000000 --- a/backend/app/quotas.py +++ /dev/null @@ -1,72 +0,0 @@ -from sqlalchemy import select,func -from .models import Job,User,Asset,utcnow -from datetime import timedelta -import shutil -import asyncio -from .v2_models import QuotaReservation -from .errors import fail -CREATION_OPERATIONS={"jobs.create","workflow.run","batch.create"} - -async def reserve_budget(session,owner_id,operation,units=1,bytes_reserved=0,settings=None): - owner=await session.scalar(select(User).where(User.id==owner_id).with_for_update()) - if owner is None or owner.disabled:fail(403,"owner_disabled","Owner is disabled") - if operation in CREATION_OPERATIONS: - recent=await session.scalar(select(func.count()).select_from(QuotaReservation).where(QuotaReservation.owner_id==owner_id,QuotaReservation.operation.in_(CREATION_OPERATIONS),QuotaReservation.created_at>utcnow()-timedelta(minutes=1))) - if recent>=getattr(settings,"max_creation_commands_per_minute",6):fail(429,"quota_exceeded","Creation rate limit reached") - active=Job.state.notin_(["succeeded","failed","cancelled","timed_out"]) - own=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==owner_id,active)) - total=await session.scalar(select(func.count()).select_from(Job).where(active)) - if own+units>getattr(settings,"max_owner_jobs",500) or total+units>getattr(settings,"max_global_jobs",2000): - fail(429,"quota_exceeded","Unfinished task quota exceeded") - row=QuotaReservation(owner_id=owner_id,operation=operation,units=units,bytes_reserved=bytes_reserved) - session.add(row) - return row - -async def check_parent_capacity(session,settings,owner_id,kind): - from .v2_models import WorkflowRun,Batch - model,terminal,owner_limit,global_limit=(WorkflowRun,{'succeeded','cancelled','failed'},settings.max_owner_runs,settings.max_global_runs) if kind=='run' else (Batch,{'succeeded','cancelled','completed_with_errors'},settings.max_owner_batches,settings.max_global_batches) - active=model.state.notin_(terminal) - own=await session.scalar(select(func.count()).select_from(model).where(model.owner_id==owner_id,active)) - total=await session.scalar(select(func.count()).select_from(model).where(active)) - if own>=owner_limit or total>=global_limit: - fail(429,'quota_exceeded','Queued workflow or batch limit reached') - - -async def check_storage_budget(session,settings,owner_id,incoming_bytes=0,new_jobs=0,global_incoming_bytes=None): - size=await session.scalar(select(func.coalesce(func.sum(Asset.size_bytes),0)).where( - Asset.owner_id==owner_id,Asset.ready.is_(True)|Asset.deleted_at.is_(None))) - if size+incoming_bytes>getattr(settings,"max_owner_asset_bytes",100*1024**3):fail(429,"quota_exceeded","Owner asset quota exceeded") - if settings.mode=="production": - storage_incoming=incoming_bytes if global_incoming_bytes is None else global_incoming_bytes - # Account only this application's mounted assets/work directories. The - # independent model service owns its raw output retention policy. - def occupied(root): - total=0 - for path in root.rglob("*"): - if path.is_file() and not path.is_symlink(): - total+=path.stat().st_size - return total - tmp=(settings.asset_root.parent/"tmp").resolve() - if not tmp.is_relative_to(settings.workspace_root):raise ValueError("Temporary storage is outside workspace") - roots={settings.asset_root.resolve(),settings.job_work_root.resolve(),tmp} - # Avoid counting a nested custom mount twice. - roots=[root for root in roots if not any(root!=other and root.is_relative_to(other) for other in roots)] - actual=sum(await asyncio.gather(*(asyncio.to_thread(occupied,root) for root in roots))) - active=await session.scalar(select(func.count()).select_from(Job).where(Job.state.notin_(["succeeded","failed","cancelled","timed_out"]))) - reserved=(active+new_jobs)*settings.max_output_bytes*2 - if actual+reserved+storage_incoming>getattr(settings,"max_data_bytes",2*1024**4):fail(503,"storage_insufficient","Application output and temporary storage budget exceeded") - disk=shutil.disk_usage(settings.asset_root) - minimum=max(getattr(settings,"min_free_bytes",50*1024**3),int(disk.total*.05)) - if disk.free-reserved-storage_incominggetattr(settings,"max_owner_asset_bytes",100*1024**3):raise AssetBudgetError() diff --git a/backend/app/resource_policy.py b/backend/app/resource_policy.py deleted file mode 100644 index 00b7278..0000000 --- a/backend/app/resource_policy.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Admission is evaluated at phase boundaries. A closing window never cancels work.""" -from datetime import datetime,timezone,timedelta -from .runtime_policy import read_runtime_policy -# fixed UTC+8 has no DST; avoids depending on OS IANA data on Windows. -SHANGHAI=timezone(timedelta(hours=8)) - -def execution_policy(now=None, *, settings=None): - policy=read_runtime_policy(settings) - now=now or datetime.now(timezone.utc) - if now.tzinfo is None: now=now.replace(tzinfo=timezone.utc) - local=now.astimezone(SHANGHAI) - opened=local.hour>=21 or local.hour<8 - next_at=local.replace(hour=21,minute=0,second=0,microsecond=0) - if local.hour>=21: next_at+=timedelta(days=1) - enabled=policy["batch_window_enabled"] - return {"timezone":"Asia/Shanghai","start":"21:00","end":"08:00", - "batch_window_enabled":enabled,"configuration_error":policy["configuration_error"], - "batch_open":not policy["configuration_error"] and (not enabled or opened), - "next_batch_at":next_at.astimezone(timezone.utc).isoformat() if enabled and not policy["configuration_error"] else None, - "close_behavior":"finish_current"} - -def admits(job,now=None, *, settings=None): - if job.cancel_requested or job.desired_state!="run": return False - if set(job.hold_reasons or [])-{"window"}: return False - if job.execution_mode!="batch":return True - policy=read_runtime_policy(settings) - if policy["configuration_error"]:return False - return not policy["batch_window_enabled"] or execution_policy(now)["batch_open"] - -def resource_plan(task_type,input_kind=None): - if task_type=="audio.transcribe": return [("extract_audio","cpu_media"),("transcribe","new_gpu")] if input_kind=="video" else [("transcribe","new_gpu")] - if task_type=="media.structure": return [("sample_frames","cpu_media"),("describe_frames","qwen_http")] if input_kind=="video" else [("describe_frames","qwen_http")] - if task_type=="math.solve":return [("solve","qwen_http")] - return [("execute","new_gpu" if task_type in {"image.generate","video.generate","defect.generate"} else "cpu_media")] diff --git a/backend/app/retention.py b/backend/app/retention.py deleted file mode 100644 index 6abb8f9..0000000 --- a/backend/app/retention.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Conservative first-release GC: inventory only, then explicit opt-in deletion. -Unknown/untracked files are never deleted. Asset references protect live snapshots. -""" -from datetime import timedelta -from sqlalchemy import select -from .models import Asset,JobAsset,utcnow -from .v2_models import AssetReference,SharedAsset -from .assets import confined - -async def collect_garbage(db,settings,dry_run=True,grace_days=14): - report={"dry_run":dry_run,"candidates":[],"deleted":[],"protected":[]} - # Hold the database unit lock across reference recheck and unlink to exclude - # new snapshot references. This service is only called in maintenance. - async with db.session() as session: - rows=(await session.scalars(select(Asset).where(Asset.deleted_at settings.max_output_bytes: + raise ValueError( + "Output exceeds reserved asset limit; retained for operator reconciliation" + ) + await validate_workflow_output(job, source, settings, run_kind=run_kind) + directory = confined(settings.asset_root, Path(job.owner_id) / asset_id) + directory.mkdir(parents=True) + suffix = ( + source.suffix.lower() + if re.fullmatch("\\.[a-z0-9]{1,10}", source.suffix.lower()) + else ".bin" + ) + destination = directory / ("original" + suffix) + + def copy(): + with safe_file(settings.job_work_root, source) as src, destination.open("xb") as dst: + shutil.copyfileobj(src, dst, 1024 * 1024) + + try: + await file_thread(copy) + asset = await build_asset( + settings, + job.owner_id, + asset_id, + destination, + source.name, + origin="generated", + source_job_id=job.id, + source_upstream_id=job.upstream_id, + source_output_index=index, + ready=False, + ) + async with db.session() as session: + current = await session.scalar( + select(Job).where( + Job.id == job.id, Job.owner_id == job.owner_id, Job.deleted_at.is_(None) + ) + ) + if current is None: + raise ValueError("Archived job cannot import output") + if execution_fence: + from app.services.orchestration.executions import gpu_publication_matches + + current = await session.get(Job, job.id) + if not await gpu_publication_matches(session, current, execution_fence): + raise ValueError("Stale GPU result import") + from app.services.quotas import enforce_owner_asset_budget + + await enforce_owner_asset_budget(session, settings, job.owner_id, asset.size_bytes) + session.add(asset) + await session.flush() + from app.services.folders import add_asset_folder + + await add_asset_folder(session, asset, current.output_folder_id, allow_missing=True) + if execution_fence: + from app.models import AssetReference + + session.add( + AssetReference( + owner_id=job.owner_id, + asset_id=asset.id, + ref_kind="execution", + ref_id=execution_fence["execution_id"], + ) + ) + await session.commit() + return asset + except BaseException: + raise + + +async def upload( + runtime, + file=None, + name: str | None = None, + actor: Actor = None, + content_length="0", + folder_id=None, +): + from app.services.user_deletion import owner_upload + + try: + async with owner_upload(runtime, actor.id): + return await _upload(runtime, file, name, actor, content_length, folder_id) + finally: + await file.close() + + +async def _upload( + runtime, + file=None, + name: str | None = None, + actor: Actor = None, + content_length="0", + folder_id=None, +): + settings = runtime.settings + from app.core.maintenance import require_writable + from app.services.quotas import check_storage_budget + + require_writable(settings) + async with runtime.db.session() as session: + from app.services.folders import owned_folder + + if folder_id: + await owned_folder(session, folder_id, actor.id, lock=True) + await check_storage_budget( + session, + settings, + actor.id, + min( + max(0, int(content_length)) + if content_length.isdigit() + else settings.max_upload_bytes, + settings.max_upload_bytes, + ), + ) + asset_id = new_id() + directory = confined(settings.asset_root, Path(actor.id) / asset_id) + directory.mkdir(parents=True) + original_name = (file.filename or "素材").replace("\\", "/").rsplit("/", 1)[-1] + suffix = Path(original_name).suffix.lower() + if not re.fullmatch("\\.[a-z0-9]{1,10}", suffix): + suffix = ".bin" + path, size = (directory / ("original" + suffix), 0) + commit_started = False + try: + with path.open("xb") as output: + while chunk := (await file.read(1024 * 1024)): + size += len(chunk) + if size > settings.max_upload_bytes: + fail(413, "upload_too_large", "文件超过上传大小限制") + output.write(chunk) + if not size: + fail(422, "empty_upload", "文件不能为空") + asset = await build_asset( + settings, actor.id, asset_id, path, name or original_name or "素材", origin="upload" + ) + if asset.kind not in {"image", "video", "audio"}: + fail(422, "unsupported_upload", "上传仅支持图片、视频或音频") + async with runtime.db.session() as session: + from app.services.quotas import enforce_owner_asset_budget + + owner = await session.scalar(select(User).where(User.id == actor.id).with_for_update()) + if owner is None or owner.disabled: + fail(403, "owner_disabled", "账号已停用,上传未保存") + await enforce_owner_asset_budget(session, settings, actor.id, asset.size_bytes) + session.add(asset) + await session.flush() + from app.services.folders import assign_asset_folders + + await assign_asset_folders(session, asset, [folder_id] if folder_id else []) + commit_started = True + emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)}) + await session.commit() + return asset_dto(asset) + except BaseException as exc: + if not commit_started: + shutil.rmtree(directory, ignore_errors=True) + if hasattr(exc, "code") and hasattr(exc, "message"): + fail(422, exc.code, exc.message) + raise + finally: + await file.close() + + +async def list_assets( + runtime, + page: int = 1, + page_size: int = 24, + kind: str = "", + q: str = "", + tag: str = "", + favorite: bool | None = None, + origin: str = "", + actor: Actor = None, + folder_id: str = "", +): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with runtime.db.session() as session: + query = select(Asset).where( + Asset.owner_id == actor.id, + Asset.library_scope == "private", + Asset.deleted_at.is_(None), + Asset.ready.is_(True), + ) + from app.services.folders import folder_filter + + query = query.where(await folder_filter(session, Asset, actor.id, folder_id)) + if kind: + query = query.where(Asset.kind == kind) + if q: + query = query.where(Asset.name.contains(q[:255], autoescape=True)) + from app.models import AssetTag + + if favorite is not None: + query = query.where(Asset.favorite == favorite) + if origin: + query = query.where(Asset.origin == origin) + if tag: + query = query.where( + Asset.id.in_( + select(AssetTag.asset_id).where( + AssetTag.owner_id == actor.id, AssetTag.tag == tag + ) + ) + ) + total = await session.scalar(select(func.count()).select_from(query.subquery())) + rows = ( + await session.scalars( + query.order_by(Asset.created_at.desc(), Asset.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + return { + "items": [asset_dto(a) for a in rows], + "total": total, + "page": page, + "page_size": page_size, + } + + +async def get_asset(asset_id: str, runtime, actor: Actor = None): + async with runtime.db.session() as session: + return asset_dto(await owned_asset(session, asset_id, actor.id)) + + +async def patch_asset(asset_id: str, body: AssetPatch, runtime, actor: Actor = None): + async with runtime.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + if body.folder_ids is not None: + from app.services.folders import assign_asset_folders + + await assign_asset_folders(session, asset, body.folder_ids) + if body.name is not None: + asset.name = body.name.strip() or asset.name + if body.tags is not None: + if any((not tag.strip() or len(tag) > 64 for tag in body.tags)): + fail(422, "invalid_tag", "标签须为 1–64 个字符") + asset.tags = list(dict.fromkeys((tag.strip() for tag in body.tags))) + from app.models import AssetTag + + await session.execute(delete(AssetTag).where(AssetTag.asset_id == asset.id)) + session.add_all( + (AssetTag(owner_id=actor.id, asset_id=asset.id, tag=tag) for tag in asset.tags) + ) + if body.favorite is not None: + asset.favorite = body.favorite + emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)}) + await touch_source_job(session, asset) + await session.commit() + return asset_dto(asset) + + +async def delete_asset(asset_id: str, runtime, actor: Actor = None): + async with runtime.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id, include_deleted=True) + from app.services.asset_deletion import remove_asset + from app.models import Submission + + await remove_asset(session, runtime.settings, asset) + await session.execute( + update(Submission) + .where( + Submission.owner_id == actor.id, + Submission.status != "purged", + Submission.resource_json["asset_id"].as_string() == asset.id, + ) + .values(status="purged") + ) + emit_asset(session, actor.id, "asset.deleted", {"id": asset.id}) + await touch_source_job(session, asset) + await session.commit() + return None diff --git a/backend/app/services/auth.py b/backend/app/services/auth.py new file mode 100644 index 0000000..4768f6b --- /dev/null +++ b/backend/app/services/auth.py @@ -0,0 +1,271 @@ +import asyncio +from datetime import timedelta +import re +import secrets +from sqlalchemy import delete, select, func, or_ +from sqlalchemy.exc import IntegrityError +from app.core.errors import fail +from app.models import Session, User, utcnow +from app.schemas.auth import Login, CreateUser, UserPatch, PasswordChange, UsernameChange +from app.core.security import Actor, token_hash, hash_password, verify_password, validate_password + + +def user_dto(user): + return { + "id": user.id, + "username": user.username, + "display_name": user.display_name, + "role": user.role, + "disabled": user.disabled, + "must_change_password": user.must_change_password, + } + + +def validated_username(username): + username = username.strip().lower() + if not re.fullmatch("[a-z0-9_.-]{3,64}", username): + fail(422, "invalid_username", "用户名须为 3–64 位字母、数字、点、横线或下划线") + return username + + +async def bootstrap_admin(db, settings): + if not settings.admin_username and (not settings.admin_password): + return + if not settings.admin_username or not settings.admin_password: + raise ValueError("Both ADMIN_USERNAME and ADMIN_PASSWORD are required for bootstrap") + validate_password(settings.admin_password, minimum=6) + async with db.session() as session: + # 管理员可以改名;停用管理员也不能触发旧账号重建或恢复初始密码。 + # 同时保留配置同名普通用户的保护,不覆盖原账号或把它提升为管理员。 + exists = await session.scalar( + select(User.id) + .where( + or_(User.role == "admin", User.username == settings.admin_username.strip().lower()) + ) + .limit(1) + ) + if exists is not None: + return + session.add( + User( + username=settings.admin_username.strip().lower(), + display_name=settings.admin_display_name, + role="admin", + must_change_password=True, + password_hash=await asyncio.to_thread(hash_password, settings.admin_password), + ) + ) + await session.commit() + + +async def login(body: Login, runtime): + async with runtime.db.session() as session: + user = await session.scalar( + select(User).where(User.username == body.username.strip().lower()) + ) + valid = await asyncio.to_thread( + verify_password, body.password, user.password_hash if user else "" + ) + if not valid or user is None or user.disabled: + fail(401, "invalid_credentials", "用户名或密码不正确") + token, csrf = (secrets.token_urlsafe(32), secrets.token_urlsafe(32)) + settings = runtime.settings + session.add( + Session( + token_hash=token_hash(token), + user_id=user.id, + csrf_token=csrf, + expires_at=utcnow() + timedelta(hours=settings.session_hours), + ) + ) + await session.commit() + return {"user": user_dto(user), "csrf_token": csrf}, token + + +async def me(actor: Actor = None): + return { + "user": { + "id": actor.id, + "username": actor.username, + "display_name": actor.display_name, + "role": actor.role, + "must_change_password": actor.must_change_password, + }, + "csrf_token": actor.csrf_token, + } + + +async def logout(runtime, actor: Actor = None): + async with runtime.db.session() as session: + await session.execute(delete(Session).where(Session.token_hash == actor.token_hash)) + await session.commit() + return None + + +async def require_session_user(session, actor): + if actor.auth_kind != "session": + fail(403, "session_required", "此操作需要登录会话") + # 鉴权依赖与业务事务之间可能发生停用、改密或重新登录,写入前复核真实会话。 + user = await session.scalar( + select(User) + .join(Session, Session.user_id == User.id) + .where( + User.id == actor.id, + User.disabled.is_(False), + Session.token_hash == actor.token_hash, + Session.expires_at > utcnow(), + ) + .with_for_update() + ) + if user is None: + fail(401, "session_expired", "登录已失效,请重新登录") + return user + + +async def require_admin_session(session, actor): + user = await require_session_user(session, actor) + if user.role != "admin": + fail(403, "admin_required", "此操作仅限管理员") + return user + + +async def create_user(body: CreateUser, runtime, actor: Actor = None): + if actor.role != "admin" or actor.auth_kind != "session": + fail(403, "admin_required", "此操作仅限管理员") + username = validated_username(body.username) + validate_password(body.password, minimum=6) + async with runtime.db.session() as session: + await require_admin_session(session, actor) + user = User( + username=username, + display_name=body.display_name.strip() or username, + password_hash=await asyncio.to_thread(hash_password, body.password), + ) + session.add(user) + try: + await session.commit() + except IntegrityError: + fail(409, "username_exists", "用户名已存在") + return user_dto(user) + + +async def list_users(runtime, page: int = 1, page_size: int = 24, actor: Actor = None): + if actor.role != "admin" or actor.auth_kind != "session": + fail(403, "admin_required", "Administrator session required") + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "Invalid page") + async with runtime.db.session() as session: + await require_admin_session(session, actor) + total = await session.scalar(select(func.count()).select_from(User)) + rows = ( + await session.scalars( + select(User) + .order_by(User.created_at, User.id) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + return { + "items": [user_dto(u) for u in rows], + "total": total, + "page": page, + "page_size": page_size, + } + + +async def patch_user(user_id: str, body: UserPatch, runtime, actor: Actor = None): + if actor.role != "admin" or actor.auth_kind != "session": + fail(403, "admin_required", "此操作仅限管理员") + from app.models import Job, WorkflowRun, Batch + from app.domain.tasks import TERMINAL, RUN_TERMINAL + from app.services.events import emit_job + from app.services.workflows import emit_run + from app.services.batches import emit_batch + + async with runtime.db.session() as session: + await require_admin_session(session, actor) + user = await session.scalar(select(User).where(User.id == user_id).with_for_update()) + if not user: + fail(404, "user_not_found", "用户不存在") + if body.disabled and user_id == actor.id: + fail(409, "self_disable", "不能禁用当前登录账号") + if body.disabled and user.role == "admin" and not user.disabled: + count = await session.scalar( + select(func.count()) + .select_from(User) + .where(User.role == "admin", User.disabled.is_(False)) + ) + if count <= 1: + fail(409, "last_admin", "不能禁用最后一个管理员") + if body.display_name is not None: + user.display_name = body.display_name.strip() or user.display_name + if body.disabled is not None: + user.disabled = body.disabled + if body.disabled: + await session.execute(delete(Session).where(Session.user_id == user_id)) + # 禁用是可恢复的:令牌由鉴权层的 disabled 检查阻断,不能在这里永久撤销。 + for model, terminal, emit in ( + (Job, TERMINAL, emit_job), + (WorkflowRun, RUN_TERMINAL, emit_run), + (Batch, {"succeeded", "cancelled", "completed_with_errors"}, emit_batch), + ): + query = select(model).where(model.owner_id == user_id, model.deleted_at.is_(None)) + if body.disabled: + query = query.where(model.state.notin_(terminal)) + for record in (await session.scalars(query)).all(): + reasons = set(record.hold_reasons or []) + updated = ( + reasons | {"admin_suspend"} + if body.disabled + else reasons - {"admin_suspend"} + ) + if reasons == updated: + continue + # 只恢复管理员禁用引入的暂停,保留用户手动暂停、批量时段等约束。 + record.hold_reasons = sorted(updated) + if ( + not body.disabled + and isinstance(record, WorkflowRun) + and (record.error_json or {}).get("code") == "owner_disabled" + ): + record.error_json = None + await emit(session, record) + await session.commit() + result = user_dto(user) + runtime.coordinator.wake() + return result + + +async def change_password(body: PasswordChange, runtime, actor: Actor = None): + if actor.auth_kind != "session": + fail(403, "session_required", "Session required") + validate_password(body.new_password) + async with runtime.db.session() as session: + user = await require_session_user(session, actor) + if not await asyncio.to_thread(verify_password, body.current_password, user.password_hash): + fail(403, "invalid_password", "当前密码不正确") + user.password_hash = await asyncio.to_thread(hash_password, body.new_password) + user.must_change_password = False + await session.execute(delete(Session).where(Session.user_id == actor.id)) + await session.commit() + return {"requires_relogin": True} + + +async def change_username(body: UsernameChange, runtime, actor: Actor = None): + if actor.auth_kind != "session": + fail(403, "session_required", "此操作需要登录会话") + username = validated_username(body.username) + async with runtime.db.session() as session: + user = await require_session_user(session, actor) + if not await asyncio.to_thread(verify_password, body.current_password, user.password_hash): + fail(403, "invalid_password", "当前密码不正确") + if username == user.username: + return user_dto(user) + # 资源与会话绑定稳定的用户 ID;改名仅更新用户名,唯一约束处理并发占名。 + user.username = username + try: + await session.commit() + except IntegrityError: + await session.rollback() + fail(409, "username_exists", "用户名已存在") + return user_dto(user) diff --git a/backend/app/services/batches.py b/backend/app/services/batches.py new file mode 100644 index 0000000..baa4b38 --- /dev/null +++ b/backend/app/services/batches.py @@ -0,0 +1,367 @@ +from app.services.orchestration.batch_holds import member_holds +from app.services.snapshots import snapshot_batch +from fastapi import HTTPException +from sqlalchemy import select +from app.core.security import Actor +from app.core.errors import fail +from app.services.events import emit_asset, emit_job +from app.schemas.jobs import Submit +from app.services.jobs import create_jobs +from app.domain.tasks import TERMINAL +from app.models import Job, utcnow +from app.services.submissions import accept_submission, request_payload +from app.models import Batch, BatchItem, WorkflowDraft, WorkflowRun, Execution +from app.services.snapshots import owned, page_rows +from app.services.workflows import ( + create_run, + control_run, + wake, + RUN_TERMINAL, + check_batch_capability, + emit_run, +) +from app.schemas.batches import BatchCreate, BatchControl + +"Persistent mixed workflow/job batches with independently eligible members." + + +async def emit_batch(s, b): + if b.deleted_at is not None: + return + b.version += 1 + snap = await snapshot_batch(s, b.owner_id, b.id) + emit_asset(s, b.owner_id, "batch.updated", {"batch": snap["batch"], "items": snap["items"]}) + + +async def active_member(s, items): + eligible = [ + i + for i in items + if i.state not in {"succeeded", "cancelled", "failed", "timed_out", "blocked"} + ] + for item in eligible: + if item.target_kind == "run": + target = await s.get(WorkflowRun, item.target_id) + if ( + target + and target.deleted_at is None + and ("batch_wait" not in (target.hold_reasons or [])) + ): + return item + else: + jobs = ( + await s.scalars( + select(Job).where( + Job.batch_id == item.batch_id, + Job.batch_item_index == item.item_index, + Job.state.not_in(TERMINAL), + ) + ) + ).all() + if any(("batch_wait" not in (j.hold_reasons or []) for j in jobs)): + return item + return eligible[0] if eligible else None + + +async def advance_batches(s, settings): + batches = ( + await s.scalars( + select(Batch) + .where( + Batch.deleted_at.is_(None), + Batch.state.not_in({"succeeded", "cancelled", "completed_with_errors"}), + ) + .order_by(Batch.created_at, Batch.id) + .with_for_update() + ) + ).all() + for b in batches: + if b.spec_snapshot.get("kind") == "story_candidates": + continue + items = ( + await s.scalars( + select(BatchItem).where(BatchItem.batch_id == b.id).order_by(BatchItem.item_index) + ) + ).all() + before = (b.state, tuple((i.state for i in items))) + for item in items: + if item.target_kind == "run": + target = await s.get(WorkflowRun, item.target_id) + item.state = target.state + else: + jobs = ( + await s.scalars( + select(Job).where( + Job.batch_id == b.id, Job.batch_item_index == item.item_index + ) + ) + ).all() + if all((j.state in TERMINAL for j in jobs)): + item.state = ( + "succeeded" + if all((j.state == "succeeded" for j in jobs)) + else "cancelled" + if all((j.state == "cancelled" for j in jobs)) + else "failed" + ) + elif any((j.state in {"running", "collecting", "cancelling"} for j in jobs)): + item.state = "running" + else: + item.state = "queued" + if item.state in {"failed", "cancelled", "timed_out", "blocked"}: + target_jobs = ( + select(Job.id).where(Job.run_id == item.target_id) + if item.target_kind == "run" + else select(Job.id).where( + Job.batch_id == b.id, Job.batch_item_index == item.item_index + ) + ) + pending = await s.scalar( + select(Execution.id).where( + Execution.job_id.in_(target_jobs), + Execution.state.not_in({"exited", "results_ready"}), + ) + ) + if pending: + item.state = "cleanup_pending" + active = await active_member(s, items) + for item in items: + if item.target_kind == "run": + target = await s.get(WorkflowRun, item.target_id) + holds = sorted(member_holds(target.hold_reasons, b, False)) + if target.hold_reasons != holds: + target.hold_reasons = holds + await emit_run(s, target) + jobs = ( + await s.scalars( + select(Job).where(Job.run_id == item.target_id, Job.state.not_in(TERMINAL)) + ) + ).all() + else: + jobs = ( + await s.scalars( + select(Job).where( + Job.batch_id == b.id, + Job.batch_item_index == item.item_index, + Job.state.not_in(TERMINAL), + ) + ) + ).all() + for j in jobs: + holds = member_holds(j.hold_reasons, b, False) + if item.target_kind == "run": + holds -= {"quota", "storage"} + holds |= set(target.hold_reasons or []) - {"quota", "storage"} + holds = sorted(holds) + if j.hold_reasons != holds: + j.hold_reasons = holds + await emit_job(s, j) + if all((i.state in RUN_TERMINAL | {"timed_out"} for i in items)): + b.state = ( + "cancelled" + if b.desired_state == "cancel" + else "succeeded" + if all((i.state == "succeeded" for i in items)) + else "completed_with_errors" + ) + b.finished_at = utcnow() + elif b.desired_state == "cancel": + b.state = "cancelling" + elif b.desired_state == "pause" or b.hold_reasons: + b.state = "paused" + elif not active: + b.state = "blocked" + else: + b.state = "running" + if before != (b.state, tuple((i.state for i in items))): + await emit_batch(s, b) + + +async def post_batch( + body: BatchCreate, runtime, idempotency_key: str | None = None, actor: Actor = None +): + from app.core.maintenance import require_writable + + require_writable(runtime.settings) + capability_error = None + try: + await check_batch_capability( + runtime, [i.task_type if i.kind == "job" else "video.generate" for i in body.items] + ) + except HTTPException as exc: + capability_error = exc + async with runtime.db.session() as s: + sub = await accept_submission( + s, actor.id, "batch.create", idempotency_key, 2, request_payload(body) + ) + if sub.resource_json: + b = await owned(s, Batch, sub.resource_json["batch_id"], actor.id) + else: + if capability_error: + raise capability_error + from app.services.quotas import reserve_budget, check_parent_capacity + + await reserve_budget(s, actor.id, "batch.create", units=0, settings=runtime.settings) + await check_parent_capacity(s, runtime.settings, actor.id, "batch") + b = Batch(owner_id=actor.id, name=body.name, spec_snapshot=request_payload(body)) + s.add(b) + await s.flush() + frozen_drafts = {} + for item in body.items: + if item.kind == "workflow": + d = await owned(s, WorkflowDraft, item.draft_id, actor.id) + if d.version != item.expected_version or d.revision != item.draft_revision: + fail(409, "draft_version_conflict", "Draft version conflict.") + frozen_drafts[d.id] = d + for idx, item in enumerate(body.items): + if item.kind == "workflow": + r = await create_run( + s, + actor.id, + item.draft_id, + frozen_drafts[item.draft_id].version, + item.draft_revision, + "batch", + batch_id=b.id, + batch_item_index=idx, + settings=runtime.settings, + output_folder_id=item.output_folder_id + if "output_folder_id" in item.model_fields_set + else ..., + ) + kind, target = ("run", r.id) + else: + jobs = await create_jobs( + s, + Submit( + task_type=item.task_type, + input=item.input, + parameters=item.parameters, + count=item.count, + execution_mode="batch", + **{ + field: getattr(item, field) + for field in ("folder_id", "output_folder_id") + if field in item.model_fields_set + }, + ), + actor, + runtime.settings, + key=f"batch:{b.id}:{idx}", + internal=True, + ) + for j in jobs: + j.batch_id = b.id + j.batch_item_index = idx + await emit_job(s, j) + kind, target = ("job", jobs[0].id) + s.add( + BatchItem( + batch_id=b.id, + item_index=idx, + target_kind=kind, + target_id=target, + spec_json=request_payload(item), + ) + ) + sub.resource_json = {"batch_id": b.id} + await emit_batch(s, b) + await s.commit() + snap = await snapshot_batch(s, actor.id, b.id) + wake(runtime) + return snap + + +async def list_batches(runtime, page: int = 1, page_size: int = 24, actor: Actor = None): + async with runtime.db.session() as s: + rows, data = await page_rows(s, Batch, actor, page, page_size) + return {**data, "items": [(await snapshot_batch(s, actor.id, b.id))["batch"] for b in rows]} + + +async def get_batch(id: str, runtime, actor: Actor = None): + async with runtime.db.session() as s: + return await snapshot_batch(s, actor.id, id) + + +async def delete_batch(id: str, runtime, if_match: str | None = None, actor: Actor = None): + from app.services.deletions import archive_records + + async with runtime.db.session() as s: + b = await s.scalar(select(Batch).where(Batch.id == id, Batch.owner_id == actor.id)) + is_story = b and b.spec_snapshot.get("kind") == "story_candidates" + if is_story: + from app.services.stories.deletion import delete_candidate_batch + + return await delete_candidate_batch(runtime, actor, id, if_match) + async with runtime.db.session() as s: + result = await archive_records(s, Batch, id, actor.id, if_match) + await s.commit() + return result + + +async def batch_control( + id: str, body: BatchControl, runtime, idempotency_key: str | None = None, actor: Actor = None +): + async with runtime.db.session() as s: + sub = await accept_submission( + s, actor.id, "batch.control", idempotency_key, 2, {"batch_id": id, **body.model_dump()} + ) + b = await owned(s, Batch, id, actor.id) + if not sub.resource_json: + if body.expected_version is not None and b.version != body.expected_version: + fail(409, "batch_version_conflict", "批次版本冲突") + if b.state not in {"succeeded", "cancelled", "completed_with_errors"}: + if b.desired_state == "cancel" and body.desired_state != "cancel": + fail(409, "batch_cancelled", "取消不可逆") + b.desired_state = body.desired_state + runs = ( + await s.scalars(select(WorkflowRun).where(WorkflowRun.batch_id == b.id)) + ).all() + for r in runs: + if body.desired_state == "cancel": + await control_run(s, r, "cancel") + else: + holds = set(r.hold_reasons or []) + if body.desired_state == "pause": + holds.add("batch_pause") + else: + holds.discard("batch_pause") + r.hold_reasons = sorted(holds) + jobs = ( + await s.scalars( + select(Job).where(Job.batch_id == b.id, Job.state.not_in(TERMINAL)) + ) + ).all() + for j in jobs: + holds = set(j.hold_reasons or []) + if body.desired_state == "pause": + holds.add("batch_pause") + else: + holds.discard("batch_pause") + j.hold_reasons = sorted(holds) + if body.desired_state == "cancel": + j.desired_state = "cancel" + j.cancel_requested = True + if ( + not j.upstream_id + and (not j.upstream_payload) + and (j.phase not in {"cpu_running", "preparing"}) + ): + j.state = "cancelled" + j.phase = "cancelled" + j.finished_at = utcnow() + elif j.state != "collecting": + j.state = "cancelling" + j.phase = "cancellation_pending" + await emit_job(s, j) + await advance_batches(s, runtime.settings) + if b.spec_snapshot.get("kind") == "story_candidates": + from app.services.stories.candidates import advance_candidate_batches + + await advance_candidate_batches(s, runtime.settings) + await emit_batch(s, b) + sub.resource_json = {"batch_id": id} + await s.commit() + snap = await snapshot_batch(s, actor.id, id) + wake(runtime) + return snap diff --git a/backend/app/services/deletions.py b/backend/app/services/deletions.py new file mode 100644 index 0000000..d5e3b88 --- /dev/null +++ b/backend/app/services/deletions.py @@ -0,0 +1,214 @@ +"""Transactional archival of owner records; execution and asset audit rows survive.""" + +from sqlalchemy import delete, or_, select +from app.core.errors import fail +from app.services.events import emit_asset +from app.models import Job, JobAsset, utcnow +from app.models import ( + AssetReference, + Batch, + Execution, + Submission, + WorkflowDraft, + WorkflowRun, + WorkflowStep, +) + +JOB_TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"} +RUN_TERMINAL = {"succeeded", "failed", "cancelled"} +BATCH_TERMINAL = {"succeeded", "cancelled", "completed_with_errors"} +MODEL_KEYS = { + Job: "job_ids", + WorkflowRun: "run_ids", + WorkflowDraft: "draft_ids", + Batch: "batch_ids", +} +EVENT_NAMES = { + Job: "job.deleted", + WorkflowRun: "workflow.deleted", + WorkflowDraft: "draft.deleted", + Batch: "batch.deleted", +} + + +# 历史归档与素材物理删除是两条流程:保留生成素材,只在整棵执行树清理确认后释放引用。 +async def archive_records(session, model, record_id, owner_id, if_match=None): + """Validate the complete tree before changing anything in the caller's unit.""" + root = await session.scalar( + select(model).where(model.id == record_id, model.owner_id == owner_id).with_for_update() + ) + if root is None: + fail(404, "resource_not_found", "记录不存在") + groups = {Job: [], WorkflowRun: [], WorkflowDraft: [], Batch: []} + groups[model] = [root] + if model is WorkflowDraft: + groups[WorkflowRun] = list( + ( + await session.scalars( + select(WorkflowRun) + .where(WorkflowRun.owner_id == owner_id, WorkflowRun.draft_id == root.id) + .order_by(WorkflowRun.created_at, WorkflowRun.id) + .with_for_update() + ) + ).all() + ) + elif model is Batch: + groups[WorkflowRun] = list( + ( + await session.scalars( + select(WorkflowRun) + .where(WorkflowRun.owner_id == owner_id, WorkflowRun.batch_id == root.id) + .order_by(WorkflowRun.created_at, WorkflowRun.id) + .with_for_update() + ) + ).all() + ) + run_ids = [run.id for run in groups[WorkflowRun]] + if model is not Job: + child_filter = Job.run_id.in_(run_ids) + if model is WorkflowDraft and root.kind == "story_v3": + from app.models import ShotCandidate + + candidate_jobs = select(ShotCandidate.job_id).where( + ShotCandidate.draft_id == root.id, ShotCandidate.owner_id == owner_id + ) + child_filter = or_(child_filter, Job.id.in_(candidate_jobs)) + if model is Batch: + child_filter = or_(child_filter, Job.batch_id == root.id) + groups[Job] = list( + ( + await session.scalars( + select(Job) + .where(Job.owner_id == owner_id, child_filter) + .order_by(Job.created_at, Job.id) + .with_for_update() + ) + ).all() + ) + result = { + "deleted": {MODEL_KEYS[kind]: [row.id for row in rows] for kind, rows in groups.items()} + } + if root.deleted_at is not None: + return result + if if_match is not None and if_match.strip('"') != str(root.version): + fail(409, "version_conflict", "记录已更新,请刷新后重试删除") + if model is Job and (root.run_id or root.batch_id): + fail(409, "parent_control_required", "请在所属工作流或批次中删除此任务") + if model is WorkflowRun and root.batch_id: + fail(409, "parent_control_required", "请删除所属批次") + if model is WorkflowDraft: + batch_ids = { + run.batch_id for run in groups[WorkflowRun] if run.batch_id and run.deleted_at is None + } + if batch_ids and await session.scalar( + select(Batch.id) + .where(Batch.id.in_(batch_ids), Batch.owner_id == owner_id, Batch.deleted_at.is_(None)) + .limit(1) + ): + fail(409, "parent_control_required", "草稿仍有关联批次,请先删除所属批次") + for kind, terminal in ( + (Job, JOB_TERMINAL), + (WorkflowRun, RUN_TERMINAL), + (Batch, BATCH_TERMINAL), + ): + if any((row.deleted_at is None and row.state not in terminal for row in groups[kind])): + fail(409, "deletion_requires_terminal", "请先取消活动任务,等待执行结束后再删除") + job_ids = [job.id for job in groups[Job]] + executions = ( + list( + ( + await session.scalars( + select(Execution).where(Execution.job_id.in_(job_ids)).with_for_update() + ) + ).all() + ) + if job_ids + else [] + ) + if any((execution.state not in {"exited", "results_ready"} for execution in executions)): + fail(409, "cleanup_pending", "执行尚未确认清理,请等待清理完成后再删除") + if job_ids: + in_use = await session.scalar( + select(WorkflowRun.id) + .join(WorkflowStep, WorkflowStep.run_id == WorkflowRun.id) + .where( + WorkflowRun.deleted_at.is_(None), + WorkflowRun.id.not_in(run_ids), + WorkflowStep.selected_job_id.in_(job_ids), + ) + .limit(1) + ) + if in_use: + fail(409, "resource_in_use", "任务产物仍被其他工作流运行复用,请先删除该运行") + now = utcnow() + for kind in (Job, WorkflowRun, WorkflowDraft, Batch): + for row in groups[kind]: + if row.deleted_at is not None: + continue + row.deleted_at = now + row.version += 1 + emit_asset(session, owner_id, EVENT_NAMES[kind], {"id": row.id, "version": row.version}) + if run_ids: + drafts = ( + await session.scalars( + select(WorkflowDraft) + .where( + WorkflowDraft.owner_id == owner_id, + WorkflowDraft.current_run_id.in_(run_ids), + WorkflowDraft.deleted_at.is_(None), + ) + .with_for_update() + ) + ).all() + from app.services.snapshots import draft_dto + + for draft in drafts: + draft.current_run_id = None + draft.version += 1 + draft.updated_at = now + emit_asset(session, owner_id, "draft.updated", {"draft": draft_dto(draft)}) + for draft in groups[WorkflowDraft]: + draft.current_run_id = None + draft.updated_at = now + if job_ids: + await session.execute(delete(JobAsset).where(JobAsset.job_id.in_(job_ids))) + refs = [] + if run_ids: + refs.append((AssetReference.ref_kind == "run") & AssetReference.ref_id.in_(run_ids)) + if groups[WorkflowDraft]: + refs.append( + (AssetReference.ref_kind == "draft") + & AssetReference.ref_id.in_([d.id for d in groups[WorkflowDraft]]) + ) + if executions: + refs.append( + (AssetReference.ref_kind == "execution") + & AssetReference.ref_id.in_([e.id for e in executions]) + ) + if refs: + await session.execute( + delete(AssetReference).where(AssetReference.owner_id == owner_id, or_(*refs)) + ) + archived_ids = {row.id for rows in groups.values() for row in rows} + submissions = ( + await session.scalars( + select(Submission) + .where(Submission.owner_id == owner_id, Submission.status != "purged") + .with_for_update() + ) + ).all() + for submission in submissions: + if references_any(submission.resource_json, archived_ids): + submission.status = "purged" + await session.flush() + return result + + +def references_any(value, ids): + if isinstance(value, str): + return value in ids + if isinstance(value, dict): + return any((references_any(item, ids) for item in value.values())) + if isinstance(value, list): + return any((references_any(item, ids) for item in value)) + return False diff --git a/backend/app/services/editor_media.py b/backend/app/services/editor_media.py new file mode 100644 index 0000000..1a11607 --- /dev/null +++ b/backend/app/services/editor_media.py @@ -0,0 +1,129 @@ +"""编辑字幕投影:作者数据与最后编译的绝对帧分离。""" + +from copy import deepcopy +import math + +from app.domain.timeline import Subtitle + + +def shot_ranges(manifest): + position, ranges = 0, {} + for sid, shot in zip(manifest["shot_ids"], manifest["spec"]["shots"], strict=True): + duration = shot.get("edit", {}).get("duration_frames", shot.get("duration_frames", 120)) + if type(duration) is not int or duration < 1: + raise ValueError("镜头选用时长无效") + ranges[sid] = (position, position + duration) + position += duration + return ranges, position + + +def audio_segment_ranges(manifest, bindings): + ranges, _ = shot_ranges(manifest) + grouped = {sid: [] for sid in ranges} + for segment in manifest.get("audio", {}).get("segments", []): + if segment["shot_id"] not in ranges: + raise ValueError("旁白对应的镜头已删除,请删除该段或重新绑定") + grouped[segment["shot_id"]].append(segment) + output = {} + spoken = manifest.get("audio", {}).get("mode") == "generated_narration" + for sid, segments in grouped.items(): + start, end = ranges[sid] + if not segments: + continue + cursor, weight = start, sum(max(1, len(s["text"].strip())) for s in segments) + consumed = 0 + for segment in segments: + if spoken: + binding = bindings.get("audio:" + segment["id"], {}) + if binding.get("sample_count") is not None: + duration = (int(binding["sample_count"]) + 1999) // 2000 + elif binding.get("duration_frames") is not None: + duration = int(binding["duration_frames"]) + elif binding.get("duration_seconds") is not None: + seconds = float(binding["duration_seconds"]) + if not math.isfinite(seconds): + raise ValueError("配音时长无效") + duration = math.ceil(seconds * 24) + else: + raise ValueError("配音尚未完成,无法计算字幕时间") + target = cursor + duration + else: + consumed += max(1, len(segment["text"].strip())) + target = start + (end - start) * consumed // weight + if target <= cursor or target > end: + raise ValueError("旁白超出镜头选用时长,请调整文案、语速或镜头时长") + output[segment["id"]] = (cursor, target) + cursor = target + return output + + +def materialize_cues(manifest, bindings): + """保留稳定字幕身份;文字和时间覆盖互相独立,不改调用者的编辑数据。""" + captions = manifest.get("captions", {}) + cues = deepcopy(captions.get("cues", [])) + if captions.get("mode", "none") not in {"script", "ai_script"}: + return cues + segments = manifest.get("audio", {}).get("segments", []) + known = {cue.get("segment_id"): cue for cue in cues if cue.get("segment_id")} + ranges = audio_segment_ranges(manifest, bindings) + for segment in segments: + sid = segment["id"] + if not segment["text"].strip(): + raise ValueError("请补全旁白文案或生成自动文案") + start, end = ranges[sid] + cue = known.get(sid) + if cue is None: + cues.append( + { + "id": sid, + "anchor": "audio_segment", + "segment_id": sid, + "start_frame": 0, + "end_frame": end - start, + "text": segment["text"], + "text_override": False, + "timing_override": False, + } + ) + else: + if not cue.get("text_override", False): + cue["text"] = segment["text"] + if not cue.get("timing_override", False): + cue["start_frame"], cue["end_frame"] = 0, end - start + return cues + + +def compile_captions(manifest, bindings): + if manifest.get("captions", {}).get("mode", "none") == "none": + return [] + shots, total = shot_ranges(manifest) + cues = materialize_cues(manifest, bindings) + segment_ranges = None + output = [] + for cue in cues: + anchor, offset, limit = cue.get("anchor", "absolute"), 0, total + if anchor == "shot": + if cue.get("shot_id") not in shots: + raise ValueError("字幕对应的镜头已删除,请重新绑定") + offset, end = shots[cue["shot_id"]] + limit = end - offset + elif anchor == "audio_segment": + if segment_ranges is None: + segment_ranges = audio_segment_ranges(manifest, bindings) + if cue.get("segment_id") not in segment_ranges: + raise ValueError("字幕对应的音频段已删除,请重新绑定") + offset, end = segment_ranges[cue["segment_id"]] + limit = end - offset + elif anchor != "absolute": + raise ValueError("字幕时间锚点无效") + a, b = cue["start_frame"], cue["end_frame"] + if type(a) is not int or type(b) is not int or a < 0 or b <= a or b > limit: + raise ValueError("字幕时间越界,请调整后再成片") + try: + row = Subtitle(start_frame=offset + a, end_frame=offset + b, text=cue["text"]) + except ValueError as exc: + raise ValueError("字幕文字为空或含不支持的控制字符") from exc + output.append(row.model_dump()) + if len(output) > 1000: + raise ValueError("字幕数量超过1000条") + return sorted(output, key=lambda row: (row["start_frame"], row["end_frame"])) diff --git a/backend/app/services/editor_modes.py b/backend/app/services/editor_modes.py new file mode 100644 index 0000000..0774996 --- /dev/null +++ b/backend/app/services/editor_modes.py @@ -0,0 +1,306 @@ +"""同一草稿的可逆编辑入口;模式、当前事实和保护引用在同一事务提交。""" + +from copy import deepcopy +import uuid +from sqlalchemy import select, or_ +from fastapi import HTTPException +from app.models import WorkflowDraft, WorkflowRun, ShotCandidate, Batch, BatchItem, Job, Execution +from app.domain.editors import is_editor_auto, validate_manifest +from app.core.errors import fail + + +def require_auto(d): + if d.editor_manifest and not is_editor_auto(d): + fail(409, "editor_mode_conflict", "当前为逐步骤确认,请先切换为自动成片") + + +def manual_spec(d, strict=False): + if not d.editor_manifest or is_editor_auto(d): + return deepcopy(d.spec) + m = d.editor_manifest + raw = deepcopy(m["spec"]) + raw["render"]["audio"] = ( + deepcopy(m["audio"].get("track")) if m["audio"]["mode"] != "silent" else None + ) + from app.services.editor_media import compile_captions + + try: + raw["render"]["subtitles"] = compile_captions(m, m["bindings"]) + if strict and m["audio"]["mode"] == "generated_narration" and not raw["render"]["audio"]: + fail(422, "missing_audio_track", "旁白尚未合成,请切回自动成片生成或选择人工音轨") + except HTTPException: + if strict: + raise + raw["render"]["subtitles"] = [] + except ValueError as exc: + if strict: + fail(422, "invalid_timeline", str(exc)) + raw["render"]["subtitles"] = [] + audio = raw["render"]["audio"] + frames = raw["render"]["total_frames"] + if ( + audio + and audio["offset_frame"] + (audio["source_end_ms"] - audio["source_start_ms"]) * 24 / 1000 + > frames + ): + if strict: + fail(422, "invalid_timeline", "音轨超出成片范围") + raw["render"]["audio"] = None + return raw + + +async def assert_idle(s, d): + from app.domain.tasks import RUN_TERMINAL, TERMINAL + + runs = select(WorkflowRun.id).where( + WorkflowRun.owner_id == d.owner_id, WorkflowRun.draft_id == d.id + ) + candidates = select(ShotCandidate.id).where( + ShotCandidate.owner_id == d.owner_id, ShotCandidate.draft_id == d.id + ) + batches = select(BatchItem.batch_id).where( + or_( + BatchItem.target_id == d.id, + BatchItem.target_id.in_(candidates), + BatchItem.target_id.in_(runs), + ) + ) + pending_run = await s.scalar( + select(WorkflowRun.id) + .where(WorkflowRun.id.in_(runs), WorkflowRun.state.not_in(RUN_TERMINAL)) + .limit(1) + ) + pending_candidate = await s.scalar( + select(ShotCandidate.id) + .where( + ShotCandidate.id.in_(candidates), + ShotCandidate.deleted_at.is_(None), + ShotCandidate.state.not_in({"ready", "failed"}), + ) + .limit(1) + ) + pending_batch = await s.scalar( + select(Batch.id) + .where( + Batch.owner_id == d.owner_id, + Batch.id.in_(batches), + Batch.state.not_in({"succeeded", "cancelled", "completed_with_errors"}), + ) + .limit(1) + ) + related_jobs = select(Job.id).where( + Job.owner_id == d.owner_id, + or_( + Job.run_id.in_(runs), + Job.id.in_(select(ShotCandidate.job_id).where(ShotCandidate.id.in_(candidates))), + Job.batch_id.in_(batches), + ), + ) + pending_job = await s.scalar( + select(Job.id).where(Job.id.in_(related_jobs), Job.state.not_in(TERMINAL)).limit(1) + ) + pending_execution = await s.scalar( + select(Execution.id) + .where( + Execution.job_id.in_(related_jobs), Execution.state.not_in({"exited", "results_ready"}) + ) + .limit(1) + ) + if any((pending_run, pending_candidate, pending_batch, pending_job, pending_execution)): + fail(409, "mode_switch_busy", "故事仍有运行、候选或执行等待清理,请结束后再切换") + + +async def import_candidates(s, d, settings): + if d.kind != "story_v3": + return + from app.services.stories.common import current_hash, private_asset, add_ref, candidate_dto + from app.services.workflows import verified_output + from app.services.events import emit_asset + + for key, b in d.editor_manifest["bindings"].items(): + kind, sid = key.split(":", 1) + if kind not in {"frame", "video"}: + continue + a = await private_asset( + s, b["asset_id"], d.owner_id, "image" if kind == "frame" else "video" + ) + if a.sha256 != b["sha256"] or not await verified_output(a, settings): + fail(409, "asset_integrity_failed", "自动素材校验失败") + h = await current_hash(s, d, sid, kind, source_kind="manual", source_sha256=a.sha256) + existing = await s.scalar( + select(ShotCandidate).where( + ShotCandidate.owner_id == d.owner_id, + ShotCandidate.draft_id == d.id, + ShotCandidate.shot_id == sid, + ShotCandidate.kind == kind, + ShotCandidate.asset_id == a.id, + ShotCandidate.context_hash == h, + ShotCandidate.deleted_at.is_(None), + ShotCandidate.state == "ready", + ) + ) + if existing: + continue + from app.domain.stories import digest + + provenance = deepcopy(b) + c = ShotCandidate( + owner_id=d.owner_id, + draft_id=d.id, + shot_id=sid, + kind=kind, + source_kind="manual", + state="ready", + asset_id=a.id, + asset_sha256=a.sha256, + context_hash=h, + generation_hash=digest({"editor_import": provenance, "context_hash": h}), + created_revision=d.revision, + plan_json={ + "task_type": None, + "input": {}, + "parameters": {}, + "editor_import": provenance, + "input_snapshot": {"reference_mode": "manual", "actual_image_refs": []}, + }, + ) + s.add(c) + await s.flush() + await add_ref(s, d, a.id, "candidate", c.id) + emit_asset(s, d.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)}) + + +async def change_mode(runtime, actor, draft_id, body, key): + from app.core.maintenance import require_writable + from app.services.auth import require_session_user + from app.services.snapshots import owned + from app.services.submissions import accept_submission, request_payload + from app.services.editors import check_version, load_manifest, write_manifest, dto + + require_writable(runtime.settings) + async with runtime.db.session() as s: + await require_session_user(s, actor) + d = await owned(s, WorkflowDraft, draft_id, actor.id) + if d.kind != "story_v3": + fail(422, "mode_not_supported", "当前仅故事支持切换逐步骤确认") + sub = await accept_submission( + s, actor.id, "editor.mode", key, 1, {"draft_id": draft_id, **request_payload(body)} + ) + if not sub.resource_json: + check_version(d, body.expected_version) + await assert_idle(s, d) + m = await load_manifest(s, d) + m["editing_mode"] = body.mode + await write_manifest(s, d, m, runtime.settings) + if body.mode == "manual": + await import_candidates(s, d, runtime.settings) + sub.resource_json = {"draft_id": d.id} + result = await dto(s, d) + from app.services.stories.common import story_dto + + result["story"] = await story_dto(s, d) + await s.commit() + return result + + +async def sync_manual_patch(s, d, new_spec): + if not d.editor_manifest or is_editor_auto(d): + return + from app.services.editors import sync_editor_refs + + m = deepcopy(d.editor_manifest) + baseline = manual_spec(d) + render = new_spec.get("render", {}) + if render.get("audio") != baseline.get("render", {}).get("audio"): + m["audio"]["track"] = deepcopy(render.get("audio")) + m["audio"]["mode"] = "manual_track" if render.get("audio") else "silent" + if render.get("subtitles", []) != baseline.get("render", {}).get("subtitles", []): + m["captions"]["mode"] = "manual" if render.get("subtitles") else "none" + # 对投影里没有改变的字幕保留稳定ID、锚点及人工override;只转换确实改动的条目。 + from app.services.editor_media import compile_captions + + originals = [] + for cue in m["captions"]["cues"]: + single = deepcopy(m) + single["captions"] = {"mode": "manual", "cues": [cue]} + try: + rendered = compile_captions(single, m["bindings"]) + except ValueError: + continue + if len(rendered) == 1: + originals.append((rendered[0], cue)) + updated = [] + for c in render.get("subtitles", []): + match = next((i for i, (rendered, _) in enumerate(originals) if rendered == c), None) + if match is not None: + updated.append(deepcopy(originals.pop(match)[1])) + else: + updated.append( + dict( + id=uuid.uuid4().hex, + anchor="absolute", + text_override=True, + timing_override=True, + **c, + ) + ) + m["captions"]["cues"] = updated + old_ids = dict(zip([x.get("key") for x in m["spec"]["shots"]], m["shot_ids"])) + ids = [ + x["id"] if m["source_kind"] == "story" else old_ids.get(x.get("key"), uuid.uuid4().hex) + for x in new_spec["shots"] + ] + removed_segments = {x["id"] for x in m["audio"]["segments"] if x["shot_id"] not in ids} + m["audio"]["segments"] = [x for x in m["audio"]["segments"] if x["shot_id"] in ids] + m["captions"]["cues"] = [ + c + for c in m["captions"]["cues"] + if not ( + c["anchor"] == "shot" + and c.get("shot_id") not in ids + or c["anchor"] == "audio_segment" + and c.get("segment_id") in removed_segments + ) + ] + for segment_id in removed_segments: + m["bindings"].pop("audio:" + segment_id, None) + m["spec"] = deepcopy(new_spec) + m["shot_ids"] = ids + m["bindings"] = { + k: v + for k, v in m["bindings"].items() + if not k.startswith(("frame:", "video:")) or k.split(":", 1)[1] in ids + } + for sid in ids: + if not any(x["shot_id"] == sid for x in m["audio"]["segments"]): + m["audio"]["segments"].append(dict(id=uuid.uuid4().hex, shot_id=sid, text="")) + m = validate_manifest(m) + await sync_editor_refs(s, d, m) + d.editor_manifest = m + d.spec = deepcopy(m["spec"]) + + +async def sync_manual_selection(s, d, row, asset, candidate=None): + if not d.editor_manifest or is_editor_auto(d): + return + from app.services.editors import sync_editor_refs + + m = deepcopy(d.editor_manifest) + key = row.kind + ":" + row.shot_id + if asset: + provenance = (candidate.plan_json.get("editor_import") if candidate else None) or m[ + "bindings" + ].get(key, {}) + b = ( + deepcopy(provenance) + if provenance.get("asset_id") == asset.id and provenance.get("sha256") == asset.sha256 + else {} + ) + b.update( + asset_id=asset.id, sha256=asset.sha256, kind=asset.kind, source="manual", locked=True + ) + m["bindings"][key] = b + else: + m["bindings"].pop(key, None) + await sync_editor_refs(s, d, m) + d.editor_manifest = m diff --git a/backend/app/services/editors.py b/backend/app/services/editors.py new file mode 100644 index 0000000..50b0d35 --- /dev/null +++ b/backend/app/services/editors.py @@ -0,0 +1,443 @@ +"""编辑命令:真实会话复核、CAS、资源引用与幂等回执在同一事务提交。""" + +from copy import deepcopy +from math import ceil +from types import SimpleNamespace +from sqlalchemy import select, delete +from app.models import WorkflowDraft, WorkflowRun, WorkflowStep, Asset, AssetReference, User, utcnow +from app.core.errors import fail +from app.core.maintenance import require_writable +from app.domain.editors import ( + validate_manifest, + manifest_from_draft, + editor_issues, + collect_manifest_asset_ids, + editing_mode, + MODE_CAPABILITIES, +) +from app.services.auth import require_session_user +from app.services.snapshots import owned, asset_dto, snapshot_run +from app.services.submissions import accept_submission, request_payload + + +async def sync_editor_refs(session, draft, manifest): + assets = {} + for id in sorted(collect_manifest_asset_ids(manifest)): + asset = await session.scalar( + select(Asset) + .where( + Asset.id == id, + Asset.owner_id == draft.owner_id, + Asset.library_scope == "private", + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + ) + .with_for_update() + ) + if not asset: + fail(404, "asset_not_found", "素材不存在或不可访问") + assets[id] = asset + for key, b in manifest["bindings"].items(): + a = assets[b["asset_id"]] + if a.kind != b["kind"]: + fail(422, "wrong_asset_kind", "绑定素材类型不正确") + b["sha256"] = a.sha256 + if a.duration_seconds is not None: + b["duration_seconds"] = a.duration_seconds + b["duration_frames"] = ( + ceil(a.duration_seconds * 24) + if a.kind == "audio" + else round(a.duration_seconds * 24) + ) + + def image_refs(value): + if isinstance(value, dict): + for key, item in value.items(): + if key == "image_asset_id" and item: + yield item + elif key == "reference_asset_ids": + yield from item + else: + yield from image_refs(item) + elif isinstance(value, list): + for item in value: + yield from image_refs(item) + + if any(assets[id].kind != "image" for id in image_refs(manifest["spec"])): + fail(422, "wrong_asset_kind", "视觉参考必须为图片素材") + track = manifest["audio"].get("track") + if track and assets[track["asset_id"]].kind != "audio": + fail(422, "wrong_asset_kind", "音轨需要音频素材") + # 独立草稿引用不能依赖旧 Run 的存活。 + await session.execute( + delete(AssetReference).where( + AssetReference.owner_id == draft.owner_id, + AssetReference.ref_kind == "draft", + AssetReference.ref_id == draft.id, + ) + ) + for id in assets: + session.add( + AssetReference(owner_id=draft.owner_id, asset_id=id, ref_kind="draft", ref_id=draft.id) + ) + return assets + + +async def load_manifest(session, draft): + m = manifest_from_draft(draft) + if draft.editor_manifest or draft.kind != "story_v3": + return m + from app.services.stories.common import selections, current_hash, selection_source_kind + + latest = await selections(session, draft) + for row in latest.values(): + if not row.asset_id or row.shot_id not in m["shot_ids"]: + continue + a = await session.get(Asset, row.asset_id) + if ( + not a + or a.owner_id != draft.owner_id + or a.deleted_at is not None + or not a.ready + or a.library_scope != "private" + ): + continue + source_kind = await selection_source_kind(session, row) + if row.context_hash != await current_hash( + session, + draft, + row.shot_id, + row.kind, + latest=latest, + source_kind=source_kind, + source_sha256=a.sha256, + ): + continue + expected = "image" if row.kind == "frame" else "video" + if a.kind != expected or row.decision_json.get("asset_sha256") != a.sha256: + continue + m["bindings"][row.kind + ":" + row.shot_id] = dict( + asset_id=a.id, sha256=a.sha256, kind=a.kind, source="manual", locked=True + ) + return m + + +async def dto(session, draft, manifest=None): + m = manifest if manifest is not None else await load_manifest(session, draft) + ids = collect_manifest_asset_ids(m) + assets = ( + ( + await session.scalars( + select(Asset).where( + Asset.id.in_(ids), Asset.owner_id == draft.owner_id, Asset.deleted_at.is_(None) + ) + ) + ).all() + if ids + else [] + ) + return dict( + draft_id=draft.id, + editing_mode=editing_mode(draft), + capabilities={ + **MODE_CAPABILITIES, + "mode_switch": draft.kind == "story_v3", + "manual": draft.kind == "story_v3", + }, + name=draft.name, + version=draft.version, + revision=draft.revision, + manifest=m, + issues=editor_issues(m), + assets=[asset_dto(a) for a in assets], + ) + + +def check_version(draft, version): + if draft.version != version: + fail(409, "draft_version_conflict", "草稿已更新,请刷新版本") + + +async def write_manifest(session, draft, manifest, settings=None): + m = validate_manifest(manifest) + if settings: + from app.core.runtime_policy import read_runtime_policy + + policy = read_runtime_policy(settings) + if policy.get("configuration_error"): + fail(503, "runtime_policy_unavailable", "运行配置无效") + if len(m["shot_ids"]) > policy["workflow_max_shots"]: + fail(422, "workflow_shot_limit", "镜头数量超过当前限制") + if (m["source_kind"] == "story") != (draft.kind == "story_v3"): + fail(422, "invalid_editor_manifest", "草稿类型不能改变") + # 来源只作谱系,允许已经归档的同草稿历史,绝不能跨owner/draft扩大可读范围。 + if m.get("base_run_id"): + source = await session.scalar( + select(WorkflowRun.id).where( + WorkflowRun.id == m["base_run_id"], + WorkflowRun.owner_id == draft.owner_id, + WorkflowRun.draft_id == draft.id, + ) + ) + if not source: + fail(404, "resource_not_found", "来源运行不存在或不属于此草稿") + await sync_editor_refs(session, draft, m) + draft.editor_manifest = m + draft.spec = deepcopy(m["spec"]) + draft.version += 1 + draft.revision += 1 + draft.updated_at = utcnow() + await session.flush() + from app.services.events import emit_asset + + if draft.kind == "story_v3": + from app.services.stories.common import story_dto + + emit_asset( + session, draft.owner_id, "story.updated", {"story": await story_dto(session, draft)} + ) + else: + from app.services.snapshots import draft_dto + + emit_asset(session, draft.owner_id, "draft.updated", {"draft": draft_dto(draft)}) + + +async def get_editor(runtime, actor, draft_id): + async with runtime.db.session() as s: + d = await owned(s, WorkflowDraft, draft_id, actor.id) + return await dto(s, d) + + +def sanitize_bindings(manifest, old): + for key, b in manifest["bindings"].items(): + previous = old.get("bindings", {}).get(key, {}) + if previous.get("asset_id") == b["asset_id"] and previous.get("sha256") == b["sha256"]: + manifest["bindings"][key] = deepcopy(previous) + manifest["bindings"][key]["locked"] = b.get("locked", False) + else: + for field in ( + "input_hash", + "context_hash", + "source_run_id", + "source_job_id", + "generation_parameters", + "duration_seconds", + "duration_frames", + "sample_count", + ): + b.pop(field, None) + b["source"] = "manual" + + +async def run_manifest(session, run): + if run.result_manifest: + return {**deepcopy(run.result_manifest), "base_run_id": run.id} + if run.plan_snapshot and run.plan_snapshot.get("manifest"): + return {**deepcopy(run.plan_snapshot["manifest"]), "base_run_id": run.id} + source = SimpleNamespace( + id=run.draft_id, + kind="story_v3" if run.spec_snapshot.get("schema_version") == 3 else "three_shot", + spec=run.spec_snapshot, + editor_manifest=None, + ) + m = manifest_from_draft(source) + m["base_run_id"] = run.id + for selection in run.spec_snapshot.get("render_inputs", {}).get("selections", []): + if selection.get("shot_id") not in m["shot_ids"]: + continue + a = await session.get(Asset, selection.get("asset_id")) + if not a or a.owner_id != run.owner_id or a.deleted_at is not None or not a.ready: + fail(404, "asset_not_found", "冻结运行素材不可访问") + kind = selection.get("kind") + prefix = "frame" if kind in {"frame", "image"} else "video" + m["bindings"][prefix + ":" + selection["shot_id"]] = dict( + asset_id=a.id, sha256=a.sha256, kind=a.kind, source="reused", source_run_id=run.id + ) + # legacy 实际输出按冻结顺序恢复,不能读取当前草稿或选择。 + steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id))).all() + from app.models import Job + + for index, id in enumerate(m["shot_ids"]): + shot = m["spec"]["shots"][index] + step = next((x for x in steps if x.step_key == shot.get("key", f"shot_{index + 1}")), None) + if step and step.selected_job_id: + job = await session.get(Job, step.selected_job_id) + if job and job.owner_id == run.owner_id: + from app.services.workflows import selected_output + + a = await selected_output(session, job.id, run.owner_id) + if a: + m["bindings"]["video:" + id] = dict( + asset_id=a.id, + sha256=a.sha256, + kind=a.kind, + source="reused", + source_run_id=run.id, + source_job_id=job.id, + ) + return m + + +async def apply_run_result(session, run, settings): + if run.state != "succeeded" or not run.result_manifest or run.desired_state == "cancel": + return False + owner = await session.scalar(select(User).where(User.id == run.owner_id).with_for_update()) + d = await session.scalar( + select(WorkflowDraft) + .where( + WorkflowDraft.id == run.draft_id, + WorkflowDraft.owner_id == run.owner_id, + WorkflowDraft.deleted_at.is_(None), + ) + .with_for_update() + ) + + if ( + not owner + or owner.disabled + or not d + or d.version != run.source_draft_version + or (d.editor_manifest and editing_mode(d) != "auto") + ): + run.apply_state = "conflict" + return False + if run.output_goal == "film" and run.state == "succeeded" and run.current_output_asset_id: + d.current_run_id = run.id + run.result_manifest = {**deepcopy(run.result_manifest), "base_run_id": run.id} + await write_manifest(session, d, run.result_manifest, settings) + run.apply_state = "applied" + return True + + +async def command(runtime, actor, draft_id, body, key, operation): + require_writable(runtime.settings) + async with runtime.db.session() as s: + await require_session_user(s, actor) + payload = request_payload(body) + # 可选改名为空时仍使用旧请求指纹,升级前已接纳的保存可以原幂等键重放。 + if operation == "editor.save" and body.name is None: + payload.pop("name", None) + sub = await accept_submission( + s, actor.id, operation, key, 1, {"draft_id": draft_id, **payload} + ) + d = await owned(s, WorkflowDraft, draft_id, actor.id) + from app.services.editor_modes import require_auto + + require_auto(d) + if sub.resource_json: + if operation == "editor.run": + return await snapshot_run(s, actor.id, sub.resource_json["run_id"]) + return await dto(s, d) + check_version(d, body.expected_version) + from app.services.editor_modes import require_auto + + require_auto(d) + if not d.editor_manifest: + from app.services.editor_modes import assert_idle + + await assert_idle(s, d) + if operation == "editor.save": + m = body.manifest.model_dump(mode="json") + if m["editing_mode"] != "auto": + fail(409, "editor_mode_conflict", "编辑模式只能通过切换命令修改") + m["editing_mode"] = "auto" + sanitize_bindings(m, await load_manifest(s, d)) + if body.name is not None: + d.name = body.name + await write_manifest(s, d, m, runtime.settings) + elif operation in {"editor.from_run", "editor.apply"}: + r = await owned(s, WorkflowRun, body.run_id, actor.id) + if r.draft_id != d.id: + fail(404, "resource_not_found", "运行不属于此草稿") + if operation == "editor.apply": + if r.state != "succeeded" or not r.result_manifest: + fail(409, "run_result_unavailable", "运行尚无可应用结果") + if r.source_draft_version != d.version: + fail(409, "draft_version_conflict", "草稿已编辑,请显式恢复运行版本") + if operation == "editor.apply": + r.apply_state = "applied" + if r.output_goal == "film" and r.state == "succeeded" and r.current_output_asset_id: + d.current_run_id = r.id + restored = await run_manifest(s, r) + restored["editing_mode"] = "auto" + await write_manifest(s, d, restored, runtime.settings) + else: + from app.services.orchestration.editor_engine import start_editor_run + from app.services.quotas import reserve_budget + + await reserve_budget(s, actor.id, "editor.run", units=0, settings=runtime.settings) + r = await start_editor_run(s, d, await load_manifest(s, d), body, runtime.settings) + sub.resource_json = {"draft_id": d.id, "run_id": r.id} + await s.commit() + result = await snapshot_run(s, actor.id, r.id) + from app.services.workflows import wake + + wake(runtime) + return result + sub.resource_json = {"draft_id": d.id} + result = await dto(s, d) + await s.commit() + return result + + +async def save_editor(runtime, actor, draft_id, body, key): + return await command(runtime, actor, draft_id, body, key, "editor.save") + + +async def from_run(runtime, actor, draft_id, body, key): + return await command(runtime, actor, draft_id, body, key, "editor.from_run") + + +async def apply_editor(runtime, actor, draft_id, body, key): + return await command(runtime, actor, draft_id, body, key, "editor.apply") + + +async def start_editor_request(runtime, actor, draft_id, body, key): + # 外部健康探测不占业务锁;接纳事务仍重新校验会话、草稿版本及计划。 + from app.models import Submission + + async with runtime.db.session() as s: + await require_session_user(s, actor) + previous = await s.scalar( + select(Submission).where( + Submission.owner_id == actor.id, + Submission.operation == "editor.run", + Submission.key == key, + ) + ) + d = await owned(s, WorkflowDraft, draft_id, actor.id) + from app.services.editor_modes import require_auto + + require_auto(d) + m = await load_manifest(s, d) + replay = previous is not None and bool(previous.resource_json) + needs_speech = ( + body.output_goal == "film" or any(t.startswith("audio:") for t in body.targets) + ) and m["audio"]["mode"] == "generated_narration" + if needs_speech and not replay: + if not getattr(runtime.settings, "tts_base_url", "") or not getattr( + runtime.settings, "tts_voices", () + ): + fail(503, "capability_unavailable", "中文配音服务尚未配置") + probe = getattr(runtime.provider, "speech_health", None) + if probe: + try: + health = await probe() + except Exception: + fail(503, "capability_unavailable", "配音服务暂不可用") + if not health.get("configured") or not health.get("reachable"): + fail(503, "capability_unavailable", "配音服务暂不可用") + return await command(runtime, actor, draft_id, body, key, "editor.run") + + +async def plan_editor_request(runtime, actor, draft_id, body): + async with runtime.db.session() as s: + await require_session_user(s, actor) + d = await owned(s, WorkflowDraft, draft_id, actor.id) + check_version(d, body.expected_version) + from app.services.editor_modes import require_auto + + require_auto(d) + from app.services.orchestration.editor_engine import plan_editor + + return await plan_editor(s, d, await load_manifest(s, d), body, runtime.settings) diff --git a/backend/app/services/events.py b/backend/app/services/events.py new file mode 100644 index 0000000..8affb89 --- /dev/null +++ b/backend/app/services/events.py @@ -0,0 +1,74 @@ +from sqlalchemy import select +from app.core.security import token_hash +from app.services.snapshots import job_dto +from app.models import Event, Session, User, utcnow + + +# 与业务更新共用调用方事务,禁止改成提交前发往后台的临时通知。 +async def emit_job(session, job, *, increment=True): + if increment: + job.version += 1 + await session.flush() + session.add( + Event( + owner_id=job.owner_id, + job_id=job.id, + event_type="job.updated", + data={"job": await job_dto(session, job)}, + ) + ) + + +def emit_asset(session, owner_id, event_type, data): + session.add(Event(owner_id=owner_id, event_type=event_type, data=data)) + + +async def event_batch(db, owner_id, after, limit=100): + async with db.session() as session: + events = ( + await session.scalars( + select(Event) + .where(Event.owner_id == owner_id, Event.id > after) + .order_by(Event.id) + .limit(limit) + ) + ).all() + return [{"id": event.id, "event": event.event_type, "data": event.data} for event in events] + + +async def session_is_active(db, token): + if not token: + return False + if token.startswith("Bearer "): + from app.models import ApiToken + + async with db.session() as session: + return ( + await session.scalar( + select(ApiToken.id) + .join(User, User.id == ApiToken.owner_id) + .where( + ApiToken.token_hash == token_hash(token[7:]), + ApiToken.revoked_at.is_(None), + User.disabled.is_(False), + ApiToken.expires_at.is_(None) | (ApiToken.expires_at > utcnow()), + ) + ) + is not None + ) + async with db.session() as session: + return ( + await session.scalar( + select(Session.token_hash) + .join(User, User.id == Session.user_id) + .where( + Session.token_hash == token_hash(token), + Session.expires_at > utcnow(), + User.disabled.is_(False), + ) + ) + is not None + ) + + +emit_event = emit_asset diff --git a/backend/app/services/folders.py b/backend/app/services/folders.py new file mode 100644 index 0000000..2ea9eb9 --- /dev/null +++ b/backend/app/services/folders.py @@ -0,0 +1,296 @@ +from sqlalchemy import select, delete +from sqlalchemy.exc import IntegrityError +from app.models import Folder, AssetFolder, Asset, Job, WorkflowDraft, WorkflowRun, User, utcnow +from app.core.errors import fail +from app.core.maintenance import require_writable +from app.services.snapshots import iso, asset_dto, draft_dto +from app.services.events import emit_asset + + +def folder_dto(folder): + return dict( + id=folder.id, + name=folder.name, + parent_id=folder.parent_id, + created_at=iso(folder.created_at), + updated_at=iso(folder.updated_at), + ) + + +async def owned_folder(session, folder_id, owner_id, *, lock=False): + query = select(Folder).where(Folder.id == folder_id, Folder.owner_id == owner_id) + if lock: + query = query.with_for_update() + folder = await session.scalar(query) + if folder is None: + fail(404, "folder_not_found", "文件夹不存在") + return folder + + +async def lock_owner(session, owner_id): + # 同用户目录树变更共用锁,防止并发互移形成循环或同级重名竞态。 + await session.scalar(select(User).where(User.id == owner_id).with_for_update()) + + +async def create_folder(session, owner_id, name, parent_id=None, *, unique_name=False): + await lock_owner(session, owner_id) + name = name.strip() + if not name or len(name) > 255: + fail(422, "invalid_folder_name", "文件夹名称无效") + if parent_id is not None: + await owned_folder(session, parent_id, owner_id, lock=True) + candidate, suffix = name, 2 + # 使用数据库的比较规则(包括 MySQL collation),避免自动后缀与唯一约束不一致。 + while await session.scalar( + select(Folder.id).where( + Folder.owner_id == owner_id, + Folder.parent_key == (parent_id or ""), + Folder.name == candidate, + ) + ): + if not unique_name: + fail(409, "folder_name_conflict", "同级文件夹已存在") + ending = f" ({suffix})" + candidate = name[: 255 - len(ending)] + ending + suffix += 1 + folder = Folder( + owner_id=owner_id, name=candidate, parent_id=parent_id, parent_key=parent_id or "" + ) + # 唯一约束是最终并发防线;事务回滚和提交均由调用方控制。 + try: + session.add(folder) + await session.flush() + except IntegrityError: + fail(409, "folder_name_conflict", "同级文件夹已存在") + emit_asset(session, owner_id, "folder.created", {"folder": folder_dto(folder)}) + return folder + + +async def assign_asset_folders(session, asset, folder_ids, *, mode="move", allow_missing=False): + if mode not in {"move", "add"}: + fail(422, "invalid_folder_mode", "分类操作无效") + targets = [] + for folder_id in dict.fromkeys(folder_ids): + # allow_missing 仅容忍目标被删除;存在但属于他人的目录始终拒绝。 + folder = await session.scalar( + select(Folder).where(Folder.id == folder_id).with_for_update() + ) + if folder is None and allow_missing: + continue + if folder is None or folder.owner_id != asset.owner_id: + fail(404, "folder_not_found", "文件夹不存在") + targets.append(folder.id) + if "folder_links" not in asset.__dict__: + await session.refresh(asset, ["folder_links"]) + current = {link.folder_id: link for link in asset.folder_links} + desired = set(targets) | (set(current) if mode == "add" else set()) + asset.folder_links[:] = [ + current[f] if f in current else AssetFolder(folder_id=f) for f in sorted(desired) + ] + await session.flush() + return asset + + +async def add_asset_folder(session, asset, folder_id, *, allow_missing=False): + if folder_id is not None: + await assign_asset_folders( + session, asset, [folder_id], mode="add", allow_missing=allow_missing + ) + return asset + + +async def list_folders(*, runtime, actor): + async with runtime.db.session() as session: + rows = ( + await session.scalars( + select(Folder) + .where(Folder.owner_id == actor.id) + .order_by(Folder.created_at, Folder.id) + ) + ).all() + return {"items": [folder_dto(row) for row in rows]} + + +async def create(*, runtime, actor, body): + require_writable(runtime.settings) + async with runtime.db.session() as session: + row = await create_folder(session, actor.id, body.name, body.parent_id) + result = folder_dto(row) + await session.commit() + return result + + +async def patch(*, runtime, actor, folder_id, body): + require_writable(runtime.settings) + async with runtime.db.session() as session: + await lock_owner(session, actor.id) + row = await owned_folder(session, folder_id, actor.id, lock=True) + parent_id = body.parent_id if "parent_id" in body.model_fields_set else row.parent_id + cursor = parent_id + while cursor is not None: + if cursor == row.id: + fail(409, "folder_cycle", "不能将文件夹移入自身或子文件夹") + cursor = (await owned_folder(session, cursor, actor.id, lock=True)).parent_id + name = body.name if "name" in body.model_fields_set else row.name + conflict = await session.scalar( + select(Folder.id).where( + Folder.owner_id == actor.id, + Folder.parent_key == (parent_id or ""), + Folder.name == name, + Folder.id != row.id, + ) + ) + if conflict: + fail(409, "folder_name_conflict", "同级文件夹已存在") + row.name, row.parent_id, row.parent_key = name, parent_id, parent_id or "" + row.updated_at = utcnow() + await session.flush() + result = folder_dto(row) + emit_asset(session, actor.id, "folder.updated", {"folder": result}) + await session.commit() + return result + + +async def remove(*, runtime, actor, folder_id): + require_writable(runtime.settings) + async with runtime.db.session() as session: + await lock_owner(session, actor.id) + row = await owned_folder(session, folder_id, actor.id, lock=True) + # CAS 版本随分类变动推进;数据库仅级联分类记录,媒体与业务实体全部保留。 + folders = (await session.scalars(select(Folder).where(Folder.owner_id == actor.id))).all() + ids = {row.id} + while True: + descendants = {f.id for f in folders if f.parent_id in ids} + if descendants <= ids: + break + ids |= descendants + # 先收集受影响的本人素材;删除后的 selectin 集合必须刷新,事件不能携带旧成员。 + assets = ( + await session.scalars( + select(Asset) + .where( + Asset.owner_id == actor.id, + Asset.deleted_at.is_(None), + Asset.library_scope == "private", + Asset.ready.is_(True), + Asset.id.in_( + select(AssetFolder.asset_id).where(AssetFolder.folder_id.in_(ids)) + ), + ) + .with_for_update() + ) + ).all() + changed = [] + for model in (Job, WorkflowDraft, WorkflowRun): + rows = ( + await session.scalars( + select(model) + .where( + model.owner_id == actor.id, + (model.folder_id.in_(ids)) + | (model.output_folder_id.in_(ids) if model != WorkflowDraft else False), + ) + .with_for_update() + ) + ).all() + for record in rows: + if record.folder_id in ids: + record.folder_id = None + if model != WorkflowDraft and record.output_folder_id in ids: + record.output_folder_id = None + record.version += 1 + if model == WorkflowDraft: + record.updated_at = utcnow() + if record.deleted_at is None: + changed.append(record) + await session.flush() + await session.execute( + delete(Folder).where(Folder.id == row.id, Folder.owner_id == actor.id) + ) + for asset in assets: + await session.refresh(asset, ["folder_links"]) + emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)}) + for record in changed: + await emit_classified_record(session, record, increment=False) + # 与归属更新同事务写入;其他会话刷新树与目标选择器时才能看见一致状态。 + for deleted_id in sorted(ids): + emit_asset(session, actor.id, "folder.deleted", {"folder_id": deleted_id}) + await session.commit() + + +async def assign(*, runtime, actor, body): + require_writable(runtime.settings) + if body.mode == "add" and body.kind != "assets": + fail(422, "invalid_folder_mode", "只有素材支持加入多个文件夹") + model = {"assets": Asset, "jobs": Job, "drafts": WorkflowDraft, "runs": WorkflowRun}[body.kind] + ids = set(body.ids) + async with runtime.db.session() as session: + await lock_owner(session, actor.id) + if body.folder_id is not None: + await owned_folder(session, body.folder_id, actor.id, lock=True) + query = select(model).where( + model.id.in_(ids), model.owner_id == actor.id, model.deleted_at.is_(None) + ) + if model == Asset: + query = query.where(Asset.ready.is_(True), Asset.library_scope == "private") + rows = (await session.scalars(query.with_for_update())).all() + # 完整校验后才产生任何写入或事件,避免批量部分成功。 + if len(rows) != len(ids): + fail(404, "record_not_found", "记录不存在") + for row in rows: + if model == Asset: + await assign_asset_folders( + session, row, [body.folder_id] if body.folder_id else [], mode=body.mode + ) + emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(row)}) + else: + row.folder_id = body.folder_id + await emit_classified_record(session, row) + emit_asset( + session, + actor.id, + "folder.contents_changed", + {"kind": body.kind, "folder_id": body.folder_id, "ids": sorted(ids), "mode": body.mode}, + ) + await session.commit() + return dict(updated=len(rows), kind=body.kind, folder_id=body.folder_id) + + +async def emit_classified_record(session, record, *, increment=True): + """分类只推进 CAS version;故事内容 revision 与既有 SSE 合同保持不变。""" + if isinstance(record, Job): + from app.services.events import emit_job + + await emit_job(session, record, increment=increment) + elif isinstance(record, WorkflowRun): + from app.services.workflows import emit_run + + await emit_run(session, record, increment=increment) + else: + if increment: + record.version += 1 + record.updated_at = utcnow() + if record.kind == "story_v3": + from app.services.stories.common import emit_story + + await emit_story(session, record) + else: + emit_asset(session, record.owner_id, "draft.updated", {"draft": draft_dto(record)}) + + +async def folder_filter(session, model, owner_id, folder_id): + """列表过滤条件:空为全部,unclassified 为动态未分类视图。""" + from sqlalchemy import true + + if not folder_id: + return true() + if folder_id != "unclassified": + await owned_folder(session, folder_id, owner_id) + if model == Asset: + membership = select(AssetFolder.asset_id).where(AssetFolder.asset_id == Asset.id) + if folder_id != "unclassified": + membership = membership.where(AssetFolder.folder_id == folder_id) + return ~membership.exists() if folder_id == "unclassified" else membership.exists() + return ( + model.folder_id.is_(None) if folder_id == "unclassified" else model.folder_id == folder_id + ) diff --git a/backend/app/services/jobs.py b/backend/app/services/jobs.py new file mode 100644 index 0000000..e010527 --- /dev/null +++ b/backend/app/services/jobs.py @@ -0,0 +1,573 @@ +from datetime import timezone +from app.domain.tasks import GPU_TYPES, CPU_TYPES, TERMINAL +import hashlib +import json +from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError +from app.services.assets import owned_asset +from app.core.security import Actor +from app.services.snapshots import job_dto +from app.core.errors import fail +from app.services.events import emit_job +from app.models import Event, Job, JobAsset, new_id, utcnow +from app.schemas.jobs import Submit + + +async def owned_job(session, job_id, owner_id): + job = await session.scalar( + select(Job) + .where(Job.id == job_id, Job.owner_id == owner_id, Job.deleted_at.is_(None)) + .with_for_update() + ) + if job is None: + fail(404, "job_not_found", "任务不存在") + return job + + +def input_ids(inputs, parameters): + result = [] + for field in ("image_asset_id", "audio_asset_id", "asset_id", "video_asset_id"): + if inputs.get(field): + result.append(inputs[field]) + if inputs.get("asset_ids"): + if not isinstance(inputs["asset_ids"], list): + fail(422, "invalid_assets", "asset_ids 必须为素材编号列表") + result.extend(inputs["asset_ids"]) + if "reference_asset_ids" in inputs: + if not isinstance(inputs["reference_asset_ids"], list): + fail(422, "invalid_assets", "参考图必须为素材编号列表") + result.extend(inputs["reference_asset_ids"]) + for replacement in inputs.get("replacements", []): + if not isinstance(replacement, dict) or not isinstance( + replacement.get("reference_asset_id"), str + ): + fail(422, "invalid_assets", "替换人物需要参考图编号") + result.append(replacement["reference_asset_id"]) + for segment in inputs.get("segments", []): + if not isinstance(segment, dict) or not isinstance(segment.get("asset_id"), str): + fail(422, "invalid_assets", "音频段需要素材编号") + result.append(segment["asset_id"]) + for clip in parameters.get("clips", []): + if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str): + fail(422, "invalid_clip", "每个片段需要素材编号") + result.append(clip["asset_id"]) + if parameters.get("audio_asset_id"): + result.append(parameters["audio_asset_id"]) + if any((not isinstance(value, str) or len(value) > 64 for value in result)): + fail(422, "invalid_assets", "素材编号格式不正确") + return list(dict.fromkeys(result)) + + +async def validate_submission(session, body, owner_id, settings, *, frozen_workflow=False): + if body.task_type not in GPU_TYPES | CPU_TYPES: + fail(422, "unsupported_task", "不支持此任务类型") + allowed = { + "prompt", + "negative_prompt", + "image_asset_id", + "audio_asset_id", + "asset_id", + "asset_ids", + "reference_asset_ids", + "video_asset_id", + "analysis_job_id", + "replacements", + } + if body.task_type == "text.script.generate": + allowed |= {"shots", "context"} + if body.task_type == "audio.assemble": + allowed |= {"segments", "total_frames"} + if set(body.input) - allowed: + fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL") + if body.count > 1 and body.task_type not in { + "image.generate", + "image.reference.generate", + "defect.generate", + }: + fail(422, "batch_not_supported", "此任务类型不支持批量生成") + if body.task_type == "audio.speech" and (not settings.tts_base_url): + fail(422, "speech_unavailable", "尚未配置真实配音服务") + from app.adapters.provider.client import ProviderError, validate_arguments + + try: + validate_arguments(body.task_type, body.input, body.parameters, settings) + except ProviderError as exc: + fail(400, exc.code, exc.message) + prompt = body.input.get("prompt", "") + if not isinstance(prompt, str) or len(prompt) > 8000: + fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本") + if body.task_type in { + "image.generate", + "video.generate", + "defect.generate", + "math.solve", + "audio.speech", + "image.reference.generate", + } and (not prompt.strip()): + fail(422, "prompt_required", "请输入提示词或文本") + ids = input_ids(body.input, body.parameters) + assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids} + if body.task_type == "audio.assemble" and any(a.kind != "audio" for a in assets.values()): + fail(422, "wrong_asset_kind", "旁白装配只接受音频素材") + for asset_id in body.input.get("reference_asset_ids", []): + if assets[asset_id].kind != "image": + fail(422, "wrong_asset_kind", "参考图必须为图片素材") + if body.task_type in {"video.people.analyze", "video.replace"}: + if assets[body.input["video_asset_id"]].kind != "video": + fail(422, "wrong_asset_kind", "源素材必须是视频") + from app.adapters.media import inspect_video_timeline + from app.adapters.storage import confined + + source = assets[body.input["video_asset_id"]] + try: + duration = await inspect_video_timeline( + confined(settings.asset_root, source.storage_key, exists=True), settings + ) + except ProviderError as exc: + fail(422, exc.code, exc.message) + if duration > settings.video_edit_max_seconds + 0.001: + fail(422, "video_too_long", "源视频超过当前时长限制") + for row in body.input.get("replacements", []): + if assets[row["reference_asset_id"]].kind != "image": + fail(422, "wrong_asset_kind", "人物参考素材必须是图片") + if body.task_type == "video.replace": + await resolve_analysis_binding(session, body.input, body.parameters, owner_id, settings) + required = { + "defect.generate": "image_asset_id", + "audio.transcribe": "audio_asset_id", + "media.structure": "asset_id", + } + if body.task_type in required: + key = required[body.task_type] + value = body.input.get(key) or ( + body.input.get("asset_id") if key == "audio_asset_id" else None + ) + if not value: + fail(422, "asset_required", "此任务需要输入素材") + for key, kinds in (("image_asset_id", {"image"}), ("audio_asset_id", {"audio", "video"})): + if body.input.get(key) and assets[body.input[key]].kind not in kinds: + fail(422, "wrong_asset_kind", "输入素材类型不正确") + if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in { + "image", + "video", + }: + fail(422, "wrong_asset_kind", "素材理解需要图片或视频") + if body.task_type == "audio.transcribe": + source_id = body.input.get("audio_asset_id") or body.input.get("asset_id") + if assets[source_id].kind not in {"audio", "video"}: + fail(422, "wrong_asset_kind", "转写需要音频或视频素材") + if body.task_type == "video.compose" and (not ids): + fail(422, "clips_required", "请添加待合成片段") + if body.task_type == "video.compose": + if not frozen_workflow: + from app.core.runtime_policy import read_runtime_policy + + policy = read_runtime_policy(settings) + if policy.get("configuration_error"): + fail(503, "runtime_policy_unavailable", "运行配置无效,请联系管理员") + if len(body.parameters.get("clips", [])) > policy["workflow_max_shots"]: + fail( + 422, + "workflow_shot_limit", + f"当前配置最多允许{policy['workflow_max_shots']}个视频片段", + ) + if any( + (assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])) + ): + fail(422, "wrong_asset_kind", "编排片段必须为视频素材") + audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id") + if audio_id and assets[audio_id].kind != "audio": + fail(422, "wrong_asset_kind", "成片音轨必须为音频素材") + if body.scheduled_at is not None and body.scheduled_at.tzinfo is None: + fail(422, "timezone_required", "定时任务时间须包含时区") + return ids + + +# 调用方统一提交:幂等记录、任务、素材引用和事件必须同生共死,不能在内部单独 commit。 +async def create_jobs( + session, body, actor, settings, key=None, internal=False, *, frozen_workflow=False +): + if key is not None and (not 1 <= len(key) <= 128): + fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128") + from app.services.submissions import request_payload + + payload = request_payload(body) + if body.execution_mode == "interactive": + payload.pop("execution_mode", None) + try: + fingerprint = hashlib.sha256( + json.dumps(payload, sort_keys=True, ensure_ascii=False, allow_nan=False).encode() + ).hexdigest() + except (ValueError, TypeError): + fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON") + if key: + existing = ( + await session.scalars( + select(Job) + .where(Job.owner_id == actor.id, Job.request_key == key) + .order_by(Job.batch_index) + ) + ).all() + if existing: + if existing[0].request_hash != fingerprint: + fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数") + if any((job.deleted_at is not None for job in existing)): + fail(410, "resource_purged", "此幂等键对应的任务已删除") + from app.services.submissions import accept_submission + + saved = await accept_submission( + session, actor.id, "jobs.create", key, 2, request_payload(body) + ) + saved.resource_json = {"job_ids": [job.id for job in existing]} + return existing + from app.services.submissions import accept_submission + + record = ( + await accept_submission(session, actor.id, "jobs.create", key, 2, request_payload(body)) + if key + else None + ) + from app.services.quotas import reserve_budget + + await reserve_budget( + session, + actor.id, + "workflow.child" if internal else "jobs.create", + units=body.count, + settings=settings, + ) + from app.core.maintenance import require_writable + + require_writable(settings) + if ( + actor.auth_kind == "bearer" + and body.execution_mode == "interactive" + and ("interactive:write" not in actor.scopes) + ): + fail(403, "scope_required", "Machine tokens require interactive:write for interactive jobs") + from app.services.quotas import check_storage_budget + + await check_storage_budget(session, settings, actor.id, new_jobs=body.count) + if ( + settings.max_interactive_gpu_jobs > 0 + and body.execution_mode == "interactive" + and (body.task_type in GPU_TYPES) + ): + active = await session.scalar( + select(func.count()) + .select_from(Job) + .where( + Job.owner_id == actor.id, + Job.execution_mode == "interactive", + Job.task_type.in_(GPU_TYPES), + Job.state.notin_(TERMINAL), + ) + ) + if active + body.count > settings.max_interactive_gpu_jobs: + fail(429, "quota_exceeded", "Interactive GPU queue limit reached") + ids = await validate_submission( + session, body, actor.id, settings, frozen_workflow=frozen_workflow + ) + scheduled = ( + body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) + if body.scheduled_at + else None + ) + from app.services.folders import owned_folder + + folder_id = body.folder_id + output_folder_id = ( + body.output_folder_id if "output_folder_id" in body.model_fields_set else folder_id + ) + for target in {folder_id, output_folder_id} - {None}: + await owned_folder(session, target, actor.id, lock=True) + jobs = [] + for index in range(body.count): + job_id = new_id() + future = scheduled and scheduled > utcnow() + parameters = dict(body.parameters) + if body.task_type == "video.replace": + parameters["_video_edit_binding"] = await resolve_analysis_binding( + session, body.input, parameters, actor.id, settings + ) + if body.count > 1: + parameters["seed"] = (parameters.get("seed", 42) + index) % 2**32 + job = Job( + id=job_id, + owner_id=actor.id, + folder_id=folder_id, + output_folder_id=output_folder_id, + task_type=body.task_type, + state="scheduled" if future else "submitting", + phase="scheduled" if future else "waiting_dispatch", + execution_mode=body.execution_mode, + version=1, + input_json=body.input, + parameters=parameters, + request_key=key, + request_hash=fingerprint, + batch_index=index, + upstream_key="cmvr-visual:" + job_id, + scheduled_at=scheduled, + next_action_at=scheduled if future else utcnow(), + attempt_count=0, + work_attempt=0, + preemptions=0, + cancel_requested=False, + ) + session.add(job) + await session.flush() + session.add_all((JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids)) + await emit_job(session, job, increment=False) + jobs.append(job) + if record is not None: + record.resource_json = {"job_ids": [job.id for job in jobs]} + return jobs + + +def wake(runtime): + runtime.coordinator.wake() + + +async def submit(body: Submit, runtime, idempotency_key: str | None = None, actor: Actor = None): + recovering = False + if idempotency_key: + async with runtime.db.session() as session: + recovering = bool( + await session.scalar( + select(Job.id) + .where(Job.owner_id == actor.id, Job.request_key == idempotency_key) + .limit(1) + ) + ) + if body.execution_mode == "batch" and body.task_type in GPU_TYPES and (not recovering): + provider = runtime.provider + capabilities = ( + await provider.upstream_capabilities() + if hasattr(provider, "upstream_capabilities") + else {} + ) + if capabilities.get("protocol_version", 0) < 2 or not capabilities.get( + "admission_policy", False + ): + fail(503, "upstream_protocol_incompatible", "Batch requires scheduling protocol v2") + async with runtime.db.session() as session: + try: + jobs = await create_jobs(session, body, actor, runtime.settings, idempotency_key) + await session.commit() + except IntegrityError: + await session.rollback() + jobs = await create_jobs(session, body, actor, runtime.settings, idempotency_key) + await session.commit() + result = {"jobs": [await job_dto(session, job) for job in jobs]} + wake(runtime) + return result + + +async def list_jobs( + runtime, + page: int = 1, + page_size: int = 24, + task_type: str = "", + state: str = "", + root_only: bool = False, + actor: Actor = None, + folder_id: str = "", +): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with runtime.db.session() as session: + query = select(Job).where(Job.owner_id == actor.id, Job.deleted_at.is_(None)) + from app.services.folders import folder_filter + + query = query.where(await folder_filter(session, Job, actor.id, folder_id)) + if root_only: + query = query.where(Job.run_id.is_(None)) + if task_type: + query = query.where(Job.task_type == task_type) + if state: + query = query.where(Job.state == state) + total = await session.scalar(select(func.count()).select_from(query.subquery())) + jobs = ( + await session.scalars( + query.order_by(Job.created_at.desc(), Job.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + cursor = ( + await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0 + ) + return { + "items": [await job_dto(session, job) for job in jobs], + "total": total, + "page": page, + "page_size": page_size, + "cursor": cursor, + } + + +async def get_job(job_id: str, runtime, actor: Actor = None): + async with runtime.db.session() as session: + return await job_dto(session, await owned_job(session, job_id, actor.id)) + + +async def delete_job(job_id: str, runtime, if_match: str | None = None, actor: Actor = None): + from app.services.deletions import archive_records + + async with runtime.db.session() as session: + result = await archive_records(session, Job, job_id, actor.id, if_match) + await session.commit() + return result + + +async def cancel(job_id: str, runtime, actor: Actor = None): + async with runtime.db.session() as session: + job = await owned_job(session, job_id, actor.id) + if job.state not in TERMINAL and job.state != "collecting": + job.cancel_requested = True + if ( + job.upstream_id is None + and job.upstream_payload is None + and (job.phase not in {"cpu_running", "preparing"}) + ): + job.state, job.phase, job.finished_at = ("cancelled", "cancelled", utcnow()) + else: + job.state, job.phase = ("cancelling", "cancellation_pending") + await emit_job(session, job) + await session.commit() + result = await job_dto(session, job) + wake(runtime) + return result + + +async def retry(job_id: str, runtime, idempotency_key: str | None = None, actor: Actor = None): + async with runtime.db.session() as session: + old = await owned_job(session, job_id, actor.id) + if old.state not in TERMINAL: + fail(409, "job_not_finished", "请先等待或取消当前任务") + if old.run_id: + fail(409, "workflow_child", "Use workflow step retry") + if old.batch_id: + fail(409, "parent_control_required", "Batch members require parent control") + from app.services.submissions import accept_submission + + record = ( + await accept_submission( + session, actor.id, "jobs.retry", idempotency_key, 2, {"job_id": job_id} + ) + if idempotency_key + else None + ) + if record and record.resource_json.get("job_ids"): + jobs = list( + ( + await session.scalars( + select(Job).where( + Job.owner_id == actor.id, + Job.id.in_(record.resource_json["job_ids"]), + Job.deleted_at.is_(None), + ) + ) + ).all() + ) + if len(jobs) != len(record.resource_json["job_ids"]): + fail(410, "resource_purged", "重试任务已删除") + return {"jobs": [await job_dto(session, job) for job in jobs]} + from app.models import Execution + + unsafe = await session.scalar( + select(Execution.id) + .where( + Execution.job_id == old.id, + Execution.state.in_(["allocated", "running", "stopping", "unknown"]), + ) + .limit(1) + ) + if unsafe: + fail(409, "cleanup_pending", "Previous execution has not confirmed cleanup") + body = Submit( + folder_id=old.folder_id, + output_folder_id=old.output_folder_id, + task_type=old.task_type, + input=old.input_json, + parameters={k: v for k, v in old.parameters.items() if k != "_video_edit_binding"}, + execution_mode=old.execution_mode, + ) + jobs = await create_jobs(session, body, actor, runtime.settings) + if record: + record.resource_json = {"job_ids": [j.id for j in jobs]} + await session.commit() + result = {"jobs": [await job_dto(session, job) for job in jobs]} + wake(runtime) + return result + + +async def resolve_analysis_binding(session, inputs, parameters, owner_id, settings): + from app.domain.video_editing import safe_analysis, video_defaults + from app.domain.errors import MediaError + + analysis = await owned_job(session, inputs["analysis_job_id"], owner_id) + if ( + analysis.task_type != "video.people.analyze" + or analysis.state != "succeeded" + or not analysis.upstream_id + ): + fail(422, "invalid_analysis", "请选择已成功的人物分析任务") + source = await owned_asset(session, inputs["video_asset_id"], owner_id) + try: + result = safe_analysis(analysis.result_json, settings) + except MediaError as exc: + fail(422, exc.code, exc.message) + p = video_defaults("video.replace", settings) | parameters + a = video_defaults("video.people.analyze", settings) | analysis.parameters + if ( + analysis.input_json.get("video_asset_id") != source.id + or result["source_sha256"] != source.sha256 + or any(a[k] != p[k] for k in ("profile", "max_pixels", "fps")) + or result["video"]["width"] * result["video"]["height"] > p["max_pixels"] + or any(result["video"][key] % 16 for key in ("width", "height")) + ): + fail(422, "analysis_source_mismatch", "人物分析与源视频或画面规格不一致,请重新分析") + people = {row["id"] for row in result["people"]} + if any(row["person_id"] not in people for row in inputs["replacements"]): + fail(422, "unknown_person", "所选人物不属于此视频分析") + from app.adapters.media import inspect_media + from app.adapters.storage import confined + from app.services.artifacts import digest_file + import asyncio + + path = confined(settings.asset_root, source.storage_key, exists=True) + if await asyncio.to_thread(digest_file, path) != source.sha256: + fail(422, "analysis_source_mismatch", "源视频字节已变更") + from app.adapters.media import inspect_video_timeline + + duration = await inspect_video_timeline(path, settings) + if abs(result["video"]["duration_seconds"] - duration) > 1 / 24 + 0.05: + fail(422, "analysis_source_mismatch", "人物分析与源视频时间轴不一致") + info = await inspect_media(path, settings) + from app.services.video_editing import audio_duration + + source_audio_duration = ( + await audio_duration(path, settings, fallback=info["duration_seconds"]) + if info.get("has_audio") + else None + ) + references = {} + for row in inputs["replacements"]: + image = await owned_asset(session, row["reference_asset_id"], owner_id) + if image.kind != "image": + fail(422, "wrong_asset_kind", "人物参考素材必须为图片") + references[image.id] = image.sha256 + return { + "source_has_audio": bool(info.get("has_audio")), + "source_audio_duration": source_audio_duration, + "source_video_duration": duration, + "reference_sha256": references, + "analysis_id": analysis.upstream_id, + "analysis_token": result["analysis_token"], + "source_sha256": source.sha256, + "profile": result["profile"], + "video": result["video"], + "owner_id": owner_id, + } diff --git a/backend/app/services/orchestration/__init__.py b/backend/app/services/orchestration/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/app/services/orchestration/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/app/services/orchestration/admission_clock.py b/backend/app/services/orchestration/admission_clock.py new file mode 100644 index 0000000..9f5547f --- /dev/null +++ b/backend/app/services/orchestration/admission_clock.py @@ -0,0 +1,74 @@ +"""Durable clock-anomaly gate, applied only to new batch phases.""" + +from datetime import datetime, timezone, timedelta +import json +import math +import os +from pathlib import Path +import time +import uuid + +SHANGHAI = timezone(timedelta(hours=8)) + + +class AdmissionClock: + def __init__(self, path): + self.path = Path(path) + self.watermark = 0.0 + self.closed_through = "" + self.reason = None + self.valid = True + if self.path.exists(): + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + self.watermark = float(data["max_seen"]) + self.closed_through = data["closed_through"] + if not math.isfinite(self.watermark) or not 0 <= self.watermark <= 253402300799: + raise ValueError("Invalid timestamp") + datetime.fromisoformat(self.closed_through) + except (ValueError, KeyError, TypeError, OSError): + self.valid = False + + def observe(self, now=None): + if not self.valid: + self.reason = "clock_state_invalid" + return False + try: + now = time.time() if now is None else float(now) + if not math.isfinite(now): + raise ValueError() + local = datetime.fromtimestamp(now, timezone.utc).astimezone(SHANGHAI) + except (ValueError, TypeError, OverflowError, OSError): + self.reason = "clock_invalid" + return False + closed = (local.date() if local.hour >= 8 else local.date() - timedelta(days=1)).isoformat() + next_closed = max(self.closed_through, closed) + next_watermark = max(self.watermark, now) + if int(next_watermark) > int(self.watermark) or next_closed != self.closed_through: + temporary = self.path.with_name(self.path.name + "." + uuid.uuid4().hex + ".tmp") + try: + self.path.parent.mkdir(parents=True, exist_ok=True) + with temporary.open("x", encoding="utf-8") as stream: + json.dump({"max_seen": next_watermark, "closed_through": next_closed}, stream) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.path) + self.watermark, self.closed_through = (next_watermark, next_closed) + except OSError: + self.reason = "clock_state_unwritable" + return False + finally: + try: + temporary.unlink(missing_ok=True) + except OSError: + pass + if now < self.watermark - 5: + self.reason = "clock_rollback" + return False + if local.hour >= 21 or local.hour < 8: + window_end = local.date() + timedelta(days=1) if local.hour >= 21 else local.date() + if window_end.isoformat() <= self.closed_through: + self.reason = "window_already_closed" + return False + self.reason = None + return True diff --git a/backend/app/services/orchestration/batch_holds.py b/backend/app/services/orchestration/batch_holds.py new file mode 100644 index 0000000..8ac1d02 --- /dev/null +++ b/backend/app/services/orchestration/batch_holds.py @@ -0,0 +1,23 @@ +"""批次暂停/等待规则与创建流程分离,避免工作流和批次服务反向依赖。""" + +from app.models import Batch + + +def member_holds(holds, b, waiting): + holds = set(holds or []) | set(b.hold_reasons or []) + if b.desired_state == "pause": + holds.add("batch_pause") + else: + holds.discard("batch_pause") + if waiting: + holds.add("batch_wait") + else: + holds.discard("batch_wait") + return holds + + +async def run_member_holds(s, r): + b = await s.get(Batch, r.batch_id) + if b is None or b.deleted_at is not None: + return set(r.hold_reasons or []) | {"batch_wait"} + return member_holds(r.hold_reasons, b, False) diff --git a/backend/app/services/orchestration/coordinator.py b/backend/app/services/orchestration/coordinator.py new file mode 100644 index 0000000..88c3627 --- /dev/null +++ b/backend/app/services/orchestration/coordinator.py @@ -0,0 +1,1193 @@ +import asyncio +from datetime import timedelta +import json +import logging +import time +from pathlib import Path +import re +from filelock import FileLock +from sqlalchemy import case, func, or_, select +from app.adapters.storage import confined, safe_file +from app.services.assets import import_output, validate_workflow_output +from app.services.snapshots import asset_dto, public_value +from app.services.events import emit_asset, emit_job +from app.domain.tasks import GPU_TYPES, TERMINAL +from app.models import Asset, Job, JobAsset, User, utcnow + +LOG = logging.getLogger(__name__) +GPU_FENCE_UNSET = object() + + +class PhaseDeferred(Exception): + pass + + +class Coordinator: + def __init__(self, settings, db, provider): + self.settings, self.db, self.provider = (settings, db, provider) + self._task = None + self._cpu = {} + self._preparing = {} + self._collecting = {} + self._cpu_initial_pool = {} + self._pools = {name: asyncio.Semaphore(1) for name in ("new_gpu", "cpu_media", "qwen_http")} + self._held_pool = {} + self._blocked_pools = set() + from app.services.orchestration.admission_clock import AdmissionClock + + self._admission_clock = AdmissionClock(settings.state_root / "admission-clock.json") + self._control_sent = {} + self._run_lock = asyncio.Lock() + self._wake = asyncio.Event() + self._file_lock = FileLock(str(settings.state_root / "coordinator.lock")) + self._closing = False + self.after_tick = None + self.last_tick_success = None + self._cancel_sent = set() + self._uncertain_cpu = set() + + def wake(self): + self._wake.set() + + async def start(self): + self._file_lock.acquire(timeout=0) + try: + async with self.db.session() as session: + rows = ( + await session.scalars( + select(Job).where( + Job.deleted_at.is_(None), + Job.state.notin_(TERMINAL), + Job.task_type.notin_(GPU_TYPES), + Job.state.in_(["running", "cancelling"]), + ) + ) + ).all() + from app.models import Execution + from app.services.artifacts import verify_manifest + + for job in rows: + execution = ( + await session.get(Execution, job.current_execution_id) + if job.current_execution_id + else None + ) + manifest = execution.manifest_json if execution else None + if not manifest: + candidates = sorted( + (self.settings.job_work_root / job.id).glob( + "attempt-*/result-manifest.json" + ) + ) + for candidate in reversed(candidates): + try: + found = json.loads(candidate.read_text(encoding="utf-8")) + if found.get("execution_id") == job.current_execution_id: + manifest = found + break + except (ValueError, OSError): + pass + if manifest and execution: + try: + paths = verify_manifest(self.settings.job_work_root, manifest) + if manifest.get("fence_token") != execution.fence_token: + raise ValueError("Fence mismatch") + job.upstream_result = { + "cpu_outputs": paths, + "cpu_result": manifest["result"], + "metadata": manifest["metadata"], + } + job.state, job.phase = ("collecting", "importing_outputs") + execution.manifest_json = manifest + execution.state = "results_ready" + await emit_job(session, job) + continue + except (ValueError, OSError, KeyError): + pass + if execution and ( + execution.resource_pool == "qwen_http" or job.task_type == "audio.speech" + ): + self._blocked_pools.add(execution.resource_pool) + execution.state = "unknown" + job.state = "cancelled" if job.cancel_requested else "needs_attention" + job.phase, job.finished_at = (job.state, utcnow()) + job.error_json = { + "code": "worker_interrupted", + "message": "服务重启中断了此任务,可手动重试", + "retriable": True, + } + await emit_job(session, job) + blocked = ( + await session.scalars( + select(Execution).where( + Execution.resource_pool.in_(["qwen_http", "cpu_media"]), + Execution.state == "unknown", + ) + ) + ).all() + self._blocked_pools.update((execution.resource_pool for execution in blocked)) + await session.commit() + self._task = asyncio.create_task(self._loop(), name="cmvr-coordinator") + except BaseException: + self._file_lock.release() + raise + + async def close(self): + self._closing = True + if self._task: + self._task.cancel() + await asyncio.gather(self._task, return_exceptions=True) + background = [*self._cpu.values(), *self._preparing.values(), *self._collecting.values()] + for task in background: + task.cancel() + await asyncio.gather(*background, return_exceptions=True) + if self._file_lock.is_locked: + self._file_lock.release() + + async def _loop(self): + while True: + try: + await self.run_once() + self.last_tick_success = time.monotonic() + except asyncio.CancelledError: + raise + except Exception: + LOG.exception("Coordinator tick failed; persisted work remains recoverable") + self._wake.clear() + try: + await asyncio.wait_for(self._wake.wait(), timeout=self.settings.poll_seconds) + except asyncio.TimeoutError: + pass + + async def _job(self, job_id): + async with self.db.session() as session: + return await session.get(Job, job_id) + + # 网络返回可能晚于取消/删除;以事务内重新读取的权威状态裁决,不能用旧对象发布结果。 + async def _update(self, job_id, *, fresh_dispatch=False, remote_observation=None, **changes): + async with self.db.session() as session: + job = await session.get(Job, job_id) + if job is None or job.deleted_at is not None or job.state in TERMINAL: + return job + execution_changed = False + if remote_observation is not None: + from app.services.orchestration.executions import ( + observe_gpu_execution, + gpu_result_fence, + ) + from app.models import Execution + + previous_execution_id = job.current_execution_id + accepted, execution = await observe_gpu_execution(session, job, remote_observation) + if not accepted: + return job + execution_changed = job.current_execution_id != previous_execution_id or any( + ( + isinstance(row, Execution) and session.is_modified(row) + for row in session.dirty + ) + ) + if remote_observation["state"] == "succeeded" and execution: + from app.services.orchestration.executions import packed_gpu_result + + changes["upstream_result"] = packed_gpu_result( + remote_observation.get("result") or {}, gpu_result_fence(execution) + ) + if job.cancel_requested: + if fresh_dispatch or changes.get("state") in { + "collecting", + "succeeded", + "failed", + "timed_out", + "cancelled", + }: + changes = { + "state": "cancelled", + "phase": "cancelled", + "finished_at": utcnow(), + "result_json": None, + "error_json": None, + "sync_warning": None, + } + elif changes.get("state") in {"queued", "running", "submitting"}: + changes["state"], changes["phase"] = ("cancelling", "cancellation_pending") + changed = execution_changed + for key, value in changes.items(): + if getattr(job, key) != value: + setattr(job, key, value) + if key not in {"next_action_at", "sync_failures"}: + changed = True + if changed: + await emit_job(session, job) + await session.commit() + return job + + async def _assets(self, job): + async with self.db.session() as session: + assets = ( + await session.scalars( + select(Asset) + .join(JobAsset, JobAsset.asset_id == Asset.id) + .where( + JobAsset.job_id == job.id, + Asset.owner_id == job.owner_id, + Asset.library_scope == "private", + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + ) + ) + ).all() + return { + asset.id: confined(self.settings.asset_root, asset.storage_key, exists=True) + for asset in assets + } + + async def _workdir(self, job): + job = await self._update(job.id, work_attempt=job.work_attempt + 1) + path = confined( + self.settings.job_work_root, Path(job.id) / f"attempt-{job.work_attempt:04d}" + ) + path.mkdir(parents=True, exist_ok=False) + return (job, path) + + async def _warning(self, job_id, error): + job = await self._job(job_id) + await self._update( + job_id, + sync_warning="上游连接或结果导入暂不可用,正在恢复同步", + sync_failures=job.sync_failures + 1, + next_action_at=utcnow() + timedelta(seconds=min(30, 2 ** min(job.sync_failures, 5))), + ) + LOG.warning("Job %s external boundary unavailable: %s", job_id, type(error).__name__) + + async def _failure(self, job_id, exc): + job = await self._job(job_id) + if job is None or job.deleted_at is not None: + return + from app.models import Execution + + async with self.db.session() as session: + job = await session.get(Job, job_id) + if job is None or job.deleted_at is not None: + return + execution = ( + await session.get(Execution, job.current_execution_id) + if job.current_execution_id + else None + ) + if execution: + unknown = ( + execution.resource_pool == "qwen_http" or job.task_type == "audio.speech" + ) and getattr(exc, "retriable", False) + execution.state = "unknown" if unknown else "exited" + execution.finished_at = utcnow() + if unknown: + self._blocked_pools.add(execution.resource_pool) + await session.commit() + if execution and execution.state == "unknown": + await self._update( + job_id, + state="needs_attention", + phase="remote_outcome_unknown", + error_json={ + "code": "remote_outcome_unknown", + "message": "Remote request completion is unconfirmed", + "retriable": False, + }, + ) + return + code = getattr(exc, "code", "processing_failed") + message = getattr(exc, "message", "任务处理失败,请联系管理员查看服务日志") + await self._update( + job_id, + state="cancelled" if job.cancel_requested else "failed", + phase="cancelled" if job.cancel_requested else "failed", + finished_at=utcnow(), + error_json={ + "code": code, + "message": message, + "retriable": bool(getattr(exc, "retriable", False)), + }, + ) + + # 只有当前 execution 的 fence 匹配才能发布;收集到文件不代表结果已对用户可见。 + async def _complete(self, job_id, result, *, gpu_fence=GPU_FENCE_UNSET): + async with self.db.session() as session: + job = await session.get(Job, job_id) + if job is None or job.deleted_at is not None or job.state in TERMINAL: + return + if gpu_fence is not GPU_FENCE_UNSET: + from app.services.orchestration.executions import gpu_publication_matches + + if not await gpu_publication_matches(session, job, gpu_fence): + return + if job.cancel_requested: + job.state, job.phase = ("cancelled", "cancelled") + job.result_json, job.error_json, job.sync_warning = (None, None, None) + job.finished_at = utcnow() + await emit_job(session, job) + await session.commit() + return + outputs = ( + await session.scalars( + select(Asset) + .where( + Asset.source_job_id == job_id, + Asset.owner_id == job.owner_id, + Asset.library_scope == "private", + Asset.deleted_at.is_(None), + ) + .order_by(Asset.source_output_index) + ) + ).all() + if not outputs: + raise ValueError("Completed job has no imported artifacts") + for asset in outputs: + if gpu_fence is not GPU_FENCE_UNSET and gpu_fence: + from app.models import AssetReference + + binding = await session.scalar( + select(AssetReference.id).where( + AssetReference.asset_id == asset.id, + AssetReference.ref_kind == "execution", + AssetReference.ref_id == gpu_fence["execution_id"], + ) + ) + if not binding: + raise ValueError("Output belongs to a different execution") + if not asset.ready: + asset.ready = True + emit_asset(session, job.owner_id, "asset.created", {"asset": asset_dto(asset)}) + job.state, job.phase = ("succeeded", "completed") + job.result_json, job.finished_at, job.sync_warning = (result, utcnow(), None) + await emit_job(session, job) + await session.commit() + + def _clock_allows(self, job): + if job.execution_mode != "batch": + return True + return self._batch_clock_allows() + + def _batch_clock_allows(self): + from app.core.runtime_policy import read_runtime_policy + from app.services.orchestration.resource_policy import execution_policy + + policy = read_runtime_policy(self.settings) + if policy["configuration_error"]: + return False + if not policy["batch_window_enabled"]: + return True + return execution_policy()["batch_open"] and self._admission_clock.observe() + + # 新任务按创建顺序补队,观察/重试的 next_action_at 仅用于退避,不能改写新任务 FIFO。 + async def run_once(self, *, force=False): + if getattr(self.settings, "inference_remote_files", False): + try: + async with asyncio.timeout(3): + await self.provider.runtime_status() + except Exception: + if getattr(self.settings, "_remote_policy_error", None) != "runtime_policy_invalid": + self.settings._remote_policy_error = "runtime_policy_unavailable" + from app.core.runtime_policy import read_runtime_policy + + policy = read_runtime_policy(self.settings) + if policy["batch_window_enabled"] and (not policy["configuration_error"]): + self._admission_clock.observe() + async with self._run_lock: + for job_id, task in list(self._cpu.items()): + if task.done(): + self._cpu.pop(job_id) + self._cpu_initial_pool.pop(job_id, None) + await asyncio.gather(task, return_exceptions=True) + for pending in (self._preparing, self._collecting): + for jid, task in list(pending.items()): + if task.done(): + pending.pop(jid) + await asyncio.gather(task, return_exceptions=True) + async with self.db.session() as session: + query = select(Job).where(Job.deleted_at.is_(None), Job.state.notin_(TERMINAL)) + if not force: + query = query.where(Job.next_action_at <= utcnow()) + ordering = ( + case((Job.cancel_requested.is_(True), 0), else_=1), + Job.next_action_at, + Job.created_at, + Job.batch_index, + Job.id, + ) + jobs = list((await session.scalars(query.order_by(*ordering).limit(50))).all()) + fresh = ( + select(Job) + .join(User, User.id == Job.owner_id) + .where( + User.disabled.is_(False), + Job.deleted_at.is_(None), + Job.state.notin_(TERMINAL), + Job.task_type.in_(GPU_TYPES), + Job.upstream_id.is_(None), + Job.desired_state == "run", + or_( + Job.hold_reasons == func.json_array(), + Job.hold_reasons == func.json_array("window"), + ), + Job.state.in_(["submitting", "queued", "scheduled"]), + or_(Job.sync_failures == 0, Job.next_action_at <= utcnow()) + if not force + else True, + or_(Job.scheduled_at.is_(None), Job.scheduled_at <= utcnow()), + ) + ) + if not self._batch_clock_allows(): + fresh = fresh.where(Job.execution_mode != "batch") + ready = list( + ( + await session.scalars( + fresh.order_by(Job.created_at, Job.batch_index, Job.id).limit(25) + ) + ).all() + ) + ready_ids = {j.id for j in ready} + jobs = ready + [j for j in jobs if j.id not in ready_ids] + cpu = await session.scalar( + query.where( + Job.task_type.notin_(GPU_TYPES), + or_(Job.scheduled_at.is_(None), Job.scheduled_at <= utcnow()), + ) + .order_by(*ordering) + .limit(1) + ) + if cpu is not None: + jobs = [cpu] + [job for job in jobs if job.id != cpu.id] + from app.services.orchestration.resource_policy import admits + + for job in jobs: + if ( + job.task_type not in GPU_TYPES + or job.upstream_id + or job.upstream_payload is not None + or (job.state in {"collecting", "needs_attention", "paused", "pausing"}) + or job.cancel_requested + ): + continue + if job.scheduled_at and job.scheduled_at > utcnow(): + continue + if ( + not admits(job, settings=self.settings) + or not self._clock_allows(job) + or (not await self._owner_enabled(job.owner_id)) + ): + continue + from app.core.maintenance import maintenance_active + + if maintenance_active(self.settings): + continue + if job.id not in self._preparing and len(self._preparing) < 4: + self._preparing[job.id] = asyncio.create_task( + self._gpu(job, prepare_only=True), name=f"prepare-{job.id}" + ) + if self._preparing: + await asyncio.wait(list(self._preparing.values()), timeout=0.1) + async with self.db.session() as session: + ready = list( + ( + await session.scalars( + fresh.where(Job.upstream_payload.is_not(None)) + .order_by(Job.created_at, Job.batch_index, Job.id) + .limit(25) + ) + ).all() + ) + ready = [ + j for j in ready if j.id not in self._preparing or self._preparing[j.id].done() + ] + ready_ids = {j.id for j in ready} + jobs = ready + [j for j in jobs if j.id not in ready_ids] + if cpu is not None: + jobs = [cpu] + [j for j in jobs if j.id != cpu.id] + for job in jobs: + job = await self._job(job.id) + if job.scheduled_at and job.scheduled_at > utcnow(): + continue + job = await self._update( + job.id, next_action_at=utcnow() + timedelta(seconds=self.settings.poll_seconds) + ) + if job.state in TERMINAL: + continue + from app.core.maintenance import maintenance_active + + holds = set(job.hold_reasons or []) + if maintenance_active(self.settings): + holds.add("maintenance") + else: + holds.discard("maintenance") + if holds != set(job.hold_reasons or []): + job = await self._update(job.id, hold_reasons=sorted(holds)) + if job.id in self._cpu: + if job.cancel_requested and job.state != "collecting": + held = self._held_pool.get(job.id) + draining_http = held == "qwen_http" or ( + job.task_type == "audio.speech" and held == "cpu_media" + ) + if not draining_http: + self._cpu[job.id].cancel() + continue + if job.id in self._uncertain_cpu: + await self._update(job.id, state="needs_attention", phase="outcome_unknown") + continue + if job.state == "needs_attention" or ( + job.state in {"paused", "pausing"} and (not job.upstream_id) + ): + continue + from app.core.maintenance import maintenance_active + + if ( + job.state != "collecting" + and (not job.upstream_id) + and (not job.cancel_requested) + and ( + not admits(job, settings=self.settings) + or not self._clock_allows(job) + or maintenance_active(self.settings) + or (not await self._owner_enabled(job.owner_id)) + ) + ): + continue + if job.id in self._collecting: + continue + if job.id in self._preparing and (not self._preparing[job.id].done()): + continue + if job.task_type in GPU_TYPES: + if job.state == "collecting": + if len(self._collecting) < 2: + self._collecting[job.id] = asyncio.create_task( + self._gpu(job), name=f"collect-{job.id}" + ) + elif ( + job.upstream_id or job.upstream_payload is not None or job.cancel_requested + ): + if ( + not job.upstream_id + and (not job.cancel_requested) + and (job.id not in ready_ids) + ): + continue + await self._gpu(job) + elif job.state == "collecting": + if len(self._collecting) < 2: + self._collecting[job.id] = asyncio.create_task( + self._collect_cpu_background(job), name=f"collect-{job.id}" + ) + elif job.state in {"submitting", "queued", "scheduled", "cancelling"}: + from app.services.orchestration.resource_policy import resource_plan + + initial_pool = resource_plan(job.task_type)[0][1] + if sum((pool == initial_pool for pool in self._cpu_initial_pool.values())) < 25: + self._cpu_initial_pool[job.id] = initial_pool + self._cpu[job.id] = asyncio.create_task( + self._run_cpu(job), name=f"cpu-job-{job.id}" + ) + if self._collecting: + await asyncio.wait(list(self._collecting.values()), timeout=0.1) + if self.after_tick is not None: + await self.after_tick() + + async def _collect_cpu_background(self, job): + try: + await self._collect_cpu(job) + except Exception as exc: + await self._warning(job.id, exc) + + # 上游 POST 前先持久化 payload 与幂等键;响应丢失时复用原键恢复,不能另建一次执行。 + async def _gpu(self, job, *, prepare_only=False): + try: + job = await self._job(job.id) + if job is None or job.deleted_at is not None or job.state in TERMINAL: + return + if job.state == "collecting": + await self._collect_gpu(job) + return + if not job.upstream_id: + if job.cancel_requested and job.upstream_payload is None: + await self._update( + job.id, state="cancelled", phase="cancelled", finished_at=utcnow() + ) + return + if job.upstream_payload is None: + job = await self._update(job.id, phase="preparing", state="submitting") + job, work = await self._workdir(job) + from app.domain.execution import current_phase_callback + + async def prepare_phase(key, pool): + from app.services.orchestration.resource_policy import admits + + current = await self._job(job.id) + if not admits(current, settings=self.settings): + raise PhaseDeferred() + await self._enter_phase(job.id, key, pool, nonblocking=True) + + token = current_phase_callback.set(prepare_phase) + try: + parameters = dict(job.parameters) + frozen_binding = parameters.pop("_video_edit_binding", None) + extra = {} + if job.task_type == "video.replace": + from app.services.jobs import resolve_analysis_binding + + async with self.db.session() as session: + binding = await resolve_analysis_binding( + session, job.input_json, parameters, job.owner_id, self.settings + ) + if frozen_binding != binding: + raise ValueError("Frozen analysis binding changed") + extra["analysis_binding"] = binding + payload = await self.provider.prepare_gpu_payload( + job.task_type, + job.input_json, + parameters, + await self._assets(job), + work, + **extra, + ) + finally: + current_phase_callback.reset(token) + held = self._held_pool.pop(job.id, None) + if held: + self._pools[held].release() + payload["scheduling"] = { + "execution_mode": job.execution_mode, + "principal_id": job.owner_id, + "policy_version": job.policy_version, + **{ + key: getattr(job, key) + for key in ("batch_id", "run_id", "step_key") + if getattr(job, key) + }, + } + job = await self._update( + job.id, upstream_payload=payload, phase="dispatching", fresh_dispatch=True + ) + if job.state in TERMINAL: + return + job = await self._job(job.id) + if job.cancel_requested: + await self._update( + job.id, state="cancelled", phase="cancelled", finished_at=utcnow() + ) + return + if prepare_only: + return + from app.services.orchestration.resource_policy import admits + + if not job.cancel_requested and ( + not admits(job, settings=self.settings) + or not self._clock_allows(job) + or (not await self._owner_enabled(job.owner_id)) + ): + return + if job.execution_mode == "batch": + capabilities = ( + await self.provider.upstream_capabilities() + if hasattr(self.provider, "upstream_capabilities") + else {} + ) + if capabilities.get("protocol_version", 0) < 2 or not capabilities.get( + "admission_policy", False + ): + await self._update( + job.id, sync_warning="Batch requires upstream scheduling protocol v2" + ) + return + remote = await self.provider.submit(job.upstream_payload, job.upstream_key) + remote_id = remote.get("id") + if not isinstance(remote_id, str) or not remote_id: + raise ValueError("Upstream omitted its job ID") + job = await self._update(job.id, upstream_id=remote_id) + else: + controls = {"manual", "batch_pause", "admin_suspend", "batch_wait", "maintenance"} + desired = ( + "pause" + if job.desired_state == "pause" or controls.intersection(job.hold_reasons or []) + else "run" + ) + if job.cancel_requested and job.id not in self._cancel_sent: + remote = await self.provider.cancel(job.upstream_id) + self._cancel_sent.add(job.id) + elif ( + not job.cancel_requested + and hasattr(self.provider, "control") + and (self._control_sent.get(job.id) != desired) + ): + remote = await self.provider.control( + job.upstream_id, + desired, + "cmvr:" + job.id + ":" + str(job.version) + ":" + desired, + ) + self._control_sent[job.id] = desired + else: + remote = await self.provider.query(job.upstream_id) + await self._apply_remote(job.id, remote, defer_collection=True) + except PhaseDeferred: + await self._update(job.id, state="submitting", phase="waiting_phase") + except asyncio.CancelledError: + raise + except Exception as exc: + if getattr(exc, "code", None) in {"quota_exceeded", "storage_insufficient"}: + await self._failure(job.id, exc) + elif not job.upstream_id and getattr(exc, "code", None) == "upstream_rejected": + await self._failure(job.id, exc) + elif ( + getattr(exc, "retriable", False) + or job.upstream_payload is not None + or job.upstream_id + ): + await self._warning(job.id, exc) + else: + LOG.exception("Job %s preparation failed", job.id) + await self._failure(job.id, exc) + + async def _apply_remote(self, job_id, remote, *, defer_collection=False): + state = remote.get("state") + if state not in { + "queued", + "running", + "paused", + "pausing", + "succeeded", + "failed", + "cancelled", + "timed_out", + }: + raise ValueError("Invalid upstream job state") + job = await self._job(job_id) + changes = { + "state": state, + "phase": remote.get("stage") or state, + "attempt_count": int(remote.get("attempt_count", job.attempt_count)), + "preemptions": int(remote.get("preemptions", job.preemptions)), + "last_preempted_reason": public_value(remote.get("last_preempted_reason")), + "sync_warning": None, + "sync_failures": 0, + "next_action_at": utcnow() + timedelta(seconds=self.settings.poll_seconds), + } + if state == "running" and (not job.started_at): + changes["started_at"] = utcnow() + if state == "succeeded": + changes.update( + state="collecting", + phase="importing_outputs", + upstream_result=remote.get("result") or {}, + ) + elif state in TERMINAL: + changes["finished_at"] = utcnow() + if state in {"failed", "timed_out"}: + changes["error_json"] = { + "code": "upstream_" + state, + "message": "模型任务未完成,请检查参数或重试", + "retriable": True, + } + job = await self._update(job_id, remote_observation=remote, **changes) + if job.state == "collecting": + if defer_collection: + if job.id not in self._collecting and len(self._collecting) < 2: + self._collecting[job.id] = asyncio.create_task( + self._gpu(job), name=f"collect-{job.id}" + ) + else: + await self._collect_gpu(job) + + async def _collect_gpu(self, job): + fence = (job.upstream_result or {}).get("_visual_execution") + from app.services.orchestration.executions import gpu_publication_matches + + async with self.db.session() as session: + current = await session.get(Job, job.id) + matches = await gpu_publication_matches(session, current, fence) + if not matches and "_visual_result_json" not in (job.upstream_result or {}): + # 旧记录只有MySQL重编码后的对象;只读重取同一远端结果,原SHA完全匹配才修复封装。 + remote = await self.provider.query(job.upstream_id) + from app.services.orchestration.executions import recover_legacy_gpu_result + + async with self.db.session() as session: + current = await session.get(Job, job.id) + matches = await recover_legacy_gpu_result(session, current, remote, fence) + if matches: + await session.commit() + if matches: + job = await self._job(job.id) + if not matches: + raise ValueError("Stale GPU execution result") + from app.services.orchestration.executions import gpu_result + + private = gpu_result(job) + outputs = private.get("outputs") + if not isinstance(outputs, list) or not outputs: + raise ValueError("Succeeded upstream job has no outputs") + directory = confined(self.settings.job_work_root, Path(job.id) / "imports") + directory.mkdir(parents=True, exist_ok=True) + assets = [] + selected_indices = None + if job.task_type in {"video.people.analyze", "video.replace"}: + from app.services.video_editing import validate_result_metadata + + metadata, selected_indices = validate_result_metadata(job, outputs, self.settings) + if job.task_type == "video.people.analyze": + from app.services.assets import owned_asset + + async with self.db.session() as session: + source = await owned_asset( + session, job.input_json["video_asset_id"], job.owner_id + ) + if metadata["source_sha256"] != source.sha256: + raise ValueError("Analysis source SHA mismatch") + if job.task_type == "video.generate" and ( + (job.run_id and job.step_key != "compose") + or (job.request_key or "").startswith("candidate:") + ): + selected_indices = (private.get("metadata") or {}).get("final_output_indices") + if ( + not isinstance(selected_indices, list) + or not selected_indices + or any((type(i) is not int or i < 0 or i >= len(outputs) for i in selected_indices)) + ): + raise ValueError( + "Workflow requires explicit final enhanced output indices from upstream" + ) + for index, output in enumerate(outputs): + if selected_indices is not None and index not in selected_indices: + continue + async with self.db.session() as session: + existing = await session.scalar( + select(Asset).where( + Asset.source_job_id == job.id, + Asset.owner_id == job.owner_id, + Asset.library_scope == "private", + Asset.source_output_index == index, + ) + ) + if existing: + if fence: + from app.models import AssetReference + + async with self.db.session() as session: + binding = await session.scalar( + select(AssetReference.id).where( + AssetReference.asset_id == existing.id, + AssetReference.ref_kind == "execution", + AssetReference.ref_id == fence["execution_id"], + ) + ) + if not binding: + raise ValueError("Output belongs to a different execution") + from app.services.artifacts import digest_file + + path = confined(self.settings.asset_root, existing.storage_key, exists=True) + if ( + path.stat().st_size != existing.size_bytes + or digest_file(path) != existing.sha256 + ): + raise ValueError("Imported artifact is missing or corrupt") + await validate_workflow_output(job, path, self.settings) + assets.append(existing) + continue + raw = output.get("path", "") if isinstance(output, dict) else str(output) + suffix = Path(raw).suffix.lower() + if not re.fullmatch("\\.[a-z0-9]{1,10}", suffix): + suffix = ".bin" + destination = directory / f"output-{index:04d}{suffix}" + await self.provider.download(job.upstream_id, index, destination) + assets.append( + await import_output( + self.db, self.settings, job, destination, index, execution_fence=fence + ) + ) + result = public_value(private.get("metadata", {})) + if job.task_type in {"video.people.analyze", "video.replace"}: + result = metadata + if job.task_type == "video.people.analyze": + previews = {a.source_output_index: a for a in assets} + indexes = [metadata["poster_output_index"]] + [ + p["thumbnail_output_index"] for p in metadata["people"] + ] + if any(i not in previews or previews[i].kind != "image" for i in indexes): + raise ValueError("Analysis requires every real image preview") + if job.task_type == "audio.transcribe": + for asset in assets: + if asset.kind == "json" and asset.size_bytes <= 5 * 1024 * 1024: + with safe_file(self.settings.asset_root, asset.storage_key) as stream: + transcript = json.load(stream) + result = { + "text": transcript.get("text", ""), + "segments": transcript.get("segments", []), + } + break + await self._complete(job.id, result, gpu_fence=fence) + + async def _owner_enabled(self, owner_id): + async with self.db.session() as session: + owner = await session.get(User, owner_id) + return owner is not None and (not owner.disabled) + + async def _enter_phase(self, job_id, phase_key, pool, *, nonblocking=False): + previous = self._held_pool.pop(job_id, None) + if previous: + self._pools[previous].release() + from app.services.orchestration.resource_policy import admits + from app.core.maintenance import maintenance_active + + while True: + job = await self._job(job_id) + if job is None or job.deleted_at is not None or job.state in TERMINAL: + raise asyncio.CancelledError() + if job.cancel_requested: + raise asyncio.CancelledError() + if ( + admits(job, settings=self.settings) + and self._clock_allows(job) + and (pool not in self._blocked_pools) + and (not maintenance_active(self.settings)) + and await self._owner_enabled(job.owner_id) + ): + break + if nonblocking: + raise PhaseDeferred() + await self._update(job_id, phase="waiting_phase:" + phase_key) + await asyncio.sleep(min(1, self.settings.poll_seconds)) + if nonblocking and self._pools[pool].locked(): + raise PhaseDeferred() + await self._pools[pool].acquire() + job = await self._job(job_id) + if ( + job.deleted_at is not None + or job.state in TERMINAL + or job.cancel_requested + or (not admits(job, settings=self.settings)) + or (not self._clock_allows(job)) + or (pool in self._blocked_pools) + or maintenance_active(self.settings) + or (not await self._owner_enabled(job.owner_id)) + ): + self._pools[pool].release() + if nonblocking: + raise PhaseDeferred() + return await self._enter_phase(job_id, phase_key, pool) + self._held_pool[job_id] = pool + async with self.db.session() as session: + current = await session.get(Job, job_id) + if current.current_execution_id: + from app.models import Execution + from app.services.orchestration.executions import begin_execution + + active = await session.get(Execution, current.current_execution_id) + if active and (active.phase_key != phase_key or active.resource_pool != pool): + active.state = "exited" + active.finished_at = utcnow() + await begin_execution(session, job_id, phase_key, pool) + await session.commit() + await self._update(job_id, phase="cpu_running") + + # 取消协程不能证明共享 HTTP 调用已停止;未知结果须隔离资源池,禁止自动重放。 + async def _run_cpu(self, job): + phase_token = None + try: + job = await self._job(job.id) + if job is None or job.deleted_at is not None: + return + if job.cancel_requested: + await self._update( + job.id, state="cancelled", phase="cancelled", finished_at=utcnow() + ) + return + if job.state in TERMINAL or job.cancel_requested: + if job.state not in TERMINAL: + await self._update( + job.id, state="cancelled", phase="cancelled", finished_at=utcnow() + ) + return + job, work = await self._workdir(job) + from app.services.orchestration.executions import begin_execution + from app.services.orchestration.resource_policy import resource_plan + from app.domain.execution import current_phase_callback + + phase_token = current_phase_callback.set( + lambda phase, pool: self._enter_phase(job.id, phase, pool) + ) + initial_pool = resource_plan(job.task_type)[0][1] + await self._enter_phase(job.id, "execute", initial_pool) + job = await self._update( + job.id, + state="running", + phase="cpu_running", + started_at=utcnow(), + attempt_count=job.attempt_count + 1, + ) + if job.cancel_requested or job.state in TERMINAL: + if job.state not in TERMINAL: + await self._update( + job.id, state="cancelled", phase="cancelled", finished_at=utcnow() + ) + return + async with self.db.session() as session: + execution = await begin_execution( + session, job.id, resource_pool=resource_plan(job.task_type)[0][1] + ) + await session.commit() + result = await self.provider.run_cpu( + job.task_type, job.input_json, job.parameters, await self._assets(job), work + ) + from app.models import Execution + + async with self.db.session() as session: + current = await session.get(Job, job.id) + if current.cancel_requested: + execution = await session.get(Execution, current.current_execution_id) + if execution: + execution.state = "exited" + execution.finished_at = utcnow() + current.state, current.phase, current.finished_at = ( + "cancelled", + "cancelled", + utcnow(), + ) + current.result_json = None + current.error_json = None + await emit_job(session, current) + await session.commit() + return + from app.services.artifacts import write_manifest + from app.models import Execution + + async with self.db.session() as session: + current = await session.get(Job, job.id) + execution = await session.get(Execution, current.current_execution_id) + manifest = write_manifest( + self.settings.job_work_root, + work, + execution.id, + execution.fence_token, + result.outputs, + result.result, + result.metadata, + ) + from app.services.orchestration.executions import accept_manifest + + async with self.db.session() as session: + if not await accept_manifest( + session, execution.id, execution.fence_token, manifest + ): + current = await session.get(Job, job.id) + if current.cancel_requested: + execution.state = "exited" + execution.finished_at = utcnow() + current.state, current.phase, current.finished_at = ( + "cancelled", + "cancelled", + utcnow(), + ) + current.result_json = None + current.error_json = None + await emit_job(session, current) + await session.commit() + return + await session.commit() + job = await self._job(job.id) + if job.cancel_requested: + await self._update( + job.id, state="cancelled", phase="cancelled", finished_at=utcnow() + ) + return + if not isinstance(result.outputs, list) or not result.outputs: + raise ValueError("CPU provider returned no artifacts") + private = { + "cpu_outputs": [ + str(confined(self.settings.job_work_root, p, exists=True)) + for p in result.outputs + ], + "cpu_result": result.result, + "metadata": result.metadata, + } + job = await self._update( + job.id, state="collecting", phase="importing_outputs", upstream_result=private + ) + if job.state not in TERMINAL: + await self._collect_cpu(job) + except asyncio.CancelledError: + held = self._held_pool.get(job.id) + current = await self._job(job.id) + if ( + self._closing + and (not current.cancel_requested) + and (current.current_execution_id is None) + ): + await self._update( + job.id, + state="queued", + phase="waiting_for_resource", + started_at=None, + finished_at=None, + error_json=None, + ) + return + unknown = held == "qwen_http" or ( + job.task_type == "audio.speech" and held == "cpu_media" + ) + if unknown: + self._blocked_pools.add(held) + from app.models import Execution + + async with self.db.session() as session: + current = await session.get(Job, job.id) + active = ( + await session.get(Execution, current.current_execution_id) + if current.current_execution_id + else None + ) + if active and active.state not in {"results_ready", "exited"}: + active.state = "unknown" if unknown else "exited" + active.finished_at = utcnow() + await session.commit() + job = await self._job(job.id) + if job.state != "collecting": + await self._update( + job.id, + state="cancelled" if job.cancel_requested else "failed", + phase="cancelled" if job.cancel_requested else "interrupted", + finished_at=utcnow(), + error_json=None + if job.cancel_requested + else { + "code": "worker_interrupted", + "message": "任务因服务停止而中断", + "retriable": True, + }, + ) + except Exception as exc: + job = await self._job(job.id) + if job.state == "collecting" and getattr(exc, "code", None) not in { + "quota_exceeded", + "storage_insufficient", + }: + await self._warning(job.id, exc) + else: + LOG.exception("CPU job %s failed", job.id) + try: + await self._failure(job.id, exc) + except Exception: + self._uncertain_cpu.add(job.id) + LOG.exception("CPU outcome uncertain; execution is quarantined") + finally: + previous = self._held_pool.pop(job.id, None) + if previous: + self._pools[previous].release() + if phase_token is not None: + from app.domain.execution import current_phase_callback + + current_phase_callback.reset(phase_token) + + async def _collect_cpu(self, job): + job = await self._job(job.id) + if job is None or job.deleted_at is not None or job.state in TERMINAL: + return + private = job.upstream_result or {} + for index, source in enumerate(private.get("cpu_outputs", [])): + await import_output(self.db, self.settings, job, Path(source), index) + await self._complete(job.id, public_value(private.get("cpu_result", {}))) diff --git a/backend/app/services/orchestration/editor_engine.py b/backend/app/services/orchestration/editor_engine.py new file mode 100644 index 0000000..96ce2fc --- /dev/null +++ b/backend/app/services/orchestration/editor_engine.py @@ -0,0 +1,965 @@ +"""编辑器 typed DAG;仅冻结配方及派发 Job,不执行模型。""" + +from copy import deepcopy +from types import SimpleNamespace +import secrets +import math +from sqlalchemy import select +from fastapi import HTTPException +from app.models import ( + Asset, + AssetReference, + Job, + WorkflowRun, + WorkflowStep, + User, + Execution, + utcnow, +) +from app.core.errors import fail +from app.domain.errors import MediaError +from app.domain.tasks import TERMINAL +from app.domain.stories import compile_story, ordered_reference_ids, canvas +from app.services.workflows import digest, verified_output, emit_run + + +def build_recipes(manifest, reusable, body, settings, story_compiled=None): + spec = manifest["spec"] + force = set(body.get("force", [])) + recipes = [] + lookup = {} + portrait = spec.get("profile") == "portrait_1080_v1" + width, height = (704, 1280) if portrait else (1280, 704) + compiled = {x["shot_id"]: x for x in (story_compiled or {}).get("shots", [])} + audio = manifest.get("audio", {}) + segments = audio.get("segments", []) + needs_script = ( + audio.get("mode") == "generated_narration" + or manifest.get("captions", {}).get("mode") == "ai_script" + ) and any(not s.get("text", "").strip() for s in segments) + if "script" in force: + needs_script = True + + def add(key, kind, unit, binding=None, deps=(), inputs=None, parameters=None, context=None): + reuse = reusable.get(binding) if binding and binding not in force else None + if ( + reuse + and (reuse.get("source") == "generated" or reuse.get("context_hash") is not None) + and reuse.get("context_hash") != context + ): + reuse = None + # seed是选中变体;源帧数仅决定是否足长,其余实际参数不得漂移。 + if reuse and reuse.get("generation_parameters") and reuse.get("source") != "manual": + actual = reuse["generation_parameters"] + excluded = {"seed", "num_frames"} if kind == "video.generate" else {"seed"} + if {k: v for k, v in actual.items() if k not in excluded} != { + k: v for k, v in (parameters or {}).items() if k not in excluded + }: + reuse = None + item = dict( + key=key, + kind=kind, + unit_id=unit, + binding_key=binding, + dependencies=[] if reuse else list(deps), + input=inputs or {}, + parameters=parameters or {}, + context_hash=context, + reuse=deepcopy(reuse), + forced=(binding in force or key in force), + ) + original = manifest.get("bindings", {}).get(binding) or reusable.get(binding) or {} + if original.get("locked") and not reuse and binding not in force: + item["issue"] = { + "code": "locked_dependency_changed", + "unit_id": unit, + "binding_key": binding, + "message": "锁定素材已失效或不再匹配当前生成输入,请解锁或明确强制重生成", + } + recipes.append(item) + if binding: + lookup[binding] = key + lookup[key] = key + return item + + if needs_script: + add( + "script", + "text.script.generate", + "script", + inputs={ + "shots": [ + dict( + shot_id=sid, + name=s.get("name", ""), + visual_prompt=s.get("visual_prompt", s.get("prompt", "")), + motion_prompt=s.get("motion_prompt", ""), + duration_frames=_frames(s), + ) + for sid, s in zip(manifest["shot_ids"], spec["shots"]) + ], + "context": spec.get("context", {}), + }, + parameters={"model": getattr(settings, "qwen_model", "Qwen3.5-27B")}, + ) + speech_by_shot = {} + if audio.get("mode") == "generated_narration": + for i, seg in enumerate(segments, 1): + params = { + "voice": seg.get("voice") + or audio.get("voice") + or (getattr(settings, "tts_voices", ()) or ("",))[0], + "speed": seg.get("speed") or audio.get("speed", 1.0), + "model": getattr(settings, "tts_model", ""), + } + context = digest({"segment": seg, "parameters": params}) if seg.get("text") else None + item = add( + f"speech_{i:04d}", + "audio.speech", + seg["id"], + "audio:" + seg["id"], + ["script"] if needs_script and not seg.get("text") else [], + {"prompt": seg.get("text", "")}, + params, + context, + ) + speech_by_shot.setdefault(seg["shot_id"], []).append(item["key"]) + for i, (sid, shot) in enumerate(zip(manifest["shot_ids"], spec["shots"]), 1): + frame = f"frame_{i:04d}" + video = f"video_{i:04d}" + item = compiled.get(sid, {}) + refs = ordered_reference_ids(item.get("references", [])) + fp = shot.get("frame_parameters", {}) + seed = fp.get("seed", shot.get("parameters", {}).get("seed", 42)) + context = digest( + { + "visual": item.get("context_hash", shot.get("prompt")), + "seed": seed, + "profile": spec.get("profile"), + } + ) + fi = { + "prompt": item.get("frame_prompt", shot.get("visual_prompt", shot.get("prompt", ""))), + "negative_prompt": item.get("effective_settings", {}).get("negative_prompt", ""), + } + if refs: + fi["reference_asset_ids"] = refs + params = dict( + width=width, + height=height, + seed=seed, + num_inference_steps=40 if refs else 50, + guidance_scale=1.0 if refs else 4.0, + ) + if refs: + params.update( + profile=getattr( + settings, "reference_generation_profile", "qwen-image-edit-2511-v1" + ), + true_cfg_scale=4.0, + ) + context = digest({"visual_context": context, "requested_parameters": params}) + add( + frame, + "image.reference.generate" if refs else "image.generate", + sid, + "frame:" + sid, + inputs=fi, + parameters=params, + context=context, + ) + vp = shot.get("video_parameters", {}) + source_seconds = vp.get("source_seconds", (_frames(shot) + 23) // 24) + params = dict( + width=width, + height=height, + num_frames=4 * ((source_seconds * 24 + 3) // 4) + 1, + fps=24, + upscale=vp.get("upscale", True), + upscale_width=1056 if portrait else 1920, + upscale_height=1920 if portrait else 1056, + seed=vp.get("seed", shot.get("parameters", {}).get("seed", 42)), + num_inference_steps=vp.get("num_inference_steps", 50), + guidance_scale=vp.get("guidance_scale", 5.0), + tile_size=128, + ) + # trim和请求源长不使已足长的真实源失效;其余生成意图仍参与上下文。 + vc = digest( + { + "frame_context": context, + "motion": shot.get("motion_prompt", shot.get("prompt", "")), + "profile": spec.get("profile"), + "seed": params["seed"], + "steps": params["num_inference_steps"], + "guidance_scale": params["guidance_scale"], + "upscale": params["upscale"], + } + ) + base_vc = vc + if reusable.get("frame:" + sid): + vc = digest({"context": base_vc, "frame_sha256": reusable["frame:" + sid]["sha256"]}) + if "frame:" + sid in force: + reusable = {k: v for k, v in reusable.items() if k != "video:" + sid} + add( + video, + "video.generate", + sid, + "video:" + sid, + [frame] + speech_by_shot.get(sid, []), + { + "prompt": shot.get("motion_prompt", shot.get("prompt", "")) + or "静态镜头,保持画面主体和外观一致" + }, + params, + vc, + ) + recipes[-1]["base_context_hash"] = base_vc + if audio.get("mode") == "generated_narration": + add( + "assemble", + "audio.assemble", + "audio", + deps=[k for v in speech_by_shot.values() for k in v], + parameters={"fps": 24}, + ) + if manifest.get("captions", {}).get("mode") not in {"none", None}: + add( + "captions", + "captions.compile", + "captions", + deps=(["script"] if needs_script else []) + + [k for v in speech_by_shot.values() for k in v], + ) + add( + "compose", + "video.compose", + "film", + deps=[f"video_{i:04d}" for i in range(1, len(spec["shots"]) + 1)] + + (["assemble"] if audio.get("mode") == "generated_narration" else []) + + (["captions"] if "captions" in lookup else []), + ) + bykey = {r["key"]: r for r in recipes} + targets = ( + ["compose"] + if body.get("output_goal", "film") == "film" + else body.get("targets") or ["video:" + x for x in manifest["shot_ids"]] + ) + wanted = set() + + def include(key): + if key not in bykey: + fail(422, "invalid_target", "执行目标不存在") + if key in wanted: + return + wanted.add(key) + for dep in bykey[key]["dependencies"]: + include(dep) + + for target in targets: + include(lookup.get(target, target)) + for target in force: + if target not in lookup: + fail(422, "invalid_target", "强制生成目标不存在") + # 显式强制节点也是执行目标,即使静音/关闭字幕不再依赖文案。 + include(lookup[target]) + chosen = [r for r in recipes if r["key"] in wanted] + for r in chosen: + if ( + r["key"].startswith("frame_") + and r["reuse"] + and any(r["key"] in other["dependencies"] for other in chosen) + ): + b = r["reuse"] + if (b.get("_width", width), b.get("_height", height)) != (width, height): + if b.get("locked") and r["binding_key"] not in force: + r["issue"] = { + "code": "locked_dependency_changed", + "unit_id": r["unit_id"], + "binding_key": r["binding_key"], + "message": "锁定首帧需要调整尺寸,请解锁或明确强制重生成", + } + r.update( + kind="image.prepare_frame", + reuse=None, + input={"image_asset_id": b["asset_id"]}, + parameters={ + "width": width, + "height": height, + "fit": spec["render"].get("fit", "contain"), + }, + ) + if r["reuse"]: + r["reuse"] = {k: v for k, v in r["reuse"].items() if not k.startswith("_")} + return chosen + + +def _frames(shot): + return shot.get("edit", {}).get("duration_frames", shot.get("duration_frames", 120)) + + +async def _asset(session, owner, binding, settings, kind=None, minimum_frames=None): + a = await session.get(Asset, binding.get("asset_id")) + if ( + not a + or a.owner_id != owner + or a.deleted_at + or not a.ready + or a.library_scope != "private" + or a.sha256 != binding.get("sha256") + or (kind and a.kind != kind) + ): + return None + if minimum_frames and ( + a.duration_seconds is None or round(a.duration_seconds * 24) < minimum_frames + ): + return None + if not await verified_output(a, settings): + return None + if a.kind == "video": + from app.services.stories.candidates import validate_video + + shot = SimpleNamespace( + edit=SimpleNamespace(start_frame=0, duration_frames=minimum_frames or 0) + ) + try: + await validate_video(a, shot, settings) + except Exception: + return None + return a + + +async def plan_editor(session, draft, manifest, body, settings): + body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body + from app.services.editors import editor_issues + + issues = editor_issues(manifest) + if manifest.get("captions", {}).get("mode") == "none": + cue_ids = {c["id"] for c in manifest["captions"].get("cues", [])} + issues = [i for i in issues if i.get("unit_id") not in cue_ids] + reusable = {} + spec = manifest["spec"] + for key, binding in manifest.get("bindings", {}).items(): + minimum = None + if key.startswith("video:") and key[6:] in manifest["shot_ids"]: + shot = spec["shots"][manifest["shot_ids"].index(key[6:])] + minimum = shot.get("edit", {}).get("start_frame", 0) + _frames(shot) + a = await _asset(session, draft.owner_id, binding, settings, binding.get("kind"), minimum) + if a: + reusable[key] = deepcopy(binding) + reusable[key].update(_width=a.width, _height=a.height) + if a.duration_seconds is not None: + reusable[key].update( + duration_seconds=a.duration_seconds, + duration_frames=math.ceil(a.duration_seconds * 24) + if a.kind == "audio" + else round(a.duration_seconds * 24), + ) + for sid, shot in zip(manifest["shot_ids"], spec["shots"]): + if ( + shot.get("image_asset_id") + and "frame:" + sid not in reusable + and not manifest.get("bindings", {}).get("frame:" + sid, {}).get("locked") + ): + a = await session.get(Asset, shot["image_asset_id"]) + if a: + binding = { + "asset_id": a.id, + "sha256": a.sha256, + "kind": "image", + "source": "manual", + "_width": a.width, + "_height": a.height, + } + if await _asset(session, draft.owner_id, binding, settings, "image"): + reusable["frame:" + sid] = binding + compiled_issues = [] + compiled = None + if spec.get("schema_version") == 3: + from app.services.stories.common import spec_assets + + model, assets = await spec_assets(session, draft.owner_id, spec, settings) + compiled = compile_story(model, assets) + compiled_issues = [ + dict(e, unit_id=x["shot_id"]) for x in compiled["shots"] for e in x["errors"] + ] + recipes = build_recipes(manifest, reusable, body, settings, compiled) + # 仅在实际目标祖先闭包内报告锁定冲突;独立素材任务不被无关锁定阻挡。 + issues.extend(r["issue"] for r in recipes if r.get("issue")) + generating_frames = { + r["unit_id"] + for r in recipes + if r["kind"] in {"image.generate", "image.reference.generate"} and not r["reuse"] + } + issues.extend(i for i in compiled_issues if i["unit_id"] in generating_frames) + if any( + r["kind"] == "audio.speech" + and not r["reuse"] + and ( + not getattr(settings, "tts_base_url", None) + or not getattr(settings, "tts_model", None) + or r["parameters"]["voice"] not in (getattr(settings, "tts_voices", ()) or ()) + ) + for r in recipes + ): + issues.append({"code": "speech_unavailable", "message": "尚未配置真实配音服务"}) + from app.services.editors import collect_manifest_asset_ids + + frozen_hashes = {} + for aid in collect_manifest_asset_ids(manifest): + a = await session.get(Asset, aid) + if a and a.owner_id == draft.owner_id and a.ready and a.deleted_at is None: + frozen_hashes[aid] = a.sha256 + result = { + "asset_sha256": frozen_hashes, + "output_goal": body.get("output_goal", "film"), + "source_version": draft.version, + "issues": issues, + "steps": [ + { + **r, + "status": "reuse" + if r["reuse"] + else "pending_dependency" + if r["dependencies"] + else "generate", + } + for r in recipes + ], + } + result["plan_hash"] = digest( + { + "manifest": manifest, + "version": draft.version, + "plan": result, + "execution_mode": body.get("execution_mode", "interactive"), + "output_folder_id": body.get("output_folder_id"), + } + ) + return result + + +async def start_editor_run(session, draft, manifest, body, settings): + body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body + plan = await plan_editor(session, draft, manifest, body, settings) + if body.get("expected_version") != draft.version: + fail(409, "draft_version_conflict", "草稿已更新") + if body.get("expected_plan_hash") != plan["plan_hash"]: + fail(409, "plan_changed", "执行计划已改变") + if any( + i["code"] in {"speech_unavailable", "locked_dependency_changed"} for i in plan["issues"] + ) or (plan["issues"] and plan["output_goal"] == "film"): + fail(422, "editor_issues", "请先处理编辑问题") + from app.services.quotas import check_parent_capacity + + await check_parent_capacity(session, settings, draft.owner_id, "run") + from app.services.folders import owned_folder + + folder = body.get("output_folder_id", draft.folder_id) + if folder: + await owned_folder(session, folder, draft.owner_id, lock=True) + frozen = deepcopy(manifest) + recipes = deepcopy(plan["steps"]) + for recipe in recipes: + # 保留作者请求参数与接纳后实际参数两层,force变体后续可直接复用。 + recipe["requested_parameters"] = deepcopy(recipe["parameters"]) + if recipe["forced"] and "seed" in recipe["parameters"]: + prior = manifest.get("bindings", {}).get(recipe.get("binding_key"), {}) + used = { + recipe["parameters"]["seed"], + (prior.get("generation_parameters") or {}).get("seed"), + } + seed = secrets.randbits(32) + while seed in used: + seed = (seed + 1) % 2**32 + recipe["parameters"]["seed"] = seed + if recipe["reuse"] and recipe["binding_key"]: + frozen["bindings"][recipe["binding_key"]] = deepcopy(recipe["reuse"]) + r = WorkflowRun( + owner_id=draft.owner_id, + draft_id=draft.id, + draft_revision=draft.revision, + folder_id=draft.folder_id, + output_folder_id=folder, + run_kind="story_auto" if manifest["source_kind"] == "story" else "workflow_auto", + output_goal=plan["output_goal"], + source_draft_version=draft.version, + base_run_id=manifest.get("base_run_id"), + spec_snapshot=deepcopy(manifest["spec"]), + spec_hash=digest(manifest["spec"]), + plan_snapshot={ + "manifest": deepcopy(manifest), + "asset_sha256": plan["asset_sha256"], + "steps": recipes, + "plan_hash": plan["plan_hash"], + }, + result_manifest=frozen, + execution_mode=body.get("execution_mode", "interactive"), + apply_state="pending", + ) + session.add(r) + await session.flush() + refids = set() + for recipe in recipes: + result = recipe["reuse"] + session.add( + WorkflowStep( + run_id=r.id, + step_key=recipe["key"], + kind=recipe["kind"], + dependencies=recipe["dependencies"], + semantic_input_hash=digest(recipe), + recipe_json=recipe, + state="succeeded" if result else "waiting", + result_json=deepcopy(result), + ) + ) + if result: + refids.add(result["asset_id"]) + # 冻结源也必须持有独立引用,归档草稿不得回收运行依赖。 + from app.services.editors import collect_manifest_asset_ids + + refids.update(collect_manifest_asset_ids(frozen)) + for aid in refids: + session.add(AssetReference(owner_id=r.owner_id, asset_id=aid, ref_kind="run", ref_id=r.id)) + await session.flush() + await emit_run(session, r, False) + return r + + +async def _add_ref(session, r, asset): + existing = await session.scalar( + select(AssetReference.id).where( + AssetReference.asset_id == asset.id, + AssetReference.ref_kind == "run", + AssetReference.ref_id == r.id, + ) + ) + if not existing: + session.add( + AssetReference(owner_id=r.owner_id, asset_id=asset.id, ref_kind="run", ref_id=r.id) + ) + + +async def _resolve(session, r, step, settings): + manifest = deepcopy(r.result_manifest) + recipe = step.recipe_json + inputs = deepcopy(recipe["input"]) + params = deepcopy(recipe["parameters"]) + bindings = manifest["bindings"] + spec = manifest["spec"] + if step.kind == "audio.speech": + seg = next(s for s in manifest["audio"]["segments"] if s["id"] == recipe["unit_id"]) + inputs["prompt"] = seg["text"] + if step.kind == "video.generate": + binding = bindings.get("frame:" + recipe["unit_id"], {}) + if not await _asset(session, r.owner_id, binding, settings, "image"): + fail(409, "dependency_changed", "首帧不可用") + inputs["image_asset_id"] = binding["asset_id"] + shot = next( + s for sid, s in zip(manifest["shot_ids"], spec["shots"]) if sid == recipe["unit_id"] + ) + duration = sum( + bindings.get("audio:" + s["id"], {}).get("duration_frames", 0) + for s in manifest["audio"]["segments"] + if s["shot_id"] == recipe["unit_id"] + ) + if duration > _frames(shot): + fail(409, "invalid_timeline", "配音超出镜头时长") + if shot.get("edit", {}).get("start_frame", 0) + _frames(shot) > params["num_frames"]: + fail(409, "generation_source_too_short", "选用区间超出生成源长度") + if step.kind == "audio.assemble": + offsets = {} + ends = {} + offset = 0 + for sid, shot in zip(manifest["shot_ids"], spec["shots"]): + offsets[sid] = offset + offset += _frames(shot) + ends[sid] = offset + segments = [] + for s in manifest["audio"]["segments"]: + b = bindings["audio:" + s["id"]] + segments.append({"asset_id": b["asset_id"], "offset_frame": offsets[s["shot_id"]]}) + offsets[s["shot_id"]] += b["duration_frames"] + if offsets[s["shot_id"]] > ends[s["shot_id"]]: + fail(409, "invalid_timeline", "配音超出镜头时长") + inputs = {"segments": segments, "total_frames": offset} + if step.kind in {"video.compose", "captions.compile"}: + from app.services.editor_media import compile_captions, materialize_cues + + subtitles = compile_captions(manifest, bindings) + if step.kind == "captions.compile": + return { + "input": {}, + "parameters": {}, + "input_sha256": {}, + "captions": subtitles, + "editable_cues": materialize_cues(manifest, bindings), + } + frozen = deepcopy(spec) + frozen["render"]["subtitles"] = subtitles + frozen["render"]["audio"] = ( + manifest.get("audio", {}).get("track") + if manifest.get("audio", {}).get("mode") != "silent" + else None + ) + clips = [] + for sid, shot in zip(manifest["shot_ids"], spec["shots"]): + b = bindings.get("video:" + sid, {}) + start = shot.get("edit", {}).get("start_frame", 0) + frames = _frames(shot) + a = await _asset(session, r.owner_id, b, settings, "video", start + frames) + if not a: + fail(409, "dependency_changed", "视频源不可用") + from app.adapters.media import inspect_video_track + from app.adapters.storage import confined + + track = await inspect_video_track( + confined(settings.asset_root, a.storage_key, exists=True), settings + ) + clips.append( + { + "shot_id": sid, + "asset_id": a.id, + "sha256": a.sha256, + "width": track["width"], + "height": track["height"], + "fps": track["fps"], + "source_frames": track["frames"], + "start_frame": start, + "duration_frames": frames, + } + ) + inputs = {"asset_ids": [c["asset_id"] for c in clips]} + if frozen["render"].get("audio"): + inputs["audio_asset_id"] = frozen["render"]["audio"]["asset_id"] + params = {"clips": [{"asset_id": c["asset_id"]} for c in clips]} + if spec.get("schema_version") == 3: + params.update( + story_spec=frozen, + render_inputs={"clips": clips, "fps": 24, "canvas": list(canvas(spec["profile"]))}, + ) + else: + params["workflow_spec"] = frozen + ids = set(inputs.get("asset_ids", []) + inputs.get("reference_asset_ids", [])) + ids.update(inputs[k] for k in ("image_asset_id", "audio_asset_id") if inputs.get(k)) + ids.update(s["asset_id"] for s in inputs.get("segments", [])) + hashes = {} + for aid in ids: + a = await session.get(Asset, aid) + if not a or not await _asset( + session, + r.owner_id, + { + "asset_id": aid, + "sha256": (r.plan_snapshot or {}).get("asset_sha256", {}).get(aid, a.sha256), + }, + settings, + ): + fail(409, "dependency_changed", "依赖素材已改变") + hashes[aid] = a.sha256 + if step.kind == "video.compose" and "render_inputs" in params and inputs.get("audio_asset_id"): + aid = inputs["audio_asset_id"] + params["render_inputs"]["audio"] = {"asset_id": aid, "sha256": hashes[aid]} + return {"input": inputs, "parameters": params, "input_sha256": hashes} + + +async def create_editor_child(session, r, step, settings): + from app.services.jobs import create_jobs + from app.services.events import emit_job + from app.schemas.jobs import Submit + + if step.resolved_input_json is None: + step.resolved_input_json = await _resolve(session, r, step, settings) + step.semantic_input_hash = digest(step.resolved_input_json) + resolved = step.resolved_input_json + if step.kind == "captions.compile": + step.result_json = {"cues": resolved["captions"]} + step.state = "succeeded" + manifest = deepcopy(r.result_manifest) + manifest["captions"]["cues"] = resolved["editable_cues"] + r.result_manifest = manifest + return None + # retry也必须验证冻结依赖的字节,绝不把新素材偷偷套入旧输入。 + for aid, sha in resolved["input_sha256"].items(): + if not await _asset(session, r.owner_id, {"asset_id": aid, "sha256": sha}, settings): + fail(409, "dependency_changed", "冻结依赖已改变") + step.explicit_attempt += 1 + jobs = await create_jobs( + session, + Submit( + task_type=step.kind, + input=resolved["input"], + parameters=resolved["parameters"], + execution_mode=r.execution_mode, + folder_id=r.folder_id, + output_folder_id=r.output_folder_id, + ), + SimpleNamespace(id=r.owner_id, auth_kind="session", scopes=[]), + settings, + key=f"run:{r.id}:{step.step_key}:{step.explicit_attempt}", + internal=True, + frozen_workflow=True, + ) + j = jobs[0] + j.run_id = r.id + j.step_key = step.step_key + j.explicit_attempt = step.explicit_attempt + j.desired_state = r.desired_state + j.hold_reasons = list(r.hold_reasons or []) + step.selected_job_id = j.id + step.state = "ready" + step.version += 1 + await emit_job(session, j) + return j + + +async def _collect(session, r, step, job, settings): + kind = { + "text.script.generate": "json", + "audio.speech": "audio", + "audio.assemble": "audio", + "video.compose": "video", + "video.generate": "video", + }.get(step.kind, "image") + a = await session.scalar( + select(Asset) + .where( + Asset.source_job_id == job.id, + Asset.owner_id == r.owner_id, + Asset.library_scope == "private", + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + Asset.kind == kind, + ) + .order_by(Asset.source_output_index) + ) + if not a or not await verified_output(a, settings): + fail(409, "invalid_output", "生成产物不可用") + manifest = deepcopy(r.result_manifest) + if step.kind == "text.script.generate": + texts = {x["shot_id"]: x["text"] for x in (job.result_json or {}).get("segments", [])} + if set(texts) != set(manifest["shot_ids"]): + fail(409, "invalid_output", "旁白镜头不完整") + for seg in manifest["audio"]["segments"]: + if not seg.get("text"): + seg["text"] = texts[seg["shot_id"]] + result = { + "asset_id": a.id, + "sha256": a.sha256, + "kind": a.kind, + "segments": deepcopy(manifest["audio"]["segments"]), + } + else: + if kind == "video": + from app.services.stories.candidates import validate_video + + await validate_video( + a, + None, + settings, + generated=step.kind == "video.generate", + parameters=step.recipe_json["parameters"], + ) + if not a.width or not a.height or a.duration_seconds is None: + fail(409, "invalid_output", "视频元数据不完整") + if ( + step.kind == "video.generate" + and round(a.duration_seconds * 24) + < step.recipe_json["parameters"]["num_frames"] - 1 + ): + fail(409, "invalid_output", "生成视频帧数不足") + if kind == "image" and ( + a.width != step.recipe_json["parameters"]["width"] + or a.height != step.recipe_json["parameters"]["height"] + ): + fail(409, "invalid_output", "首帧尺寸不匹配") + if kind == "audio" and (a.duration_seconds is None or a.duration_seconds <= 0): + fail(409, "invalid_output", "音频时长无效") + context = step.recipe_json.get("context_hash") + if step.kind == "audio.speech": + seg = next( + s for s in manifest["audio"]["segments"] if s["id"] == step.recipe_json["unit_id"] + ) + context = digest({"segment": seg, "parameters": step.recipe_json["parameters"]}) + if step.kind == "video.generate": + context = digest( + { + "context": step.recipe_json["base_context_hash"], + "frame_sha256": manifest["bindings"]["frame:" + step.recipe_json["unit_id"]][ + "sha256" + ], + } + ) + result = { + "asset_id": a.id, + "sha256": a.sha256, + "kind": a.kind, + "source": "manual" if step.kind == "image.prepare_frame" else "generated", + "source_run_id": r.id, + "source_job_id": job.id, + "input_hash": step.semantic_input_hash, + "context_hash": context, + "generation_parameters": deepcopy(step.resolved_input_json["parameters"]), + } + if a.duration_seconds is not None: + result.update( + duration_seconds=a.duration_seconds, + duration_frames=math.ceil(a.duration_seconds * 24) + if kind == "audio" + else round(a.duration_seconds * 24), + ) + if kind == "audio" and isinstance((job.result_json or {}).get("sample_count"), int): + samples = job.result_json["sample_count"] + if samples <= 0 or job.result_json.get("sample_rate", 48000) != 48000: + fail(409, "invalid_output", "音频采样元数据无效") + result.update(sample_count=samples, duration_frames=(samples + 1999) // 2000) + key = step.recipe_json.get("binding_key") + if key: + manifest["bindings"][key] = result + if step.kind == "audio.assemble": + manifest["audio"]["track"] = { + "asset_id": a.id, + "source_start_ms": 0, + "source_end_ms": math.floor(a.duration_seconds * 1000), + "offset_frame": 0, + "short_policy": "silence", + } + if step.kind == "video.compose": + r.current_output_asset_id = a.id + step.result_json = result + step.state = "succeeded" + step.version += 1 + r.result_manifest = manifest + await _add_ref(session, r, a) + + +async def advance_editor_run(session, r, settings): + from app.services.orchestration.workflow_engine import child_capacity + from app.core.maintenance import maintenance_active + + if r.state in {"succeeded", "cancelled", "failed"}: + return + steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == r.id))).all() + bykey = {s.step_key: s for s in steps} + before = digest( + { + "state": r.state, + "output": r.current_output_asset_id, + "error": r.error_json, + "holds": r.hold_reasons, + "steps": [(s.step_key, s.state, s.version) for s in steps], + } + ) + r.hold_reasons = sorted(set(r.hold_reasons or []) - {"quota", "storage"}) + if (r.error_json or {}).get("admission_pending"): + r.error_json = None + selected = [] + for step in steps: + if not step.selected_job_id or step.state == "succeeded": + continue + j = await session.get(Job, step.selected_job_id) + if ( + not j + or j.run_id != r.id + or j.step_key != step.step_key + or j.explicit_attempt != step.explicit_attempt + ): + continue + selected.append(j) + if j.state == "succeeded": + try: + await _collect(session, r, step, j, settings) + except (HTTPException, ValueError, MediaError): + step.state = "blocked" + r.error_json = {"code": "invalid_output", "step_key": step.step_key} + elif j.state in {"failed", "timed_out", "needs_attention"}: + step.state = "blocked" + elif j.state == "cancelled": + step.state = "cancelled" + else: + step.state = "running" if j.state in {"running", "collecting"} else "ready" + if r.desired_state == "cancel": + active = await session.scalar( + select(Execution.id) + .join(Job, Job.id == Execution.job_id) + .where(Job.run_id == r.id, Execution.state.not_in({"exited", "results_ready"})) + ) + r.state = ( + "cancelled" + if not active and all(j.state in TERMINAL for j in selected) + else "cancelling" + ) + if r.state == "cancelled": + r.finished_at = utcnow() + elif any(s.state in {"blocked", "cancelled"} for s in steps): + r.state = "blocked" + if not r.error_json: + r.error_json = { + "code": "step_failed", + "step_key": next(s.step_key for s in steps if s.state in {"blocked", "cancelled"}), + } + elif r.desired_state == "pause" or r.hold_reasons: + r.state = "paused" + elif all(s.state == "succeeded" for s in steps): + r.state = "succeeded" + r.finished_at = utcnow() + from app.services.editors import apply_run_result + + try: + async with session.begin_nested(): + await apply_run_result(session, r, settings) + except HTTPException: + # 成果已经生成;晚编辑或无关旧绑定失效只阻止自动应用。 + await session.refresh(r) + r.apply_state = "conflict" + else: + owner = await session.get(User, r.owner_id) + if not owner or owner.disabled: + r.state = "paused" + r.hold_reasons = sorted(set(r.hold_reasons or []) | {"admin_suspend"}) + else: + r.state = "running" + r.started_at = r.started_at or utcnow() + admitted = 0 + for recipe in r.plan_snapshot["steps"]: + step = bykey[recipe["key"]] + if ( + step.state == "succeeded" + or step.selected_job_id + or not all(bykey[d].state == "succeeded" for d in step.dependencies) + ): + continue + if admitted >= 8 or maintenance_active(settings): + break + if not await child_capacity(session, r, step, settings): + r.hold_reasons = ["quota"] + break + try: + async with session.begin_nested(): + await create_editor_child(session, r, step, settings) + except (HTTPException, ValueError, MediaError) as exc: + await session.refresh(step) + code = ( + exc.detail.get("code") + if isinstance(exc, HTTPException) and isinstance(exc.detail, dict) + else "invalid_timeline" + ) + if code in {"quota_exceeded", "storage_insufficient"}: + r.hold_reasons = ["quota" if code == "quota_exceeded" else "storage"] + break + step.state = "blocked" + r.state = "blocked" + r.error_json = {"code": code, "step_key": step.step_key} + break + admitted += 1 + after = digest( + { + "state": r.state, + "output": r.current_output_asset_id, + "error": r.error_json, + "holds": r.hold_reasons, + "steps": [(s.step_key, s.state, s.version) for s in steps], + } + ) + if before != after: + await emit_run(session, r) diff --git a/backend/app/services/orchestration/executions.py b/backend/app/services/orchestration/executions.py new file mode 100644 index 0000000..f643c82 --- /dev/null +++ b/backend/app/services/orchestration/executions.py @@ -0,0 +1,326 @@ +import secrets +from sqlalchemy import select, func +from app.models import Job, utcnow +from app.models import Execution + + +async def begin_execution(session, job_id, phase_key="execute", resource_pool="cpu_media"): + job = await session.get(Job, job_id) + if not job or job.deleted_at is not None: + raise ValueError("Job is unavailable") + ordinal = ( + await session.scalar(select(func.max(Execution.ordinal)).where(Execution.job_id == job_id)) + or 0 + ) + 1 + row = Execution( + job_id=job_id, + ordinal=ordinal, + phase_key=phase_key, + resource_pool=resource_pool, + fence_token=secrets.token_hex(24), + state="running", + started_at=utcnow(), + ) + session.add(row) + await session.flush() + job.current_execution_id = row.id + return row + + +async def accept_manifest(session, execution_id, fence_token, manifest): + row = await session.get(Execution, execution_id) + if not row or row.fence_token != fence_token: + return False + job = await session.get(Job, row.job_id) + if ( + not job + or job.deleted_at is not None + or job.current_execution_id != execution_id + or job.cancel_requested + ): + return False + row.manifest_json = manifest + row.state = "results_ready" + row.finished_at = utcnow() + return True + + +async def request_control(session, job_id, desired_state, expected_execution_id=None): + job = await session.get(Job, job_id) + if ( + not job + or job.deleted_at is not None + or (expected_execution_id and job.current_execution_id != expected_execution_id) + ): + return {"accepted": False} + if job.state in {"succeeded", "failed", "cancelled", "timed_out"}: + return {"accepted": False, "state": job.state} + if job.desired_state != "cancel": + job.desired_state = desired_state + if desired_state == "cancel": + job.cancel_requested = True + return { + "accepted": True, + "execution_id": job.current_execution_id, + "desired_state": job.desired_state, + } + + +async def observe_gpu_execution(session, job, remote): + """Observe real upstream attempts without fabricating missed/queued claims. + + Return (accepted_snapshot, current_observed_execution). This runs inside the + same transaction as the Job update/event, under the database unit lock. + """ + import hashlib + + if not job or job.deleted_at is not None: + return (False, None) + if remote.get("id") and remote["id"] != job.upstream_id: + return (False, None) + attempt = int(remote.get("attempt_count", job.attempt_count)) + if attempt < 0: + raise ValueError("Invalid upstream attempt") + rows = list( + ( + await session.scalars( + select(Execution) + .where(Execution.job_id == job.id, Execution.phase_key.like("gpu:%")) + .order_by(Execution.ordinal) + ) + ).all() + ) + highest = max( + [job.attempt_count] + [(row.manifest_json or {}).get("upstream_attempt", 0) for row in rows] + ) + if attempt < highest: + return (False, None) + state = remote["state"] + identity = f"{job.upstream_id}:{attempt}" + if remote.get("execution_id") and remote["execution_id"] != identity: + raise ValueError("Upstream execution identity mismatch") + execution = next( + (row for row in rows if (row.manifest_json or {}).get("upstream_execution_id") == identity), + None, + ) + if ( + execution + and remote.get("fence_token") + and ((execution.manifest_json or {}).get("upstream_fence") != remote["fence_token"]) + ): + return (False, None) + if execution and execution.state in {"exited", "results_ready"}: + if execution.state == "exited" and state in {"running", "succeeded"}: + return (False, None) + if execution.state == "results_ready" and state != "succeeded": + return (False, None) + unlaunched = remote.get("stage") == "launching" or ( + "runner_pid" in remote + and remote["runner_pid"] is None + and ("started_at" in remote) + and (remote["started_at"] is None) + ) + actual = attempt > 0 and ( + state == "running" + and (not unlaunched) + or ( + state in {"succeeded", "failed", "timed_out", "cancelled"} + and (not unlaunched or execution is not None) + ) + ) + if execution is None and actual: + previous = ( + await session.get(Execution, job.current_execution_id) + if job.current_execution_id + else None + ) + if previous and previous.state == "running": + previous.state = "exited" + previous.finished_at = utcnow() + previous.manifest_json = {**(previous.manifest_json or {}), "superseded_by": identity} + execution = await begin_execution(session, job.id, f"gpu:{attempt}", "new_gpu") + execution.manifest_json = { + "schema": 1, + "kind": "upstream_gpu", + "upstream_id": job.upstream_id, + "upstream_execution_id": identity, + "upstream_attempt": attempt, + "upstream_fence": remote.get("fence_token") or identity, + "local_fence": execution.fence_token, + } + if execution is None: + no_runner = ( + "runner_pid" in remote + and remote["runner_pid"] is None + or remote.get("cleanup_ack") is True + ) + if no_runner and state in {"queued", "paused", "cancelled"} and job.current_execution_id: + previous = await session.get(Execution, job.current_execution_id) + if previous and previous.phase_key.startswith("gpu:") and (previous.state == "running"): + previous.state = "exited" + previous.finished_at = utcnow() + previous.manifest_json = { + **(previous.manifest_json or {}), + "cleanup_ack": True, + "ack_observed_attempt": attempt, + } + return (True, None) + manifest = dict(execution.manifest_json or {}) + manifest["observed_state"] = state + if state == "succeeded": + result = remote.get("result") or {} + digest = hashlib.sha256(canonical_gpu_result(result).encode()).hexdigest() + if execution.state == "results_ready" and manifest.get("result_hash") != digest: + return (False, None) + manifest["result_hash"] = digest + execution.state = "results_ready" + execution.finished_at = utcnow() + elif state in {"failed", "cancelled", "timed_out"}: + execution.state = "exited" + execution.finished_at = utcnow() + elif state in {"queued", "paused"}: + no_runner = ( + "runner_pid" in remote + and remote["runner_pid"] is None + or remote.get("cleanup_ack") is True + ) + if no_runner: + execution.state = "exited" + execution.finished_at = utcnow() + manifest["cleanup_ack"] = True + execution.manifest_json = manifest + return (True, execution) + + +def gpu_result_fence(execution): + manifest = execution.manifest_json or {} + return { + "execution_id": execution.id, + "fence_token": execution.fence_token, + "upstream_execution_id": manifest.get("upstream_execution_id"), + "upstream_attempt": manifest.get("upstream_attempt"), + "result_hash": manifest.get("result_hash"), + } + + +async def gpu_publication_matches(session, job, fence): + import hashlib + + if not job or job.deleted_at is not None: + return False + if not fence: + return job.current_execution_id is None + if job.current_execution_id != fence.get("execution_id"): + return False + execution = await session.get(Execution, job.current_execution_id) + if ( + not execution + or execution.job_id != job.id + or execution.state != "results_ready" + or (execution.fence_token != fence.get("fence_token")) + ): + return False + manifest = execution.manifest_json or {} + result = { + key: value + for key, value in (job.upstream_result or {}).items() + if key != "_visual_execution" + } + try: + serialized = result.get("_visual_result_json") + if serialized is not None: + if set(result) != {"_visual_result_json"}: + return False + gpu_result(job) + else: + serialized = canonical_gpu_result(result) + digest = hashlib.sha256(serialized.encode()).hexdigest() + except (ValueError, TypeError, AttributeError): + return False + return ( + manifest.get("upstream_execution_id") == fence.get("upstream_execution_id") + and manifest.get("upstream_attempt") == job.attempt_count == fence.get("upstream_attempt") + and (manifest.get("result_hash") == digest == fence.get("result_hash")) + ) + + +def canonical_gpu_result(result): + import json + + if not isinstance(result, dict) or {"_visual_execution", "_visual_result_json"} & result.keys(): + raise ValueError("Invalid upstream result envelope") + return json.dumps(result, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def packed_gpu_result(result, fence): + # MySQL JSON会将某些double重编码为相邻值。将摘要覆盖的原JSON保存为字符串, + # 恢复时仍逐字节校验原SHA,不对数值舍入,也不削弱attempt/fence约束。 + return {"_visual_result_json": canonical_gpu_result(result), "_visual_execution": dict(fence)} + + +def gpu_result(job): + import json + + value = job.upstream_result or {} + if "_visual_result_json" not in value: + return {key: child for key, child in value.items() if key != "_visual_execution"} + if set(value) != {"_visual_result_json", "_visual_execution"} or not isinstance( + value["_visual_result_json"], str + ): + raise ValueError("Invalid persisted GPU result envelope") + result = json.loads(value["_visual_result_json"]) + if canonical_gpu_result(result) != value["_visual_result_json"]: + raise ValueError("Noncanonical persisted GPU result") + return result + + +async def recover_legacy_gpu_result(session, job, remote, fence): + import hashlib + + if ( + not job + or job.deleted_at is not None + or job.cancel_requested + or "_visual_result_json" in (job.upstream_result or {}) + ): + return False + if not fence or job.current_execution_id != fence.get("execution_id"): + return False + execution = await session.get(Execution, job.current_execution_id) + if ( + not execution + or execution.state != "results_ready" + or execution.job_id != job.id + or execution.fence_token != fence.get("fence_token") + ): + return False + manifest = execution.manifest_json or {} + if ( + remote.get("id") != job.upstream_id + or remote.get("state") != "succeeded" + or type(remote.get("attempt_count")) is not int + ): + return False + if not ( + remote["attempt_count"] + == job.attempt_count + == fence.get("upstream_attempt") + == manifest.get("upstream_attempt") + ): + return False + identity = f"{job.upstream_id}:{job.attempt_count}" + if not ( + remote.get("execution_id") + == identity + == fence.get("upstream_execution_id") + == manifest.get("upstream_execution_id") + ): + return False + if manifest.get("upstream_fence") != (remote.get("fence_token") or identity): + return False + result = remote.get("result") + digest = hashlib.sha256(canonical_gpu_result(result).encode()).hexdigest() + if not (digest == manifest.get("result_hash") == fence.get("result_hash")): + return False + job.upstream_result = packed_gpu_result(result, fence) + return await gpu_publication_matches(session, job, fence) diff --git a/backend/app/services/orchestration/resource_policy.py b/backend/app/services/orchestration/resource_policy.py new file mode 100644 index 0000000..ddf99cc --- /dev/null +++ b/backend/app/services/orchestration/resource_policy.py @@ -0,0 +1,81 @@ +"""Admission is evaluated at phase boundaries. A closing window never cancels work.""" + +from datetime import datetime, timezone, timedelta +from app.core.runtime_policy import read_runtime_policy + +SHANGHAI = timezone(timedelta(hours=8)) + + +def execution_policy(now=None, *, settings=None): + policy = read_runtime_policy(settings) + now = now or datetime.now(timezone.utc) + if now.tzinfo is None: + now = now.replace(tzinfo=timezone.utc) + local = now.astimezone(SHANGHAI) + opened = local.hour >= 21 or local.hour < 8 + next_at = local.replace(hour=21, minute=0, second=0, microsecond=0) + if local.hour >= 21: + next_at += timedelta(days=1) + enabled = policy["batch_window_enabled"] + return { + "timezone": "Asia/Shanghai", + "start": "21:00", + "end": "08:00", + "batch_window_enabled": enabled, + "configuration_error": policy["configuration_error"], + "batch_open": not policy["configuration_error"] and (not enabled or opened), + "next_batch_at": next_at.astimezone(timezone.utc).isoformat() + if enabled and (not policy["configuration_error"]) + else None, + "close_behavior": "finish_current", + } + + +def admits(job, now=None, *, settings=None): + if job.cancel_requested or job.desired_state != "run": + return False + if set(job.hold_reasons or []) - {"window"}: + return False + if job.execution_mode != "batch": + return True + policy = read_runtime_policy(settings) + if policy["configuration_error"]: + return False + return not policy["batch_window_enabled"] or execution_policy(now)["batch_open"] + + +def resource_plan(task_type, input_kind=None): + if task_type == "audio.transcribe": + return ( + [("extract_audio", "cpu_media"), ("transcribe", "new_gpu")] + if input_kind == "video" + else [("transcribe", "new_gpu")] + ) + if task_type == "media.structure": + return ( + [("sample_frames", "cpu_media"), ("describe_frames", "qwen_http")] + if input_kind == "video" + else [("describe_frames", "qwen_http")] + ) + if task_type == "text.script.generate": + return [("script", "qwen_http")] + if task_type == "audio.assemble": + return [("assemble", "cpu_media")] + if task_type == "math.solve": + return [("solve", "qwen_http")] + return [ + ( + "execute", + "new_gpu" + if task_type + in { + "image.generate", + "image.reference.generate", + "video.generate", + "defect.generate", + "video.people.analyze", + "video.replace", + } + else "cpu_media", + ) + ] diff --git a/backend/app/services/orchestration/workflow_engine.py b/backend/app/services/orchestration/workflow_engine.py new file mode 100644 index 0000000..08851f5 --- /dev/null +++ b/backend/app/services/orchestration/workflow_engine.py @@ -0,0 +1,234 @@ +"""Durable orchestration only: never execute a model or a media process here.""" + +import logging +from fastapi import HTTPException +from sqlalchemy import select, func +from app.models import Job, utcnow +from app.models import WorkflowRun, WorkflowStep, AssetReference +from app.domain.tasks import TERMINAL, GPU_TYPES +from app.services.workflows import RUN_TERMINAL, create_child, emit_run, selected_output +from app.domain.timeline import ordered_step_keys + +log = logging.getLogger(__name__) +AUTOMATIC_HOLDS = {"quota", "storage"} + + +async def child_capacity(session, r, step, settings): + active = Job.state.not_in(TERMINAL) + own = await session.scalar( + select(func.count()).select_from(Job).where(Job.owner_id == r.owner_id, active) + ) + total = await session.scalar(select(func.count()).select_from(Job).where(active)) + if own >= settings.max_owner_jobs or total >= settings.max_global_jobs: + return False + if ( + settings.max_interactive_gpu_jobs > 0 + and r.execution_mode == "interactive" + and (step.kind in GPU_TYPES) + ): + gpu = await session.scalar( + select(func.count()) + .select_from(Job) + .where( + Job.owner_id == r.owner_id, + active, + Job.execution_mode == "interactive", + Job.task_type.in_(GPU_TYPES), + ) + ) + if gpu >= settings.max_interactive_gpu_jobs: + return False + return True + + +async def advance_run(session, run_id, settings): + r = await session.scalar( + select(WorkflowRun) + .where(WorkflowRun.id == run_id, WorkflowRun.deleted_at.is_(None)) + .with_for_update() + ) + if not r or r.state in RUN_TERMINAL: + return + if r.run_kind in {"story_auto", "workflow_auto"}: + from app.services.orchestration.editor_engine import advance_editor_run + + return await advance_editor_run(session, r, settings) + before = (r.state, r.current_output_asset_id, r.error_json, tuple(r.hold_reasons or [])) + r.hold_reasons = sorted(set(r.hold_reasons or []) - AUTOMATIC_HOLDS) + if (r.error_json or {}).get("admission_pending"): + r.error_json = None + steps = ( + await session.scalars( + select(WorkflowStep).where(WorkflowStep.run_id == r.id).order_by(WorkflowStep.step_key) + ) + ).all() + bykey = {s.step_key: s for s in steps} + changed = False + selected = [] + for step in steps: + if not step.selected_job_id: + continue + job = await session.get(Job, step.selected_job_id) + if job is None or job.owner_id != r.owner_id or job.deleted_at is not None: + continue + selected.append(job) + state = ( + "succeeded" + if job.state == "succeeded" + else "blocked" + if job.state in {"failed", "timed_out", "needs_attention"} + else "cancelled" + if job.state == "cancelled" + else "paused" + if job.state == "paused" + else "running" + if job.state in {"running", "collecting"} + else "ready" + ) + if state == "succeeded": + output = await selected_output(session, job.id, r.owner_id) + if output is None: + state = "blocked" + else: + ref = await session.scalar( + select(AssetReference.id).where( + AssetReference.asset_id == output.id, + AssetReference.ref_kind == "run", + AssetReference.ref_id == r.id, + ) + ) + if not ref: + session.add( + AssetReference( + owner_id=r.owner_id, asset_id=output.id, ref_kind="run", ref_id=r.id + ) + ) + if step.state != state: + step.state = state + step.version += 1 + changed = True + if r.desired_state == "cancel": + if all((j.state in TERMINAL for j in selected)): + r.state = "cancelled" + r.finished_at = utcnow() + else: + r.state = "cancelling" + else: + blocked = next((s for s in steps if s.state == "blocked"), None) + if blocked: + r.state = "blocked" + r.error_json = {"code": "step_failed", "step_key": blocked.step_key} + elif bykey["compose"].state == "succeeded": + a = await selected_output(session, bykey["compose"].selected_job_id, r.owner_id) + if a: + r.current_output_asset_id = a.id + r.state = "succeeded" + r.finished_at = utcnow() + else: + r.state = "blocked" + r.error_json = {"code": "dependency_changed"} + elif r.desired_state == "pause" or r.hold_reasons: + r.state = "paused" + else: + r.state = "running" + r.started_at = r.started_at or utcnow() + # 每 tick 最多接纳 8 个新子任务只是有界补队,后续 tick 会继续,不是单用户总量配额。 + admitted_this_tick = 0 + for key in ordered_step_keys(r.spec_snapshot): + step = bykey[key] + if step.state == "succeeded": + continue + if step.state == "cancelled": + r.state = "blocked" + r.error_json = {"code": "step_cancelled", "step_key": key} + break + if not step.selected_job_id and all( + (bykey[dep].state == "succeeded" for dep in step.dependencies) + ): + from app.core.maintenance import maintenance_active + + if maintenance_active(settings): + r.state = "queued" + break + if admitted_this_tick >= 8: + break + if not await child_capacity(session, r, step, settings): + r.hold_reasons = sorted(set(r.hold_reasons or []) | {"quota"}) + r.error_json = {"code": "quota_exceeded", "admission_pending": True} + break + try: + async with session.begin_nested(): + await create_child(session, r, step, settings) + except HTTPException as exc: + code = exc.detail.get("code") if isinstance(exc.detail, dict) else None + if code not in {"quota_exceeded", "storage_insufficient"}: + raise + await session.refresh(step) + await session.refresh(r) + hold = "quota" if code == "quota_exceeded" else "storage" + r.hold_reasons = sorted(set(r.hold_reasons or []) | {hold}) + r.error_json = {"code": code, "admission_pending": True} + break + admitted_this_tick += 1 + changed = True + if changed or before != ( + r.state, + r.current_output_asset_id, + r.error_json, + tuple(r.hold_reasons or []), + ): + await emit_run(session, r) + + +async def advance_workflows(db, settings, provider): + from app.services.batches import advance_batches + from app.services.stories.candidates import feed_candidates + + async with db.session() as session: + await feed_candidates(session, settings) + await advance_batches(session, settings) + ids = ( + await session.scalars( + select(WorkflowRun.id) + .where(WorkflowRun.deleted_at.is_(None), WorkflowRun.state.not_in(RUN_TERMINAL)) + .order_by(WorkflowRun.created_at, WorkflowRun.id) + ) + ).all() + await session.commit() + for run_id in ids: + try: + async with db.session() as session: + await advance_run(session, run_id, settings) + await session.commit() + except Exception as exc: + if isinstance(exc, HTTPException): + code = ( + exc.detail.get("code", "workflow_admission_failed") + if isinstance(exc.detail, dict) + else "workflow_admission_failed" + ) + else: + log.exception("Workflow advancement failed for %s", run_id) + code = "workflow_orchestration_failed" + async with db.session() as session: + r = await session.scalar( + select(WorkflowRun) + .where(WorkflowRun.id == run_id, WorkflowRun.deleted_at.is_(None)) + .with_for_update() + ) + if r is None or r.state in RUN_TERMINAL: + continue + hold = { + "quota_exceeded": "quota", + "storage_insufficient": "storage", + "owner_disabled": "admin_suspend", + }.get(code) + if hold: + r.hold_reasons = sorted(set(r.hold_reasons or []) | {hold}) + r.state = "queued" if hold in AUTOMATIC_HOLDS else "blocked" + r.error_json = {"code": code, "admission_pending": hold in AUTOMATIC_HOLDS} + await emit_run(session, r) + await session.commit() + async with db.session() as session: + await advance_batches(session, settings) + await session.commit() diff --git a/backend/app/services/quotas.py b/backend/app/services/quotas.py new file mode 100644 index 0000000..1993fd3 --- /dev/null +++ b/backend/app/services/quotas.py @@ -0,0 +1,184 @@ +from sqlalchemy import select, func +from app.models import Job, User, Asset, utcnow +from datetime import timedelta +import shutil +import asyncio +from app.models import QuotaReservation +from app.core.errors import fail + +CREATION_OPERATIONS = { + "jobs.create", + "workflow.run", + "editor.run", + "batch.create", + "story.candidate.create", + "story.candidate.batch", + "story.candidate.retry", + "story.render", +} + + +async def reserve_budget(session, owner_id, operation, units=1, bytes_reserved=0, settings=None): + owner = await session.scalar(select(User).where(User.id == owner_id).with_for_update()) + if owner is None or owner.disabled: + fail(403, "owner_disabled", "Owner is disabled") + if operation in CREATION_OPERATIONS: + recent = await session.scalar( + select(func.count()) + .select_from(QuotaReservation) + .where( + QuotaReservation.owner_id == owner_id, + QuotaReservation.operation.in_(CREATION_OPERATIONS), + QuotaReservation.created_at > utcnow() - timedelta(minutes=1), + ) + ) + if recent >= getattr(settings, "max_creation_commands_per_minute", 6): + fail(429, "quota_exceeded", "Creation rate limit reached") + active = Job.state.notin_(["succeeded", "failed", "cancelled", "timed_out"]) + own = await session.scalar( + select(func.count()).select_from(Job).where(Job.owner_id == owner_id, active) + ) + total = await session.scalar(select(func.count()).select_from(Job).where(active)) + if own + units > getattr(settings, "max_owner_jobs", 500) or total + units > getattr( + settings, "max_global_jobs", 2000 + ): + fail(429, "quota_exceeded", "Unfinished task quota exceeded") + row = QuotaReservation( + owner_id=owner_id, operation=operation, units=units, bytes_reserved=bytes_reserved + ) + session.add(row) + return row + + +async def check_parent_capacity(session, settings, owner_id, kind): + from app.models import WorkflowRun, Batch + + model, terminal, owner_limit, global_limit = ( + ( + WorkflowRun, + {"succeeded", "cancelled", "failed"}, + settings.max_owner_runs, + settings.max_global_runs, + ) + if kind == "run" + else ( + Batch, + {"succeeded", "cancelled", "completed_with_errors"}, + settings.max_owner_batches, + settings.max_global_batches, + ) + ) + active = model.state.notin_(terminal) + own = await session.scalar( + select(func.count()).select_from(model).where(model.owner_id == owner_id, active) + ) + total = await session.scalar(select(func.count()).select_from(model).where(active)) + if model is Batch: + from app.models import ShotCandidate + + # 独立候选命令没有Batch行,以同次接纳的plan ID作为父计划;旧计划保守按候选计数。 + group_id = func.coalesce( + ShotCandidate.plan_json["parent_plan_id"].as_string(), ShotCandidate.id + ) + pending = ( + ShotCandidate.deleted_at.is_(None), + ShotCandidate.batch_id.is_(None), + ShotCandidate.state.not_in({"ready", "failed"}), + ) + own += await session.scalar( + select(func.count(func.distinct(group_id))).where( + *pending, ShotCandidate.owner_id == owner_id + ) + ) + total += await session.scalar(select(func.count(func.distinct(group_id))).where(*pending)) + if own >= owner_limit or total >= global_limit: + fail(429, "quota_exceeded", "Queued workflow or batch limit reached") + + +async def check_story_candidate_capacity(session, settings, owner_id, units): + from app.models import ShotCandidate + + # 持久计划与活动Job分别计数;一个大故事可以等待补队,不能按500个活动Job限额拒收。 + pending = ( + ShotCandidate.deleted_at.is_(None), + ShotCandidate.job_id.is_(None), + ShotCandidate.state.not_in({"ready", "failed"}), + ) + own = await session.scalar( + select(func.count()) + .select_from(ShotCandidate) + .where(*pending, ShotCandidate.owner_id == owner_id) + ) + total = await session.scalar(select(func.count()).select_from(ShotCandidate).where(*pending)) + if ( + own + units > settings.max_owner_story_candidates + or total + units > settings.max_global_story_candidates + ): + fail(429, "quota_exceeded", "Queued story candidate plan limit reached") + + +async def check_storage_budget( + session, settings, owner_id, incoming_bytes=0, new_jobs=0, global_incoming_bytes=None +): + size = await session.scalar( + select(func.coalesce(func.sum(Asset.size_bytes), 0)).where( + Asset.owner_id == owner_id, Asset.ready.is_(True) | Asset.deleted_at.is_(None) + ) + ) + if size + incoming_bytes > getattr(settings, "max_owner_asset_bytes", 100 * 1024**3): + fail(429, "quota_exceeded", "Owner asset quota exceeded") + if settings.mode == "production": + storage_incoming = ( + incoming_bytes if global_incoming_bytes is None else global_incoming_bytes + ) + + def occupied(root): + total = 0 + for path in root.rglob("*"): + if path.is_file() and (not path.is_symlink()): + total += path.stat().st_size + return total + + tmp = (settings.asset_root.parent / "tmp").resolve() + if not tmp.is_relative_to(settings.workspace_root): + raise ValueError("Temporary storage is outside workspace") + roots = {settings.asset_root.resolve(), settings.job_work_root.resolve(), tmp} + roots = [ + root + for root in roots + if not any((root != other and root.is_relative_to(other) for other in roots)) + ] + actual = sum(await asyncio.gather(*(asyncio.to_thread(occupied, root) for root in roots))) + active = await session.scalar( + select(func.count()) + .select_from(Job) + .where(Job.state.notin_(["succeeded", "failed", "cancelled", "timed_out"])) + ) + reserved = (active + new_jobs) * settings.max_output_bytes * 2 + if actual + reserved + storage_incoming > getattr(settings, "max_data_bytes", 2 * 1024**4): + fail( + 503, + "storage_insufficient", + "Application output and temporary storage budget exceeded", + ) + disk = shutil.disk_usage(settings.asset_root) + minimum = max(getattr(settings, "min_free_bytes", 50 * 1024**3), int(disk.total * 0.05)) + if disk.free - reserved - storage_incoming < minimum: + fail(503, "storage_insufficient", "Insufficient reserved storage") + + +class AssetBudgetError(ValueError): + code = "quota_exceeded" + message = "Owner asset storage quota exceeded; output retained for reconciliation" + retriable = False + + +async def enforce_owner_asset_budget(session, settings, owner_id, incoming_bytes): + await session.scalar(select(User).where(User.id == owner_id).with_for_update()) + size = await session.scalar( + select(func.coalesce(func.sum(Asset.size_bytes), 0)).where( + Asset.owner_id == owner_id, Asset.ready.is_(True) | Asset.deleted_at.is_(None) + ) + ) + if size + incoming_bytes > getattr(settings, "max_owner_asset_bytes", 100 * 1024**3): + raise AssetBudgetError() diff --git a/backend/app/services/retention.py b/backend/app/services/retention.py new file mode 100644 index 0000000..5561f32 --- /dev/null +++ b/backend/app/services/retention.py @@ -0,0 +1,50 @@ +"""Conservative first-release GC: inventory only, then explicit opt-in deletion. +Unknown/untracked files are never deleted. Asset references protect live snapshots. +""" + +from datetime import timedelta +from sqlalchemy import select +from app.models import Asset, JobAsset, utcnow +from app.models import AssetReference, SharedAsset +from app.adapters.storage import confined + + +async def collect_garbage(db, settings, dry_run=True, grace_days=14): + report = {"dry_run": dry_run, "candidates": [], "deleted": [], "protected": []} + async with db.session() as session: + rows = ( + await session.scalars( + select(Asset).where(Asset.deleted_at < utcnow() - timedelta(days=grace_days)) + ) + ).all() + for asset in rows: + referenced = await session.scalar( + select(JobAsset.job_id).where(JobAsset.asset_id == asset.id).limit(1) + ) + snapshot = await session.scalar( + select(AssetReference.id).where(AssetReference.asset_id == asset.id).limit(1) + ) + publication = await session.scalar( + select(SharedAsset.id) + .where(SharedAsset.asset_id == asset.id, SharedAsset.withdrawn_at.is_(None)) + .limit(1) + ) + if referenced or snapshot or publication or (not asset.ready): + report["protected"].append(asset.id) + continue + report["candidates"].append(asset.id) + if not dry_run: + from app.core.maintenance import maintenance_active + + if not maintenance_active(settings): + raise RuntimeError("Physical GC requires maintenance") + for key in (asset.storage_key, asset.thumbnail_key): + if key: + path = confined(settings.asset_root, key) + if path.is_file(): + path.unlink() + asset.ready = False + report["deleted"].append(asset.id) + if not dry_run: + await session.commit() + return report diff --git a/backend/app/services/shared_assets.py b/backend/app/services/shared_assets.py new file mode 100644 index 0000000..fab0a0b --- /dev/null +++ b/backend/app/services/shared_assets.py @@ -0,0 +1,366 @@ +import hashlib +from pathlib import Path +import re +import shutil +from sqlalchemy import func, select, update +from app.adapters.storage import confined, file_thread, safe_file +from app.services.assets import owned_asset +from app.core.security import Actor +from app.services.snapshots import asset_dto, iso +from app.core.errors import fail +from app.services.events import emit_asset +from app.models import Asset, User, new_id +from app.models import AssetReference, AssetTag, SharedAsset, Submission +from app.schemas.shared_assets import EmptyPayload + +"Authenticated publication snapshots and independent private imports." + + +def shared_dto(publication, asset, publisher, actor): + base = f"/api/shared-assets/{publication.id}" + return { + "id": publication.id, + "name": asset.name, + "kind": asset.kind, + "mime_type": asset.mime_type, + "size_bytes": asset.size_bytes, + "width": asset.width, + "height": asset.height, + "duration_seconds": asset.duration_seconds, + "tags": asset.tags or [], + "created_at": iso(publication.created_at), + "publisher_id": publisher.id, + "publisher_name": publisher.display_name or publisher.username, + "is_owner": publication.publisher_id == actor.id, + "version": publication.version, + "preview_url": base + "/content", + "thumbnail_url": base + "/thumbnail" if asset.kind in {"image", "video"} else None, + "download_url": base + "/content?download=1", + } + + +def shared_query(): + return ( + select(SharedAsset, Asset, User) + .join(Asset, Asset.id == SharedAsset.asset_id) + .join(User, User.id == SharedAsset.publisher_id) + .where( + SharedAsset.withdrawn_at.is_(None), + Asset.deleted_at.is_(None), + Asset.ready.is_(True), + Asset.library_scope == "shared", + ) + ) + + +async def available_shared(session, shared_id): + row = ( + await session.execute(shared_query().where(SharedAsset.id == shared_id).with_for_update()) + ).first() + if row is None: + fail(404, "shared_asset_not_found", "共享素材不存在或已撤回") + return row + + +# 发布与导入各自复制独立字节和 ID;删除原素材或撤回发布不得破坏他人的私有副本。 +async def copy_asset(settings, source, owner_id, *, scope): + """Copy verified regular files into a fresh directory; never link source bytes.""" + asset_id = new_id() + directory = confined(settings.asset_root, Path(owner_id) / asset_id) + directory.mkdir(parents=True) + + def copy_files(): + suffix = Path(source.storage_key).suffix.lower() + if not re.fullmatch("\\.[a-z0-9]{1,10}", suffix): + suffix = ".bin" + destination = directory / ("original" + suffix) + digest, size = (hashlib.sha256(), 0) + with ( + safe_file(settings.asset_root, source.storage_key) as src, + destination.open("xb") as dst, + ): + while chunk := src.read(1024 * 1024): + size += len(chunk) + if size > source.size_bytes: + raise ValueError("Source size changed") + digest.update(chunk) + dst.write(chunk) + if size != source.size_bytes or digest.hexdigest() != source.sha256: + raise ValueError("Source integrity check failed") + thumbnail = None + if source.thumbnail_key: + thumbnail = directory / "thumbnail.jpg" + with ( + safe_file(settings.asset_root, source.thumbnail_key) as src, + thumbnail.open("xb") as dst, + ): + shutil.copyfileobj(src, dst, 1024 * 1024) + return (destination, thumbnail) + + try: + path, thumbnail = await file_thread(copy_files) + asset = Asset( + id=asset_id, + owner_id=owner_id, + name=source.name, + library_scope=scope, + storage_key=path.relative_to(settings.asset_root).as_posix(), + thumbnail_key=thumbnail.relative_to(settings.asset_root).as_posix() + if thumbnail + else None, + kind=source.kind, + mime_type=source.mime_type, + size_bytes=source.size_bytes, + sha256=source.sha256, + width=source.width, + height=source.height, + duration_seconds=source.duration_seconds, + tags=list(source.tags or []), + favorite=False, + origin="shared", + ready=True, + source_job_id=None, + source_upstream_id=None, + source_output_index=None, + ) + return (asset, directory) + except BaseException as exc: + shutil.rmtree(directory, ignore_errors=True) + if isinstance(exc, (OSError, ValueError)): + fail(404, "file_unavailable", "素材文件不可用") + raise + + +async def copy_budget(session, settings, owner_id, size_bytes): + owner = await session.scalar(select(User).where(User.id == owner_id).with_for_update()) + if owner is None or owner.disabled: + fail(403, "owner_disabled", "用户不可用") + from app.services.quotas import check_storage_budget + + await check_storage_budget(session, settings, owner_id, size_bytes) + + +def add_tags(session, asset): + session.add_all( + (AssetTag(owner_id=asset.owner_id, asset_id=asset.id, tag=tag) for tag in asset.tags or []) + ) + + +async def publish_asset( + asset_id: str, + runtime, + body: EmptyPayload | None = None, + idempotency_key: str | None = None, + actor: Actor = None, +): + from app.core.maintenance import require_writable + from app.services.submissions import accept_submission + + settings = runtime.settings + require_writable(settings) + directory, commit_started = (None, False) + try: + async with runtime.db.session() as session: + record = ( + await accept_submission( + session, actor.id, "assets.publish", idempotency_key, 2, {"asset_id": asset_id} + ) + if idempotency_key is not None + else None + ) + if record and record.resource_json.get("shared_asset_id"): + row = ( + await session.execute( + shared_query().where( + SharedAsset.id == record.resource_json["shared_asset_id"], + SharedAsset.publisher_id == actor.id, + ) + ) + ).first() + if row is None: + fail(410, "resource_purged", "共享发布已撤回") + return shared_dto(*row, actor) + source = await owned_asset(session, asset_id, actor.id) + row = ( + await session.execute( + shared_query().where( + SharedAsset.source_asset_id == source.id, + SharedAsset.publisher_id == actor.id, + ) + ) + ).first() + if row: + publication, snapshot, publisher = row + else: + await copy_budget(session, settings, actor.id, source.size_bytes) + snapshot, directory = await copy_asset(settings, source, actor.id, scope="shared") + session.add(snapshot) + await session.flush() + add_tags(session, snapshot) + publication = SharedAsset( + id=new_id(), + publisher_id=actor.id, + asset_id=snapshot.id, + source_asset_id=source.id, + version=1, + ) + session.add(publication) + await session.flush() + session.add( + AssetReference( + owner_id=actor.id, + asset_id=snapshot.id, + ref_kind="shared", + ref_id=publication.id, + ) + ) + publisher = await session.get(User, actor.id) + if record: + record.resource_json = {"shared_asset_id": publication.id} + commit_started = True + await session.commit() + return shared_dto(publication, snapshot, publisher, actor) + except BaseException: + if directory is not None and (not commit_started): + shutil.rmtree(directory, ignore_errors=True) + raise + + +async def list_shared_assets( + runtime, + q: str = "", + kind: str = "", + tag: str = "", + mine: bool = False, + page: int = 1, + page_size: int = 24, + actor: Actor = None, +): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with runtime.db.session() as session: + query = shared_query() + if q: + query = query.where(Asset.name.contains(q[:255], autoescape=True)) + if kind: + query = query.where(Asset.kind == kind) + if tag: + query = query.where(Asset.id.in_(select(AssetTag.asset_id).where(AssetTag.tag == tag))) + if mine: + query = query.where(SharedAsset.publisher_id == actor.id) + total = await session.scalar(select(func.count()).select_from(query.subquery())) + rows = ( + await session.execute( + query.order_by(SharedAsset.created_at.desc(), SharedAsset.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + return { + "items": [shared_dto(*row, actor) for row in rows], + "total": total, + "page": page, + "page_size": page_size, + } + + +async def get_shared_asset(shared_id: str, runtime, actor: Actor = None): + async with runtime.db.session() as session: + return shared_dto(*await available_shared(session, shared_id), actor) + + +async def import_shared_asset( + shared_id: str, + runtime, + body=None, + idempotency_key: str | None = None, + actor: Actor = None, +): + from app.core.maintenance import require_writable + from app.services.submissions import accept_submission + + folder_id = getattr(body, "folder_id", None) + settings = runtime.settings + require_writable(settings) + directory, commit_started = (None, False) + try: + async with runtime.db.session() as session: + from app.services.folders import owned_folder, assign_asset_folders + + record = ( + await accept_submission( + session, + actor.id, + "shared.import", + idempotency_key, + 2, + { + "shared_asset_id": shared_id, + **({"folder_id": folder_id} if folder_id else {}), + }, + ) + if idempotency_key is not None + else None + ) + if record and record.resource_json.get("asset_id"): + existing = await session.scalar( + select(Asset).where( + Asset.id == record.resource_json["asset_id"], + Asset.owner_id == actor.id, + Asset.library_scope == "private", + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + ) + ) + if existing is None: + fail(410, "resource_purged", "导入素材已删除") + return asset_dto(existing) + if folder_id: + # 已完成的幂等请求先恢复素材;仅首次导入校验目标,目录删除不使成功结果失效。 + # 先只校验权限;copy_budget 锁用户后,成员绑定再锁目录,保持用户→目录锁序。 + await owned_folder(session, folder_id, actor.id) + _, source, _ = await available_shared(session, shared_id) + await copy_budget(session, settings, actor.id, source.size_bytes) + asset, directory = await copy_asset(settings, source, actor.id, scope="private") + session.add(asset) + await session.flush() + await assign_asset_folders(session, asset, [folder_id] if folder_id else []) + add_tags(session, asset) + if record: + record.resource_json = {"asset_id": asset.id} + emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)}) + commit_started = True + await session.commit() + return asset_dto(asset) + except BaseException: + if directory is not None and (not commit_started): + shutil.rmtree(directory, ignore_errors=True) + raise + + +async def withdraw_shared_asset(shared_id: str, runtime, actor: Actor = None): + async with runtime.db.session() as session: + publication = await session.scalar( + select(SharedAsset) + .where(SharedAsset.id == shared_id, SharedAsset.publisher_id == actor.id) + .with_for_update() + ) + if publication is None: + fail(404, "shared_asset_not_found", "共享素材不存在") + from app.services.asset_deletion import remove_asset + + snapshot = await session.get(Asset, publication.asset_id) + if snapshot is None or snapshot.library_scope != "shared" or snapshot.owner_id != actor.id: + fail(409, "invalid_shared_snapshot", "共享素材存储记录异常,无法安全删除") + await remove_asset(session, runtime.settings, snapshot, publication=publication) + await session.execute( + update(Submission) + .where( + Submission.owner_id == actor.id, + Submission.status != "purged", + Submission.resource_json["shared_asset_id"].as_string() == publication.id, + ) + .values(status="purged") + ) + await session.commit() + return None diff --git a/backend/app/services/snapshots.py b/backend/app/services/snapshots.py new file mode 100644 index 0000000..bc51877 --- /dev/null +++ b/backend/app/services/snapshots.py @@ -0,0 +1,354 @@ +import re +from sqlalchemy import select +from app.models import Asset, JobAsset + + +def iso(value): + return value.isoformat(timespec="milliseconds") + "Z" if value is not None else None + + +def public_value(value): + if isinstance(value, dict): + return { + k: public_value(v) + for k, v in value.items() + if k + not in { + "path", + "output_dir", + "storage_key", + "api_key", + "token", + "request_path", + "_video_edit_binding", + "_visual_result_json", + "_visual_execution", + } + } + if isinstance(value, list): + return [public_value(v) for v in value] + if isinstance(value, str): + value = re.sub("/(?:workspace|run|data|home|var|tmp|srv)/[^\\s,;]+", "[server file]", value) + return re.sub("[A-Za-z]:[\\\\/][^\\s,;]+", "[server file]", value) + return value + + +def asset_dto(asset): + return { + "id": asset.id, + "folder_ids": asset.folder_ids, + "name": asset.name, + "kind": asset.kind, + "mime_type": asset.mime_type, + "size_bytes": asset.size_bytes, + "width": asset.width, + "height": asset.height, + "duration_seconds": asset.duration_seconds, + "preview_url": f"/api/assets/{asset.id}/content", + "thumbnail_url": f"/api/assets/{asset.id}/thumbnail" + if asset.kind in {"image", "video"} + else None, + "download_url": f"/api/assets/{asset.id}/content?download=1", + "source_job_id": asset.source_job_id, + "source_output_index": asset.source_output_index, + "origin": asset.origin, + "tags": asset.tags or [], + "favorite": asset.favorite, + "created_at": iso(asset.created_at), + } + + +async def job_dto(session, job): + assets = ( + await session.scalars( + select(Asset) + .where( + Asset.source_job_id == job.id, + Asset.owner_id == job.owner_id, + Asset.library_scope == "private", + Asset.deleted_at.is_(None), + Asset.ready.is_(True), + ) + .order_by(Asset.source_output_index) + ) + ).all() + inputs = ( + await session.scalars(select(JobAsset.asset_id).where(JobAsset.job_id == job.id)) + ).all() + return { + "id": job.id, + "folder_id": job.folder_id, + "output_folder_id": job.output_folder_id, + "task_type": job.task_type, + "state": job.state, + "phase": job.phase, + "version": job.version, + "execution_mode": job.execution_mode, + "desired_state": job.desired_state, + "hold_reasons": job.hold_reasons or [], + "run_id": job.run_id, + "step_key": job.step_key, + "batch_id": job.batch_id, + "current_execution_id": job.current_execution_id, + "explicit_attempt": job.explicit_attempt, + "prompt": job.input_json.get("prompt", ""), + "parameters": public_value(job.parameters), + "input_asset_ids": list(inputs), + "result_assets": [asset_dto(a) for a in assets], + "result": public_value(job.result_json), + "progress": None, + "queue_position": None, + "upstream_id": job.upstream_id, + "attempt_count": job.attempt_count, + "preemptions": job.preemptions, + "last_preempted_reason": job.last_preempted_reason, + "cancel_requested": job.cancel_requested, + "error": job.error_json, + "sync_warning": job.sync_warning, + "created_at": iso(job.created_at), + "scheduled_at": iso(job.scheduled_at), + "started_at": iso(job.started_at), + "finished_at": iso(job.finished_at), + } + + +from sqlalchemy import func, or_ +from app.models import Event, Job, WorkflowDraft, WorkflowRun, WorkflowStep, Batch, BatchItem +from app.domain.timeline import ordered_step_keys +from app.core.errors import fail + + +def draft_dto(d): + return dict( + id=d.id, + folder_id=d.folder_id, + name=d.name, + kind=d.kind, + spec=d.spec, + editor_manifest=d.editor_manifest, + revision=d.revision, + version=d.version, + current_run_id=d.current_run_id, + created_at=iso(d.created_at), + updated_at=iso(d.updated_at), + ) + + +def step_dto(s): + return { + k: getattr(s, k) + for k in ( + "id", + "run_id", + "step_key", + "kind", + "state", + "selected_job_id", + "explicit_attempt", + "dependencies", + "semantic_input_hash", + "version", + ) + } + + +# 对外查询始终同时约束 owner 与删除标记;管理员身份不绕过私有资源隔离。 +async def owned(session, model, id, owner_id): + row = await session.scalar( + select(model) + .where(model.id == id, model.owner_id == owner_id, model.deleted_at.is_(None)) + .with_for_update() + ) + if row is None: + fail(404, "resource_not_found", "记录不存在") + return row + + +async def cursor(session, owner_id): + await session.flush() + return await session.scalar(select(func.max(Event.id)).where(Event.owner_id == owner_id)) or 0 + + +async def snapshot_run(session, owner_id, run_id): + r = await owned(session, WorkflowRun, run_id, owner_id) + d = await owned(session, WorkflowDraft, r.draft_id, owner_id) + steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == r.id))).all() + auto = r.run_kind in {"story_auto", "workflow_auto"} + keys = ( + [x["key"] for x in (r.plan_snapshot or {}).get("steps", [])] + if auto + else ordered_step_keys(r.spec_snapshot) + ) + order = {key: i for i, key in enumerate(keys)} + steps.sort(key=lambda step: (order.get(step.step_key, len(order)), step.step_key)) + selected = [step.selected_job_id for step in steps if step.selected_job_id] + jobs = ( + await session.scalars( + select(Job) + .where( + Job.owner_id == owner_id, + Job.deleted_at.is_(None), + or_(Job.run_id == r.id, Job.id.in_(selected)), + ) + .order_by(Job.created_at, Job.id) + ) + ).all() + outputs = [] + if r.current_output_asset_id: + a = await session.get(Asset, r.current_output_asset_id) + if ( + a + and a.owner_id == owner_id + and (a.library_scope == "private") + and a.ready + and (a.deleted_at is None) + ): + outputs = [asset_dto(a)] + if auto: + seen = {a["id"] for a in outputs} + for step in steps: + aid = (step.result_json or {}).get("asset_id") + if aid and aid not in seen: + a = await session.get(Asset, aid) + if ( + a + and a.owner_id == owner_id + and a.library_scope == "private" + and a.ready + and a.deleted_at is None + ): + outputs.append(asset_dto(a)) + seen.add(aid) + run = { + k: getattr(r, k) + for k in ( + "id", + "folder_id", + "output_folder_id", + "draft_id", + "draft_revision", + "state", + "desired_state", + "execution_mode", + "version", + "batch_id", + "hold_reasons", + ) + } + run.update( + error=r.error_json, + created_at=iso(r.created_at), + started_at=iso(r.started_at), + finished_at=iso(r.finished_at), + result_assets=outputs, + completed_steps=sum((s.state == "succeeded" for s in steps)), + total_steps=len(steps), + ) + if auto: + run.update( + run_kind=r.run_kind, + output_goal=r.output_goal, + apply_state=r.apply_state, + source_draft_version=r.source_draft_version, + frozen_spec=r.spec_snapshot, + editor_manifest=r.result_manifest or (r.plan_snapshot or {}).get("manifest"), + ) + frozen_draft = { + **draft_dto(d), + "spec": r.spec_snapshot, + "revision": r.draft_revision, + "editor_manifest": (r.plan_snapshot or {}).get("manifest"), + } + elif r.spec_snapshot.get("schema_version") == 3: + frozen = {k: v for k, v in r.spec_snapshot.items() if k != "render_inputs"} + run.update(frozen_spec=frozen, render_inputs=r.spec_snapshot["render_inputs"]) + frozen_draft = {**draft_dto(d), "spec": frozen, "revision": r.draft_revision} + else: + frozen_draft = draft_dto(d) + return dict( + draft=frozen_draft, + run=run, + steps=[ + { + **step_dto(s), + **( + { + "recipe": public_value(s.recipe_json), + "resolved_input": public_value(s.resolved_input_json), + "result": public_value(s.result_json), + } + if auto + else {} + ), + } + for s in steps + ], + jobs=[await job_dto(session, j) for j in jobs], + cursor=await cursor(session, owner_id), + ) + + +async def page_rows(s, model, actor, page, page_size, *filters): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + q = select(model).where(model.owner_id == actor.id, model.deleted_at.is_(None), *filters) + total = await s.scalar(select(func.count()).select_from(q.subquery())) + rows = ( + await s.scalars( + q.order_by(model.created_at.desc(), model.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + return ( + rows, + dict(total=total, page=page, page_size=page_size, cursor=await cursor(s, actor.id)), + ) + + +def batch_dto(b, items): + return dict( + id=b.id, + name=b.name, + state=b.state, + desired_state=b.desired_state, + hold_reasons=b.hold_reasons or [], + version=b.version, + created_at=iso(b.created_at), + finished_at=iso(b.finished_at), + total_items=len(items), + completed_items=sum((i.state == "succeeded" for i in items)), + current_item_index=next((i.item_index for i in items if i.state == "running"), None), + active_item_indices=[ + i.item_index for i in items if i.state in {"running", "cleanup_pending"} + ], + active_item_count=sum((i.state in {"running", "cleanup_pending"} for i in items)), + ) + + +async def snapshot_batch(s, owner, id): + b = await owned(s, Batch, id, owner) + items = ( + await s.scalars( + select(BatchItem).where(BatchItem.batch_id == b.id).order_by(BatchItem.item_index) + ) + ).all() + return { + "batch": batch_dto(b, items), + "items": [ + { + k: getattr(i, k) + for k in ( + "id", + "batch_id", + "item_index", + "target_kind", + "target_id", + "state", + "spec_json", + ) + } + for i in items + ], + "cursor": await cursor(s, owner), + } diff --git a/backend/app/services/stories/__init__.py b/backend/app/services/stories/__init__.py new file mode 100644 index 0000000..944b395 --- /dev/null +++ b/backend/app/services/stories/__init__.py @@ -0,0 +1 @@ +"""故事工作室 v3;旧工作流服务保留原协议。""" diff --git a/backend/app/services/stories/api.py b/backend/app/services/stories/api.py new file mode 100644 index 0000000..ee9aec6 --- /dev/null +++ b/backend/app/services/stories/api.py @@ -0,0 +1,672 @@ +"""故事命令的单事务边界:幂等结果、CAS、可信选择和引用一起提交。""" + +import asyncio +from sqlalchemy import select, delete, func +from app.models import ( + WorkflowDraft, + WorkflowRun, + WorkflowStep, + ShotCandidate, + ShotSelection, + AssetReference, + Batch, + BatchItem, + User, + utcnow, +) +from app.core.errors import fail +from app.domain.editors import is_editor_auto +from app.core.maintenance import require_writable +from app.domain.stories import digest, canvas +from app.services.stories.common import ( + story, + cas, + shot_model, + spec_assets, + preview, + selections, + current_hash, + private_asset, + story_dto, + readiness, + candidate_dto, + selection_dto, + add_ref, + emit_story, +) +from app.services.stories.candidates import make_candidate, refresh_candidate, validate_video +from app.services.submissions import accept_submission, request_payload +from app.services.events import emit_asset +from app.services.snapshots import snapshot_run, cursor +from app.schemas.stories import CandidateCreate + + +async def create(runtime, actor, body): + require_writable(runtime.settings) + async with runtime.db.session() as s: + model, assets = await spec_assets(s, actor.id, body.spec, runtime.settings) + from app.services.folders import owned_folder, create_folder + + folder_id = body.folder_id + if folder_id: + await owned_folder(s, folder_id, actor.id, lock=True) + elif "folder_id" not in body.model_fields_set and body.create_folder: + folder_id = (await create_folder(s, actor.id, body.name, unique_name=True)).id + d = WorkflowDraft( + owner_id=actor.id, + name=body.name, + folder_id=folder_id, + kind="story_v3", + spec=model.model_dump(mode="json"), + ) + s.add(d) + await s.flush() + for a in assets.values(): + await add_ref(s, d, a.id, "draft", d.id) + dto = await emit_story(s, d) + await s.commit() + return dto + + +async def listing(runtime, actor, page, page_size, folder_id=""): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with runtime.db.session() as s: + q = select(WorkflowDraft).where( + WorkflowDraft.owner_id == actor.id, + WorkflowDraft.kind == "story_v3", + WorkflowDraft.deleted_at.is_(None), + ) + from app.services.folders import folder_filter + + q = q.where(await folder_filter(s, WorkflowDraft, actor.id, folder_id)) + total = await s.scalar(select(func.count()).select_from(q.subquery())) + rows = ( + await s.scalars( + q.order_by(WorkflowDraft.created_at.desc(), WorkflowDraft.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + return dict( + items=[await story_dto(s, d) for d in rows], + total=total, + page=page, + page_size=page_size, + cursor=await cursor(s, actor.id), + ) + + +async def get(runtime, actor, id, view=None): + async with runtime.db.session() as s: + d = await story(s, id, actor.id) + if view == "preview": + return await preview(s, d) + if view == "readiness": + return await readiness(s, d) + return await story_dto(s, d) + + +async def patch(runtime, actor, id, body, if_match): + require_writable(runtime.settings) + async with runtime.db.session() as s: + d = await story(s, id, actor.id) + if is_editor_auto(d): + fail(409, "editor_required", "请使用可编辑成片接口") + if if_match is None or if_match.strip('"') != str(d.version): + fail(409, "draft_version_conflict", "故事版本冲突") + if "folder_id" in body.model_fields_set: + from app.services.folders import owned_folder + + if body.folder_id: + await owned_folder(s, body.folder_id, actor.id, lock=True) + d.folder_id = body.folder_id + if body.name is not None: + d.name = body.name + cleared = [] + if body.spec is not None: + model, assets = await spec_assets(s, actor.id, body.spec, runtime.settings) + removed_shots = {shot["id"] for shot in d.spec["shots"]} - { + shot.id for shot in model.shots + } + if removed_shots: + latest = await selections(s, d) + retired = [ + row.id for (shot_id, _), row in latest.items() if shot_id in removed_shots + ] + # 镜头移除后审批仅留审计;只释放当前选择的引用,Run/候选仍各自保护素材。 + await s.execute( + delete(AssetReference).where( + AssetReference.owner_id == actor.id, + AssetReference.ref_kind == "selection", + AssetReference.ref_id.in_(retired), + ) + ) + for (shot_id, _), previous in latest.items(): + if shot_id not in removed_shots or not ( + previous.candidate_id or previous.asset_id + ): + continue + # 追加空选择让删除成为真实失效边界;同ID重建或晚到结果均不能复活旧批准。 + row = ShotSelection( + owner_id=actor.id, + draft_id=d.id, + shot_id=shot_id, + kind=previous.kind, + candidate_id=None, + asset_id=None, + context_hash=previous.context_hash, + version=previous.version + 1, + decision_json={ + "asset_sha256": None, + "approver_id": actor.id, + "generation_hash": None, + "compiler_version": "story-v3-v1", + "clear_reason": "shot_removed", + }, + ) + s.add(row) + cleared.append(row) + d.spec = model.model_dump(mode="json") + await s.execute( + delete(AssetReference).where( + AssetReference.ref_kind == "draft", AssetReference.ref_id == d.id + ) + ) + for a in assets.values(): + await add_ref(s, d, a.id, "draft", d.id) + if d.editor_manifest: + from app.services.editor_modes import sync_manual_patch + + await sync_manual_patch(s, d, model.model_dump(mode="json")) + dto = await emit_story(s, d, True) + for row in cleared: + emit_asset( + s, actor.id, "selection.updated", {"selection": await selection_dto(s, d, row)} + ) + await s.commit() + return dto + + +async def command(s, d, actor, operation, key, body): + if is_editor_auto(d): + fail(409, "editor_required", "请使用可编辑成片接口") + sub = await accept_submission( + s, + actor.id, + "story." + operation, + key, + 3, + {"draft_id": d.id, **request_payload(body)}, + ) + if sub.resource_json: + return sub, sub.resource_json["response"] + cas(d, body.expected_version) + return sub, None + + +async def create_candidates(runtime, actor, id, body, key, batch=False, retry_id=None): + require_writable(runtime.settings) + if ( + getattr(body, "execution_mode", None) == "interactive" + and actor.auth_kind == "bearer" + and "interactive:write" not in actor.scopes + ): + fail(403, "scope_required", "Interactive scope required.") + async with runtime.db.session() as s: + d = await story(s, id, actor.id) + if is_editor_auto(d): + fail(409, "editor_required", "请使用可编辑成片接口") + operation = ( + "candidate.retry" if retry_id else "candidate.batch" if batch else "candidate.create" + ) + # retry target is part of the durable body; keys cannot be replayed against another candidate. + payload = request_payload(body) + if retry_id: + payload["candidate_id"] = retry_id + sub = await accept_submission( + s, actor.id, "story." + operation, key, 3, {"draft_id": id, **payload} + ) + if sub.resource_json: + return sub.resource_json["response"] + cas(d, body.expected_version) + from app.services.quotas import ( + reserve_budget, + check_parent_capacity, + check_story_candidate_capacity, + ) + + await reserve_budget(s, actor.id, "story." + operation, units=0, settings=runtime.settings) + b = None + if batch: + if len(set(body.shot_ids)) != len(body.shot_ids): + fail(422, "duplicate_shot", "镜头编号不可重复") + if not retry_id: + units = body.count * (len(body.shot_ids) if batch else 1) + pending = not (getattr(body, "source_kind", None) == "manual" and body.kind == "video") + if pending: + await check_parent_capacity(s, runtime.settings, actor.id, "batch") + await check_story_candidate_capacity(s, runtime.settings, actor.id, units) + if batch: + b = Batch( + owner_id=actor.id, + name=d.name, + spec_snapshot={"kind": "story_candidates", "draft_id": d.id}, + state="queued", + ) + s.add(b) + await s.flush() + candidates = [] + compiled = await preview(s, d) + latest = await selections(s, d) + if retry_id: + old = await s.scalar( + select(ShotCandidate).where( + ShotCandidate.id == retry_id, + ShotCandidate.draft_id == d.id, + ShotCandidate.owner_id == actor.id, + ShotCandidate.deleted_at.is_(None), + ) + ) + if old is None: + fail(404, "candidate_not_found", "候选不存在") + await refresh_candidate(s, d, old, runtime.settings) + if old.state != "failed": + fail(409, "candidate_not_retryable", "仅失败候选可以重试") + if ( + old.plan_json.get("execution_mode") == "interactive" + and actor.auth_kind == "bearer" + and "interactive:write" not in actor.scopes + ): + fail(403, "scope_required", "Interactive scope required.") + if old.job_id: + from app.models import Execution, Job + + active = await s.scalar( + select(Execution.id) + .where( + Execution.job_id == old.job_id, + Execution.state.not_in({"exited", "results_ready"}), + ) + .limit(1) + ) + previous_job = await s.get(Job, old.job_id) + if active or ( + previous_job + and previous_job.state == "needs_attention" + and not (previous_job.error_json or {}).get("safe_to_retry") + ): + fail(409, "cleanup_pending", "候选执行尚未确认清理,不能重复派发") + shot_model(d, old.shot_id) + await check_parent_capacity(s, runtime.settings, actor.id, "batch") + await check_story_candidate_capacity(s, runtime.settings, actor.id, 1) + c = ShotCandidate( + owner_id=d.owner_id, + draft_id=d.id, + shot_id=old.shot_id, + kind=old.kind, + source_kind=old.source_kind, + context_hash=old.context_hash, + generation_hash=old.generation_hash, + created_revision=old.created_revision, + plan_json={**old.plan_json, "parent_plan_id": sub.id}, + ) + s.add(c) + await s.flush() + refs = ( + await s.scalars( + select(AssetReference).where( + AssetReference.ref_kind == "candidate", AssetReference.ref_id == old.id + ) + ) + ).all() + for ref in refs: + await add_ref(s, d, ref.asset_id, "candidate", c.id) + candidates.append(c) + else: + from app.services.stories.candidates import capabilities + + # 只在本次锁定草稿的事务内复用;大计划不会按每个候选重编译故事或重查上游能力。 + prepared = { + "compiled": compiled, + "selections": latest, + "capabilities": await capabilities(runtime) + if body.kind == "frame" and getattr(body, "source_kind", "generated") == "generated" + else None, + } + for sid in body.shot_ids if batch else [body.shot_id]: + values = body.model_dump() + if "output_folder_id" not in body.model_fields_set: + values.pop("output_folder_id", None) + values.pop("shot_ids", None) + values["shot_id"] = sid + request = CandidateCreate.model_validate(values) + if request.source_kind == "manual" and request.count != 1: + fail(422, "manual_count", "人工素材只创建一个候选") + for index in range(body.count): + c = await make_candidate( + s, d, request, runtime, index, b.id if b else None, prepared=prepared + ) + # 接纳组只用于父计划计数,不参与实际模型输入哈希,也不改变冻结输入。 + c.plan_json = {**c.plan_json, "parent_plan_id": sub.id} + candidates.append(c) + if b: + s.add( + BatchItem( + batch_id=b.id, + item_index=len(candidates) - 1, + target_kind="candidate", + target_id=c.id, + spec_json={"candidate_id": c.id}, + ) + ) + response = { + "story": await emit_story(s, d), + "candidates": [await candidate_dto(s, d, c, compiled, latest) for c in candidates], + } + if b: + response["batch_id"] = b.id + sub.resource_json = { + "draft_id": id, + "candidate_ids": [c.id for c in candidates], + "response": response, + } + await s.commit() + runtime.coordinator.wake() + return response + + +async def candidates_list(runtime, actor, id, shot_id, kind, page, page_size): + if page < 1 or not 1 <= page_size <= 100 or kind not in {None, "frame", "video"}: + fail(422, "invalid_page", "候选分页参数无效") + async with runtime.db.session() as s: + d = await story(s, id, actor.id) + q = select(ShotCandidate).where( + ShotCandidate.owner_id == actor.id, + ShotCandidate.draft_id == id, + ShotCandidate.deleted_at.is_(None), + ) + if shot_id: + q = q.where(ShotCandidate.shot_id == shot_id) + if kind: + q = q.where(ShotCandidate.kind == kind) + total = await s.scalar(select(func.count()).select_from(q.subquery())) + rows = ( + await s.scalars( + q.order_by(ShotCandidate.created_at.desc(), ShotCandidate.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + for c in rows: + # 镜头删除后候选保留审计,但异步结果不会恢复已删除的镜头。 + if any(x["id"] == c.shot_id for x in d.spec["shots"]): + await refresh_candidate(s, d, c, runtime.settings) + items = [await candidate_dto(s, d, c) for c in rows] + await s.commit() + return dict(items=items, total=total, page=page, page_size=page_size) + + +async def select_candidate(runtime, actor, id, body, key, clear=False): + require_writable(runtime.settings) + async with runtime.db.session() as s: + d = await story(s, id, actor.id) + sub, replay = await command( + s, d, actor, "selection.clear" if clear else "selection.confirm", key, body + ) + if replay is not None: + return replay + shot = shot_model(d, body.shot_id) + h = await current_hash(s, d, body.shot_id, body.kind) + a, c = None, None + if not clear: + c = await s.scalar( + select(ShotCandidate) + .where( + ShotCandidate.id == body.candidate_id, + ShotCandidate.owner_id == actor.id, + ShotCandidate.draft_id == id, + ShotCandidate.shot_id == body.shot_id, + ShotCandidate.kind == body.kind, + ShotCandidate.deleted_at.is_(None), + ) + .with_for_update() + ) + if not c: + fail(404, "candidate_not_found", "候选不属于此故事镜头") + await refresh_candidate(s, d, c, runtime.settings) + if c.state != "ready" or not c.asset_id: + fail(409, "candidate_not_ready", "候选尚未完成或未通过产物校验") + h = await current_hash( + s, + d, + body.shot_id, + body.kind, + source_kind=c.source_kind, + source_sha256=c.asset_sha256, + ) + if c.context_hash != h: + fail(409, "candidate_stale", "画面设定已改变,请重新生成或人工复核") + a = await private_asset( + s, c.asset_id, actor.id, "image" if body.kind == "frame" else "video" + ) + if a.sha256 != c.asset_sha256: + fail(409, "asset_integrity_failed", "候选素材SHA已改变") + from app.services.workflows import verified_output + + if not await verified_output(a, runtime.settings): + fail(409, "asset_integrity_failed", "素材字节或SHA已改变") + if body.kind == "video": + await validate_video( + a, + shot, + runtime.settings, + c.source_kind == "generated", + c.plan_json["parameters"], + ) + latest = await selections(s, d) + previous = latest.get((shot.id, body.kind)) + row = ShotSelection( + owner_id=actor.id, + draft_id=id, + shot_id=shot.id, + kind=body.kind, + candidate_id=c.id if c else None, + asset_id=a.id if a else None, + decision_json={ + "asset_sha256": a.sha256 if a else None, + "approver_id": actor.id, + "generation_hash": c.generation_hash if c else None, + "source_kind": c.source_kind if c else None, + "compiler_version": "story-v3-v1", + }, + context_hash=h, + version=previous.version + 1 if previous else 1, + ) + s.add(row) + await s.flush() + # 旧选择只保留审计。当前选择和历史 Run 各自持有独立素材引用。 + if previous: + await s.execute( + delete(AssetReference).where( + AssetReference.ref_kind == "selection", AssetReference.ref_id == previous.id + ) + ) + if a: + await add_ref(s, d, a.id, "selection", row.id) + from app.services.editor_modes import sync_manual_selection + + await sync_manual_selection(s, d, row, a, c) + dto = await emit_story(s, d, True) + emit_asset(s, actor.id, "selection.updated", {"selection": await selection_dto(s, d, row)}) + sub.resource_json = {"draft_id": id, "selection_id": row.id, "response": dto} + await s.commit() + return dto + + +async def render(runtime, actor, id, body, key): + require_writable(runtime.settings) + if ( + body.execution_mode == "interactive" + and actor.auth_kind == "bearer" + and "interactive:write" not in actor.scopes + ): + fail(403, "scope_required", "Interactive scope required.") + async with runtime.db.session() as s: + await s.scalar(select(User).where(User.id == actor.id).with_for_update()) + d = await story(s, id, actor.id) + sub, replay = await command(s, d, actor, "render", key, body) + if replay is not None: + return replay + from app.services.editor_modes import manual_spec + + render_spec = manual_spec(d, strict=True) + from app.services.quotas import check_parent_capacity, reserve_budget + + await reserve_budget(s, actor.id, "story.render", units=0, settings=runtime.settings) + await check_parent_capacity(s, runtime.settings, actor.id, "run") + if body.execution_mode == "interactive": + from app.domain.tasks import RUN_TERMINAL + + active = await s.scalar( + select(WorkflowRun.id) + .where( + WorkflowRun.owner_id == actor.id, + WorkflowRun.deleted_at.is_(None), + WorkflowRun.execution_mode == "interactive", + WorkflowRun.state.not_in(RUN_TERMINAL), + ) + .limit(1) + ) + if active: + fail(429, "quota_exceeded", "已有活动交互工作流") + status = await readiness(s, d) + if not status["ready"]: + fail(409, "story_not_ready", "请先确认所有镜头所需的素材选择") + latest, clips = await selections(s, d), [] + for raw in render_spec["shots"]: + shot = shot_model(d, raw["id"]) + selection = latest[(shot.id, "video")] + a = await private_asset(s, selection.asset_id, actor.id, "video") + if a.sha256 != selection.decision_json.get("asset_sha256"): + fail(409, "asset_integrity_failed", "选择确认的素材SHA已改变") + await validate_video(a, shot, runtime.settings) + clips.append( + dict( + shot_id=shot.id, + asset_id=a.id, + sha256=a.sha256, + selection_id=selection.id, + selection_version=selection.version, + start_frame=shot.edit.start_frame, + duration_frames=shot.edit.duration_frames, + width=a.width, + height=a.height, + ) + ) + if getattr(runtime.settings, "inference_remote_files", False): + # 多片段解码期间持有事务锁,协调器无法续更策略;最终准入前直接核验上游。 + try: + async with asyncio.timeout(3): + await runtime.provider.runtime_status() + except Exception: + fail(503, "runtime_policy_unavailable", "运行配置无效") + _, assets = await spec_assets(s, actor.id, render_spec, runtime.settings) + from app.services.workflows import verified_output + + for a in assets.values(): + if not await verified_output(a, runtime.settings): + fail(409, "asset_integrity_failed", "参考素材或音轨校验失败") + frozen_inputs = {"clips": clips, "canvas": list(canvas(render_spec["profile"])), "fps": 24} + frozen_inputs["selections"] = [ + { + "id": x.id, + "shot_id": x.shot_id, + "kind": x.kind, + "version": x.version, + "candidate_id": x.candidate_id, + "asset_id": x.asset_id, + "asset_sha256": x.decision_json.get("asset_sha256"), + } + for x in latest.values() + if x.candidate_id and any(raw["id"] == x.shot_id for raw in render_spec["shots"]) + ] + audio = render_spec["render"]["audio"] + if audio: + frozen_inputs["audio"] = { + "asset_id": audio["asset_id"], + "sha256": assets[audio["asset_id"]].sha256, + } + snapshot = {**render_spec, "render_inputs": frozen_inputs} + output_folder_id = ( + body.output_folder_id if "output_folder_id" in body.model_fields_set else d.folder_id + ) + if output_folder_id: + from app.services.folders import owned_folder + + await owned_folder(s, output_folder_id, actor.id, lock=True) + r = WorkflowRun( + folder_id=d.folder_id, + output_folder_id=output_folder_id, + owner_id=actor.id, + draft_id=id, + draft_revision=d.revision, + spec_snapshot=snapshot, + spec_hash=digest(snapshot), + execution_mode=body.execution_mode, + ) + s.add(r) + await s.flush() + s.add( + WorkflowStep( + run_id=r.id, + step_key="compose", + kind="video.compose", + dependencies=[], + semantic_input_hash=digest(snapshot), + ) + ) + for aid in ( + {c["asset_id"] for c in clips} + | set(assets) + | {x.asset_id for x in latest.values() if x.asset_id} + ): + await add_ref(s, d, aid, "run", r.id) + d.current_run_id = r.id + d.version += 1 + d.updated_at = utcnow() + await emit_story(s, d) + from app.services.workflows import emit_run + + await emit_run(s, r, False) + response = await snapshot_run(s, actor.id, r.id) + sub.resource_json = {"draft_id": id, "run_id": r.id, "response": response} + await s.commit() + runtime.coordinator.wake() + return response + + +async def runs(runtime, actor, id, page, page_size): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with runtime.db.session() as s: + await story(s, id, actor.id) + q = select(WorkflowRun).where( + WorkflowRun.owner_id == actor.id, + WorkflowRun.draft_id == id, + WorkflowRun.deleted_at.is_(None), + ) + total = await s.scalar(select(func.count()).select_from(q.subquery())) + rows = ( + await s.scalars( + q.order_by(WorkflowRun.created_at.desc(), WorkflowRun.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + ) + ).all() + return dict( + items=[(await snapshot_run(s, actor.id, r.id))["run"] for r in rows], + total=total, + page=page, + page_size=page_size, + ) diff --git a/backend/app/services/stories/candidates.py b/backend/app/services/stories/candidates.py new file mode 100644 index 0000000..2d6ff80 --- /dev/null +++ b/backend/app/services/stories/candidates.py @@ -0,0 +1,514 @@ +"""持久候选计划与有界补队;人工等待永远不占模型执行槽。""" + +from types import SimpleNamespace +from fastapi import HTTPException +from sqlalchemy import select +from app.models import Asset, Job, ShotCandidate, Batch, BatchItem, WorkflowDraft, User, utcnow +from app.domain.stories import digest, ordered_reference_ids, text_frame_prompt +from app.core.errors import fail +from app.adapters.provider.contracts import capabilities as provider_capabilities +from app.schemas.jobs import Submit +from app.services.jobs import create_jobs +from app.services.events import emit_asset +from app.services.stories.common import ( + preview, + shot_model, + current_hash, + selections, + selection_dto, + private_asset, + candidate_dto, + add_ref, +) + + +async def capabilities(runtime): + from app.core.runtime_policy import read_runtime_policy + + entries = {x["task_type"]: x for x in provider_capabilities(runtime.settings)} + ref = entries.get("image.reference.generate", {}) + available = bool(ref.get("available")) + maximum = getattr(runtime.settings, "reference_max_images", 3) + reason = None if available else "多图参考模型尚未通过真实通道认证" + if available: + method = getattr(runtime.provider, "upstream_capabilities", None) + try: + remote = await method() if method else {} + upstream = remote.get("reference_generation", {}) + available = upstream.get("available") is True and upstream.get("profile") == getattr( + runtime.settings, "reference_generation_profile", "qwen-image-edit-2511-v1" + ) + if ( + type(upstream.get("max_reference_images")) is int + and upstream["max_reference_images"] > 0 + ): + maximum = min(maximum, upstream["max_reference_images"]) + else: + available = False + except Exception: + available = False + if not available: + reason = "上游多图参考能力不可用" + return dict( + enabled=getattr(runtime.settings, "story_studio_enabled", True), + reference_generation=dict( + available=available, + task_type="image.reference.generate", + max_reference_images=maximum, + model=ref.get("model", "Qwen-Image-Edit-2511"), + reason=reason, + ), + frame_text_generation={ + "available": bool(entries.get("image.generate", {}).get("available")) + }, + max_shots=read_runtime_policy(runtime.settings)["workflow_max_shots"], + ) + + +async def make_candidate(s, d, body, runtime, seed_offset=0, batch_id=None, *, prepared=None): + shot = shot_model(d, body.shot_id) + compiled = prepared["compiled"] if prepared else await preview(s, d) + latest = prepared["selections"] if prepared else None + item = next(x for x in compiled["shots"] if x["shot_id"] == shot.id) + refs = ordered_reference_ids(item["references"]) + reference_mode = body.reference_mode or ("reference" if refs else "text") + prompt = item["frame_prompt"] if reference_mode == "reference" else text_frame_prompt(item) + needs_text_prompt = body.kind == "frame" and body.source_kind == "generated" + errors = [e for e in item["errors"] if e["code"] not in {"prompt_required", "prompt_too_long"}] + if needs_text_prompt and (not prompt.strip() or len(prompt) > 8000): + errors.append({"code": "invalid_prompt"}) + if errors: + fail(422, "invalid_story_shot", "镜头编译失败,请检查提示词和引用") + width, height = (704, 1280) if d.spec["profile"] == "portrait_1080_v1" else (1280, 704) + inputs, parameters = {}, {} + source = None + mode = body.execution_mode + if body.source_kind == "manual": + if not body.asset_id: + fail(422, "asset_required", "请选择人工素材") + source = await private_asset( + s, body.asset_id, d.owner_id, "image" if body.kind == "frame" else "video" + ) + task_type = "image.prepare_frame" if body.kind == "frame" else None + inputs = {"image_asset_id": source.id} if task_type else {} + parameters = ( + {"width": width, "height": height, "fit": d.spec["render"]["fit"]} if task_type else {} + ) + elif body.kind == "frame": + caps = prepared["capabilities"] if prepared else await capabilities(runtime) + if reference_mode == "reference": + if not caps["reference_generation"]["available"]: + fail( + 503, "reference_generation_unavailable", caps["reference_generation"]["reason"] + ) + if not refs or len(refs) > caps["reference_generation"]["max_reference_images"]: + fail(422, "reference_count", "参考图数量超出当前模型限制") + task_type = "image.reference.generate" + inputs = { + "prompt": prompt, + "negative_prompt": item["effective_settings"]["negative_prompt"], + "reference_asset_ids": refs, + } + parameters = dict( + profile=getattr( + runtime.settings, "reference_generation_profile", "qwen-image-edit-2511-v1" + ), + width=width, + height=height, + seed=(shot.frame_parameters.seed + seed_offset) % 2**32, + num_inference_steps=40, + guidance_scale=1.0, + true_cfg_scale=4.0, + ) + else: + if not caps["frame_text_generation"]["available"]: + fail(503, "frame_text_generation_unavailable", "文生图服务不可用") + task_type = "image.generate" + inputs = { + "prompt": prompt, + "negative_prompt": item["effective_settings"]["negative_prompt"], + } + parameters = dict( + width=width, + height=height, + seed=(shot.frame_parameters.seed + seed_offset) % 2**32, + num_inference_steps=50, + guidance_scale=4.0, + ) + else: + if ( + shot.edit.start_frame + shot.edit.duration_frames + > shot.video_parameters.source_seconds * 24 + ): + fail( + 422, + "generation_source_too_short", + "选用区间超出本次生成源长度,请增加源时长或缩短选用区间", + ) + latest = latest if latest is not None else await selections(s, d) + frame = latest.get((shot.id, "frame")) + dto = await selection_dto(s, d, frame, compiled, latest) if frame else None + if not dto or dto["stale"] or not dto["asset"]: + fail(409, "frame_selection_required", "请先确认当前首帧") + source = await private_asset(s, frame.asset_id, d.owner_id, "image") + task_type = "video.generate" + inputs = { + "prompt": shot.motion_prompt or "静态镜头,保持画面主体和外观一致", + "image_asset_id": source.id, + } + v = shot.video_parameters + parameters = dict( + width=width, + height=height, + num_frames=4 * ((v.source_seconds * 24 + 3) // 4) + 1, + fps=24, + upscale=v.upscale, + upscale_width=1056 if width == 704 else 1920, + upscale_height=1920 if width == 704 else 1056, + seed=(v.seed + seed_offset) % 2**32, + num_inference_steps=v.num_inference_steps, + guidance_scale=v.guidance_scale, + tile_size=128, + ) + plan = { + "task_type": task_type, + "input": inputs, + "parameters": parameters, + "execution_mode": mode, + "input_sha256": {a.id: a.sha256 for a in [source] if a}, + "references": item["references"], + "adapter_version": "story-candidate-v1", + "input_snapshot": { + "reference_mode": "reference" + if task_type == "image.reference.generate" + else "text" + if task_type == "image.generate" + else "manual" + if body.source_kind == "manual" + else "approved_frame", + "actual_image_refs": inputs.get( + "reference_asset_ids", + [inputs["image_asset_id"]] if inputs.get("image_asset_id") else [], + ), + }, + } + generation_hash = digest(plan) + output_folder_id = ( + body.output_folder_id if "output_folder_id" in body.model_fields_set else d.folder_id + ) + if output_folder_id: + from app.services.folders import owned_folder + + await owned_folder(s, output_folder_id, d.owner_id, lock=True) + plan = {**plan, "folder_id": d.folder_id, "output_folder_id": output_folder_id} + c = ShotCandidate( + owner_id=d.owner_id, + draft_id=d.id, + shot_id=shot.id, + kind=body.kind, + source_kind=body.source_kind, + context_hash=await current_hash( + s, + d, + shot.id, + body.kind, + compiled, + latest, + source_kind=body.source_kind, + source_sha256=source.sha256 if source else None, + ), + generation_hash=generation_hash, + created_revision=d.revision, + plan_json=plan, + batch_id=batch_id, + ) + s.add(c) + await s.flush() + for id in set(refs + ([source.id] if source else [])): + await add_ref(s, d, id, "candidate", c.id) + if source and body.kind == "video" and body.source_kind == "manual": + await validate_video(source, shot, runtime.settings, generated=False) + c.asset_id, c.asset_sha256, c.state = source.id, source.sha256, "ready" + emit_asset( + s, + d.owner_id, + "candidate.updated", + {"candidate": await candidate_dto(s, d, c, compiled, latest)}, + ) + return c + + +async def validate_video(asset, shot, settings, generated=False, parameters=None): + from app.services.workflows import verified_output + from app.adapters.storage import confined + from app.adapters.media import inspect_video_track + + if not await verified_output(asset, settings): + fail(409, "asset_integrity_failed", "素材字节或SHA已改变") + track = await inspect_video_track( + confined(settings.asset_root, asset.storage_key, exists=True), settings + ) + required = shot.edit.start_frame + shot.edit.duration_frames if shot else 0 + if generated: + required = max(required, parameters["num_frames"] - 1) + dims = ( + (parameters["upscale_width"], parameters["upscale_height"]) + if parameters.get("upscale") + else (parameters["width"], parameters["height"]) + ) + if (track["width"], track["height"]) != dims: + fail(409, "invalid_video_profile", "视频产物画幅不符合冻结配置") + if track["fps"] != 24 or track["frames"] < required: + fail(409, "invalid_video_frames", "视频帧率或解码帧数不满足选用区间") + + +async def refresh_candidate(s, d, c, settings): + if not c.job_id or c.deleted_at is not None: + return + if c.state == "ready": + return + j = await s.get(Job, c.job_id) + if not j or j.deleted_at is not None: + state, error = "failed", {"code": "job_deleted", "message": "候选任务已删除"} + a = None + else: + state = ( + "failed" + if j.state in {"failed", "timed_out", "needs_attention", "cancelled"} + else j.state + ) + error, a = j.error_json, None + if j.state == "succeeded": + outputs = ( + await s.scalars( + select(Asset) + .where( + Asset.source_job_id == j.id, + Asset.owner_id == d.owner_id, + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + Asset.kind == ("image" if c.kind == "frame" else "video"), + ) + .order_by(Asset.source_output_index.desc()) + ) + ).all() + # 最终增强片优先;仅将匹配实际 profile 的终态产物变为可确认候选。 + for candidate in outputs: + try: + if c.kind == "video": + await validate_video( + candidate, + None, + settings, + generated=True, + parameters=j.parameters, + ) + else: + from app.services.workflows import verified_output + + if (candidate.width, candidate.height) != ( + j.parameters["width"], + j.parameters["height"], + ) or not await verified_output(candidate, settings): + continue + a = candidate + break + except (HTTPException, ValueError): + continue + state = "ready" if a else "failed" + error = ( + None + if a + else { + "code": "invalid_candidate_output", + "message": "任务无满足冻结帧数和画幅的最终产物", + } + ) + before = (c.state, c.asset_id, c.error_json) + c.state, c.error_json = state, error + if a: + c.asset_id = a.id + c.asset_sha256 = a.sha256 + await add_ref(s, d, a.id, "candidate", c.id, add_to_folder=False) + if before != (c.state, c.asset_id, c.error_json): + c.version += 1 + emit_asset(s, d.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)}) + + +async def feed_candidates(s, settings): + from app.services.orchestration.workflow_engine import child_capacity + from app.core.maintenance import maintenance_active + + # 禁用期间保留候选原状态;启用后继续同一持久计划,避免将权限等待记成业务失败。 + rows = ( + await s.scalars( + select(ShotCandidate) + .join(User, User.id == ShotCandidate.owner_id) + .where( + User.disabled.is_(False), + ShotCandidate.deleted_at.is_(None), + ShotCandidate.state.not_in({"ready", "failed"}), + ) + .order_by(ShotCandidate.created_at, ShotCandidate.id) + .with_for_update() + ) + ).all() + admitted = 0 + for c in rows: + d = await s.get(WorkflowDraft, c.draft_id) + if not d or d.deleted_at is not None: + continue + if not any(x["id"] == c.shot_id for x in d.spec["shots"]): + if c.job_id: + from app.services.orchestration.executions import request_control + + await request_control(s, c.job_id, "cancel") + c.state, c.error_json = "failed", {"code": "shot_deleted", "message": "镜头已删除"} + c.version += 1 + emit_asset( + s, c.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)} + ) + continue + if c.job_id: + await refresh_candidate(s, d, c, settings) + continue + if admitted >= 8 or maintenance_active(settings): + continue + plan = c.plan_json + b = await s.get(Batch, c.batch_id) if c.batch_id else None + # 管理员禁用与手动暂停只冻结补队,不能把持久计划消耗成失败候选。 + if b and (b.deleted_at is not None or b.desired_state != "run" or b.hold_reasons): + continue + parent = SimpleNamespace(owner_id=c.owner_id, execution_mode=plan["execution_mode"]) + if not await child_capacity(s, parent, SimpleNamespace(kind=plan["task_type"]), settings): + continue + try: + async with s.begin_nested(): + from app.services.workflows import verified_output + + expected_sources = dict(plan.get("input_sha256", {})) + actual_refs = plan.get("input_snapshot", {}).get("actual_image_refs", []) + for ref in plan.get("references", []): + if ref["asset_id"] in actual_refs: + expected_sources[ref["asset_id"]] = ref["sha256"] + for source_id, sha in expected_sources.items(): + asset = await private_asset(s, source_id, c.owner_id, "image") + if asset.sha256 != sha or not await verified_output(asset, settings): + fail(409, "dependency_changed", "候选冻结输入图片已改变或不可用") + from app.models import Folder + + # JSON快照没有外键;补队前把已删除目标降为未分类。 + targets = {} + for field in ("folder_id", "output_folder_id"): + target = plan.get(field) + targets[field] = ( + await s.scalar( + select(Folder.id) + .where(Folder.id == target, Folder.owner_id == c.owner_id) + .with_for_update() + ) + if target + else None + ) + jobs = await create_jobs( + s, + Submit( + task_type=plan["task_type"], + input=plan["input"], + parameters=plan["parameters"], + execution_mode=plan["execution_mode"], + folder_id=targets["folder_id"], + output_folder_id=targets["output_folder_id"], + ), + SimpleNamespace(id=c.owner_id, auth_kind="session", scopes=[]), + settings, + key=f"candidate:{c.id}", + internal=True, + ) + j = jobs[0] + j.batch_id = c.batch_id + c.job_id = j.id + c.version += 1 + if c.batch_id: + bi = await s.scalar( + select(BatchItem).where( + BatchItem.batch_id == c.batch_id, BatchItem.target_id == c.id + ) + ) + j.batch_item_index = bi.item_index if bi else None + emit_asset( + s, c.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)} + ) + admitted += 1 + except HTTPException as exc: + await s.refresh(c) + if exc.detail.get("code") not in { + "quota_exceeded", + "storage_insufficient", + "owner_disabled", + }: + c.state, c.error_json = "failed", exc.detail + c.version += 1 + emit_asset( + s, c.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)} + ) + await advance_candidate_batches(s, settings) + + +async def advance_candidate_batches(s, settings): + batches = ( + await s.scalars( + select(Batch).where( + Batch.deleted_at.is_(None), + Batch.state.not_in({"succeeded", "cancelled", "completed_with_errors"}), + ) + ) + ).all() + for b in batches: + if b.spec_snapshot.get("kind") != "story_candidates": + continue + members = ( + await s.scalars(select(ShotCandidate).where(ShotCandidate.batch_id == b.id)) + ).all() + items = ( + await s.scalars( + select(BatchItem).where(BatchItem.batch_id == b.id).order_by(BatchItem.item_index) + ) + ).all() + before = (b.state, tuple((item.id, item.state) for item in items)) + if b.desired_state == "cancel": + for c in members: + if not c.job_id and c.state not in {"ready", "failed"}: + c.state = "failed" + c.error_json = {"code": "cancelled", "message": "候选批次已取消"} + c.version += 1 + d = await s.get(WorkflowDraft, c.draft_id) + emit_asset( + s, + c.owner_id, + "candidate.updated", + {"candidate": await candidate_dto(s, d, c)}, + ) + b.state = "cancelling" + elif b.desired_state == "pause" or b.hold_reasons: + b.state = "paused" + else: + b.state = "running" if any(c.job_id for c in members) else "queued" + if members and all(c.state in {"ready", "failed"} or c.deleted_at for c in members): + b.state = ( + "cancelled" + if b.desired_state == "cancel" + else "succeeded" + if all(c.state == "ready" for c in members) + else "completed_with_errors" + ) + b.finished_at = utcnow() + by_id = {c.id: c for c in members} + for item in items: + c = by_id.get(item.target_id) + if c: + item.state = "succeeded" if c.state == "ready" else c.state + if before != (b.state, tuple((item.id, item.state) for item in items)): + from app.services.batches import emit_batch + + await emit_batch(s, b) diff --git a/backend/app/services/stories/common.py b/backend/app/services/stories/common.py new file mode 100644 index 0000000..eae8aad --- /dev/null +++ b/backend/app/services/stories/common.py @@ -0,0 +1,337 @@ +"""Owner 隔离、编译、DTO 与当前追加选择视图。""" + +from sqlalchemy import select +from app.models import Asset, AssetReference, WorkflowDraft, ShotCandidate, ShotSelection, utcnow +from app.core.errors import fail +from app.domain.stories import StorySpecV3, StoryShot, compile_story, digest +from app.services.snapshots import asset_dto, iso, owned +from app.services.events import emit_asset +from app.core.runtime_policy import read_runtime_policy + + +async def story(session, id, owner): + row = await owned(session, WorkflowDraft, id, owner) + if row.kind != "story_v3": + fail(404, "resource_not_found", "故事不存在") + return row + + +def cas(d, version): + if d.version != version: + fail(409, "draft_version_conflict", "故事已更新,请刷新版本") + + +def shot_model(d, shot_id): + shot = next((s for s in d.spec["shots"] if s["id"] == shot_id), None) + if shot is None: + fail(404, "shot_not_found", "镜头已删除或不存在") + # 整体引用关系已在草稿写入时验证;读取单镜头不重复解析全部千镜头故事。 + return StoryShot.model_validate(shot) + + +async def private_asset(s, id, owner, kind=None): + a = await s.scalar( + select(Asset) + .where( + Asset.id == id, + Asset.owner_id == owner, + Asset.library_scope == "private", + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + ) + .with_for_update() + ) + if not a: + fail(404, "asset_not_found", "素材不存在或不可访问") + if kind and a.kind != kind: + fail(422, "wrong_asset_kind", "素材类型不正确") + if not a.sha256: + fail(409, "asset_not_ready", "素材尚未校验") + return a + + +async def spec_assets(s, owner, spec, settings=None): + model = spec if isinstance(spec, StorySpecV3) else StorySpecV3.model_validate(spec) + if settings: + policy = read_runtime_policy(settings) + if policy.get("configuration_error"): + fail(503, "runtime_policy_unavailable", "运行配置无效") + if len(model.shots) > policy["workflow_max_shots"]: + fail(422, "workflow_shot_limit", "镜头数量超过当前限制") + ids = [] + for item in [*model.scenes, *model.entities]: + ids.extend(item.reference_asset_ids) + for variant in getattr(item, "forms", []) + getattr(item, "appearances", []): + ids.extend(variant.reference_asset_ids) + assets = {id: await private_asset(s, id, owner, "image") for id in sorted(set(ids))} + if model.render.audio: + audio = await private_asset(s, model.render.audio.asset_id, owner, "audio") + if audio.duration_seconds is None or model.render.audio.source_end_ms > round( + audio.duration_seconds * 1000 + ): + fail(422, "invalid_timeline", "音轨选择超出源素材") + assets[audio.id] = audio + return model, assets + + +async def preview(s, d): + model, assets = await spec_assets(s, d.owner_id, d.spec) + return compile_story(model, assets) + + +async def selections(s, d): + rows = ( + await s.scalars( + select(ShotSelection) + .where(ShotSelection.draft_id == d.id, ShotSelection.owner_id == d.owner_id) + .order_by(ShotSelection.version.desc(), ShotSelection.id) + ) + ).all() + latest = {} + for row in rows: + latest.setdefault((row.shot_id, row.kind), row) + return latest + + +async def current_hash( + s, d, shot_id, kind, compiled=None, latest=None, *, source_kind="generated", source_sha256=None +): + compiled = compiled or await preview(s, d) + item = next(x for x in compiled["shots"] if x["shot_id"] == shot_id) + if kind == "frame": + return item["context_hash"] + shot = shot_model(d, shot_id) + if source_kind == "manual": + # 人工视频不曾读取首帧或Wan生成长度,过期判断只绑定实际来源与画面/运动意图。 + return digest( + { + "visual": item["context_hash"], + "motion": shot.motion_prompt, + "source_kind": "manual", + "video_sha256": source_sha256, + } + ) + latest = latest if latest is not None else await selections(s, d) + frame = latest.get((shot_id, "frame")) + a = await s.get(Asset, frame.asset_id) if frame and frame.asset_id else None + return digest( + { + "visual": item["context_hash"], + "frame_sha256": a.sha256 if a else None, + "motion": shot.motion_prompt, + "source_seconds": shot.video_parameters.source_seconds, + } + ) + + +async def selection_source_kind(s, row): + if row.decision_json.get("source_kind"): + return row.decision_json["source_kind"] + # 早期v3确认记录没有source_kind,候选审计仍保留,可读取真实来源而非猜测。 + candidate = await s.get(ShotCandidate, row.candidate_id) if row.candidate_id else None + return candidate.source_kind if candidate else "generated" + + +async def selection_dto(s, d, row, compiled=None, latest=None): + a = await s.get(Asset, row.asset_id) if row.asset_id else None + valid = ( + a + and a.owner_id == d.owner_id + and a.deleted_at is None + and a.ready + and a.sha256 == row.decision_json.get("asset_sha256") + ) + exists = any(x["id"] == row.shot_id for x in d.spec["shots"]) + source_kind = await selection_source_kind(s, row) if row.kind == "video" else "generated" + stale = ( + not exists + or row.context_hash + != await current_hash( + s, + d, + row.shot_id, + row.kind, + compiled, + latest, + source_kind=source_kind, + source_sha256=row.decision_json.get("asset_sha256"), + ) + if exists + else True + ) + return dict( + id=row.id, + draft_id=d.id, + shot_id=row.shot_id, + kind=row.kind, + candidate_id=row.candidate_id, + asset=asset_dto(a) if valid else None, + context_hash=row.context_hash, + version=row.version, + created_at=iso(row.created_at), + stale=stale, + ) + + +async def candidate_dto(s, d, c, compiled=None, latest=None): + a = await s.get(Asset, c.asset_id) if c.asset_id else None + exists = any(x["id"] == c.shot_id for x in d.spec["shots"]) + stale = ( + not exists + or c.context_hash + != await current_hash( + s, + d, + c.shot_id, + c.kind, + compiled, + latest, + source_kind=c.source_kind, + source_sha256=c.asset_sha256, + ) + if exists + else True + ) + result = dict( + id=c.id, + draft_id=c.draft_id, + shot_id=c.shot_id, + kind=c.kind, + source_kind=c.source_kind, + job_id=c.job_id, + asset=asset_dto(a) if a and a.deleted_at is None and a.ready else None, + state=c.state, + context_hash=c.context_hash, + generation_hash=c.generation_hash, + created_revision=c.created_revision, + version=c.version, + created_at=iso(c.created_at), + stale=stale, + ) + plan = c.plan_json + snapshot = plan.get("input_snapshot", {}) + result["input_summary"] = { + "reference_mode": snapshot.get( + "reference_mode", "manual" if c.source_kind == "manual" else "text" + ), + "actual_reference_asset_ids": snapshot.get("actual_image_refs", []), + "model_profile": plan.get("parameters", {}).get("profile", plan.get("task_type")), + "seed": plan.get("parameters", {}).get("seed"), + "prompt": plan.get("input", {}).get("prompt"), + "first_frame_asset_id": plan.get("input", {}).get("image_asset_id"), + } + if c.error_json: + result["error"] = c.error_json + return result + + +async def readiness(s, d, compiled=None, latest=None): + compiled = compiled or await preview(s, d) + latest = latest if latest is not None else await selections(s, d) + issues, shots = [], [] + for item in compiled["shots"]: + sid = item["shot_id"] + video = latest.get((sid, "video")) + # 冻结素材合成不运行文生图;已有视频不能被未使用的生成提示词门槛阻挡。 + own = [ + {"shot_id": sid, **e} + for e in item["errors"] + if not ( + video and video.candidate_id and e["code"] in {"prompt_required", "prompt_too_long"} + ) + ] + needs_frame = ( + video and video.candidate_id and await selection_source_kind(s, video) == "generated" + ) + for kind in ("frame", "video") if needs_frame else ("video",): + row = latest.get((sid, kind)) + dto = await selection_dto(s, d, row, compiled, latest) if row else None + if not dto or not dto["asset"] or not dto["candidate_id"]: + own.append( + dict( + shot_id=sid, + code=f"{kind}_selection_required", + message="请确认首帧" if kind == "frame" else "请选择视频", + ) + ) + elif dto["stale"]: + own.append( + dict( + shot_id=sid, + code=f"{kind}_selection_stale", + message="选择已过期,请重新确认", + ) + ) + elif kind == "video": + shot = shot_model(d, sid) + duration = dto["asset"].get("duration_seconds") + if duration is None or shot.edit.start_frame + shot.edit.duration_frames > round( + duration * 24 + ): + own.append( + dict( + shot_id=sid, + code="video_trim_exceeds_source", + message="选用区间超出当前视频源", + ) + ) + issues.extend(own) + shots.append({"shot_id": sid, "ready": not own, "issues": own}) + return {"ready": not issues, "issues": issues, "shots": shots} + + +async def story_dto(s, d): + from app.domain.editors import editing_mode + from app.services.editor_modes import manual_spec + + compiled, latest = await preview(s, d), await selections(s, d) + return dict( + editor_manifest=d.editor_manifest, + editing_mode=editing_mode(d), + capabilities={"mode_switch": True, "manual": True, "auto": True, "name_edit": True}, + id=d.id, + name=d.name, + kind=d.kind, + folder_id=d.folder_id, + spec=manual_spec(d), + revision=d.revision, + version=d.version, + created_at=iso(d.created_at), + updated_at=iso(d.updated_at), + selections=[await selection_dto(s, d, row, compiled, latest) for row in latest.values()], + readiness=await readiness(s, d, compiled, latest), + ) + + +async def add_ref(s, d, asset_id, kind, id, *, add_to_folder=True): + exists = await s.scalar( + select(AssetReference.id).where( + AssetReference.asset_id == asset_id, + AssetReference.ref_kind == kind, + AssetReference.ref_id == id, + ) + ) + if not exists: + if add_to_folder and d.folder_id and kind in {"draft", "candidate", "selection"}: + from app.services.folders import add_asset_folder + from app.models import Asset + + asset = await s.get(Asset, asset_id) + if asset is not None: + before = set(asset.folder_ids) + await add_asset_folder(s, asset, d.folder_id, allow_missing=True) + # 已发布素材的归属变化必须通知其他会话;未发布结果仍由收集器统一发布。 + if asset.ready and before != set(asset.folder_ids): + emit_asset(s, d.owner_id, "asset.updated", {"asset": asset_dto(asset)}) + s.add(AssetReference(owner_id=d.owner_id, asset_id=asset_id, ref_kind=kind, ref_id=id)) + + +async def emit_story(s, d, increment=False): + if increment: + d.version += 1 + d.revision += 1 + d.updated_at = utcnow() + await s.flush() + dto = await story_dto(s, d) + emit_asset(s, d.owner_id, "story.updated", {"story": dto}) + return dto diff --git a/backend/app/services/stories/deletion.py b/backend/app/services/stories/deletion.py new file mode 100644 index 0000000..411f80e --- /dev/null +++ b/backend/app/services/stories/deletion.py @@ -0,0 +1,163 @@ +from sqlalchemy import select, delete +from app.models import ( + AssetReference, + ShotCandidate, + ShotSelection, + Job, + Execution, + WorkflowDraft, + Batch, + Submission, + utcnow, +) +from app.core.errors import fail +from app.core.maintenance import require_writable +from app.domain.tasks import TERMINAL +from app.services.stories.common import story +from app.services.events import emit_asset + + +async def ensure_terminal(s, c): + if c.job_id: + j = await s.get(Job, c.job_id) + if j and j.deleted_at is None and j.state not in TERMINAL: + fail(409, "deletion_requires_terminal", "请先取消候选任务并等待执行结束") + execution = await s.scalar( + select(Execution.id) + .where( + Execution.job_id == c.job_id, Execution.state.not_in({"exited", "results_ready"}) + ) + .limit(1) + ) + if execution: + fail(409, "cleanup_pending", "候选执行尚未确认清理") + + +async def archive_candidate(s, c): + c.deleted_at = utcnow() + c.version += 1 + await s.execute( + delete(AssetReference).where( + AssetReference.ref_kind == "candidate", AssetReference.ref_id == c.id + ) + ) + emit_asset( + s, + c.owner_id, + "candidate.deleted", + {"id": c.id, "draft_id": c.draft_id, "version": c.version}, + ) + from app.services.deletions import references_any + + submissions = ( + await s.scalars( + select(Submission).where( + Submission.owner_id == c.owner_id, + Submission.operation.like("story.candidate.%"), + Submission.status != "purged", + ) + ) + ).all() + for sub in submissions: + if references_any(sub.resource_json, {c.id}): + sub.status = "purged" + + +async def delete_candidate(runtime, actor, id, candidate_id, if_match): + require_writable(runtime.settings) + async with runtime.db.session() as s: + await story(s, id, actor.id) + c = await s.scalar( + select(ShotCandidate) + .where( + ShotCandidate.id == candidate_id, + ShotCandidate.draft_id == id, + ShotCandidate.owner_id == actor.id, + ) + .with_for_update() + ) + if not c: + fail(404, "candidate_not_found", "候选不存在") + if c.deleted_at: + return {"deleted": {"candidate_ids": [c.id]}} + if if_match is None or if_match.strip('"') != str(c.version): + fail(409, "version_conflict", "候选版本冲突") + await ensure_terminal(s, c) + await archive_candidate(s, c) + await s.commit() + return {"deleted": {"candidate_ids": [c.id]}} + + +async def delete_story(runtime, actor, id, if_match): + from app.services.deletions import archive_records + + require_writable(runtime.settings) + async with runtime.db.session() as s: + d = await story(s, id, actor.id) + if if_match is None or if_match.strip('"') != str(d.version): + fail(409, "draft_version_conflict", "故事版本冲突") + rows = ( + await s.scalars( + select(ShotCandidate) + .where( + ShotCandidate.draft_id == id, + ShotCandidate.owner_id == actor.id, + ShotCandidate.deleted_at.is_(None), + ) + .with_for_update() + ) + ).all() + for c in rows: + await ensure_terminal(s, c) + result = await archive_records(s, WorkflowDraft, id, actor.id, if_match) + for c in rows: + await archive_candidate(s, c) + for batch_id in {c.batch_id for c in rows if c.batch_id}: + b = await s.get(Batch, batch_id) + if b and b.owner_id == actor.id and b.deleted_at is None: + b.deleted_at = utcnow() + b.version += 1 + b.state = ( + "cancelled" + if b.state not in {"succeeded", "completed_with_errors"} + else b.state + ) + emit_asset(s, actor.id, "batch.deleted", {"id": b.id, "version": b.version}) + selection_ids = select(ShotSelection.id).where( + ShotSelection.draft_id == id, ShotSelection.owner_id == actor.id + ) + await s.execute( + delete(AssetReference).where( + AssetReference.ref_kind == "selection", AssetReference.ref_id.in_(selection_ids) + ) + ) + emit_asset(s, actor.id, "story.deleted", {"id": id, "version": d.version}) + result["deleted"]["candidate_ids"] = [c.id for c in rows] + await s.commit() + return result + + +async def delete_candidate_batch(runtime, actor, id, if_match): + from app.services.deletions import archive_records + + require_writable(runtime.settings) + async with runtime.db.session() as s: + rows = ( + await s.scalars( + select(ShotCandidate) + .where( + ShotCandidate.batch_id == id, + ShotCandidate.owner_id == actor.id, + ShotCandidate.deleted_at.is_(None), + ) + .with_for_update() + ) + ).all() + for c in rows: + await ensure_terminal(s, c) + result = await archive_records(s, Batch, id, actor.id, if_match) + for c in rows: + await archive_candidate(s, c) + result["deleted"]["candidate_ids"] = [c.id for c in rows] + await s.commit() + return result diff --git a/backend/app/services/submissions.py b/backend/app/services/submissions.py new file mode 100644 index 0000000..e8f2ac4 --- /dev/null +++ b/backend/app/services/submissions.py @@ -0,0 +1,115 @@ +import hashlib +import json +from sqlalchemy import select +from app.core.security import Actor +from app.core.errors import fail +from app.models import Submission + +"Durable intent records; callers commit the record and resource in one transaction." + + +def folder_payload(body): + result = dict(body) + if result.get("folder_id") is None: + result.pop("folder_id", None) + return result + + +def request_payload(body): + # 新增归属字段省略时维持旧指纹;显式 output null 必须保留,表示取消继承目标。 + result = body.model_dump(mode="json") + for key in ("folder_id", "output_folder_id"): + if key not in body.model_fields_set: + result.pop(key, None) + if "items" in result and hasattr(body, "items"): + result["items"] = [request_payload(item) for item in body.items] + return folder_payload(result) + + +def body_hash(body, schema=2): + try: + return hashlib.sha256( + json.dumps( + {"schema": schema, "body": body}, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode() + ).hexdigest() + except (ValueError, TypeError): + fail(422, "invalid_json", "请求必须为合法JSON") + + +async def accept_submission(session, owner_id, operation, key, payload_schema, body): + if not key or not 1 <= len(key) <= 128: + fail(422, "invalid_idempotency_key", "需要1–128字符的幂等键") + digest = body_hash(body, payload_schema) + row = await session.scalar( + select(Submission).where( + Submission.owner_id == owner_id, + Submission.operation == operation, + Submission.key == key, + ) + ) + if row: + if row.body_hash != digest: + fail(409, "idempotency_conflict", "此幂等键已用于不同参数") + if row.status == "purged": + fail(410, "resource_purged", "提交结果已清理") + return row + row = Submission( + owner_id=owner_id, + operation=operation, + key=key, + payload_schema=payload_schema, + body_hash=digest, + request_json=body, + resource_json={}, + ) + session.add(row) + await session.flush() + return row + + +async def recover(key: str, runtime, operation: str, actor: Actor = None): + async with runtime.db.session() as session: + row = await session.scalar( + select(Submission).where( + Submission.owner_id == actor.id, + Submission.operation == operation, + Submission.key == key, + ) + ) + if not row and operation == "jobs.create": + from app.models import Job + + legacy = ( + await session.scalars( + select(Job) + .where(Job.owner_id == actor.id, Job.request_key == key) + .order_by(Job.batch_index) + ) + ).all() + if legacy: + if any((job.deleted_at is not None for job in legacy)): + fail(410, "resource_purged", "提交结果已删除") + resources = {"job_ids": [job.id for job in legacy]} + return { + "key": key, + "operation": operation, + "status": "accepted", + "resource_json": resources, + **resources, + } + if not row: + fail(404, "submission_not_found", "尚未找到提交记录;重试仍须使用原幂等键") + if row.status == "purged": + fail(410, "resource_purged", "提交结果已清理") + return { + "key": row.key, + "operation": row.operation, + "status": row.status, + "resource_json": row.resource_json, + **row.resource_json, + } diff --git a/backend/app/services/system.py b/backend/app/services/system.py new file mode 100644 index 0000000..4e54bd4 --- /dev/null +++ b/backend/app/services/system.py @@ -0,0 +1,123 @@ +"""状态与能力的业务读取;不持有 HTTP Request。""" + +import asyncio +import time +from sqlalchemy import text +from sqlalchemy.exc import SQLAlchemyError +from app.adapters.provider.client import capabilities as provider_capabilities +from app.core.maintenance import maintenance_active +from app.core.runtime_policy import read_runtime_policy +from app.services.orchestration.resource_policy import execution_policy +from app.domain.timeline import ( + DEFAULT_SOURCE_FRAMES, + MAX_SOURCE_FRAMES, + DEFAULT_CLIP_FRAMES, + MAX_CLIP_FRAMES, +) + + +def workflow_limits(policy): + return { + "max_shots": policy["workflow_max_shots"], + "source_frames": DEFAULT_SOURCE_FRAMES, + "default_source_frames": DEFAULT_SOURCE_FRAMES, + "max_source_frames": MAX_SOURCE_FRAMES, + "default_clip_frames": DEFAULT_CLIP_FRAMES, + "max_clip_frames": MAX_CLIP_FRAMES, + "fps": 24, + } + + +async def health(runtime): + async with runtime.db.session() as session: + await session.execute(text("SELECT 1")) + return {"status": "ok", "database": runtime.settings.sqlalchemy_url.get_backend_name()} + + +async def readiness(runtime): + checks = { + "database": False, + "coordinator": True, + "upstream_protocol": False, + "accepting": not runtime.draining and (not maintenance_active(runtime.settings)), + } + try: + async with runtime.db.session() as session: + await session.execute(text("SELECT 1")) + checks["database"] = True + except SQLAlchemyError: + pass + coordinator = runtime.coordinator + if runtime.settings.run_coordinator: + heartbeat = getattr(coordinator, "last_tick_success", None) + checks["coordinator"] = bool( + coordinator._task + and (not coordinator._task.done()) + and (heartbeat is not None) + and (time.monotonic() - heartbeat < 90) + ) + try: + caps = await asyncio.wait_for(runtime.provider.upstream_capabilities(), 3) + checks["upstream_protocol"] = caps.get("protocol_version", 0) >= 2 and bool( + caps.get("admission_policy") + ) + except (Exception, asyncio.TimeoutError): + pass + return checks + + +async def task_capabilities(runtime): + items = provider_capabilities(runtime.settings) + video = [row for row in items if row["task_type"] in {"video.people.analyze", "video.replace"}] + if any(row["available"] for row in video): + try: + upstream = (await runtime.provider.upstream_capabilities()).get("video_edit", {}) + except Exception: + upstream = {} + for row in video: + if ( + upstream.get("available") is not True + or upstream.get("profile") != row["defaults"]["profile"] + or upstream.get("fps") != 24 + ): + row["available"] = False + row["reason"] = row["description"] = "上游视频编辑未完成认证或模型版本不匹配。" + else: + for key in ("max_seconds", "max_people", "max_pixels"): + value = upstream.get(key) + if type(value) is not int or value < 1: + row["available"] = False + row["reason"] = row["description"] = "上游视频编辑能力合同无效。" + else: + row["constraints"][key] = min(row["constraints"][key], value) + for row in video: + row.setdefault("reason", None if row["available"] else row["description"]) + return items + + +async def capabilities(runtime): + policy = read_runtime_policy(runtime.settings) + return { + "editable_production": {"schema_version": 1}, + "items": await task_capabilities(runtime), + "scheduler": await runtime.provider.scheduler_status(), + "execution_policy": execution_policy(settings=runtime.settings), + "workflow_limits": workflow_limits(policy), + } + + +async def status(runtime): + policy = read_runtime_policy(runtime.settings) + online, scheduler = await asyncio.gather( + runtime.provider.health(), runtime.provider.scheduler_status() + ) + return { + "inference_online": online, + "scheduler": scheduler, + "models": await task_capabilities(runtime), + "environment": runtime.settings.mode, + "database_backend": runtime.settings.sqlalchemy_url.get_backend_name(), + "execution_policy": execution_policy(settings=runtime.settings), + "workflow_limits": workflow_limits(policy), + "public_access": getattr(runtime.settings, "public_access", False), + } diff --git a/backend/app/services/tokens.py b/backend/app/services/tokens.py new file mode 100644 index 0000000..11f41ed --- /dev/null +++ b/backend/app/services/tokens.py @@ -0,0 +1,87 @@ +import secrets +from datetime import timezone +from sqlalchemy import select +from app.core.security import Actor, token_hash +from app.models import utcnow +from app.models import ApiToken +from app.core.errors import fail +from app.services.snapshots import iso +from app.schemas.tokens import TokenInput + +SCOPES = { + "jobs:read", + "jobs:write", + "assets:read", + "assets:write", + "folders:read", + "folders:write", + "events:read", + "workflows:read", + "workflows:write", + "batches:read", + "batches:write", + "interactive:write", +} + + +def record(row): + return { + "id": row.id, + "name": row.name, + "scopes": row.scopes, + "expires_at": iso(row.expires_at), + "created_at": iso(row.created_at), + "revoked_at": iso(row.revoked_at), + } + + +def owner_session(actor): + if actor.auth_kind != "session": + fail(403, "session_required", "Session required") + + +async def list_tokens(runtime, actor: Actor = None): + owner_session(actor) + async with runtime.db.session() as session: + rows = (await session.scalars(select(ApiToken).where(ApiToken.owner_id == actor.id))).all() + return {"items": [record(r) for r in rows]} + + +async def create_token(body: TokenInput, runtime, actor: Actor = None): + owner_session(actor) + if set(body.scopes) - SCOPES: + fail(422, "invalid_scope", "Unknown token scope") + expires = body.expires_at + if expires: + if expires.tzinfo is None: + fail(422, "timezone_required", "Expiry requires timezone") + expires = expires.astimezone(timezone.utc).replace(tzinfo=None) + if expires <= utcnow(): + fail(422, "invalid_expiry", "Expiry must be in the future") + if getattr(runtime.settings, "public_access", False) and actor.must_change_password: + fail(403, "password_change_required", "Change password first") + token = "cmvr_" + secrets.token_urlsafe(36) + async with runtime.db.session() as session: + row = ApiToken( + owner_id=actor.id, + name=body.name, + scopes=list(set(body.scopes)), + token_hash=token_hash(token), + expires_at=expires, + ) + session.add(row) + await session.commit() + return {"token": token, "record": record(row)} + + +async def revoke(token_id: str, runtime, actor: Actor = None): + owner_session(actor) + async with runtime.db.session() as session: + row = await session.scalar( + select(ApiToken).where(ApiToken.id == token_id, ApiToken.owner_id == actor.id) + ) + if not row: + fail(404, "token_not_found", "Token not found") + row.revoked_at = utcnow() + await session.commit() + return None diff --git a/backend/app/services/user_deletion.py b/backend/app/services/user_deletion.py new file mode 100644 index 0000000..5a3c356 --- /dev/null +++ b/backend/app/services/user_deletion.py @@ -0,0 +1,315 @@ +"""账号删除:先取消执行,确认停止后清理字节和全部自有记录。""" + +from contextlib import asynccontextmanager +from pathlib import Path +import re +import stat + +from sqlalchemy import delete, func, or_, select, update +from app.core.errors import fail +from app.domain.tasks import TERMINAL +from app.models import ( + ApiToken, + Asset, + AssetFolder, + AssetReference, + AssetTag, + Batch, + BatchItem, + Event, + Execution, + Folder, + Job, + JobAsset, + QuotaReservation, + Session, + SharedAsset, + ShotCandidate, + ShotSelection, + Submission, + User, + WorkflowDraft, + WorkflowRun, + WorkflowStep, + utcnow, +) +from app.services.asset_deletion import owned_file_paths +from app.services.events import emit_job + +CONFIRMED = {"exited", "results_ready"} + + +@asynccontextmanager +async def owner_upload(runtime, owner_id): + """上传在事务外写字节;计数和准入检查共用DB锁,删除只请求等待。""" + counts = None + try: + async with runtime.db.session() as session: + owner = await session.scalar(select(User).where(User.id == owner_id).with_for_update()) + if owner is None or owner.disabled: + fail(403, "owner_disabled", "账号已停用,无法上传素材") + counts = getattr(runtime, "owner_uploads", None) + if counts is None: + counts = runtime.owner_uploads = {} + counts[owner_id] = counts.get(owner_id, 0) + 1 + yield + finally: + # 单事件循环内不await;异常与取消同样释放计数,零值不长期保留。 + if counts is not None: + counts[owner_id] -= 1 + if not counts[owner_id]: + del counts[owner_id] + + +def local_work_pending(runtime, job_ids): + coordinator = runtime.coordinator + return any( + job_id in pending and not pending[job_id].done() + for pending in (coordinator._cpu, coordinator._preparing, coordinator._collecting) + for job_id in job_ids + ) or bool(set(job_ids) & coordinator._uncertain_cpu) + + +async def stop_owner(session, runtime, user): + """先提交停用与取消,409后由原协调器完成真实停止,重试再删除。""" + user.disabled = True + await session.execute(delete(Session).where(Session.user_id == user.id)) + await session.execute(delete(ApiToken).where(ApiToken.owner_id == user.id)) + jobs = list( + (await session.scalars(select(Job).where(Job.owner_id == user.id).with_for_update())).all() + ) + job_ids = [job.id for job in jobs] + asset_ids = select(Asset.id).where(Asset.owner_id == user.id) + execution_refs = select(AssetReference.ref_id).where( + AssetReference.asset_id.in_(asset_ids), AssetReference.ref_kind == "execution" + ) + executions = list( + ( + await session.scalars( + select(Execution).where( + or_( + Execution.job_id.in_(job_ids), + Execution.id.in_(execution_refs), + Execution.id.in_( + [job.current_execution_id for job in jobs if job.current_execution_id] + ), + ) + ) + ) + ).all() + ) + unconfirmed = {execution.job_id for execution in executions if execution.state not in CONFIRMED} + for job in jobs: + if job.state in TERMINAL: + continue + job.desired_state, job.cancel_requested = "cancel", True + job.next_action_at = utcnow() + if ( + not job.upstream_id + and job.upstream_payload is None + and job.phase not in {"cpu_running", "preparing"} + and job.id not in unconfirmed + and not local_work_pending(runtime, [job.id]) + ): + job.state, job.phase, job.finished_at = "cancelled", "cancelled", utcnow() + elif job.state != "collecting": + job.state, job.phase = "cancelling", "cancellation_pending" + await emit_job(session, job) + from app.services.workflows import emit_run, RUN_TERMINAL + from app.services.batches import emit_batch + + for model, terminal, emit in ( + (WorkflowRun, RUN_TERMINAL, emit_run), + (Batch, {"succeeded", "cancelled", "completed_with_errors"}, emit_batch), + ): + for row in (await session.scalars(select(model).where(model.owner_id == user.id))).all(): + if row.state not in terminal: + row.desired_state, row.state = "cancel", "cancelling" + await emit(session, row) + pending = ( + any(job.state not in TERMINAL for job in jobs) + or bool(unconfirmed) + or local_work_pending(runtime, job_ids) + or bool(getattr(runtime, "owner_uploads", {}).get(user.id)) + ) + await session.commit() + return pending + + +def tree_paths(root, identifier): + """仅遍历确定归属的目录;拒绝链接、junction和设备文件,不跟随外部路径。""" + if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", identifier): + raise ValueError("Invalid owned directory") + root = Path(root).resolve() + directory = root / identifier + files, directories = [], [] + + def visit(path): + try: + metadata = path.lstat() + except FileNotFoundError: + return + if stat.S_ISLNK(metadata.st_mode) or getattr(metadata, "st_file_attributes", 0) & getattr( + stat, "FILE_ATTRIBUTE_REPARSE_POINT", 1024 + ): + raise ValueError("Linked user files are not deletion targets") + if stat.S_ISDIR(metadata.st_mode): + for child in path.iterdir(): + visit(child) + directories.append(path) + elif stat.S_ISREG(metadata.st_mode) and path != directory: + files.append(path) + else: + raise ValueError("Invalid user file") + + if not directory.is_relative_to(root) or directory == root: + raise ValueError("Directory escaped storage root") + visit(directory) + return files, directories + + +async def require_no_foreign_consumers(session, owner_id, asset_ids, job_ids, folder_ids): + """正常导入是独立副本;异常跨账号消费保守阻断,绝不取消他人任务。""" + foreign_jobs = select(Job.id).where(Job.owner_id != owner_id) + foreign_runs = select(WorkflowRun.id).where(WorkflowRun.owner_id != owner_id) + checks = ( + select(JobAsset.job_id).where( + JobAsset.asset_id.in_(asset_ids), JobAsset.job_id.in_(foreign_jobs) + ), + select(AssetReference.id).where( + AssetReference.asset_id.in_(asset_ids), AssetReference.owner_id != owner_id + ), + select(SharedAsset.id).where( + SharedAsset.asset_id.in_(asset_ids), SharedAsset.publisher_id != owner_id + ), + select(WorkflowStep.id).where( + WorkflowStep.selected_job_id.in_(job_ids), WorkflowStep.run_id.in_(foreign_runs) + ), + select(AssetFolder.asset_id) + .join(Asset, Asset.id == AssetFolder.asset_id) + .where(AssetFolder.folder_id.in_(folder_ids), Asset.owner_id != owner_id), + select(Folder.id).where(Folder.parent_id.in_(folder_ids), Folder.owner_id != owner_id), + select(Asset.id).where( + Asset.owner_id != owner_id, + or_( + Asset.storage_key.startswith(owner_id + "/", autoescape=True), + Asset.thumbnail_key.startswith(owner_id + "/", autoescape=True), + ), + ), + ) + for query in checks: + if await session.scalar(query.limit(1)): + fail(409, "resource_in_use", "资源存在跨账号引用,尚不能安全删除,请联系管理员") + + +async def purge_owner(session, runtime, owner_id): + assets = list((await session.scalars(select(Asset).where(Asset.owner_id == owner_id))).all()) + asset_ids = [asset.id for asset in assets] + job_ids = list((await session.scalars(select(Job.id).where(Job.owner_id == owner_id))).all()) + run_ids = list( + ( + await session.scalars(select(WorkflowRun.id).where(WorkflowRun.owner_id == owner_id)) + ).all() + ) + batch_ids = list( + (await session.scalars(select(Batch.id).where(Batch.owner_id == owner_id))).all() + ) + folder_ids = list( + (await session.scalars(select(Folder.id).where(Folder.owner_id == owner_id))).all() + ) + await require_no_foreign_consumers(session, owner_id, asset_ids, job_ids, folder_ids) + try: + # 全部key及目标树都检查成功才删任一字节;未知残留也限定在本账号目录。 + for asset in assets: + owned_file_paths(runtime.settings, asset) + files, directories = tree_paths(runtime.settings.asset_root, owner_id) + for job_id in job_ids: + work_files, work_directories = tree_paths(runtime.settings.job_work_root, job_id) + files.extend(work_files) + directories.extend(work_directories) + except ValueError: + fail(409, "unsafe_user_path", "资源存储路径异常,账号已停用,尚未删除资源,请联系管理员") + except OSError: + fail(503, "user_delete_failed", "文件暂时无法检查,账号已停用,请稍后重试删除") + try: + for path in files: + path.unlink(missing_ok=True) + for directory in directories: + directory.rmdir() + except OSError: + fail(503, "user_delete_failed", "资源文件尚未全部删除,账号已停用,请稍后重试删除") + + # 字节不随DB回滚:先删字节再删记录;失败保留原ID以便重试,不假报204。 + await session.execute( + update(SharedAsset) + .where(SharedAsset.source_asset_id.in_(asset_ids), SharedAsset.publisher_id != owner_id) + .values(source_asset_id=None) + ) + await session.execute( + update(Asset) + .where(Asset.source_job_id.in_(job_ids), Asset.owner_id != owner_id) + .values(source_job_id=None) + ) + for model, condition in ( + ( + AssetFolder, + or_(AssetFolder.asset_id.in_(asset_ids), AssetFolder.folder_id.in_(folder_ids)), + ), + (JobAsset, or_(JobAsset.job_id.in_(job_ids), JobAsset.asset_id.in_(asset_ids))), + (SharedAsset, SharedAsset.publisher_id == owner_id), + (AssetReference, AssetReference.owner_id == owner_id), + (AssetTag, AssetTag.owner_id == owner_id), + (ShotSelection, ShotSelection.owner_id == owner_id), + (ShotCandidate, ShotCandidate.owner_id == owner_id), + (WorkflowStep, WorkflowStep.run_id.in_(run_ids)), + (BatchItem, BatchItem.batch_id.in_(batch_ids)), + (Execution, Execution.job_id.in_(job_ids)), + (Asset, Asset.owner_id == owner_id), + (Job, Job.owner_id == owner_id), + (WorkflowRun, WorkflowRun.owner_id == owner_id), + (WorkflowDraft, WorkflowDraft.owner_id == owner_id), + (Batch, Batch.owner_id == owner_id), + (Folder, Folder.owner_id == owner_id), + (Event, Event.owner_id == owner_id), + (Submission, Submission.owner_id == owner_id), + (QuotaReservation, QuotaReservation.owner_id == owner_id), + (Session, Session.user_id == owner_id), + (ApiToken, ApiToken.owner_id == owner_id), + (User, User.id == owner_id), + ): + await session.execute(delete(model).where(condition)) + await session.commit() + + +async def delete_user(user_id, runtime, actor): + if actor.role != "admin" or actor.auth_kind != "session": + fail(403, "admin_required", "此操作仅限管理员会话") + # 与tick保持同一锁序,避免协调器读取旧Job后在删除期间重新启动执行。 + async with runtime.coordinator._run_lock: + async with runtime.db.session() as session: + from app.services.auth import require_admin_session + + await require_admin_session(session, actor) + user = await session.scalar(select(User).where(User.id == user_id).with_for_update()) + if user is None: + fail(404, "user_not_found", "用户不存在") + if user_id == actor.id: + fail(409, "cannot_delete_self", "不能删除当前登录的管理员账号") + if user.role == "admin" and not user.disabled: + count = await session.scalar( + select(func.count()) + .select_from(User) + .where(User.role == "admin", User.disabled.is_(False)) + ) + if count <= 1: + fail(409, "last_admin", "不能删除最后一个可用管理员") + pending = await stop_owner(session, runtime, user) + runtime.coordinator.wake() + if pending: + fail( + 409, + "cleanup_pending", + "账号已停用并请求取消任务,执行或上传尚未确认停止;资源仍保留,请稍后重试删除", + ) + # 停用commit后仍持有unit_lock,不给并发启用/上传留下重新准入的窗口。 + await purge_owner(session, runtime, user_id) diff --git a/backend/app/services/video_editing.py b/backend/app/services/video_editing.py new file mode 100644 index 0000000..4ee177b --- /dev/null +++ b/backend/app/services/video_editing.py @@ -0,0 +1,115 @@ +"""视频编辑结果导入前的完整性与媒体验证。""" + +import math +from app.domain.video_editing import safe_analysis +from app.services.snapshots import public_value +from app.services.orchestration.executions import gpu_result + + +def validate_result_metadata(job, outputs, settings): + raw = gpu_result(job).get("metadata", {}) + if job.task_type == "video.people.analyze": + data = safe_analysis(raw, settings, output_count=len(outputs)) + source = (job.upstream_payload or {}).get("input", {}).get("video_path", "") + # 本地与远程输入均已在准备阶段校验;结果源摘要仍须对照原素材记录。 + if not source: + raise ValueError("Analysis input binding missing") + indexes = [data["poster_output_index"]] + [ + p["thumbnail_output_index"] for p in data["people"] + ] + return public_value(data), indexes + indexes = raw.get("final_output_indices") + frozen = job.parameters.get("_video_edit_binding", {}) + if ( + not isinstance(indexes, list) + or len(indexes) != 1 + or any(type(i) is not int or not 0 <= i < len(outputs) for i in indexes) + ): + raise ValueError("Replacement final output index missing") + expected = [r["person_id"] for r in job.input_json["replacements"]] + if ( + raw.get("person_ids") != expected + or raw.get("profile") != frozen.get("profile") + or raw.get("fps") != 24 + ): + raise ValueError("Replacement output does not cover frozen people/profile") + video = frozen["video"] + if raw.get("source_frames") != video["frames"] or raw.get("output_frames") != video["frames"]: + raise ValueError("Replacement truncated source") + for key in ("width", "height"): + if type(raw.get(key)) is not int or raw[key] != video[key]: + raise ValueError("Replacement dimensions changed") + keys = { + "person_ids", + "profile", + "source_frames", + "output_frames", + "fps", + "width", + "height", + "final_output_indices", + "warnings", + } + return public_value({k: v for k, v in raw.items() if k in keys}), indexes + + +async def validate_video_output(job, source, settings): + from app.adapters.media import inspect_media, inspect_video_track + + if job.task_type != "video.replace": + return + metadata, _ = validate_result_metadata(job, gpu_result(job)["outputs"], settings) + info = await inspect_media(source, settings) + track = await inspect_video_track(source, settings) + video = job.parameters["_video_edit_binding"]["video"] + if ( + info["kind"] != "video" + or info["mime_type"] != "video/mp4" + or track["fps"] != 24 + or track["frames"] != video["frames"] + or any(track[k] != metadata[k] for k in ("width", "height")) + or abs(info["duration_seconds"] - video["duration_seconds"]) > 1 / 24 + 0.01 + ): + raise ValueError("Decoded replacement media differs from frozen source") + preserve = job.parameters.get("preserve_audio", True) + source_audio = job.parameters["_video_edit_binding"]["source_has_audio"] + if bool(info.get("has_audio")) != bool(preserve and source_audio): + raise ValueError("Replacement audio missing or unexpected") + if preserve and source_audio: + duration = await audio_duration(source, settings, fallback=video["duration_seconds"]) + original = job.parameters["_video_edit_binding"].get( + "source_audio_duration", video["duration_seconds"] + ) + if ( + not math.isfinite(duration) + or abs(duration - min(original, video["duration_seconds"])) > 0.15 + ): + raise ValueError("Replacement audio duration differs") + + +async def audio_duration(source, settings, *, fallback): + import json + from app.adapters.media import run_process, input_options + + data = json.loads( + await run_process( + [ + settings.ffprobe_bin, + "-v", + "error", + *input_options(), + "-select_streams", + "a:0", + "-show_entries", + "stream=duration", + "-of", + "json", + str(source), + ] + ) + ) + value = data["streams"][0].get("duration") + duration = fallback if value in {None, "N/A"} else float(value) + if not math.isfinite(duration) or duration <= 0: + raise ValueError("Invalid source audio duration") + return duration diff --git a/backend/app/services/workflows.py b/backend/app/services/workflows.py new file mode 100644 index 0000000..7e8ef11 --- /dev/null +++ b/backend/app/services/workflows.py @@ -0,0 +1,726 @@ +from app.services.folders import folder_filter +from app.services.snapshots import draft_dto, owned, snapshot_run, page_rows +from app.domain.tasks import RUN_TERMINAL +import asyncio +import hashlib +import json +from types import SimpleNamespace +from fastapi import HTTPException +from sqlalchemy import select, delete +from app.core.security import Actor +from app.adapters.storage import safe_file +from app.core.errors import fail +from app.services.events import emit_asset, emit_job +from app.services.jobs import create_jobs +from app.schemas.jobs import Submit +from app.domain.tasks import TERMINAL, GPU_TYPES +from app.models import Asset, Job, User, utcnow +from app.services.submissions import accept_submission, request_payload +from app.domain.timeline import WorkflowSpec, compile_timeline, generation_parameters_for_shot +from app.core.runtime_policy import read_runtime_policy +from app.models import WorkflowDraft, WorkflowRun, WorkflowStep, AssetReference, Execution +from app.schemas.workflows import DraftCreate, DraftPatch, RunCreate, Control, Retry + +"Owner scoped draft/run services. All helpers use the caller's transaction." + + +def digest(value): + return hashlib.sha256( + json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False + ).encode() + ).hexdigest() + + +async def emit_run(session, r, increment=True): + if r.deleted_at is not None: + return + if increment: + r.version += 1 + snap = await snapshot_run(session, r.owner_id, r.id) + emit_asset( + session, r.owner_id, "workflow.updated", {k: snap[k] for k in ("run", "steps", "jobs")} + ) + + +async def validate_spec(session, owner_id, spec, settings): + spec = spec if isinstance(spec, WorkflowSpec) else WorkflowSpec.model_validate(spec) + policy = read_runtime_policy(settings) + if policy.get("configuration_error"): + fail(503, "runtime_policy_unavailable", "运行配置无效,请联系管理员") + if len(spec.shots) > policy["workflow_max_shots"]: + fail( + 422, + "workflow_shot_limit", + f"当前配置最多允许{policy['workflow_max_shots']}个镜头,可由管理员调整", + ) + ids = [s.image_asset_id for s in spec.shots if s.image_asset_id] + if spec.render.audio: + ids.append(spec.render.audio.asset_id) + assets = {} + for id in sorted(set(ids)): + a = await session.scalar( + select(Asset) + .where( + Asset.id == id, + Asset.owner_id == owner_id, + Asset.library_scope == "private", + Asset.deleted_at.is_(None), + Asset.ready.is_(True), + ) + .with_for_update() + ) + if not a: + fail(404, "asset_not_found", "Asset unavailable.") + assets[id] = a + for shot in spec.shots: + if shot.image_asset_id and assets[shot.image_asset_id].kind != "image": + fail(422, "wrong_asset_kind", "参考图需要图片") + try: + plan = compile_timeline(spec, assets) + except ValueError: + fail(422, "invalid_timeline", "音轨范围超出源素材") + return (plan, assets) + + +async def check_batch_capability(runtime, task_types=("video.generate",)): + if not set(task_types) & GPU_TYPES: + return + provider = runtime.provider + method = getattr(provider, "upstream_capabilities", None) + if method is None and runtime.settings.mode == "test": + return + if method is None: + fail( + 503, "upstream_protocol_incompatible", "Batch requires upstream scheduling protocol v2." + ) + try: + caps = await method() + except Exception: + fail(503, "upstream_protocol_incompatible", "Cannot verify upstream admission protocol.") + if caps.get("protocol_version", 0) < 2 or not caps.get("admission_policy"): + fail( + 503, "upstream_protocol_incompatible", "Batch requires upstream scheduling protocol v2." + ) + + +async def verified_output(asset, settings): + """Reuse trusts the published bytes, not just the asset's database row.""" + + def verify(): + try: + with safe_file(settings.asset_root, asset.storage_key) as source: + h = hashlib.sha256() + size = 0 + while chunk := source.read(1024 * 1024): + size += len(chunk) + h.update(chunk) + return size == asset.size_bytes and h.hexdigest() == asset.sha256 + except (OSError, ValueError): + return False + + return await asyncio.to_thread(verify) + + +async def create_run( + session, + owner_id, + draft_id, + expected_version, + revision, + mode="interactive", + reuse_run_id=None, + batch_id=None, + batch_item_index=None, + *, + settings, + output_folder_id=..., +): + await session.scalar(select(User).where(User.id == owner_id).with_for_update()) + from app.services.quotas import check_parent_capacity + + await check_parent_capacity(session, settings, owner_id, "run") + d = await owned(session, WorkflowDraft, draft_id, owner_id) + if d.editor_manifest: + fail(409, "editor_required", "请使用可编辑自动成片接口") + if d.kind == "story_v3": + fail(404, "resource_not_found", "请使用故事工作室接口") + if d.version != expected_version or d.revision != revision: + fail(409, "draft_version_conflict", "草稿已更新,请刷新版本") + plan, assets = await validate_spec(session, owner_id, d.spec, settings) + if mode == "interactive": + active = await session.scalar( + select(WorkflowRun.id).where( + WorkflowRun.owner_id == owner_id, + WorkflowRun.deleted_at.is_(None), + WorkflowRun.execution_mode == "interactive", + WorkflowRun.state.not_in(RUN_TERMINAL), + ) + ) + if active: + fail(429, "quota_exceeded", "已有活动交互工作流") + # 运行接受后冻结全部镜头参数;修改草稿不得改变旧运行或 retry 的生成时长。 + snapshot = { + **plan.spec, + "compiled": { + "generation_parameters": plan.generation_parameters, + "shot_generation_parameters": plan.shot_generation_parameters, + "canvas": list(plan.canvas), + "preset_version": "wan-three-shot-v1" + if plan.spec["schema_version"] == 1 + else "wan-multi-shot-v2", + }, + } + from app.services.folders import owned_folder + + if output_folder_id is ...: + output_folder_id = d.folder_id + if output_folder_id: + await owned_folder(session, output_folder_id, owner_id, lock=True) + r = WorkflowRun( + folder_id=d.folder_id, + output_folder_id=output_folder_id, + owner_id=owner_id, + draft_id=d.id, + draft_revision=d.revision, + spec_snapshot=snapshot, + spec_hash=digest(snapshot), + execution_mode=mode, + batch_id=batch_id, + batch_item_index=batch_item_index, + ) + session.add(r) + await session.flush() + reuse = None + if reuse_run_id: + reuse = await owned(session, WorkflowRun, reuse_run_id, owner_id) + for shot in plan.spec["shots"]: + source = assets.get(shot.get("image_asset_id")) + # 选用时长只影响裁剪;实际源长度在参数中参与哈希,15→10 秒不能复用旧源。 + generation_shot = {k: v for k, v in shot.items() if k != "duration_frames"} + h = digest( + { + "shot": generation_shot, + "generation_parameters": plan.shot_generation_parameters[shot["key"]], + "source_sha256": source.sha256 if source else None, + } + ) + step = WorkflowStep( + run_id=r.id, + step_key=shot["key"], + kind="video.generate", + dependencies=[], + semantic_input_hash=h, + ) + if reuse: + old = await session.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == reuse.id, + WorkflowStep.step_key == shot["key"], + WorkflowStep.semantic_input_hash == h, + WorkflowStep.state == "succeeded", + ) + ) + if old and old.selected_job_id: + job = await session.get(Job, old.selected_job_id) + out = await selected_output(session, old.selected_job_id, owner_id) + if ( + job + and job.owner_id == owner_id + and (job.deleted_at is None) + and (job.state == "succeeded") + and out + and await verified_output(out, settings) + ): + step.selected_job_id = job.id + step.state = "succeeded" + step.explicit_attempt = old.explicit_attempt + assets[out.id] = out + from app.services.folders import add_asset_folder + + before = set(out.folder_ids) + await add_asset_folder(session, out, r.output_folder_id, allow_missing=True) + if out.ready and before != set(out.folder_ids): + from app.services.snapshots import asset_dto + + emit_asset(session, owner_id, "asset.updated", {"asset": asset_dto(out)}) + session.add(step) + session.add( + WorkflowStep( + run_id=r.id, + step_key="compose", + kind="video.compose", + dependencies=[shot["key"] for shot in plan.spec["shots"]], + semantic_input_hash=digest(snapshot), + ) + ) + for a in assets.values(): + session.add(AssetReference(owner_id=owner_id, asset_id=a.id, ref_kind="run", ref_id=r.id)) + d.current_run_id = r.id + d.version += 1 + d.updated_at = utcnow() + await session.flush() + emit_asset(session, owner_id, "draft.updated", {"draft": draft_dto(d)}) + await emit_run(session, r, False) + return r + + +async def selected_output(session, job_id, owner_id=None): + query = select(Asset).where( + Asset.source_job_id == job_id, + Asset.library_scope == "private", + Asset.kind == "video", + Asset.ready.is_(True), + Asset.deleted_at.is_(None), + ) + if owner_id is not None: + query = query.where(Asset.owner_id == owner_id) + return await session.scalar(query.order_by(Asset.source_output_index).with_for_update()) + + +async def create_child(session, r, step, settings): + if r.deleted_at is not None: + fail(410, "resource_purged", "工作流运行已删除") + snapshot = r.spec_snapshot + if snapshot.get("schema_version") == 3: + if step.kind != "video.compose": + fail(409, "invalid_story_step", "故事运行只允许冻结素材合成") + frozen = snapshot["render_inputs"] + inputs = {"asset_ids": [c["asset_id"] for c in frozen["clips"]]} + if snapshot["render"]["audio"]: + inputs["audio_asset_id"] = snapshot["render"]["audio"]["asset_id"] + p = { + "story_spec": {k: v for k, v in snapshot.items() if k != "render_inputs"}, + "render_inputs": frozen, + "clips": [{"asset_id": c["asset_id"]} for c in frozen["clips"]], + } + for clip in frozen["clips"]: + a = await session.get(Asset, clip["asset_id"]) + if ( + not a + or a.owner_id != r.owner_id + or a.deleted_at is not None + or a.sha256 != clip["sha256"] + or not await verified_output(a, settings) + ): + fail(409, "dependency_changed", "冻结视频已改变或不可用") + elif step.kind == "video.generate": + shot = next((s for s in snapshot["shots"] if s["key"] == step.step_key)) + inputs = {"prompt": shot["prompt"]} + if shot.get("image_asset_id"): + inputs["image_asset_id"] = shot["image_asset_id"] + p = {**generation_parameters_for_shot(snapshot, step.step_key), **shot["parameters"]} + else: + steps = ( + await session.scalars( + select(WorkflowStep).where( + WorkflowStep.run_id == r.id, WorkflowStep.kind == "video.generate" + ) + ) + ).all() + bykey = {s.step_key: s for s in steps} + ids = [] + hashes = [] + for shot in snapshot["shots"]: + s = bykey[shot["key"]] + a = await selected_output(session, s.selected_job_id, r.owner_id) + if not a: + fail(409, "dependency_changed", "镜头产物不存在") + ids.append(a.id) + hashes.append(a.sha256) + inputs = {"asset_ids": ids} + audio = snapshot["render"]["audio"] + if audio: + inputs["audio_asset_id"] = audio["asset_id"] + p = { + "workflow_spec": {k: v for k, v in snapshot.items() if k != "compiled"}, + "clips": [{"asset_id": a} for a in ids], + } + audio_asset = await session.get(Asset, audio["asset_id"]) if audio else None + step.semantic_input_hash = digest( + { + "spec": snapshot, + "ordered_output_sha256": hashes, + "audio_sha256": audio_asset.sha256 if audio_asset else None, + } + ) + if r.batch_id: + from app.services.orchestration.batch_holds import run_member_holds + + r.hold_reasons = sorted(await run_member_holds(session, r)) + step.explicit_attempt += 1 + jobs = await create_jobs( + session, + Submit( + task_type=step.kind, + input=inputs, + parameters=p, + execution_mode=r.execution_mode, + folder_id=r.folder_id, + output_folder_id=r.output_folder_id, + ), + SimpleNamespace(id=r.owner_id, auth_kind="session", scopes=[]), + settings, + key=f"run:{r.id}:{step.step_key}:{step.explicit_attempt}", + internal=True, + frozen_workflow=True, + ) + j = jobs[0] + j.run_id = r.id + j.step_key = step.step_key + j.batch_id = r.batch_id + j.batch_item_index = r.batch_item_index + j.explicit_attempt = step.explicit_attempt + j.desired_state = r.desired_state + j.hold_reasons = list(r.hold_reasons or []) + step.selected_job_id = j.id + step.state = "ready" + step.version += 1 + await emit_job(session, j) + return j + + +async def control_run(session, r, desired): + if r.deleted_at is not None: + fail(404, "resource_not_found", "记录不存在") + if r.state in RUN_TERMINAL: + return + if r.desired_state == "cancel" and desired != "cancel": + fail(409, "run_cancelled", "取消不可逆") + r.desired_state = desired + holds = set(r.hold_reasons or []) + if desired == "pause": + holds.add("manual") + elif desired == "run": + holds.discard("manual") + r.hold_reasons = sorted(holds) + jobs = ( + await session.scalars( + select(Job).where( + Job.run_id == r.id, + Job.owner_id == r.owner_id, + Job.deleted_at.is_(None), + Job.state.not_in(TERMINAL), + ) + ) + ).all() + for j in jobs: + j.desired_state = desired + child_holds = set(j.hold_reasons or []) + if desired == "pause": + child_holds.add("manual") + elif desired == "run": + child_holds.discard("manual") + j.hold_reasons = sorted(child_holds) + if desired == "cancel": + j.cancel_requested = True + if ( + not j.upstream_id + and (not j.upstream_payload) + and (j.phase not in {"cpu_running", "preparing"}) + ): + j.state = "cancelled" + j.phase = "cancelled" + j.finished_at = utcnow() + elif j.state != "collecting": + j.state = "cancelling" + j.phase = "cancellation_pending" + await emit_job(session, j) + r.state = "cancelling" if desired == "cancel" else "paused" if desired == "pause" else "queued" + await emit_run(session, r) + + +def wake(runtime): + runtime.coordinator.wake() + + +async def post_draft(body: DraftCreate, runtime, actor: Actor = None): + async with runtime.db.session() as s: + from app.core.maintenance import require_writable + + require_writable(runtime.settings) + plan, assets = await validate_spec(s, actor.id, body.spec, runtime.settings) + from app.services.folders import owned_folder + + if body.folder_id: + await owned_folder(s, body.folder_id, actor.id, lock=True) + d = WorkflowDraft( + owner_id=actor.id, + name=body.name, + kind=body.kind, + spec=plan.spec, + folder_id=body.folder_id, + ) + s.add(d) + await s.flush() + for a in assets.values(): + s.add(AssetReference(owner_id=actor.id, asset_id=a.id, ref_kind="draft", ref_id=d.id)) + emit_asset(s, actor.id, "draft.updated", {"draft": draft_dto(d)}) + await s.commit() + return draft_dto(d) + + +async def list_drafts( + runtime, page: int = 1, page_size: int = 24, actor: Actor = None, folder_id: str = "" +): + async with runtime.db.session() as s: + rows, data = await page_rows( + s, + WorkflowDraft, + actor, + page, + page_size, + WorkflowDraft.kind != "story_v3", + await folder_filter(s, WorkflowDraft, actor.id, folder_id), + ) + return {**data, "items": [draft_dto(d) for d in rows]} + + +async def get_draft(id: str, runtime, actor: Actor = None): + async with runtime.db.session() as s: + d = await owned(s, WorkflowDraft, id, actor.id) + if d.kind == "story_v3": + fail(404, "resource_not_found", "请使用故事工作室接口") + return draft_dto(d) + + +async def delete_draft(id: str, runtime, if_match: str | None = None, actor: Actor = None): + from app.services.deletions import archive_records + + async with runtime.db.session() as s: + d = await s.scalar( + select(WorkflowDraft).where(WorkflowDraft.id == id, WorkflowDraft.owner_id == actor.id) + ) + if d and d.kind == "story_v3": + fail(404, "resource_not_found", "请使用故事工作室接口") + result = await archive_records(s, WorkflowDraft, id, actor.id, if_match) + await s.commit() + return result + + +async def patch_draft( + id: str, body: DraftPatch, runtime, if_match: str | None = None, actor: Actor = None +): + async with runtime.db.session() as s: + d = await owned(s, WorkflowDraft, id, actor.id) + if d.editor_manifest: + fail(409, "editor_required", "请使用可编辑自动成片接口") + if d.kind == "story_v3": + fail(404, "resource_not_found", "请使用故事工作室接口") + if if_match is None or if_match.strip('"') != str(d.version): + fail(409, "draft_version_conflict", "草稿版本冲突") + if "folder_id" in body.model_fields_set: + from app.services.folders import owned_folder + + if body.folder_id: + await owned_folder(s, body.folder_id, actor.id, lock=True) + d.folder_id = body.folder_id + if body.name is not None: + d.name = body.name + if body.spec is not None: + plan, assets = await validate_spec(s, actor.id, body.spec, runtime.settings) + await s.execute( + delete(AssetReference).where( + AssetReference.ref_kind == "draft", AssetReference.ref_id == d.id + ) + ) + for a in assets.values(): + s.add( + AssetReference(owner_id=actor.id, asset_id=a.id, ref_kind="draft", ref_id=d.id) + ) + d.spec = plan.spec + d.revision += 1 + d.version += 1 + d.updated_at = utcnow() + emit_asset(s, actor.id, "draft.updated", {"draft": draft_dto(d)}) + await s.commit() + return draft_dto(d) + + +async def post_run( + id: str, body: RunCreate, runtime, idempotency_key: str | None = None, actor: Actor = None +): + from app.core.maintenance import require_writable + + require_writable(runtime.settings) + if ( + actor.auth_kind == "bearer" + and body.execution_mode == "interactive" + and ("interactive:write" not in actor.scopes) + ): + fail(403, "scope_required", "Interactive scope required.") + capability_error = None + if body.execution_mode == "batch": + try: + await check_batch_capability(runtime) + except HTTPException as exc: + capability_error = exc + async with runtime.db.session() as s: + sub = await accept_submission( + s, + actor.id, + "workflow.run", + idempotency_key, + 2, + {"draft_id": id, **request_payload(body)}, + ) + if sub.resource_json: + r = await owned(s, WorkflowRun, sub.resource_json["run_id"], actor.id) + else: + if capability_error: + raise capability_error + from app.services.quotas import reserve_budget + + await reserve_budget(s, actor.id, "workflow.run", units=0, settings=runtime.settings) + r = await create_run( + s, + actor.id, + id, + body.expected_version, + body.draft_revision, + body.execution_mode, + body.reuse_run_id, + settings=runtime.settings, + output_folder_id=body.output_folder_id + if "output_folder_id" in body.model_fields_set + else ..., + ) + sub.resource_json = {"run_id": r.id, "draft_id": id} + await s.commit() + snap = await snapshot_run(s, actor.id, r.id) + wake(runtime) + return snap + + +async def list_runs( + runtime, page: int = 1, page_size: int = 24, actor: Actor = None, folder_id: str = "" +): + async with runtime.db.session() as s: + rows, data = await page_rows( + s, + WorkflowRun, + actor, + page, + page_size, + await folder_filter(s, WorkflowRun, actor.id, folder_id), + ) + return {**data, "items": [(await snapshot_run(s, actor.id, r.id))["run"] for r in rows]} + + +async def get_run(id: str, runtime, actor: Actor = None): + async with runtime.db.session() as s: + return await snapshot_run(s, actor.id, id) + + +async def delete_run(id: str, runtime, if_match: str | None = None, actor: Actor = None): + from app.services.deletions import archive_records + + async with runtime.db.session() as s: + result = await archive_records(s, WorkflowRun, id, actor.id, if_match) + await s.commit() + return result + + +async def retry_step( + id: str, key: str, body: Retry, runtime, idempotency_key: str | None = None, actor: Actor = None +): + async with runtime.db.session() as s: + r = await owned(s, WorkflowRun, id, actor.id) + if ( + actor.auth_kind == "bearer" + and r.execution_mode == "interactive" + and ("interactive:write" not in actor.scopes) + ): + fail(403, "scope_required", "Interactive scope required.") + sub = await accept_submission( + s, + actor.id, + "workflow.retry", + idempotency_key, + 2, + {"run_id": id, "step_key": key, **body.model_dump()}, + ) + if not sub.resource_json: + if r.version != body.expected_run_version: + fail(409, "run_version_conflict", "工作流版本冲突") + step = await s.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == r.id, WorkflowStep.step_key == key + ) + ) + j = await s.get(Job, body.target_job_id) + if ( + not step + or step.selected_job_id != body.target_job_id + or (not j) + or (j.owner_id != actor.id) + or (j.deleted_at is not None) + or (r.state in RUN_TERMINAL) + or (r.desired_state == "cancel") + ): + fail(409, "step_not_retryable", "步骤不可重试") + active_execution = await s.scalar( + select(Execution.id).where( + Execution.job_id == j.id, Execution.state.not_in({"exited", "results_ready"}) + ) + ) + if active_execution: + fail(409, "cleanup_pending", "Execution cleanup must be confirmed before retry.") + if j.state == "needs_attention" and (not (j.error_json or {}).get("safe_to_retry")): + fail(409, "cleanup_pending", "执行尚未确认清理") + if j.state not in {"failed", "timed_out", "needs_attention"}: + fail(409, "step_not_retryable", "仅失败步骤允许重试") + if r.run_kind in {"story_auto", "workflow_auto"}: + from app.services.orchestration.editor_engine import create_editor_child + + await create_editor_child(s, r, step, runtime.settings) + else: + await create_child(s, r, step, runtime.settings) + r.state = "paused" if r.desired_state == "pause" or r.hold_reasons else "queued" + r.error_json = None + await emit_run(s, r) + sub.resource_json = {"run_id": r.id, "job_id": step.selected_job_id} + await s.commit() + snap = await snapshot_run(s, actor.id, id) + wake(runtime) + return snap + + +async def _control(id, desired, body, runtime, key, actor): + async with runtime.db.session() as s: + sub = await accept_submission( + s, + actor.id, + "workflow." + ("resume" if desired == "run" else desired), + key, + 2, + {"run_id": id, **body.model_dump()}, + ) + r = await owned(s, WorkflowRun, id, actor.id) + if not sub.resource_json: + if body.expected_version is not None and body.expected_version != r.version: + fail(409, "run_version_conflict", "工作流版本冲突") + await control_run(s, r, desired) + sub.resource_json = {"run_id": r.id} + await s.commit() + snap = await snapshot_run(s, actor.id, id) + wake(runtime) + return snap + + +async def cancel_run( + id: str, body: Control, runtime, idempotency_key: str | None = None, actor: Actor = None +): + return await _control(id, "cancel", body, runtime, idempotency_key, actor) + + +async def pause_run( + id: str, body: Control, runtime, idempotency_key: str | None = None, actor: Actor = None +): + return await _control(id, "pause", body, runtime, idempotency_key, actor) + + +async def resume_run( + id: str, body: Control, runtime, idempotency_key: str | None = None, actor: Actor = None +): + return await _control(id, "run", body, runtime, idempotency_key, actor) diff --git a/backend/app/shared_assets.py b/backend/app/shared_assets.py deleted file mode 100644 index a77c31b..0000000 --- a/backend/app/shared_assets.py +++ /dev/null @@ -1,277 +0,0 @@ -"""Authenticated publication snapshots and independent private imports.""" - -import asyncio -import hashlib -from pathlib import Path -import re -import shutil - -from fastapi import APIRouter, Body, Depends, Header, Request, Response -from pydantic import BaseModel, ConfigDict -from sqlalchemy import delete, func, select, update - -from .assets import confined, file_response, owned_asset, safe_file -from .auth import Actor, csrf_actor, current_actor -from .dto import asset_dto, iso -from .errors import fail -from .events import emit_asset -from .models import Asset, User, new_id, utcnow -from .v2_models import AssetReference, AssetTag, SharedAsset, Submission - -router = APIRouter(prefix="/shared-assets", tags=["shared-assets"]) -publish_router = APIRouter(prefix="/assets", tags=["shared-assets"]) - - -class EmptyPayload(BaseModel): - model_config = ConfigDict(extra="forbid") - - -def shared_dto(publication, asset, publisher, actor): - base = f"/api/shared-assets/{publication.id}" - return { - "id": publication.id, "name": asset.name, "kind": asset.kind, - "mime_type": asset.mime_type, "size_bytes": asset.size_bytes, - "width": asset.width, "height": asset.height, - "duration_seconds": asset.duration_seconds, "tags": asset.tags or [], - "created_at": iso(publication.created_at), "publisher_id": publisher.id, - "publisher_name": publisher.display_name or publisher.username, - "is_owner": publication.publisher_id == actor.id, "version": publication.version, - "preview_url": base + "/content", - "thumbnail_url": base + "/thumbnail" if asset.kind in {"image", "video"} else None, - "download_url": base + "/content?download=1", - } - - -def shared_query(): - return (select(SharedAsset, Asset, User) - .join(Asset, Asset.id == SharedAsset.asset_id) - .join(User, User.id == SharedAsset.publisher_id) - .where(SharedAsset.withdrawn_at.is_(None), Asset.deleted_at.is_(None), - Asset.ready.is_(True), Asset.library_scope == "shared")) - - -async def available_shared(session, shared_id): - row = (await session.execute(shared_query().where(SharedAsset.id == shared_id).with_for_update())).first() - if row is None: - fail(404, "shared_asset_not_found", "共享素材不存在或已撤回") - return row - - -async def copy_asset(settings, source, owner_id, *, scope): - """Copy verified regular files into a fresh directory; never link source bytes.""" - asset_id = new_id() - directory = confined(settings.asset_root, Path(owner_id) / asset_id) - directory.mkdir(parents=True) - - def copy_files(): - suffix = Path(source.storage_key).suffix.lower() - if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix): - suffix = ".bin" - destination = directory / ("original" + suffix) - digest, size = hashlib.sha256(), 0 - with safe_file(settings.asset_root, source.storage_key) as src, destination.open("xb") as dst: - while chunk := src.read(1024 * 1024): - size += len(chunk) - if size > source.size_bytes: - raise ValueError("Source size changed") - digest.update(chunk) - dst.write(chunk) - if size != source.size_bytes or digest.hexdigest() != source.sha256: - raise ValueError("Source integrity check failed") - thumbnail = None - if source.thumbnail_key: - thumbnail = directory / "thumbnail.jpg" - with safe_file(settings.asset_root, source.thumbnail_key) as src, thumbnail.open("xb") as dst: - shutil.copyfileobj(src, dst, 1024 * 1024) - return destination, thumbnail - - try: - path, thumbnail = await asyncio.to_thread(copy_files) - asset = Asset( - id=asset_id, owner_id=owner_id, name=source.name, library_scope=scope, - storage_key=path.relative_to(settings.asset_root).as_posix(), - thumbnail_key=thumbnail.relative_to(settings.asset_root).as_posix() if thumbnail else None, - kind=source.kind, mime_type=source.mime_type, size_bytes=source.size_bytes, - sha256=source.sha256, width=source.width, height=source.height, - duration_seconds=source.duration_seconds, tags=list(source.tags or []), favorite=False, - origin="shared", ready=True, source_job_id=None, source_upstream_id=None, - source_output_index=None, - ) - return asset, directory - except BaseException as exc: - shutil.rmtree(directory, ignore_errors=True) - if isinstance(exc, (OSError, ValueError)): - fail(404, "file_unavailable", "素材文件不可用") - raise - - -async def copy_budget(session, settings, owner_id, size_bytes): - # Match upload accounting, including retained soft-deleted files. Publication - # copies charge the publisher; private imports charge the importing user. - owner = await session.scalar(select(User).where(User.id == owner_id).with_for_update()) - if owner is None or owner.disabled: - fail(403, "owner_disabled", "用户不可用") - from .quotas import check_storage_budget - await check_storage_budget(session, settings, owner_id, size_bytes) - - -def add_tags(session, asset): - session.add_all(AssetTag(owner_id=asset.owner_id, asset_id=asset.id, tag=tag) for tag in (asset.tags or [])) - - -@publish_router.post("/{asset_id}/publish", status_code=201) -async def publish_asset(asset_id: str, request: Request, body: EmptyPayload | None = Body(default=None), - idempotency_key: str | None = Header(default=None), actor: Actor = Depends(csrf_actor)): - from .maintenance import require_writable - from .submissions import accept_submission - settings = request.app.state.settings - require_writable(settings) - directory, commit_started = None, False - try: - # This deployment serializes DB units. Keep source verification, copying, - # publication, and references in the same unit to exclude withdrawal/GC. - async with request.app.state.db.session() as session: - record = (await accept_submission(session, actor.id, "assets.publish", idempotency_key, - 2, {"asset_id": asset_id})) if idempotency_key is not None else None - if record and record.resource_json.get("shared_asset_id"): - row = (await session.execute(shared_query().where( - SharedAsset.id == record.resource_json["shared_asset_id"], SharedAsset.publisher_id == actor.id))).first() - if row is None: - fail(410, "resource_purged", "共享发布已撤回") - return shared_dto(*row, actor) - source = await owned_asset(session, asset_id, actor.id) - row = (await session.execute(shared_query().where( - SharedAsset.source_asset_id == source.id, SharedAsset.publisher_id == actor.id))).first() - if row: - publication, snapshot, publisher = row - else: - await copy_budget(session, settings, actor.id, source.size_bytes) - snapshot, directory = await copy_asset(settings, source, actor.id, scope="shared") - session.add(snapshot) - await session.flush() - add_tags(session, snapshot) - publication = SharedAsset(id=new_id(), publisher_id=actor.id, asset_id=snapshot.id, - source_asset_id=source.id, version=1) - session.add(publication) - await session.flush() - session.add(AssetReference(owner_id=actor.id, asset_id=snapshot.id, - ref_kind="shared", ref_id=publication.id)) - publisher = await session.get(User, actor.id) - if record: - record.resource_json = {"shared_asset_id": publication.id} - commit_started = True - await session.commit() - return shared_dto(publication, snapshot, publisher, actor) - except BaseException: - # A lost commit ACK can leave a durable publication. Retain files in that - # case for reconciliation, as the normal upload/import pipeline does. - if directory is not None and not commit_started: - shutil.rmtree(directory, ignore_errors=True) - raise - - -@router.get("") -async def list_shared_assets(request: Request, q: str = "", kind: str = "", tag: str = "", mine: bool = False, - page: int = 1, page_size: int = 24, actor: Actor = Depends(current_actor)): - if page < 1 or not 1 <= page_size <= 100: - fail(422, "invalid_page", "分页参数无效") - async with request.app.state.db.session() as session: - query = shared_query() - if q: - query = query.where(Asset.name.contains(q[:255], autoescape=True)) - if kind: - query = query.where(Asset.kind == kind) - if tag: - query = query.where(Asset.id.in_(select(AssetTag.asset_id).where(AssetTag.tag == tag))) - if mine: - query = query.where(SharedAsset.publisher_id == actor.id) - total = await session.scalar(select(func.count()).select_from(query.subquery())) - rows = (await session.execute(query.order_by(SharedAsset.created_at.desc(), SharedAsset.id.desc()) - .offset((page - 1) * page_size).limit(page_size))).all() - return {"items": [shared_dto(*row, actor) for row in rows], "total": total, - "page": page, "page_size": page_size} - - -@router.get("/{shared_id}") -async def get_shared_asset(shared_id: str, request: Request, actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - return shared_dto(*(await available_shared(session, shared_id)), actor) - - -@router.get("/{shared_id}/content") -async def shared_content(shared_id: str, request: Request, download: bool = False, - actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - _, asset, _ = await available_shared(session, shared_id) - return file_response(request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download) - - -@router.get("/{shared_id}/thumbnail") -async def shared_thumbnail(shared_id: str, request: Request, actor: Actor = Depends(current_actor)): - async with request.app.state.db.session() as session: - _, asset, _ = await available_shared(session, shared_id) - if not asset.thumbnail_key and asset.kind != "image": - fail(404, "thumbnail_unavailable", "预览图暂不可用") - return file_response(request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False) - - -@router.post("/{shared_id}/import", status_code=201) -async def import_shared_asset(shared_id: str, request: Request, body: EmptyPayload | None = Body(default=None), - idempotency_key: str | None = Header(default=None), actor: Actor = Depends(csrf_actor)): - from .maintenance import require_writable - from .submissions import accept_submission - settings = request.app.state.settings - require_writable(settings) - directory, commit_started = None, False - try: - async with request.app.state.db.session() as session: - record = (await accept_submission(session, actor.id, "shared.import", idempotency_key, - 2, {"shared_asset_id": shared_id})) if idempotency_key is not None else None - if record and record.resource_json.get("asset_id"): - existing = await session.scalar(select(Asset).where( - Asset.id == record.resource_json["asset_id"], Asset.owner_id == actor.id, - Asset.library_scope == "private", Asset.ready.is_(True), Asset.deleted_at.is_(None))) - if existing is None: - fail(410, "resource_purged", "导入素材已删除") - return asset_dto(existing) - _, source, _ = await available_shared(session, shared_id) - await copy_budget(session, settings, actor.id, source.size_bytes) - asset, directory = await copy_asset(settings, source, actor.id, scope="private") - session.add(asset) - await session.flush() - add_tags(session, asset) - if record: - record.resource_json = {"asset_id": asset.id} - emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)}) - commit_started = True - await session.commit() - return asset_dto(asset) - except BaseException: - if directory is not None and not commit_started: - shutil.rmtree(directory, ignore_errors=True) - raise - - -@router.delete("/{shared_id}", status_code=204) -async def withdraw_shared_asset(shared_id: str, request: Request, actor: Actor = Depends(csrf_actor)): - async with request.app.state.db.session() as session: - publication = await session.scalar(select(SharedAsset).where( - SharedAsset.id == shared_id, SharedAsset.publisher_id == actor.id).with_for_update()) - if publication is None: - fail(404, "shared_asset_not_found", "共享素材不存在") - if publication.withdrawn_at is None: - publication.withdrawn_at = utcnow() - publication.version += 1 - snapshot = await session.get(Asset, publication.asset_id) - if snapshot is not None: - snapshot.deleted_at = publication.withdrawn_at - await session.execute(delete(AssetReference).where( - AssetReference.asset_id == publication.asset_id, - AssetReference.ref_kind == "shared", AssetReference.ref_id == publication.id)) - # Imported private copies have their own asset_id result. Keep their - # recovery records even when the importer is also the publisher. - await session.execute(update(Submission).where( - Submission.owner_id == actor.id, Submission.status != "purged", - Submission.resource_json["shared_asset_id"].as_string() == publication.id).values(status="purged")) - await session.commit() - return Response(status_code=204) diff --git a/backend/app/submissions.py b/backend/app/submissions.py deleted file mode 100644 index d8fd56e..0000000 --- a/backend/app/submissions.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Durable intent records; callers commit the record and resource in one transaction.""" - -import hashlib - -import json - -from fastapi import APIRouter, Depends, Request - -from sqlalchemy import select - -from .auth import Actor, current_actor - -from .errors import fail - -from .v2_models import Submission - -router=APIRouter(prefix="/submissions",tags=["submissions"]) - - - -def body_hash(body, schema=2): - - try: - - return hashlib.sha256(json.dumps({"schema":schema,"body":body},sort_keys=True,separators=(",",":"),ensure_ascii=False,allow_nan=False).encode()).hexdigest() - - except (ValueError,TypeError): - - fail(422,"invalid_json","请求必须为合法JSON") - - - -async def accept_submission(session, owner_id, operation, key, payload_schema, body): - - if not key or not 1<=len(key)<=128: - - fail(422,"invalid_idempotency_key","需要1–128字符的幂等键") - - digest=body_hash(body,payload_schema) - - row=await session.scalar(select(Submission).where(Submission.owner_id==owner_id,Submission.operation==operation,Submission.key==key)) - - if row: - - if row.body_hash!=digest: - - fail(409,"idempotency_conflict","此幂等键已用于不同参数") - - if row.status=="purged": - - fail(410,"resource_purged","提交结果已清理") - - return row - - row=Submission(owner_id=owner_id,operation=operation,key=key,payload_schema=payload_schema,body_hash=digest,request_json=body,resource_json={}) - - session.add(row) - - await session.flush() - - return row - - - -@router.get("/{key}") - -async def recover(key:str,request:Request,operation:str,actor:Actor=Depends(current_actor)): - - async with request.app.state.db.session() as session: - - row=await session.scalar(select(Submission).where(Submission.owner_id==actor.id,Submission.operation==operation,Submission.key==key)) - - if not row and operation=="jobs.create": - from .models import Job - legacy=(await session.scalars(select(Job).where(Job.owner_id==actor.id,Job.request_key==key).order_by(Job.batch_index))).all() - if legacy: - if any(job.deleted_at is not None for job in legacy): - fail(410,"resource_purged","提交结果已删除") - resources={"job_ids":[job.id for job in legacy]} - return {"key":key,"operation":operation,"status":"accepted","resource_json":resources,**resources} - if not row: fail(404,"submission_not_found","尚未找到提交记录;重试仍须使用原幂等键") - - if row.status=="purged": fail(410,"resource_purged","提交结果已清理") - - return {"key":row.key,"operation":row.operation,"status":row.status,"resource_json":row.resource_json,**row.resource_json} diff --git a/backend/app/timeline.py b/backend/app/timeline.py deleted file mode 100644 index 44adbac..0000000 --- a/backend/app/timeline.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Versioned short-clip story contract. Public fields contain no executable paths.""" -from dataclasses import dataclass, field -from typing import Literal -import re -from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator - -DEFAULT_CLIP_FRAMES = 120 -MAX_CLIP_FRAMES = 360 -DEFAULT_SOURCE_FRAMES = 121 -MAX_SOURCE_FRAMES = 361 -MAX_WORKFLOW_SHOTS = 1000 -MAX_TIMELINE_FRAMES = MAX_WORKFLOW_SHOTS * MAX_CLIP_FRAMES - -class Strict(BaseModel): - model_config = ConfigDict(extra='forbid', strict=True) - -class ShotParameters(Strict): - seed: int = Field(default=42, ge=0, le=2**32-1) - -class Shot(Strict): - key: str = Field(pattern=r'^shot_[1-9][0-9]{0,3}$') - prompt: str = Field(min_length=1,max_length=8000) - duration_frames: int = Field(default=DEFAULT_CLIP_FRAMES,ge=24,le=MAX_CLIP_FRAMES) - image_asset_id: str | None = Field(default=None,min_length=1,max_length=64) - parameters: ShotParameters = Field(default_factory=ShotParameters) - @model_validator(mode='after') - def prompt_required(self): - if not self.prompt.strip(): raise ValueError('prompt_required') - return self - -class Subtitle(Strict): - start_frame: int = Field(ge=0) - end_frame: int = Field(gt=0) - text: str = Field(min_length=1,max_length=2000) - @model_validator(mode='after') - def safe(self): - if self.end_frame <= self.start_frame or not self.text.strip() or re.search(r'[\\{}\x00-\x1f\x7f]',self.text): - raise ValueError('invalid_timeline: subtitle') - return self - -class Audio(Strict): - asset_id: str = Field(min_length=1,max_length=64) - source_start_ms: int = Field(ge=0) - source_end_ms: int = Field(gt=0) - offset_frame: int = Field(default=0,ge=0) - short_policy: Literal['silence'] = 'silence' - @model_validator(mode='after') - def fits(self): - if self.source_end_ms <= self.source_start_ms: - raise ValueError('invalid_timeline: invalid audio selection') - return self - -class Render(Strict): - fps: Literal[24] = 24 - total_frames: int | None = Field(default=None,ge=1,le=MAX_TIMELINE_FRAMES) - fit: Literal['contain','cover'] = 'contain' - audio: Audio | None = None - subtitles: list[Subtitle] = Field(default_factory=list,max_length=1000) - template_version: Literal['plain-v1'] = 'plain-v1' - -class WorkflowSpec(Strict): - schema_version: Literal[1,2] = 1 - shots: list[Shot] = Field(min_length=1,max_length=MAX_WORKFLOW_SHOTS) - profile: Literal['landscape_1080_v1','portrait_1080_v1'] = 'landscape_1080_v1' - render: Render = Field(default_factory=Render) - @model_validator(mode='after') - def ordered_timeline(self): - if self.schema_version == 1 and (len(self.shots) != 3 or any('duration_frames' in s.model_fields_set for s in self.shots)): - raise ValueError('schema_version 1 requires three full-length shots') - if [s.key for s in self.shots] != [f'shot_{i}' for i in range(1,len(self.shots)+1)]: - raise ValueError('exact ordered sequential shot keys required') - frames = sum(s.duration_frames for s in self.shots) - if frames > MAX_TIMELINE_FRAMES: - raise ValueError('invalid_timeline: total frames exceed maximum story length') - if self.render.total_frames is not None and self.render.total_frames != frames: - raise ValueError('invalid_timeline: total_frames differs from shots') - self.render.total_frames = frames - if any(c.end_frame > frames for c in self.render.subtitles): - raise ValueError('invalid_timeline: subtitle exceeds canvas') - audio = self.render.audio - if audio and (audio.offset_frame >= frames or (audio.source_end_ms-audio.source_start_ms)*24 > (frames-audio.offset_frame)*1000): - raise ValueError('invalid_timeline: audio exceeds canvas') - return self - - @model_serializer(mode='wrap') - def legacy_compatible_dump(self, handler): - data = handler(self) - if self.schema_version == 1: - for shot in data['shots']:shot.pop('duration_frames',None) - return data - -@dataclass(frozen=True) -class TimelinePlan: - spec: dict - generation_parameters: dict - canvas: tuple[int,int] - frames: int = 360 - clip_frames: int = 120 - fps: int = 24 - shot_frames: tuple[int,...] = () - shot_generation_parameters: dict[str,dict] = field(default_factory=dict) - - -def ordered_step_keys(snapshot): - """The frozen shot array is authoritative, including shot_10 and later.""" - return [shot['key'] for shot in snapshot['shots']] + ['compose'] - - -def generation_parameters_for_shot(snapshot, key): - """Read accepted source parameters; legacy snapshots keep their original base.""" - compiled = snapshot['compiled'] - if 'shot_generation_parameters' not in compiled: - return compiled['generation_parameters'] - parameters = compiled['shot_generation_parameters'] - if not isinstance(parameters,dict) or key not in parameters or not isinstance(parameters[key],dict) or 'num_frames' not in parameters[key]: - raise ValueError('Frozen shot generation parameters are incomplete') - return parameters[key] - - -def compile_timeline(spec, owned_assets) -> TimelinePlan: - spec = spec if isinstance(spec,WorkflowSpec) else WorkflowSpec.model_validate(spec) - audio = spec.render.audio - if audio: - asset = owned_assets.get(audio.asset_id) - def field(name): return asset.get(name) if isinstance(asset,dict) else getattr(asset,name,None) - if asset is None or field('kind') != 'audio' or field('duration_seconds') is None or audio.source_end_ms > round(field('duration_seconds')*1000): - raise ValueError('invalid_timeline: audio source cut exceeds source') - portrait = spec.profile == 'portrait_1080_v1' - parameters = dict(width=704 if portrait else 1280,height=1280 if portrait else 704, - num_frames=DEFAULT_SOURCE_FRAMES,fps=24,upscale=True,upscale_width=1056 if portrait else 1920, - upscale_height=1920 if portrait else 1056,num_inference_steps=50,guidance_scale=5.0,tile_size=128) - per_shot = {shot.key:{**parameters,'num_frames':max(DEFAULT_SOURCE_FRAMES,4*((shot.duration_frames+3)//4)+1)} - for shot in spec.shots} - return TimelinePlan(spec.model_dump(mode='json'),parameters,(1080,1920) if portrait else (1920,1080), - frames=spec.render.total_frames,shot_frames=tuple(s.duration_frames for s in spec.shots), - shot_generation_parameters=per_shot) diff --git a/backend/app/tokens.py b/backend/app/tokens.py deleted file mode 100644 index 8cb40f7..0000000 --- a/backend/app/tokens.py +++ /dev/null @@ -1,70 +0,0 @@ -import secrets -from datetime import datetime,timezone -from fastapi import APIRouter,Depends,Request,Response -from pydantic import BaseModel,Field,ConfigDict -from sqlalchemy import select -from .auth import Actor,current_actor,csrf_actor,token_hash -from .models import User,utcnow -from .v2_models import ApiToken -from .errors import fail -from .dto import iso -router=APIRouter(prefix="/auth/tokens",tags=["tokens"]) -SCOPES={"jobs:read","jobs:write","assets:read","assets:write","events:read","workflows:read","workflows:write","batches:read","batches:write","interactive:write"} - -def record(row): - return {"id":row.id,"name":row.name,"scopes":row.scopes,"expires_at":iso(row.expires_at),"created_at":iso(row.created_at),"revoked_at":iso(row.revoked_at)} - -async def bearer_actor(request,token): - async with request.app.state.db.session() as session: - row=await session.scalar(select(ApiToken).where(ApiToken.token_hash==token_hash(token),ApiToken.revoked_at.is_(None))) - if not row or (row.expires_at and row.expires_at<=utcnow()): fail(401,"token_expired","Token unavailable") - user=await session.get(User,row.owner_id) - if not user or user.disabled: fail(401,"token_expired","Token unavailable") - path=request.url.path.removeprefix("/api/").split("/")[0] - if path=="submissions": - operation=request.query_params.get("operation","") - path="assets" if operation in {"assets.publish","shared.import"} else "workflows" if operation.startswith("workflow") else "batches" if operation.startswith("batch") else "jobs" - scope={"workflow-runs":"workflows","shared-assets":"assets"}.get(path,path)+ (":read" if request.method in {"GET","HEAD"} else ":write") - if scope not in row.scopes: fail(403,"scope_required","Token scope required: "+scope) - return Actor(user.id,user.username,user.display_name,"user","",row.token_hash,"bearer",row.scopes,user.must_change_password) - -class TokenInput(BaseModel): - model_config=ConfigDict(extra="forbid") - name:str=Field(min_length=1,max_length=128) - scopes:list[str]=Field(max_length=20) - expires_at:datetime|None=None - -def owner_session(actor): - if actor.auth_kind!="session": fail(403,"session_required","Session required") - -@router.get("") -async def list_tokens(request:Request,actor:Actor=Depends(current_actor)): - owner_session(actor) - async with request.app.state.db.session() as session: - rows=(await session.scalars(select(ApiToken).where(ApiToken.owner_id==actor.id))).all() - return {"items":[record(r) for r in rows]} - -@router.post("",status_code=201) -async def create_token(body:TokenInput,request:Request,actor:Actor=Depends(csrf_actor)): - owner_session(actor) - if set(body.scopes)-SCOPES: fail(422,"invalid_scope","Unknown token scope") - expires=body.expires_at - if expires: - if expires.tzinfo is None: fail(422,"timezone_required","Expiry requires timezone") - expires=expires.astimezone(timezone.utc).replace(tzinfo=None) - if expires<=utcnow(): fail(422,"invalid_expiry","Expiry must be in the future") - if getattr(request.app.state.settings,"public_access",False) and actor.must_change_password: fail(403,"password_change_required","Change password first") - token="cmvr_"+secrets.token_urlsafe(36) - async with request.app.state.db.session() as session: - row=ApiToken(owner_id=actor.id,name=body.name,scopes=list(set(body.scopes)),token_hash=token_hash(token),expires_at=expires) - session.add(row);await session.commit() - return {"token":token,"record":record(row)} - -@router.delete("/{token_id}",status_code=204) -async def revoke(token_id:str,request:Request,actor:Actor=Depends(csrf_actor)): - owner_session(actor) - async with request.app.state.db.session() as session: - row=await session.scalar(select(ApiToken).where(ApiToken.id==token_id,ApiToken.owner_id==actor.id)) - if not row: fail(404,"token_not_found","Token not found") - row.revoked_at=utcnow();await session.commit() - return Response(status_code=204) diff --git a/backend/app/upload_guard.py b/backend/app/upload_guard.py deleted file mode 100644 index 239218c..0000000 --- a/backend/app/upload_guard.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Authenticate and bound uploads before multipart parsing creates spool files.""" -import asyncio -from pathlib import Path -import tempfile -from fastapi import HTTPException -from starlette.requests import Request -from starlette.responses import JSONResponse -from .auth import current_actor, csrf_actor -from .quotas import check_storage_budget - - -class UploadGuard: - def __init__(self, app): - self.app=app - self.slots=asyncio.Semaphore(2) - self.lock=asyncio.Lock() - self.reserved={} - self.global_reserved=0 - - async def __call__(self, scope, receive, send): - if (scope['type']!='http' or scope['method']!='POST' - or scope['path'].rstrip('/')!='/api/assets'): - return await self.app(scope,receive,send) - request=Request(scope) - settings=request.app.state.settings - async def reject(status,code,message): - await JSONResponse({'detail':{'code':code,'message':message}},status_code=status)(scope,receive,send) - try: - actor=await current_actor(request) - await csrf_actor(request,actor) - except HTTPException as exc: - return await JSONResponse({'detail':exc.detail},status_code=exc.status_code)(scope,receive,send) - limit=settings.max_upload_bytes+1024*1024 # bounded multipart overhead - length=request.headers.get('content-length') - try: - expected=int(length) if length is not None else limit - if expected<0:raise ValueError() - except ValueError: - return await reject(400,'invalid_content_length','上传长度无效') - if expected>limit: - return await reject(413,'upload_too_large','上传超过文件大小限制') - if self.slots.locked(): - return await reject(429,'upload_busy','同时上传数量已满,请稍后重试') - await self.slots.acquire() - reservation=expected*2 # raw body plus multipart spool during parsing - reserved=False - try: - async with self.lock: - async with request.app.state.db.session() as session: - await check_storage_budget(session,settings,actor.id, - incoming_bytes=self.reserved.get(actor.id,0)+expected, - global_incoming_bytes=self.global_reserved+reservation) - self.reserved[actor.id]=self.reserved.get(actor.id,0)+expected - self.global_reserved+=reservation - reserved=True - temporary=(settings.asset_root.parent/'tmp').resolve() - if not temporary.is_relative_to(settings.workspace_root): - return await reject(503,'upload_storage_unavailable','上传暂存目录不可用') - temporary.mkdir(parents=True,exist_ok=True) - with tempfile.TemporaryFile(dir=temporary) as body: - total=0 - while True: - message=await receive() - if message['type']=='http.disconnect': - return await reject(499,'upload_disconnected','上传连接已断开') - if message['type']!='http.request':continue - chunk=message.get('body',b'') - total+=len(chunk) - if total>limit or (length is not None and total>expected): - return await reject(413,'upload_too_large','上传超过文件大小限制') - await asyncio.to_thread(body.write,chunk) - if not message.get('more_body',False):break - if length is not None and total!=expected: - return await reject(400,'invalid_content_length','上传数据长度不匹配') - await asyncio.to_thread(body.seek,0) - remaining=total - completed=False - async def replay(): - nonlocal remaining,completed - if completed:return await receive() - chunk=await asyncio.to_thread(body.read,min(1024*1024,remaining)) - remaining-=len(chunk) - completed=remaining==0 - return {'type':'http.request','body':chunk,'more_body':not completed} - await self.app(scope,replay,send) - except HTTPException as exc: - await JSONResponse({'detail':exc.detail},status_code=exc.status_code)(scope,receive,send) - finally: - if reserved: - async with self.lock: - self.reserved[actor.id]-=expected - self.global_reserved-=reservation - if self.reserved[actor.id]==0:self.reserved.pop(actor.id) - self.slots.release() diff --git a/backend/app/v2_models.py b/backend/app/v2_models.py deleted file mode 100644 index 054bcb6..0000000 --- a/backend/app/v2_models.py +++ /dev/null @@ -1,169 +0,0 @@ -from datetime import datetime -from sqlalchemy import String, Integer, JSON, ForeignKey, UniqueConstraint -from sqlalchemy.orm import Mapped, mapped_column -from .models import Base, new_id, utcnow, Timestamp - - -class WorkflowDraft(Base): - __tablename__ = "visual_drafts" - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - name: Mapped[str] = mapped_column(String(255)) - kind: Mapped[str] = mapped_column(String(48), default='three_shot') - spec: Mapped[dict] = mapped_column(JSON, default=dict) - revision: Mapped[int] = mapped_column(Integer, default=1) - version: Mapped[int] = mapped_column(Integer, default=1) - current_run_id: Mapped[str | None] = mapped_column(String(32), nullable=True) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - updated_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - - -class WorkflowRun(Base): - __tablename__ = "visual_workflow_runs" - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - draft_id: Mapped[str] = mapped_column(String(32)) - draft_revision: Mapped[int] = mapped_column(Integer) - spec_snapshot: Mapped[dict] = mapped_column(JSON, default=dict) - spec_hash: Mapped[str] = mapped_column(String(64)) - execution_mode: Mapped[str] = mapped_column(String(16), default='interactive') - state: Mapped[str] = mapped_column(String(32), default='queued') - desired_state: Mapped[str] = mapped_column(String(16), default='run') - hold_reasons: Mapped[list] = mapped_column(JSON, default=list) - version: Mapped[int] = mapped_column(Integer, default=1) - batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True) - batch_item_index: Mapped[int | None] = mapped_column(Integer, nullable=True) - current_output_asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True) - error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - - -class WorkflowStep(Base): - __tablename__ = "visual_workflow_steps" - __table_args__ = (UniqueConstraint('run_id', 'step_key'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - run_id: Mapped[str] = mapped_column(String(32)) - step_key: Mapped[str] = mapped_column(String(32)) - kind: Mapped[str] = mapped_column(String(48)) - dependencies: Mapped[list] = mapped_column(JSON, default=list) - semantic_input_hash: Mapped[str] = mapped_column(String(64)) - selected_job_id: Mapped[str | None] = mapped_column(String(32), nullable=True) - state: Mapped[str] = mapped_column(String(32), default='waiting') - explicit_attempt: Mapped[int] = mapped_column(Integer, default=0) - version: Mapped[int] = mapped_column(Integer, default=1) - - -class Batch(Base): - __tablename__ = "visual_batches" - hold_reasons: Mapped[list] = mapped_column(JSON,default=list) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - name: Mapped[str] = mapped_column(String(255)) - spec_snapshot: Mapped[dict] = mapped_column(JSON, default=dict) - state: Mapped[str] = mapped_column(String(32), default='queued') - desired_state: Mapped[str] = mapped_column(String(16), default='run') - version: Mapped[int] = mapped_column(Integer, default=1) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - - -class SharedAsset(Base): - __tablename__ = 'visual_shared_assets' - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - publisher_id: Mapped[str] = mapped_column(String(32), ForeignKey('visual_users.id'), index=True) - asset_id: Mapped[str] = mapped_column(String(32), ForeignKey('visual_assets.id'), unique=True) - source_asset_id: Mapped[str | None] = mapped_column(String(32), ForeignKey('visual_assets.id'), nullable=True, index=True) - version: Mapped[int] = mapped_column(Integer, default=1, server_default='1') - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True) - withdrawn_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - - -class BatchItem(Base): - __tablename__ = "visual_batch_items" - __table_args__ = (UniqueConstraint('batch_id', 'item_index'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - batch_id: Mapped[str] = mapped_column(String(32)) - item_index: Mapped[int] = mapped_column(Integer) - target_kind: Mapped[str] = mapped_column(String(16)) - target_id: Mapped[str] = mapped_column(String(32)) - spec_json: Mapped[dict] = mapped_column(JSON, default=dict) - state: Mapped[str] = mapped_column(String(32), default='queued') - - -class Execution(Base): - __tablename__ = "visual_job_executions" - __table_args__ = (UniqueConstraint('job_id', 'ordinal'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - job_id: Mapped[str] = mapped_column(String(32)) - ordinal: Mapped[int] = mapped_column(Integer) - phase_key: Mapped[str] = mapped_column(String(48)) - resource_pool: Mapped[str] = mapped_column(String(32)) - fence_token: Mapped[str] = mapped_column(String(64)) - state: Mapped[str] = mapped_column(String(32), default='allocated') - manifest_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) - started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) - - -class Submission(Base): - __tablename__ = "visual_submissions" - __table_args__ = (UniqueConstraint('owner_id', 'operation', 'key'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - operation: Mapped[str] = mapped_column(String(128)) - key: Mapped[str] = mapped_column(String(128)) - payload_schema: Mapped[int] = mapped_column(Integer, default=2) - body_hash: Mapped[str] = mapped_column(String(64)) - request_json: Mapped[dict] = mapped_column(JSON, default=dict) - resource_json: Mapped[dict] = mapped_column(JSON, default=dict) - status: Mapped[str] = mapped_column(String(32), default='accepted') - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - - -class AssetReference(Base): - __tablename__ = "visual_asset_refs" - __table_args__ = (UniqueConstraint('asset_id', 'ref_kind', 'ref_id'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - asset_id: Mapped[str] = mapped_column(String(32)) - ref_kind: Mapped[str] = mapped_column(String(32)) - ref_id: Mapped[str] = mapped_column(String(32)) - - -class ApiToken(Base): - __tablename__ = "visual_api_tokens" - __table_args__ = (UniqueConstraint('token_hash'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - name: Mapped[str] = mapped_column(String(128)) - token_hash: Mapped[str] = mapped_column(String(64)) - scopes: Mapped[list] = mapped_column(JSON, default=list) - expires_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - revoked_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - - -class QuotaReservation(Base): - __tablename__ = "visual_quota_reservations" - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - operation: Mapped[str] = mapped_column(String(128)) - units: Mapped[int] = mapped_column(Integer, default=1) - bytes_reserved: Mapped[int] = mapped_column(Integer, default=0) - released_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) - created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) - - -class AssetTag(Base): - __tablename__ = "visual_asset_tags" - __table_args__ = (UniqueConstraint('asset_id', 'tag'),) - id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) - owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True) - asset_id: Mapped[str] = mapped_column(String(32)) - tag: Mapped[str] = mapped_column(String(128)) diff --git a/backend/app/workflow_engine.py b/backend/app/workflow_engine.py deleted file mode 100644 index 2ce5e6c..0000000 --- a/backend/app/workflow_engine.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Durable orchestration only: never execute a model or a media process here.""" -import logging -from fastapi import HTTPException -from sqlalchemy import select, func -from .models import Job, utcnow -from .v2_models import WorkflowRun, WorkflowStep, AssetReference -from .jobs import TERMINAL, GPU_TYPES -from .workflows import RUN_TERMINAL, create_child, emit_run, selected_output -from .timeline import ordered_step_keys - -log=logging.getLogger(__name__) -AUTOMATIC_HOLDS={'quota','storage'} - -async def child_capacity(session, r, step, settings): - active=Job.state.not_in(TERMINAL) - own=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==r.owner_id,active)) - total=await session.scalar(select(func.count()).select_from(Job).where(active)) - if own>=settings.max_owner_jobs or total>=settings.max_global_jobs:return False - if settings.max_interactive_gpu_jobs>0 and r.execution_mode=='interactive' and step.kind in GPU_TYPES: - gpu=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==r.owner_id,active,Job.execution_mode=='interactive',Job.task_type.in_(GPU_TYPES))) - if gpu>=settings.max_interactive_gpu_jobs:return False - return True - -async def advance_run(session,run_id,settings): - r=await session.scalar(select(WorkflowRun).where(WorkflowRun.id==run_id,WorkflowRun.deleted_at.is_(None)).with_for_update()) - if not r or r.state in RUN_TERMINAL:return - before=(r.state,r.current_output_asset_id,r.error_json,tuple(r.hold_reasons or [])) - # Admission holds describe the last failed attempt. Recheck capacity on - # every tick; manual/admin/batch holds continue to block new children. - r.hold_reasons=sorted(set(r.hold_reasons or [])-AUTOMATIC_HOLDS) - if (r.error_json or {}).get('admission_pending'):r.error_json=None - steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id).order_by(WorkflowStep.step_key))).all() - bykey={s.step_key:s for s in steps} - changed=False - selected=[] - for step in steps: - if not step.selected_job_id:continue - job=await session.get(Job,step.selected_job_id) - if job is None or job.owner_id!=r.owner_id or job.deleted_at is not None:continue - selected.append(job) - state='succeeded' if job.state=='succeeded' else 'blocked' if job.state in {'failed','timed_out','needs_attention'} else 'cancelled' if job.state=='cancelled' else 'paused' if job.state=='paused' else 'running' if job.state in {'running','collecting'} else 'ready' - if state=='succeeded': - output=await selected_output(session,job.id,r.owner_id) - if output is None: - state='blocked' - else: - ref=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==output.id,AssetReference.ref_kind=='run',AssetReference.ref_id==r.id)) - if not ref:session.add(AssetReference(owner_id=r.owner_id,asset_id=output.id,ref_kind='run',ref_id=r.id)) - if step.state!=state:step.state=state;step.version+=1;changed=True - if r.desired_state=='cancel': - if all(j.state in TERMINAL for j in selected):r.state='cancelled';r.finished_at=utcnow() - else:r.state='cancelling' - else: - blocked=next((s for s in steps if s.state=='blocked'),None) - if blocked: - r.state='blocked';r.error_json={'code':'step_failed','step_key':blocked.step_key} - elif bykey['compose'].state=='succeeded': - a=await selected_output(session,bykey['compose'].selected_job_id,r.owner_id) - if a:r.current_output_asset_id=a.id;r.state='succeeded';r.finished_at=utcnow() - else:r.state='blocked';r.error_json={'code':'dependency_changed'} - elif r.desired_state=='pause' or r.hold_reasons: - r.state='paused' - else: - r.state='running';r.started_at=r.started_at or utcnow() - # Bound each tick's replenishment work, regardless of how many - # unfinished jobs this owner already has. Later ticks keep feeding. - admitted_this_tick=0 - for key in ordered_step_keys(r.spec_snapshot): - step=bykey[key] - if step.state=='succeeded':continue - if step.state=='cancelled': - r.state='blocked';r.error_json={'code':'step_cancelled','step_key':key};break - if not step.selected_job_id and all(bykey[dep].state=='succeeded' for dep in step.dependencies): - from .maintenance import maintenance_active - if maintenance_active(settings): - r.state='queued' - break - if admitted_this_tick>=8:break - if not await child_capacity(session,r,step,settings): - r.hold_reasons=sorted(set(r.hold_reasons or [])|{'quota'}) - r.error_json={'code':'quota_exceeded','admission_pending':True} - break - try: - # An individual rejected leaf cannot roll back siblings - # already accepted in this run's transaction. - async with session.begin_nested(): - await create_child(session,r,step,settings) - except HTTPException as exc: - code=exc.detail.get('code') if isinstance(exc.detail,dict) else None - if code not in {'quota_exceeded','storage_insufficient'}:raise - await session.refresh(step) - await session.refresh(r) - hold='quota' if code=='quota_exceeded' else 'storage' - r.hold_reasons=sorted(set(r.hold_reasons or [])|{hold}) - r.error_json={'code':code,'admission_pending':True} - break - admitted_this_tick+=1;changed=True - if changed or before!=(r.state,r.current_output_asset_id,r.error_json,tuple(r.hold_reasons or [])):await emit_run(session,r) - -async def advance_workflows(db,settings,provider): - # Each accepted run is an independent unit. A later quota/storage error - # must never roll back a child already accepted for another run. - from .batches import advance_batches - async with db.session() as session: - await advance_batches(session,settings) - ids=(await session.scalars(select(WorkflowRun.id).where(WorkflowRun.deleted_at.is_(None),WorkflowRun.state.not_in(RUN_TERMINAL)).order_by(WorkflowRun.created_at,WorkflowRun.id))).all() - await session.commit() - for run_id in ids: - try: - async with db.session() as session: - # Holds gate admission inside advance_run; reconciliation of - # cancellation and finished children always runs. - await advance_run(session,run_id,settings) - await session.commit() - except Exception as exc: - if isinstance(exc,HTTPException): - code=exc.detail.get('code','workflow_admission_failed') if isinstance(exc.detail,dict) else 'workflow_admission_failed' - else: - log.exception('Workflow advancement failed for %s',run_id) - code='workflow_orchestration_failed' - async with db.session() as session: - r=await session.scalar(select(WorkflowRun).where(WorkflowRun.id==run_id,WorkflowRun.deleted_at.is_(None)).with_for_update()) - if r is None or r.state in RUN_TERMINAL:continue - hold={'quota_exceeded':'quota','storage_insufficient':'storage','owner_disabled':'admin_suspend'}.get(code) - if hold:r.hold_reasons=sorted(set(r.hold_reasons or [])|{hold}) - r.state='queued' if hold in AUTOMATIC_HOLDS else 'blocked' - r.error_json={'code':code,'admission_pending':hold in AUTOMATIC_HOLDS} - await emit_run(session,r);await session.commit() - async with db.session() as session: - await advance_batches(session,settings) - await session.commit() diff --git a/backend/app/workflows.py b/backend/app/workflows.py deleted file mode 100644 index 0ef186a..0000000 --- a/backend/app/workflows.py +++ /dev/null @@ -1,356 +0,0 @@ -"""Owner scoped draft/run services. All helpers use the caller's transaction.""" -import asyncio -import hashlib -import json -from types import SimpleNamespace -from typing import Literal -from fastapi import APIRouter, Depends, Header, Request, HTTPException -from pydantic import Field -from sqlalchemy import func, select, delete -from .auth import Actor, csrf_actor, current_actor -from .assets import owned_asset, safe_file -from .dto import iso, job_dto, asset_dto -from .errors import fail -from .events import emit_asset, emit_job -from .jobs import create_jobs, Submit, TERMINAL, GPU_TYPES -from .models import Asset, Event, Job, User, utcnow -from .submissions import accept_submission -from .timeline import Strict, WorkflowSpec, compile_timeline, ordered_step_keys, generation_parameters_for_shot -from .runtime_policy import read_runtime_policy -from .v2_models import WorkflowDraft, WorkflowRun, WorkflowStep, AssetReference, Execution - -router=APIRouter(prefix='/workflows',tags=['workflows']) -runs_router=APIRouter(prefix='/workflow-runs',tags=['workflows']) -RUN_TERMINAL={'succeeded','cancelled','failed'} - -class DraftCreate(Strict): - name: str = Field(default='多镜头工作流',min_length=1,max_length=255) - kind: Literal['three_shot','multi_shot']='multi_shot' - spec: WorkflowSpec -class DraftPatch(Strict): - name: str | None = Field(default=None,min_length=1,max_length=255) - spec: WorkflowSpec | None = None -class RunCreate(Strict): - draft_revision: int = Field(ge=1) - expected_version: int = Field(ge=1) - execution_mode: Literal['interactive','batch']='interactive' - reuse_run_id: str | None = None -class Control(Strict): - expected_version: int | None = Field(default=None,ge=1) -class Retry(Strict): - expected_run_version: int = Field(ge=1) - target_job_id: str - -def digest(value): - return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode()).hexdigest() - -def draft_dto(d): - return dict(id=d.id,name=d.name,kind=d.kind,spec=d.spec,revision=d.revision,version=d.version,current_run_id=d.current_run_id,created_at=iso(d.created_at),updated_at=iso(d.updated_at)) - -def step_dto(s): - return {k:getattr(s,k) for k in ('id','run_id','step_key','kind','state','selected_job_id','explicit_attempt','dependencies','semantic_input_hash','version')} - -async def owned(session,model,id,owner_id): - row=await session.scalar(select(model).where(model.id==id,model.owner_id==owner_id, - model.deleted_at.is_(None)).with_for_update()) - if row is None: fail(404,'resource_not_found','记录不存在') - return row - -async def cursor(session,owner_id): - await session.flush() - return await session.scalar(select(func.max(Event.id)).where(Event.owner_id==owner_id)) or 0 - -async def snapshot_run(session,owner_id,run_id): - r=await owned(session,WorkflowRun,run_id,owner_id) - d=await owned(session,WorkflowDraft,r.draft_id,owner_id) - steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id))).all() - order={key:i for i,key in enumerate(ordered_step_keys(r.spec_snapshot))} - steps.sort(key=lambda step:(order.get(step.step_key,len(order)),step.step_key)) - selected=[step.selected_job_id for step in steps if step.selected_job_id] - from sqlalchemy import or_ - jobs=(await session.scalars(select(Job).where(Job.owner_id==owner_id,Job.deleted_at.is_(None), - or_(Job.run_id==r.id,Job.id.in_(selected))).order_by(Job.created_at,Job.id))).all() - outputs=[] - if r.current_output_asset_id: - a=await session.get(Asset,r.current_output_asset_id) - if a and a.owner_id==owner_id and a.library_scope=='private' and a.ready and a.deleted_at is None: outputs=[asset_dto(a)] - run={k:getattr(r,k) for k in ('id','draft_id','draft_revision','state','desired_state','execution_mode','version','batch_id','hold_reasons')} - run.update(error=r.error_json,created_at=iso(r.created_at),started_at=iso(r.started_at),finished_at=iso(r.finished_at),result_assets=outputs,completed_steps=sum(s.state=='succeeded' for s in steps),total_steps=len(steps)) - return dict(draft=draft_dto(d),run=run,steps=[step_dto(s) for s in steps],jobs=[await job_dto(session,j) for j in jobs],cursor=await cursor(session,owner_id)) - -async def emit_run(session,r,increment=True): - if r.deleted_at is not None:return - if increment:r.version+=1 - snap=await snapshot_run(session,r.owner_id,r.id) - emit_asset(session,r.owner_id,'workflow.updated',{k:snap[k] for k in ('run','steps','jobs')}) - -async def validate_spec(session,owner_id,spec,settings): - spec=spec if isinstance(spec,WorkflowSpec) else WorkflowSpec.model_validate(spec) - policy=read_runtime_policy(settings) - if policy.get('configuration_error'):fail(503,'runtime_policy_unavailable','运行配置无效,请联系管理员') - if len(spec.shots)>policy['workflow_max_shots']: - fail(422,'workflow_shot_limit',f"当前配置最多允许{policy['workflow_max_shots']}个镜头,可由管理员调整") - ids=[s.image_asset_id for s in spec.shots if s.image_asset_id] - if spec.render.audio:ids.append(spec.render.audio.asset_id) - assets={} - for id in sorted(set(ids)): - a=await session.scalar(select(Asset).where(Asset.id==id,Asset.owner_id==owner_id,Asset.library_scope=='private',Asset.deleted_at.is_(None),Asset.ready.is_(True)).with_for_update()) - if not a:fail(404,'asset_not_found','Asset unavailable.') - assets[id]=a - for shot in spec.shots: - if shot.image_asset_id and assets[shot.image_asset_id].kind!='image':fail(422,'wrong_asset_kind','参考图需要图片') - try:plan=compile_timeline(spec,assets) - except ValueError:fail(422,'invalid_timeline','音轨范围超出源素材') - return plan,assets - -async def check_batch_capability(request, task_types=('video.generate',)): - # CPU requests drain at a phase boundary; only GPU admission needs the - # independent upstream scheduler's protocol. - if not set(task_types) & GPU_TYPES:return - provider = request.app.state.provider - method = getattr(provider, 'upstream_capabilities', None) - if method is None and request.app.state.settings.mode == 'test': return - if method is None: fail(503, 'upstream_protocol_incompatible', 'Batch requires upstream scheduling protocol v2.') - try: - caps = await method() - except Exception: - fail(503, 'upstream_protocol_incompatible', 'Cannot verify upstream admission protocol.') - if caps.get('protocol_version', 0) < 2 or not caps.get('admission_policy'): - fail(503, 'upstream_protocol_incompatible', 'Batch requires upstream scheduling protocol v2.') - -async def verified_output(asset,settings): - """Reuse trusts the published bytes, not just the asset's database row.""" - def verify(): - try: - with safe_file(settings.asset_root,asset.storage_key) as source: - h=hashlib.sha256();size=0 - while chunk:=source.read(1024*1024):size+=len(chunk);h.update(chunk) - return size==asset.size_bytes and h.hexdigest()==asset.sha256 - except (OSError,ValueError):return False - return await asyncio.to_thread(verify) - -async def create_run(session,owner_id,draft_id,expected_version,revision,mode='interactive',reuse_run_id=None,batch_id=None,batch_item_index=None,*,settings): - await session.scalar(select(User).where(User.id==owner_id).with_for_update()) - from .quotas import check_parent_capacity - await check_parent_capacity(session,settings,owner_id,'run') - d=await owned(session,WorkflowDraft,draft_id,owner_id) - if d.version!=expected_version or d.revision!=revision:fail(409,'draft_version_conflict','草稿已更新,请刷新版本') - plan,assets=await validate_spec(session,owner_id,d.spec,settings) - if mode=='interactive': - active=await session.scalar(select(WorkflowRun.id).where(WorkflowRun.owner_id==owner_id,WorkflowRun.deleted_at.is_(None),WorkflowRun.execution_mode=='interactive',WorkflowRun.state.not_in(RUN_TERMINAL))) - if active:fail(429,'quota_exceeded','已有活动交互工作流') - snapshot={**plan.spec,'compiled':{'generation_parameters':plan.generation_parameters, - 'shot_generation_parameters':plan.shot_generation_parameters,'canvas':list(plan.canvas), - 'preset_version':'wan-three-shot-v1' if plan.spec['schema_version']==1 else 'wan-multi-shot-v2'}} - r=WorkflowRun(owner_id=owner_id,draft_id=d.id,draft_revision=d.revision,spec_snapshot=snapshot,spec_hash=digest(snapshot),execution_mode=mode,batch_id=batch_id,batch_item_index=batch_item_index) - session.add(r);await session.flush() - reuse=None - if reuse_run_id:reuse=await owned(session,WorkflowRun,reuse_run_id,owner_id) - for shot in plan.spec['shots']: - source=assets.get(shot.get('image_asset_id')) - generation_shot={k:v for k,v in shot.items() if k!='duration_frames'} - h=digest({'shot':generation_shot,'generation_parameters':plan.shot_generation_parameters[shot['key']],'source_sha256':source.sha256 if source else None}) - step=WorkflowStep(run_id=r.id,step_key=shot['key'],kind='video.generate',dependencies=[],semantic_input_hash=h) - if reuse: - old=await session.scalar(select(WorkflowStep).where(WorkflowStep.run_id==reuse.id,WorkflowStep.step_key==shot['key'],WorkflowStep.semantic_input_hash==h,WorkflowStep.state=='succeeded')) - if old and old.selected_job_id: - job=await session.get(Job,old.selected_job_id) - out=await selected_output(session,old.selected_job_id,owner_id) - if job and job.owner_id==owner_id and job.deleted_at is None and job.state=='succeeded' and out and await verified_output(out,settings): - step.selected_job_id=job.id;step.state='succeeded';step.explicit_attempt=old.explicit_attempt - assets[out.id]=out - session.add(step) - session.add(WorkflowStep(run_id=r.id,step_key='compose',kind='video.compose',dependencies=[shot['key'] for shot in plan.spec['shots']],semantic_input_hash=digest(snapshot))) - for a in assets.values():session.add(AssetReference(owner_id=owner_id,asset_id=a.id,ref_kind='run',ref_id=r.id)) - d.current_run_id=r.id;d.version+=1;d.updated_at=utcnow() - await session.flush();emit_asset(session,owner_id,'draft.updated',{'draft':draft_dto(d)});await emit_run(session,r,False) - return r - -async def selected_output(session,job_id,owner_id=None): - query=select(Asset).where(Asset.source_job_id==job_id,Asset.library_scope=='private',Asset.kind=='video',Asset.ready.is_(True),Asset.deleted_at.is_(None)) - if owner_id is not None:query=query.where(Asset.owner_id==owner_id) - return await session.scalar(query.order_by(Asset.source_output_index).with_for_update()) - -async def create_child(session,r,step,settings): - if r.deleted_at is not None:fail(410,'resource_purged','工作流运行已删除') - snapshot=r.spec_snapshot - if step.kind=='video.generate': - shot=next(s for s in snapshot['shots'] if s['key']==step.step_key) - inputs={'prompt':shot['prompt']} - if shot.get('image_asset_id'):inputs['image_asset_id']=shot['image_asset_id'] - p={**generation_parameters_for_shot(snapshot,step.step_key),**shot['parameters']} - else: - steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id,WorkflowStep.kind=='video.generate'))).all() - bykey={s.step_key:s for s in steps} - ids=[];hashes=[] - for shot in snapshot['shots']: - s=bykey[shot['key']] - a=await selected_output(session,s.selected_job_id,r.owner_id) - if not a:fail(409,'dependency_changed','镜头产物不存在') - ids.append(a.id);hashes.append(a.sha256) - inputs={'asset_ids':ids} - audio=snapshot['render']['audio'] - if audio:inputs['audio_asset_id']=audio['asset_id'] - p={'workflow_spec':{k:v for k,v in snapshot.items() if k!='compiled'},'clips':[{'asset_id':a} for a in ids]} - audio_asset=await session.get(Asset,audio['asset_id']) if audio else None - step.semantic_input_hash=digest({'spec':snapshot,'ordered_output_sha256':hashes,'audio_sha256':audio_asset.sha256 if audio_asset else None}) - if r.batch_id: - from .batches import run_member_holds - r.hold_reasons=sorted(await run_member_holds(session,r)) - step.explicit_attempt+=1 - jobs=await create_jobs(session,Submit(task_type=step.kind,input=inputs,parameters=p,execution_mode=r.execution_mode),SimpleNamespace(id=r.owner_id,auth_kind='session',scopes=[]),settings,key=f'run:{r.id}:{step.step_key}:{step.explicit_attempt}',internal=True,frozen_workflow=True) - j=jobs[0];j.run_id=r.id;j.step_key=step.step_key;j.batch_id=r.batch_id;j.batch_item_index=r.batch_item_index;j.explicit_attempt=step.explicit_attempt - j.desired_state=r.desired_state;j.hold_reasons=list(r.hold_reasons or []) - step.selected_job_id=j.id;step.state='ready';step.version+=1 - await emit_job(session,j) - return j - -async def control_run(session,r,desired): - if r.deleted_at is not None:fail(404,'resource_not_found','记录不存在') - if r.state in RUN_TERMINAL:return - if r.desired_state=='cancel' and desired!='cancel':fail(409,'run_cancelled','取消不可逆') - r.desired_state=desired - holds=set(r.hold_reasons or []) - if desired=='pause':holds.add('manual') - elif desired=='run':holds.discard('manual') - r.hold_reasons=sorted(holds) - jobs=(await session.scalars(select(Job).where(Job.run_id==r.id,Job.owner_id==r.owner_id,Job.deleted_at.is_(None),Job.state.not_in(TERMINAL)))).all() - for j in jobs: - j.desired_state=desired - child_holds=set(j.hold_reasons or []) - if desired=='pause':child_holds.add('manual') - elif desired=='run':child_holds.discard('manual') - j.hold_reasons=sorted(child_holds) - if desired=='cancel': - j.cancel_requested=True - if not j.upstream_id and not j.upstream_payload and j.phase not in {'cpu_running','preparing'}:j.state='cancelled';j.phase='cancelled';j.finished_at=utcnow() - elif j.state!='collecting':j.state='cancelling';j.phase='cancellation_pending' - await emit_job(session,j) - r.state='cancelling' if desired=='cancel' else 'paused' if desired=='pause' else 'queued' - await emit_run(session,r) - -def wake(request): - request.app.state.coordinator.wake() - -@router.post('',status_code=201) -async def post_draft(body:DraftCreate,request:Request,actor:Actor=Depends(csrf_actor)): - async with request.app.state.db.session() as s: - from .maintenance import require_writable - require_writable(request.app.state.settings) - plan,assets=await validate_spec(s,actor.id,body.spec,request.app.state.settings) - d=WorkflowDraft(owner_id=actor.id,name=body.name,kind=body.kind,spec=plan.spec);s.add(d);await s.flush() - for a in assets.values():s.add(AssetReference(owner_id=actor.id,asset_id=a.id,ref_kind='draft',ref_id=d.id)) - emit_asset(s,actor.id,'draft.updated',{'draft':draft_dto(d)});await s.commit();return draft_dto(d) - -async def page_rows(s,model,actor,page,page_size): - if page<1 or not 1<=page_size<=100:fail(422,'invalid_page','分页参数无效') - q=select(model).where(model.owner_id==actor.id,model.deleted_at.is_(None)) - total=await s.scalar(select(func.count()).select_from(q.subquery())) - rows=(await s.scalars(q.order_by(model.created_at.desc(),model.id.desc()).offset((page-1)*page_size).limit(page_size))).all() - return rows,dict(total=total,page=page,page_size=page_size,cursor=await cursor(s,actor.id)) - -@router.get('') -async def list_drafts(request:Request,page:int=1,page_size:int=24,actor:Actor=Depends(current_actor)): - async with request.app.state.db.session() as s: - rows,data=await page_rows(s,WorkflowDraft,actor,page,page_size);return {**data,'items':[draft_dto(d) for d in rows]} - -@router.get('/{id}') -async def get_draft(id:str,request:Request,actor:Actor=Depends(current_actor)): - async with request.app.state.db.session() as s:return draft_dto(await owned(s,WorkflowDraft,id,actor.id)) - -@router.delete('/{id}') -async def delete_draft(id:str,request:Request,if_match:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - from .deletions import archive_records - async with request.app.state.db.session() as s: - result=await archive_records(s,WorkflowDraft,id,actor.id,if_match) - await s.commit() - return result - -@router.patch('/{id}') -async def patch_draft(id:str,body:DraftPatch,request:Request,if_match:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - async with request.app.state.db.session() as s: - d=await owned(s,WorkflowDraft,id,actor.id) - if if_match is None or if_match.strip('"')!=str(d.version):fail(409,'draft_version_conflict','草稿版本冲突') - if body.name is not None:d.name=body.name - if body.spec is not None: - plan,assets=await validate_spec(s,actor.id,body.spec,request.app.state.settings) - await s.execute(delete(AssetReference).where(AssetReference.ref_kind=='draft',AssetReference.ref_id==d.id)) - for a in assets.values():s.add(AssetReference(owner_id=actor.id,asset_id=a.id,ref_kind='draft',ref_id=d.id)) - d.spec=plan.spec;d.revision+=1 - d.version+=1;d.updated_at=utcnow();emit_asset(s,actor.id,'draft.updated',{'draft':draft_dto(d)});await s.commit();return draft_dto(d) - -@router.post('/{id}/runs',status_code=202) -async def post_run(id:str,body:RunCreate,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - from .maintenance import require_writable - require_writable(request.app.state.settings) - if actor.auth_kind=='bearer' and body.execution_mode=='interactive' and 'interactive:write' not in actor.scopes:fail(403,'scope_required','Interactive scope required.') - capability_error=None - if body.execution_mode=='batch': - try:await check_batch_capability(request) - except HTTPException as exc:capability_error=exc - async with request.app.state.db.session() as s: - sub=await accept_submission(s,actor.id,'workflow.run',idempotency_key,2,{'draft_id':id,**body.model_dump(mode='json')}) - if sub.resource_json:r=await owned(s,WorkflowRun,sub.resource_json['run_id'],actor.id) - else: - if capability_error:raise capability_error - from .quotas import reserve_budget - await reserve_budget(s,actor.id,'workflow.run',units=0,settings=request.app.state.settings) - r=await create_run(s,actor.id,id,body.expected_version,body.draft_revision,body.execution_mode,body.reuse_run_id,settings=request.app.state.settings) - sub.resource_json={'run_id':r.id,'draft_id':id} - await s.commit();snap=await snapshot_run(s,actor.id,r.id) - wake(request);return snap - -@runs_router.get('') -async def list_runs(request:Request,page:int=1,page_size:int=24,actor:Actor=Depends(current_actor)): - async with request.app.state.db.session() as s: - rows,data=await page_rows(s,WorkflowRun,actor,page,page_size) - return {**data,'items':[(await snapshot_run(s,actor.id,r.id))['run'] for r in rows]} - -@runs_router.get('/{id}') -async def get_run(id:str,request:Request,actor:Actor=Depends(current_actor)): - async with request.app.state.db.session() as s:return await snapshot_run(s,actor.id,id) - -@runs_router.delete('/{id}') -async def delete_run(id:str,request:Request,if_match:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - from .deletions import archive_records - async with request.app.state.db.session() as s: - result=await archive_records(s,WorkflowRun,id,actor.id,if_match) - await s.commit() - return result - -@runs_router.post('/{id}/steps/{key}/retry',status_code=202) -async def retry_step(id:str,key:str,body:Retry,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)): - async with request.app.state.db.session() as s: - r=await owned(s,WorkflowRun,id,actor.id) - if actor.auth_kind=='bearer' and r.execution_mode=='interactive' and 'interactive:write' not in actor.scopes:fail(403,'scope_required','Interactive scope required.') - sub=await accept_submission(s,actor.id,'workflow.retry',idempotency_key,2,{'run_id':id,'step_key':key,**body.model_dump()}) - if not sub.resource_json: - if r.version!=body.expected_run_version:fail(409,'run_version_conflict','工作流版本冲突') - step=await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id==r.id,WorkflowStep.step_key==key)) - j=await s.get(Job,body.target_job_id) - if not step or step.selected_job_id!=body.target_job_id or not j or j.owner_id!=actor.id or j.deleted_at is not None or r.state in RUN_TERMINAL or r.desired_state=='cancel':fail(409,'step_not_retryable','步骤不可重试') - active_execution=await s.scalar(select(Execution.id).where(Execution.job_id==j.id,Execution.state.not_in({'exited','results_ready'}))) - if active_execution:fail(409,'cleanup_pending','Execution cleanup must be confirmed before retry.') - if j.state=='needs_attention' and not (j.error_json or {}).get('safe_to_retry'):fail(409,'cleanup_pending','执行尚未确认清理') - if j.state not in {'failed','timed_out','needs_attention'}:fail(409,'step_not_retryable','仅失败步骤允许重试') - await create_child(s,r,step,request.app.state.settings);r.state='paused' if r.desired_state=='pause' or r.hold_reasons else 'queued';r.error_json=None;await emit_run(s,r) - sub.resource_json={'run_id':r.id,'job_id':step.selected_job_id} - await s.commit();snap=await snapshot_run(s,actor.id,id) - wake(request);return snap - -async def _control(id,desired,body,request,key,actor): - async with request.app.state.db.session() as s: - sub=await accept_submission(s,actor.id,'workflow.'+('resume' if desired=='run' else desired),key,2,{'run_id':id,**body.model_dump()}) - r=await owned(s,WorkflowRun,id,actor.id) - if not sub.resource_json: - if body.expected_version is not None and body.expected_version!=r.version:fail(409,'run_version_conflict','工作流版本冲突') - await control_run(s,r,desired);sub.resource_json={'run_id':r.id} - await s.commit();snap=await snapshot_run(s,actor.id,id) - wake(request);return snap - -@runs_router.post('/{id}/cancel') -async def cancel_run(id:str,body:Control,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)):return await _control(id,'cancel',body,request,idempotency_key,actor) -@runs_router.post('/{id}/pause') -async def pause_run(id:str,body:Control,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)):return await _control(id,'pause',body,request,idempotency_key,actor) -@runs_router.post('/{id}/resume') -async def resume_run(id:str,body:Control,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)):return await _control(id,'run',body,request,idempotency_key,actor) diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 5009c36..bed3f59 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -8,3 +8,25 @@ asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" testpaths = ["tests"] filterwarnings = ["error::ResourceWarning"] + +[tool.ruff] +target-version = "py311" +line-length = 100 +extend-exclude = [ + "alembic/versions", + "alembic/legacy_schema.py", + "alembic/v2_schema.py", + "alembic/v2_schema_models.py", +] +force-exclude = true + +[tool.ruff.lint] +select = ["E9", "F63", "F7", "F82", "F401", "F811"] + +[tool.ruff.lint.per-file-ignores] +# pytest 通过同名参数注入显式导入的 fixture;不能按“未使用/重定义”删除这些注册。 +"tests/**" = ["F401", "F811"] + +[tool.ruff.format] +quote-style = "double" +line-ending = "lf" diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt new file mode 100644 index 0000000..282662c --- /dev/null +++ b/backend/requirements-dev.txt @@ -0,0 +1,4 @@ +-r requirements.txt + +# 开发工具固定版本;格式化不会成为生产服务的运行依赖。 +ruff==0.17.4 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 66b7ec2..a06fdb3 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -20,6 +20,7 @@ class BoundaryError(Exception): class FakeProvider: """External-service boundary only. DB, events, HTTP/auth and files are real.""" + def __init__(self): self.remote = {} self.accepted = {} @@ -40,11 +41,19 @@ class FakeProvider: async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir): resolved = dict(inputs) - for source, target in (("image_asset_id", "image_path"), ("audio_asset_id", "audio_path"), - ("asset_id", "audio_path")): + for source, target in ( + ("image_asset_id", "image_path"), + ("audio_asset_id", "audio_path"), + ("asset_id", "audio_path"), + ): if source in resolved: resolved[target] = str(assets[resolved.pop(source)]) - return {"task_type": task_type, "input": resolved, "parameters": parameters, "timeout_seconds": 3600} + return { + "task_type": task_type, + "input": resolved, + "parameters": parameters, + "timeout_seconds": 3600, + } async def submit(self, payload, idempotency_key): self.submitted_payloads.append((idempotency_key, payload)) @@ -55,7 +64,12 @@ class FakeProvider: if idempotency_key not in self.accepted: remote_id = f"remote-{len(self.accepted) + 1}" self.accepted[idempotency_key] = remote_id - self.remote[remote_id] = {"id": remote_id, "state": "queued", "attempt_count": 0, "preemptions": 0} + self.remote[remote_id] = { + "id": remote_id, + "state": "queued", + "attempt_count": 0, + "preemptions": 0, + } remote_id = self.accepted[idempotency_key] if self.lost_response: self.lost_response = False @@ -100,16 +114,28 @@ def png_bytes(): @pytest_asyncio.fixture async def system(tmp_path): - from app.config import Settings + from app.core.config import Settings from app.main import create_app - settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'test.sqlite3'}", - workspace_root=tmp_path, admin_username="admin", admin_password=PASSWORD, - run_coordinator=False, cookie_secure=False, event_heartbeat_seconds=.03) + + settings = Settings( + mode="test", + database_url=f"sqlite+aiosqlite:///{tmp_path / 'test.sqlite3'}", + workspace_root=tmp_path, + admin_username="admin", + admin_password=PASSWORD, + run_coordinator=False, + cookie_secure=False, + event_heartbeat_seconds=0.03, + ) provider = FakeProvider() app = create_app(settings, provider=provider) async with app.router.lifespan_context(app): - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: - response = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + response = await client.post( + "/api/auth/login", json={"username": "admin", "password": PASSWORD} + ) assert response.status_code == 200, response.text client.headers["X-CSRF-Token"] = response.json()["csrf_token"] yield SimpleNamespace(app=app, client=client, settings=settings, provider=provider) @@ -117,9 +143,15 @@ async def system(tmp_path): @pytest_asyncio.fixture async def other_client(system): - response = await system.client.post("/api/auth/users", json={"username": "alice", "display_name": "Alice", "password": PASSWORD}) + response = await system.client.post( + "/api/auth/users", json={"username": "alice", "display_name": "Alice", "password": PASSWORD} + ) assert response.status_code == 201, response.text - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client: - login = await client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as client: + login = await client.post( + "/api/auth/login", json={"username": "alice", "password": PASSWORD} + ) client.headers["X-CSRF-Token"] = login.json()["csrf_token"] yield client diff --git a/backend/tests/fixtures/engineering_contract.json b/backend/tests/fixtures/engineering_contract.json new file mode 100644 index 0000000..d9e40a6 --- /dev/null +++ b/backend/tests/fixtures/engineering_contract.json @@ -0,0 +1,5867 @@ +{ + "routes": [ + { + "path": "/api/assets", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/assets", + "method": "POST", + "responses": [ + "201", + "422" + ] + }, + { + "path": "/api/assets/{asset_id}", + "method": "DELETE", + "responses": [ + "204", + "422" + ] + }, + { + "path": "/api/assets/{asset_id}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/assets/{asset_id}", + "method": "PATCH", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/assets/{asset_id}/content", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/assets/{asset_id}/publish", + "method": "POST", + "responses": [ + "201", + "422" + ] + }, + { + "path": "/api/assets/{asset_id}/thumbnail", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/auth/login", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/auth/logout", + "method": "POST", + "responses": [ + "204" + ] + }, + { + "path": "/api/auth/me", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/auth/password", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/auth/tokens", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/auth/tokens", + "method": "POST", + "responses": [ + "201", + "422" + ] + }, + { + "path": "/api/auth/tokens/{token_id}", + "method": "DELETE", + "responses": [ + "204", + "422" + ] + }, + { + "path": "/api/auth/users", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/auth/users", + "method": "POST", + "responses": [ + "201", + "422" + ] + }, + { + "path": "/api/auth/users/{user_id}", + "method": "PATCH", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/batches", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/batches", + "method": "POST", + "responses": [ + "202", + "422" + ] + }, + { + "path": "/api/batches/{id}", + "method": "DELETE", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/batches/{id}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/batches/{id}/control", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/capabilities", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/events", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/health", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/jobs", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/jobs", + "method": "POST", + "responses": [ + "202", + "422" + ] + }, + { + "path": "/api/jobs/{job_id}", + "method": "DELETE", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/jobs/{job_id}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/jobs/{job_id}/cancel", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/jobs/{job_id}/retry", + "method": "POST", + "responses": [ + "202", + "422" + ] + }, + { + "path": "/api/live", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/ready", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/shared-assets", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/shared-assets/{shared_id}", + "method": "DELETE", + "responses": [ + "204", + "422" + ] + }, + { + "path": "/api/shared-assets/{shared_id}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/shared-assets/{shared_id}/content", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/shared-assets/{shared_id}/import", + "method": "POST", + "responses": [ + "201", + "422" + ] + }, + { + "path": "/api/shared-assets/{shared_id}/thumbnail", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/submissions/{key}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/system/status", + "method": "GET", + "responses": [ + "200" + ] + }, + { + "path": "/api/workflow-runs", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflow-runs/{id}", + "method": "DELETE", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflow-runs/{id}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflow-runs/{id}/cancel", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflow-runs/{id}/pause", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflow-runs/{id}/resume", + "method": "POST", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflow-runs/{id}/steps/{key}/retry", + "method": "POST", + "responses": [ + "202", + "422" + ] + }, + { + "path": "/api/workflows", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflows", + "method": "POST", + "responses": [ + "201", + "422" + ] + }, + { + "path": "/api/workflows/{id}", + "method": "DELETE", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflows/{id}", + "method": "GET", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflows/{id}", + "method": "PATCH", + "responses": [ + "200", + "422" + ] + }, + { + "path": "/api/workflows/{id}/runs", + "method": "POST", + "responses": [ + "202", + "422" + ] + } + ], + "tables": { + "visual_api_tokens": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "name", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "token_hash", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "scopes", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "list" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "expires_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "revoked_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_api_tokens_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [ + [ + "token_hash" + ] + ] + }, + "visual_asset_refs": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "asset_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "ref_kind", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "ref_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_asset_refs_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [ + [ + "asset_id", + "ref_id", + "ref_kind" + ] + ] + }, + "visual_asset_tags": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "asset_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "tag", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_asset_tags_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [ + [ + "asset_id", + "tag" + ] + ] + }, + "visual_assets": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "name", + "type": "VARCHAR(255)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "storage_key", + "type": "VARCHAR(512)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "thumbnail_key", + "type": "VARCHAR(512)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "kind", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "mime_type", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "size_bytes", + "type": "BIGINT", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "sha256", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "width", + "type": "INTEGER", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "height", + "type": "INTEGER", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "duration_seconds", + "type": "DOUBLE", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "tags", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "list" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "favorite", + "type": "BOOL", + "nullable": false, + "primary_key": false, + "default": { + "value": "False" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "origin", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "upload" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "library_scope", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "private" + }, + "server_default": "private", + "foreign_keys": [] + }, + { + "name": "ready", + "type": "BOOL", + "nullable": false, + "primary_key": false, + "default": { + "value": "True" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "source_job_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_jobs.id" + ] + }, + { + "name": "source_upstream_id", + "type": "VARCHAR(128)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "source_output_index", + "type": "INTEGER", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "deleted_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_assets_created_at", + "unique": false, + "columns": [ + "created_at" + ] + }, + { + "name": "ix_visual_assets_library_scope", + "unique": false, + "columns": [ + "library_scope" + ] + }, + { + "name": "ix_visual_assets_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + }, + { + "name": "ix_visual_assets_source_job_id", + "unique": false, + "columns": [ + "source_job_id" + ] + } + ], + "unique_constraints": [ + [ + "source_job_id", + "source_output_index" + ], + [ + "source_output_index", + "source_upstream_id" + ], + [ + "storage_key" + ] + ] + }, + "visual_batch_items": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "batch_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "item_index", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "target_kind", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "target_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "spec_json", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "dict" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "state", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "queued" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [], + "unique_constraints": [ + [ + "batch_id", + "item_index" + ] + ] + }, + "visual_batches": { + "columns": [ + { + "name": "hold_reasons", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "list" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "name", + "type": "VARCHAR(255)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "spec_snapshot", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "dict" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "state", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "queued" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "desired_state", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "run" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "version", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "finished_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "deleted_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_batches_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [] + }, + "visual_drafts": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "name", + "type": "VARCHAR(255)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "kind", + "type": "VARCHAR(48)", + "nullable": false, + "primary_key": false, + "default": { + "value": "three_shot" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "spec", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "dict" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "revision", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "version", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "current_run_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "updated_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "deleted_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_drafts_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [] + }, + "visual_job_assets": { + "columns": [ + { + "name": "job_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_jobs.id" + ] + }, + { + "name": "asset_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_assets.id" + ] + } + ], + "indexes": [], + "unique_constraints": [] + }, + "visual_job_events": { + "columns": [ + { + "name": "id", + "type": "BIGINT", + "nullable": false, + "primary_key": true, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "job_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "event_type", + "type": "VARCHAR(48)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "data", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "visual_events_owner_cursor", + "unique": false, + "columns": [ + "owner_id", + "id" + ] + } + ], + "unique_constraints": [] + }, + "visual_job_executions": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "job_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "ordinal", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "phase_key", + "type": "VARCHAR(48)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "resource_pool", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "fence_token", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "state", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "allocated" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "manifest_json", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "started_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "finished_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "error_json", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [], + "unique_constraints": [ + [ + "job_id", + "ordinal" + ] + ] + }, + "visual_jobs": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "task_type", + "type": "VARCHAR(48)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "execution_mode", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "interactive" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "policy_version", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "night-v1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "run_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "step_key", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "batch_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "batch_item_index", + "type": "INTEGER", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "explicit_attempt", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "desired_state", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "run" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "hold_reasons", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "list" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "current_execution_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "admitted_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "state", + "type": "VARCHAR(24)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "phase", + "type": "VARCHAR(48)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "version", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "input_json", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "parameters", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "request_key", + "type": "VARCHAR(128)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "request_hash", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "batch_index", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "upstream_key", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "upstream_id", + "type": "VARCHAR(128)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "upstream_payload", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "upstream_result", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "result_json", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "error_json", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "cancel_requested", + "type": "BOOL", + "nullable": false, + "primary_key": false, + "default": { + "value": "False" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "attempt_count", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "work_attempt", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "preemptions", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "last_preempted_reason", + "type": "TEXT", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "sync_warning", + "type": "VARCHAR(512)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "sync_failures", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "next_action_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "scheduled_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "started_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "finished_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "deleted_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_jobs_created_at", + "unique": false, + "columns": [ + "created_at" + ] + }, + { + "name": "ix_visual_jobs_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + }, + { + "name": "visual_jobs_dispatch", + "unique": false, + "columns": [ + "state", + "next_action_at" + ] + } + ], + "unique_constraints": [ + [ + "batch_index", + "owner_id", + "request_key" + ], + [ + "upstream_id" + ], + [ + "upstream_key" + ] + ] + }, + "visual_quota_reservations": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "operation", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "units", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "bytes_reserved", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "released_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_quota_reservations_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [] + }, + "visual_sessions": { + "columns": [ + { + "name": "token_hash", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": true, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "user_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "csrf_token", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "expires_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_sessions_expires_at", + "unique": false, + "columns": [ + "expires_at" + ] + }, + { + "name": "ix_visual_sessions_user_id", + "unique": false, + "columns": [ + "user_id" + ] + } + ], + "unique_constraints": [] + }, + "visual_shared_assets": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "publisher_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "asset_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_assets.id" + ] + }, + { + "name": "source_asset_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_assets.id" + ] + }, + { + "name": "version", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": "1", + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "withdrawn_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_shared_assets_created_at", + "unique": false, + "columns": [ + "created_at" + ] + }, + { + "name": "ix_visual_shared_assets_publisher_id", + "unique": false, + "columns": [ + "publisher_id" + ] + }, + { + "name": "ix_visual_shared_assets_source_asset_id", + "unique": false, + "columns": [ + "source_asset_id" + ] + } + ], + "unique_constraints": [ + [ + "asset_id" + ] + ] + }, + "visual_submissions": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "operation", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "key", + "type": "VARCHAR(128)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "payload_schema", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "2" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "body_hash", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "request_json", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "dict" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "resource_json", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "dict" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "status", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "accepted" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_submissions_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [ + [ + "key", + "operation", + "owner_id" + ] + ] + }, + "visual_users": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "username", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "display_name", + "type": "VARCHAR(80)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "password_hash", + "type": "VARCHAR(512)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "role", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "user" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "disabled", + "type": "BOOL", + "nullable": false, + "primary_key": false, + "default": { + "value": "False" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "must_change_password", + "type": "BOOL", + "nullable": false, + "primary_key": false, + "default": { + "value": "False" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [], + "unique_constraints": [ + [ + "username" + ] + ] + }, + "visual_workflow_runs": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "owner_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [ + "visual_users.id" + ] + }, + { + "name": "draft_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "draft_revision", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "spec_snapshot", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "dict" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "spec_hash", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "execution_mode", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "interactive" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "state", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "queued" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "desired_state", + "type": "VARCHAR(16)", + "nullable": false, + "primary_key": false, + "default": { + "value": "run" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "hold_reasons", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "list" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "version", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "batch_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "batch_item_index", + "type": "INTEGER", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "current_output_asset_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "error_json", + "type": "JSON", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "created_at", + "type": "DATETIME(6)", + "nullable": false, + "primary_key": false, + "default": { + "callable": "utcnow" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "started_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "finished_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "deleted_at", + "type": "DATETIME(6)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [ + { + "name": "ix_visual_workflow_runs_owner_id", + "unique": false, + "columns": [ + "owner_id" + ] + } + ], + "unique_constraints": [] + }, + "visual_workflow_steps": { + "columns": [ + { + "name": "id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": true, + "default": { + "callable": "new_id" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "run_id", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "step_key", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "kind", + "type": "VARCHAR(48)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "dependencies", + "type": "JSON", + "nullable": false, + "primary_key": false, + "default": { + "callable": "list" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "semantic_input_hash", + "type": "VARCHAR(64)", + "nullable": false, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "selected_job_id", + "type": "VARCHAR(32)", + "nullable": true, + "primary_key": false, + "default": null, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "state", + "type": "VARCHAR(32)", + "nullable": false, + "primary_key": false, + "default": { + "value": "waiting" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "explicit_attempt", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "0" + }, + "server_default": null, + "foreign_keys": [] + }, + { + "name": "version", + "type": "INTEGER", + "nullable": false, + "primary_key": false, + "default": { + "value": "1" + }, + "server_default": null, + "foreign_keys": [] + } + ], + "indexes": [], + "unique_constraints": [ + [ + "run_id", + "step_key" + ] + ] + } + }, + "http_contract": { + "operations": { + "/api/auth/login": { + "post": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Login" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/auth/me": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/api/auth/logout": { + "post": { + "responses": { + "204": { + "description": "Successful Response" + } + } + } + }, + "/api/auth/users": { + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateUser" + } + } + } + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "get": { + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/auth/users/{user_id}": { + "patch": { + "parameters": [ + { + "name": "user_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "User Id" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserPatch" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/auth/password": { + "post": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PasswordChange" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/assets": { + "post": { + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/Body_upload_api_assets_post" + } + } + } + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "get": { + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + }, + { + "name": "kind", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Kind" + } + }, + { + "name": "q", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Q" + } + }, + { + "name": "tag", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Tag" + } + }, + { + "name": "favorite", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Favorite" + } + }, + { + "name": "origin", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Origin" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/assets/{asset_id}": { + "get": { + "parameters": [ + { + "name": "asset_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Asset Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "patch": { + "parameters": [ + { + "name": "asset_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Asset Id" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssetPatch" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "parameters": [ + { + "name": "asset_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Asset Id" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/assets/{asset_id}/content": { + "get": { + "parameters": [ + { + "name": "asset_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Asset Id" + } + }, + { + "name": "download", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Download" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/assets/{asset_id}/thumbnail": { + "get": { + "parameters": [ + { + "name": "asset_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Asset Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/shared-assets": { + "get": { + "parameters": [ + { + "name": "q", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Q" + } + }, + { + "name": "kind", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Kind" + } + }, + { + "name": "tag", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Tag" + } + }, + { + "name": "mine", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Mine" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/shared-assets/{shared_id}": { + "get": { + "parameters": [ + { + "name": "shared_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Shared Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "parameters": [ + { + "name": "shared_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Shared Id" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/shared-assets/{shared_id}/content": { + "get": { + "parameters": [ + { + "name": "shared_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Shared Id" + } + }, + { + "name": "download", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Download" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/shared-assets/{shared_id}/thumbnail": { + "get": { + "parameters": [ + { + "name": "shared_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Shared Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/shared-assets/{shared_id}/import": { + "post": { + "parameters": [ + { + "name": "shared_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Shared Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/EmptyPayload" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/assets/{asset_id}/publish": { + "post": { + "parameters": [ + { + "name": "asset_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Asset Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/EmptyPayload" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/jobs": { + "post": { + "parameters": [ + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Submit" + } + } + } + }, + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "get": { + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + }, + { + "name": "task_type", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "Task Type" + } + }, + { + "name": "state", + "in": "query", + "required": false, + "schema": { + "type": "string", + "default": "", + "title": "State" + } + }, + { + "name": "root_only", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Root Only" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/jobs/{job_id}": { + "get": { + "parameters": [ + { + "name": "job_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Job Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "parameters": [ + { + "name": "job_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Job Id" + } + }, + { + "name": "if-match", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "If-Match" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/jobs/{job_id}/cancel": { + "post": { + "parameters": [ + { + "name": "job_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Job Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/jobs/{job_id}/retry": { + "post": { + "parameters": [ + { + "name": "job_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Job Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/events": { + "get": { + "parameters": [ + { + "name": "after", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 0, + "title": "After" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/submissions/{key}": { + "get": { + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Key" + } + }, + { + "name": "operation", + "in": "query", + "required": true, + "schema": { + "type": "string", + "title": "Operation" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/auth/tokens": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "post": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenInput" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/auth/tokens/{token_id}": { + "delete": { + "parameters": [ + { + "name": "token_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Token Id" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflows": { + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DraftCreate" + } + } + } + }, + "responses": { + "201": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "get": { + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflows/{id}": { + "get": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "if-match", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "If-Match" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "patch": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "if-match", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "If-Match" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DraftPatch" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflows/{id}/runs": { + "post": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunCreate" + } + } + } + }, + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflow-runs": { + "get": { + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflow-runs/{id}": { + "get": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "if-match", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "If-Match" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflow-runs/{id}/steps/{key}/retry": { + "post": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Key" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Retry" + } + } + } + }, + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflow-runs/{id}/cancel": { + "post": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Control" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflow-runs/{id}/pause": { + "post": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Control" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/workflow-runs/{id}/resume": { + "post": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Control" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/batches": { + "post": { + "parameters": [ + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchCreate" + } + } + } + }, + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "get": { + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1, + "title": "Page" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 24, + "title": "Page Size" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/batches/{id}": { + "get": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "if-match", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "If-Match" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/batches/{id}/control": { + "post": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Id" + } + }, + { + "name": "idempotency-key", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchControl" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/health": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/api/live": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/api/ready": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/api/capabilities": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/api/system/status": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + } + }, + "components": { + "schemas": { + "AssetPatch": { + "properties": { + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 255, + "minLength": 1 + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "tags": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array", + "maxItems": 30 + }, + { + "type": "null" + } + ], + "title": "Tags" + }, + "favorite": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Favorite" + } + }, + "type": "object", + "title": "AssetPatch" + }, + "Audio": { + "properties": { + "asset_id": { + "type": "string", + "maxLength": 64, + "minLength": 1, + "title": "Asset Id" + }, + "source_start_ms": { + "type": "integer", + "minimum": 0.0, + "title": "Source Start Ms" + }, + "source_end_ms": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Source End Ms" + }, + "offset_frame": { + "type": "integer", + "minimum": 0.0, + "title": "Offset Frame", + "default": 0 + }, + "short_policy": { + "type": "string", + "const": "silence", + "title": "Short Policy", + "default": "silence" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "asset_id", + "source_start_ms", + "source_end_ms" + ], + "title": "Audio" + }, + "BatchControl": { + "properties": { + "desired_state": { + "type": "string", + "enum": [ + "run", + "pause", + "cancel" + ], + "title": "Desired State" + }, + "expected_version": { + "anyOf": [ + { + "type": "integer", + "minimum": 1.0 + }, + { + "type": "null" + } + ], + "title": "Expected Version" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "desired_state" + ], + "title": "BatchControl" + }, + "BatchCreate": { + "properties": { + "name": { + "type": "string", + "maxLength": 255, + "minLength": 1, + "title": "Name", + "default": "夜间批次" + }, + "items": { + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/BatchWorkflow" + }, + { + "$ref": "#/components/schemas/BatchJob" + } + ] + }, + "type": "array", + "maxItems": 100, + "minItems": 1, + "title": "Items" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "items" + ], + "title": "BatchCreate" + }, + "BatchJob": { + "properties": { + "kind": { + "type": "string", + "const": "job", + "title": "Kind" + }, + "task_type": { + "type": "string", + "title": "Task Type" + }, + "input": { + "additionalProperties": true, + "type": "object", + "title": "Input" + }, + "parameters": { + "additionalProperties": true, + "type": "object", + "title": "Parameters" + }, + "count": { + "type": "integer", + "maximum": 4.0, + "minimum": 1.0, + "title": "Count", + "default": 1 + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "kind", + "task_type" + ], + "title": "BatchJob" + }, + "BatchWorkflow": { + "properties": { + "kind": { + "type": "string", + "const": "workflow", + "title": "Kind" + }, + "draft_id": { + "type": "string", + "title": "Draft Id" + }, + "draft_revision": { + "type": "integer", + "minimum": 1.0, + "title": "Draft Revision" + }, + "expected_version": { + "type": "integer", + "minimum": 1.0, + "title": "Expected Version" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "kind", + "draft_id", + "draft_revision", + "expected_version" + ], + "title": "BatchWorkflow" + }, + "Body_upload_api_assets_post": { + "properties": { + "file": { + "type": "string", + "contentMediaType": "application/octet-stream", + "title": "File" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + } + }, + "type": "object", + "required": [ + "file" + ], + "title": "Body_upload_api_assets_post" + }, + "Control": { + "properties": { + "expected_version": { + "anyOf": [ + { + "type": "integer", + "minimum": 1.0 + }, + { + "type": "null" + } + ], + "title": "Expected Version" + } + }, + "additionalProperties": false, + "type": "object", + "title": "Control" + }, + "CreateUser": { + "properties": { + "username": { + "type": "string", + "maxLength": 64, + "minLength": 1, + "title": "Username" + }, + "password": { + "type": "string", + "maxLength": 256, + "minLength": 1, + "title": "Password" + }, + "display_name": { + "type": "string", + "maxLength": 80, + "title": "Display Name", + "default": "" + } + }, + "type": "object", + "required": [ + "username", + "password" + ], + "title": "CreateUser" + }, + "DraftCreate": { + "properties": { + "name": { + "type": "string", + "maxLength": 255, + "minLength": 1, + "title": "Name", + "default": "多镜头工作流" + }, + "kind": { + "type": "string", + "enum": [ + "three_shot", + "multi_shot" + ], + "title": "Kind", + "default": "multi_shot" + }, + "spec": { + "$ref": "#/components/schemas/WorkflowSpec" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "spec" + ], + "title": "DraftCreate" + }, + "DraftPatch": { + "properties": { + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 255, + "minLength": 1 + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "spec": { + "anyOf": [ + { + "$ref": "#/components/schemas/WorkflowSpec" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false, + "type": "object", + "title": "DraftPatch" + }, + "EmptyPayload": { + "properties": {}, + "additionalProperties": false, + "type": "object", + "title": "EmptyPayload" + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail" + } + }, + "type": "object", + "title": "HTTPValidationError" + }, + "Login": { + "properties": { + "username": { + "type": "string", + "maxLength": 64, + "minLength": 1, + "title": "Username" + }, + "password": { + "type": "string", + "maxLength": 256, + "minLength": 1, + "title": "Password" + } + }, + "type": "object", + "required": [ + "username", + "password" + ], + "title": "Login" + }, + "PasswordChange": { + "properties": { + "current_password": { + "type": "string", + "maxLength": 256, + "title": "Current Password" + }, + "new_password": { + "type": "string", + "maxLength": 256, + "title": "New Password" + } + }, + "type": "object", + "required": [ + "current_password", + "new_password" + ], + "title": "PasswordChange" + }, + "Render": { + "properties": { + "fps": { + "type": "integer", + "const": 24, + "title": "Fps", + "default": 24 + }, + "total_frames": { + "anyOf": [ + { + "type": "integer", + "maximum": 360000.0, + "minimum": 1.0 + }, + { + "type": "null" + } + ], + "title": "Total Frames" + }, + "fit": { + "type": "string", + "enum": [ + "contain", + "cover" + ], + "title": "Fit", + "default": "contain" + }, + "audio": { + "anyOf": [ + { + "$ref": "#/components/schemas/Audio" + }, + { + "type": "null" + } + ] + }, + "subtitles": { + "items": { + "$ref": "#/components/schemas/Subtitle" + }, + "type": "array", + "maxItems": 1000, + "title": "Subtitles" + }, + "template_version": { + "type": "string", + "const": "plain-v1", + "title": "Template Version", + "default": "plain-v1" + } + }, + "additionalProperties": false, + "type": "object", + "title": "Render" + }, + "Retry": { + "properties": { + "expected_run_version": { + "type": "integer", + "minimum": 1.0, + "title": "Expected Run Version" + }, + "target_job_id": { + "type": "string", + "title": "Target Job Id" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "expected_run_version", + "target_job_id" + ], + "title": "Retry" + }, + "RunCreate": { + "properties": { + "draft_revision": { + "type": "integer", + "minimum": 1.0, + "title": "Draft Revision" + }, + "expected_version": { + "type": "integer", + "minimum": 1.0, + "title": "Expected Version" + }, + "execution_mode": { + "type": "string", + "enum": [ + "interactive", + "batch" + ], + "title": "Execution Mode", + "default": "interactive" + }, + "reuse_run_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Reuse Run Id" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "draft_revision", + "expected_version" + ], + "title": "RunCreate" + }, + "Shot": { + "properties": { + "key": { + "type": "string", + "pattern": "^shot_[1-9][0-9]{0,3}$", + "title": "Key" + }, + "prompt": { + "type": "string", + "maxLength": 8000, + "minLength": 1, + "title": "Prompt" + }, + "duration_frames": { + "type": "integer", + "maximum": 360.0, + "minimum": 24.0, + "title": "Duration Frames", + "default": 120 + }, + "image_asset_id": { + "anyOf": [ + { + "type": "string", + "maxLength": 64, + "minLength": 1 + }, + { + "type": "null" + } + ], + "title": "Image Asset Id" + }, + "parameters": { + "$ref": "#/components/schemas/ShotParameters" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "key", + "prompt" + ], + "title": "Shot" + }, + "ShotParameters": { + "properties": { + "seed": { + "type": "integer", + "maximum": 4294967295.0, + "minimum": 0.0, + "title": "Seed", + "default": 42 + } + }, + "additionalProperties": false, + "type": "object", + "title": "ShotParameters" + }, + "Submit": { + "properties": { + "execution_mode": { + "type": "string", + "enum": [ + "interactive", + "batch" + ], + "title": "Execution Mode", + "default": "interactive" + }, + "task_type": { + "type": "string", + "title": "Task Type" + }, + "input": { + "additionalProperties": true, + "type": "object", + "title": "Input" + }, + "parameters": { + "additionalProperties": true, + "type": "object", + "title": "Parameters" + }, + "count": { + "type": "integer", + "maximum": 4.0, + "minimum": 1.0, + "title": "Count", + "default": 1 + }, + "scheduled_at": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ], + "title": "Scheduled At" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "task_type" + ], + "title": "Submit" + }, + "Subtitle": { + "properties": { + "start_frame": { + "type": "integer", + "minimum": 0.0, + "title": "Start Frame" + }, + "end_frame": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "End Frame" + }, + "text": { + "type": "string", + "maxLength": 2000, + "minLength": 1, + "title": "Text" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "start_frame", + "end_frame", + "text" + ], + "title": "Subtitle" + }, + "TokenInput": { + "properties": { + "name": { + "type": "string", + "maxLength": 128, + "minLength": 1, + "title": "Name" + }, + "scopes": { + "items": { + "type": "string" + }, + "type": "array", + "maxItems": 20, + "title": "Scopes" + }, + "expires_at": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ], + "title": "Expires At" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "name", + "scopes" + ], + "title": "TokenInput" + }, + "UserPatch": { + "properties": { + "display_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + { + "type": "null" + } + ], + "title": "Display Name" + }, + "disabled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Disabled" + } + }, + "type": "object", + "title": "UserPatch" + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array", + "title": "Location" + }, + "msg": { + "type": "string", + "title": "Message" + }, + "type": { + "type": "string", + "title": "Error Type" + }, + "input": { + "title": "Input" + }, + "ctx": { + "type": "object", + "title": "Context" + } + }, + "type": "object", + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError" + }, + "WorkflowSpec": { + "properties": { + "schema_version": { + "type": "integer", + "enum": [ + 1, + 2 + ], + "title": "Schema Version", + "default": 1 + }, + "shots": { + "items": { + "$ref": "#/components/schemas/Shot" + }, + "type": "array", + "maxItems": 1000, + "minItems": 1, + "title": "Shots" + }, + "profile": { + "type": "string", + "enum": [ + "landscape_1080_v1", + "portrait_1080_v1" + ], + "title": "Profile", + "default": "landscape_1080_v1" + }, + "render": { + "$ref": "#/components/schemas/Render" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "shots" + ], + "title": "WorkflowSpec" + } + } + } + } +} diff --git a/backend/tests/fixtures/video_analysis_gpu_result.json b/backend/tests/fixtures/video_analysis_gpu_result.json new file mode 100644 index 0000000..f9f6b45 --- /dev/null +++ b/backend/tests/fixtures/video_analysis_gpu_result.json @@ -0,0 +1,203 @@ +{ + "outputs": [ + { + "path": "preview-0.png" + }, + { + "path": "preview-1.png" + }, + { + "path": "preview-2.png" + } + ], + "metadata": { + "stages": [ + { + "profile": "wan-animate-replace-v1", + "analysis_token": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "source_sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "video": { + "width": 848, + "height": 464, + "fps": 24, + "frames": 121, + "duration_seconds": 5.041667 + }, + "poster_output_index": 0, + "people": [ + { + "id": "person_0001", + "label": "人物1", + "thumbnail_output_index": 1, + "first_frame": 0, + "last_frame": 120, + "confidence": 0.9170905351638794, + "samples": [ + { + "frame": 0, + "bbox": [ + 0.47287735849056606, + 0.08620689655172414, + 0.8231132075471698, + 0.9956896551724138 + ] + }, + { + "frame": 60, + "bbox": [ + 0.482311320754717, + 0.0625, + 0.8537735849056604, + 0.9956896551724138 + ] + }, + { + "frame": 120, + "bbox": [ + 0.4964622641509434, + 0.02586206896551724, + 0.8997641509433962, + 0.9935344827586207 + ] + } + ] + }, + { + "id": "person_0002", + "label": "人物2", + "thumbnail_output_index": 2, + "first_frame": 0, + "last_frame": 120, + "confidence": 0.823920488357544, + "samples": [ + { + "frame": 0, + "bbox": [ + 0.24646226415094338, + 0.22198275862068967, + 0.4846698113207547, + 0.9978448275862069 + ] + }, + { + "frame": 60, + "bbox": [ + 0.23113207547169812, + 0.19827586206896552, + 0.4846698113207547, + 0.9978448275862069 + ] + }, + { + "frame": 120, + "bbox": [ + 0.1580188679245283, + 0.17456896551724138, + 0.46226415094339623, + 0.9956896551724138 + ] + } + ] + } + ], + "warnings": [] + } + ], + "allocator_budget_gib": 68.0, + "reserve_gib": 8.0, + "isolation": "allocator cap and NVML admission are not hardware isolation", + "final_output_indices": [ + 0, + 1, + 2 + ], + "profile": "wan-animate-replace-v1", + "analysis_token": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "source_sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "video": { + "width": 848, + "height": 464, + "fps": 24, + "frames": 121, + "duration_seconds": 5.041667 + }, + "poster_output_index": 0, + "people": [ + { + "id": "person_0001", + "label": "人物1", + "thumbnail_output_index": 1, + "first_frame": 0, + "last_frame": 120, + "confidence": 0.9170905351638794, + "samples": [ + { + "frame": 0, + "bbox": [ + 0.47287735849056606, + 0.08620689655172414, + 0.8231132075471698, + 0.9956896551724138 + ] + }, + { + "frame": 60, + "bbox": [ + 0.482311320754717, + 0.0625, + 0.8537735849056604, + 0.9956896551724138 + ] + }, + { + "frame": 120, + "bbox": [ + 0.4964622641509434, + 0.02586206896551724, + 0.8997641509433962, + 0.9935344827586207 + ] + } + ] + }, + { + "id": "person_0002", + "label": "人物2", + "thumbnail_output_index": 2, + "first_frame": 0, + "last_frame": 120, + "confidence": 0.823920488357544, + "samples": [ + { + "frame": 0, + "bbox": [ + 0.24646226415094338, + 0.22198275862068967, + 0.4846698113207547, + 0.9978448275862069 + ] + }, + { + "frame": 60, + "bbox": [ + 0.23113207547169812, + 0.19827586206896552, + 0.4846698113207547, + 0.9978448275862069 + ] + }, + { + "frame": 120, + "bbox": [ + 0.1580188679245283, + 0.17456896551724138, + 0.46226415094339623, + 0.9956896551724138 + ] + } + ] + } + ], + "warnings": [] + } +} \ No newline at end of file diff --git a/backend/tests/media_longshot_linux.py b/backend/tests/media_longshot_linux.py index 208eb0d..0aca2d3 100644 --- a/backend/tests/media_longshot_linux.py +++ b/backend/tests/media_longshot_linux.py @@ -1,35 +1,68 @@ """Explicit real-FFmpeg acceptance for mixed native-length workflow clips.""" + from types import SimpleNamespace import pytest -from app.media import MediaError, compose_workflow, inspect_video_track, run_process -from app.timeline import compile_timeline +from app.adapters.media import MediaError, compose_workflow, inspect_video_track, run_process +from app.domain.timeline import compile_timeline @pytest.mark.asyncio async def test_real_five_ten_fifteen_second_clips_produce_thirty_seconds(tmp_path): - settings = SimpleNamespace(workspace_root=tmp_path, ffmpeg_bin='ffmpeg', ffprobe_bin='ffprobe', - max_output_bytes=100 * 1024 * 1024) - body = {'schema_version': 2, 'profile': 'landscape_1080_v1', 'shots': [ - {'key': f'shot_{i}', 'prompt': f'shot {i}', 'duration_frames': frames} - for i, frames in enumerate((120, 240, 360), 1)]} + settings = SimpleNamespace( + workspace_root=tmp_path, + ffmpeg_bin="ffmpeg", + ffprobe_bin="ffprobe", + max_output_bytes=100 * 1024 * 1024, + ) + body = { + "schema_version": 2, + "profile": "landscape_1080_v1", + "shots": [ + {"key": f"shot_{i}", "prompt": f"shot {i}", "duration_frames": frames} + for i, frames in enumerate((120, 240, 360), 1) + ], + } plan = compile_timeline(body, {}) sources = [] - for index, color in enumerate(('red', 'green', 'blue'), 1): - source = tmp_path / f'source-{index}.mp4' - frames = plan.shot_generation_parameters[f'shot_{index}']['num_frames'] - await run_process(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', - f'color=c={color}:s=1920x1056:r=24', '-frames:v', str(frames), - '-c:v', 'libx264', '-preset', 'ultrafast', '-threads', '2', str(source)]) + for index, color in enumerate(("red", "green", "blue"), 1): + source = tmp_path / f"source-{index}.mp4" + frames = plan.shot_generation_parameters[f"shot_{index}"]["num_frames"] + await run_process( + [ + "ffmpeg", + "-v", + "error", + "-f", + "lavfi", + "-i", + f"color=c={color}:s=1920x1056:r=24", + "-frames:v", + str(frames), + "-c:v", + "libx264", + "-preset", + "ultrafast", + "-threads", + "2", + str(source), + ] + ) sources.append(source) - output = await compose_workflow(plan, tmp_path / 'output', settings=settings, sources=sources) + output = await compose_workflow(plan, tmp_path / "output", settings=settings, sources=sources) track = await inspect_video_track(output.outputs[0], settings) - assert track['frames'] == 720 and track['fps'] == 24 - assert (track['width'], track['height']) == (1920, 1080) - assert abs(track['duration'] - 30) < .05 - await run_process(['ffmpeg', '-v', 'error', '-threads', '2', '-i', str(output.outputs[0]), '-f', 'null', '-']) + assert track["frames"] == 720 and track["fps"] == 24 + assert (track["width"], track["height"]) == (1920, 1080) + assert abs(track["duration"] - 30) < 0.05 + await run_process( + ["ffmpeg", "-v", "error", "-threads", "2", "-i", str(output.outputs[0]), "-f", "null", "-"] + ) # A real short source cannot be stretched or frozen to impersonate15 seconds. with pytest.raises(MediaError): - await compose_workflow(plan, tmp_path / 'invalid-output', settings=settings, - sources=[sources[0], sources[1], sources[0]]) + await compose_workflow( + plan, + tmp_path / "invalid-output", + settings=settings, + sources=[sources[0], sources[1], sources[0]], + ) diff --git a/backend/tests/media_v2_linux.py b/backend/tests/media_v2_linux.py index 0c35063..b800c5d 100644 --- a/backend/tests/media_v2_linux.py +++ b/backend/tests/media_v2_linux.py @@ -1,61 +1,178 @@ """Explicit Linux FFmpeg acceptance: pytest tests/media_v2_linux.py -q. Not part of portable suite; requires real FFmpeg/libx264/drawtext and Noto fonts. """ + from pathlib import Path from types import SimpleNamespace import pytest -from app.timeline import compile_timeline -from app.media import compose_workflow, inspect_video_track, run_process, MediaError +from app.domain.timeline import compile_timeline +from app.adapters.media import compose_workflow, inspect_video_track, run_process, MediaError from test_timeline_v2 import spec + @pytest.mark.asyncio -@pytest.mark.parametrize('profile,fit',[('landscape_1080_v1','contain'),('landscape_1080_v1','cover'),('portrait_1080_v1','contain'),('portrait_1080_v1','cover')]) -async def test_real_fixed_frame_workflow(tmp_path,profile,fit): - settings=SimpleNamespace(workspace_root=tmp_path,ffmpeg_bin='ffmpeg',ffprobe_bin='ffprobe',max_output_bytes=100*1024*1024) - body=spec();body['profile']=profile;body['render']={'fit':fit,'audio':{'asset_id':'audio','source_start_ms':3000,'source_end_ms':18000,'offset_frame':0},'subtitles':[{'start_frame':119,'end_frame':241,'text':'Across shots'},{'start_frame':241,'end_frame':360,'text':'Final frame'}]} - audio=tmp_path/'audio.wav' - await run_process(['ffmpeg','-v','error','-f','lavfi','-i','sine=frequency=440:sample_rate=48000','-t','18',str(audio)]) - plan=compile_timeline(body,{'audio':{'kind':'audio','duration_seconds':18}}) - w,h=plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height'] - sources=[] - for index,color in enumerate(('red','green','blue')): - source=tmp_path/f'source-{index}.mp4' - await run_process(['ffmpeg','-v','error','-f','lavfi','-i',f'color=c={color}:s={w}x{h}:r=24','-frames:v','121','-c:v','libx264','-preset','ultrafast','-threads','2',str(source)]) +@pytest.mark.parametrize( + "profile,fit", + [ + ("landscape_1080_v1", "contain"), + ("landscape_1080_v1", "cover"), + ("portrait_1080_v1", "contain"), + ("portrait_1080_v1", "cover"), + ], +) +async def test_real_fixed_frame_workflow(tmp_path, profile, fit): + settings = SimpleNamespace( + workspace_root=tmp_path, + ffmpeg_bin="ffmpeg", + ffprobe_bin="ffprobe", + max_output_bytes=100 * 1024 * 1024, + ) + body = spec() + body["profile"] = profile + body["render"] = { + "fit": fit, + "audio": { + "asset_id": "audio", + "source_start_ms": 3000, + "source_end_ms": 18000, + "offset_frame": 0, + }, + "subtitles": [ + {"start_frame": 119, "end_frame": 241, "text": "Across shots"}, + {"start_frame": 241, "end_frame": 360, "text": "Final frame"}, + ], + } + audio = tmp_path / "audio.wav" + await run_process( + [ + "ffmpeg", + "-v", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000", + "-t", + "18", + str(audio), + ] + ) + plan = compile_timeline(body, {"audio": {"kind": "audio", "duration_seconds": 18}}) + w, h = plan.generation_parameters["upscale_width"], plan.generation_parameters["upscale_height"] + sources = [] + for index, color in enumerate(("red", "green", "blue")): + source = tmp_path / f"source-{index}.mp4" + await run_process( + [ + "ffmpeg", + "-v", + "error", + "-f", + "lavfi", + "-i", + f"color=c={color}:s={w}x{h}:r=24", + "-frames:v", + "121", + "-c:v", + "libx264", + "-preset", + "ultrafast", + "-threads", + "2", + str(source), + ] + ) sources.append(source) - result=await compose_workflow(plan,tmp_path/'work',settings=settings,sources=sources,audio=audio) - track=await inspect_video_track(result.outputs[0],settings) - assert track['frames']==360 and track['fps']==24 - assert (track['width'],track['height'])==plan.canvas - assert abs(track['duration']-15)<=.10 + result = await compose_workflow( + plan, tmp_path / "work", settings=settings, sources=sources, audio=audio + ) + track = await inspect_video_track(result.outputs[0], settings) + assert track["frames"] == 360 and track["fps"] == 24 + assert (track["width"], track["height"]) == plan.canvas + assert abs(track["duration"] - 15) <= 0.10 # Decode full output, not just the muxer metadata. - await run_process(['ffmpeg','-v','error','-i',str(result.outputs[0]),'-f','null','-']) + await run_process(["ffmpeg", "-v", "error", "-i", str(result.outputs[0]), "-f", "null", "-"]) + @pytest.mark.asyncio async def test_real_119_frame_source_rejected(tmp_path): - settings=SimpleNamespace(workspace_root=tmp_path,ffmpeg_bin='ffmpeg',ffprobe_bin='ffprobe',max_output_bytes=100*1024*1024) - source=tmp_path/'short.mp4' - await run_process(['ffmpeg','-v','error','-f','lavfi','-i','color=c=red:s=1920x1056:r=24','-frames:v','119','-c:v','libx264','-preset','ultrafast','-threads','2',str(source)]) - with pytest.raises(MediaError,match='120'): - await compose_workflow(compile_timeline(spec(),{}),tmp_path/'work',settings=settings,sources=[source]*3) + settings = SimpleNamespace( + workspace_root=tmp_path, + ffmpeg_bin="ffmpeg", + ffprobe_bin="ffprobe", + max_output_bytes=100 * 1024 * 1024, + ) + source = tmp_path / "short.mp4" + await run_process( + [ + "ffmpeg", + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=red:s=1920x1056:r=24", + "-frames:v", + "119", + "-c:v", + "libx264", + "-preset", + "ultrafast", + "-threads", + "2", + str(source), + ] + ) + with pytest.raises(MediaError, match="120"): + await compose_workflow( + compile_timeline(spec(), {}), tmp_path / "work", settings=settings, sources=[source] * 3 + ) @pytest.mark.asyncio async def test_real_variable_sixteen_second_workflow(tmp_path): from test_multishot_v3 import story - settings=SimpleNamespace(workspace_root=tmp_path,ffmpeg_bin='ffmpeg',ffprobe_bin='ffprobe',max_output_bytes=100*1024*1024) - body=story(durations=[24,120,120,120]) - body['render']={'subtitles':[{'start_frame':361,'end_frame':384,'text':'Beyond fifteen seconds'}]} - plan=compile_timeline(body,{}) - sources=[] - w,h=plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height'] - for index,color in enumerate(('red','green','blue','yellow')): - source=tmp_path/f'source-{index}.mp4' - await run_process(['ffmpeg','-v','error','-f','lavfi','-i',f'color=c={color}:s={w}x{h}:r=24','-frames:v','121','-c:v','libx264','-preset','ultrafast','-threads','2',str(source)]) + + settings = SimpleNamespace( + workspace_root=tmp_path, + ffmpeg_bin="ffmpeg", + ffprobe_bin="ffprobe", + max_output_bytes=100 * 1024 * 1024, + ) + body = story(durations=[24, 120, 120, 120]) + body["render"] = { + "subtitles": [{"start_frame": 361, "end_frame": 384, "text": "Beyond fifteen seconds"}] + } + plan = compile_timeline(body, {}) + sources = [] + w, h = plan.generation_parameters["upscale_width"], plan.generation_parameters["upscale_height"] + for index, color in enumerate(("red", "green", "blue", "yellow")): + source = tmp_path / f"source-{index}.mp4" + await run_process( + [ + "ffmpeg", + "-v", + "error", + "-f", + "lavfi", + "-i", + f"color=c={color}:s={w}x{h}:r=24", + "-frames:v", + "121", + "-c:v", + "libx264", + "-preset", + "ultrafast", + "-threads", + "2", + str(source), + ] + ) sources.append(source) - result=await compose_workflow(plan,tmp_path/'work',settings=settings,sources=sources) - track=await inspect_video_track(result.outputs[0],settings) - assert track['frames']==384 and track['fps']==24 - assert (track['width'],track['height'])==(1920,1080) - assert abs(track['duration']-16)<=.10 - assert result.result['clip_count']==4 - await run_process(['ffmpeg','-v','error','-i',str(result.outputs[0]),'-f','null','-']) + result = await compose_workflow(plan, tmp_path / "work", settings=settings, sources=sources) + track = await inspect_video_track(result.outputs[0], settings) + assert track["frames"] == 384 and track["fps"] == 24 + assert (track["width"], track["height"]) == (1920, 1080) + assert abs(track["duration"] - 16) <= 0.10 + assert result.result["clip_count"] == 4 + await run_process(["ffmpeg", "-v", "error", "-i", str(result.outputs[0]), "-f", "null", "-"]) diff --git a/backend/tests/mysql_v2_linux.py b/backend/tests/mysql_v2_linux.py index 5e67a19..39c6842 100644 --- a/backend/tests/mysql_v2_linux.py +++ b/backend/tests/mysql_v2_linux.py @@ -1,4 +1,5 @@ """Opt-in MySQL API regression, restricted to the isolated verification host.""" + import asyncio import os from pathlib import Path @@ -11,13 +12,14 @@ from sqlalchemy.engine import make_url from sqlalchemy.ext.asyncio import create_async_engine from alembic import command from alembic.config import Config -from app.config import Settings +from app.core.config import Settings from app.main import create_app from conftest import FakeProvider, PASSWORD from test_auth import test_login_cookie_csrf_and_revocation from test_jobs import test_lost_submit_response_recovers_same_id_and_known_id_never_resubmits from test_core_v2 import test_submission_changed_body_conflicts_and_recovers +from test_fifo_json import test_prepared_fifo_uses_native_json_and_preserves_payload_and_holds from test_workflows_v2 import ( test_snapshot_version_idempotency_owner, test_engine_durable_sequential_cancel_and_no_new_job, @@ -26,34 +28,52 @@ from test_workflows_v2 import ( test_batch_does_not_advance_while_previous_cleanup_unknown, ) -@pytest_asyncio.fixture -async def system(tmp_path): - url=make_url(os.environ['CMVR_VERIFY_MYSQL_URL']) - if url.host not in {'cmvr-visual-v2-test-mysql', 'cmvr-visual-v4-test-mysql'}:raise RuntimeError('Refusing non-isolated database') - name='cmvr_visual_verify_'+uuid.uuid4().hex[:12] - engine=create_async_engine(url.set(database='mysql')) - async with engine.begin() as c: - await c.execute(text(f'CREATE DATABASE `{name}` CHARACTER SET utf8mb4')) - config=Config(str(Path(__file__).parents[1]/'alembic.ini')) - config.attributes['url']=url.set(database=name) - try: - await asyncio.to_thread(command.upgrade,config,'head') - settings=Settings(mode='production',database_url=url.set(database=name),workspace_root=tmp_path, - admin_username='admin',admin_password=PASSWORD,run_coordinator=False,cookie_secure=False) - provider=FakeProvider() - async def caps():return {'protocol_version':2,'admission_policy':True} - provider.upstream_capabilities=caps - app=create_app(settings,provider=provider) - async with app.router.lifespan_context(app): - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test') as client: - login=await client.post('/api/auth/login',json={'username':'admin','password':PASSWORD}) - assert login.status_code==200 - client.headers['X-CSRF-Token']=login.json()['csrf_token'] - yield SimpleNamespace(app=app,client=client,settings=settings,provider=provider) - finally: - async with engine.begin() as c: - await c.execute(text(f'DROP DATABASE `{name}`')) - await engine.dispose() @pytest_asyncio.fixture -async def wf(system):return system +async def system(tmp_path): + url = make_url(os.environ["CMVR_VERIFY_MYSQL_URL"]) + if url.host not in {"cmvr-visual-v2-test-mysql", "cmvr-visual-v4-test-mysql"}: + raise RuntimeError("Refusing non-isolated database") + name = "cmvr_visual_verify_" + uuid.uuid4().hex[:12] + engine = create_async_engine(url.set(database="mysql")) + async with engine.begin() as c: + await c.execute(text(f"CREATE DATABASE `{name}` CHARACTER SET utf8mb4")) + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + config.attributes["url"] = url.set(database=name) + try: + await asyncio.to_thread(command.upgrade, config, "head") + settings = Settings( + mode="production", + database_url=url.set(database=name), + workspace_root=tmp_path, + admin_username="admin", + admin_password=PASSWORD, + run_coordinator=False, + cookie_secure=False, + ) + provider = FakeProvider() + + async def caps(): + return {"protocol_version": 2, "admission_policy": True} + + provider.upstream_capabilities = caps + app = create_app(settings, provider=provider) + async with app.router.lifespan_context(app): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + login = await client.post( + "/api/auth/login", json={"username": "admin", "password": PASSWORD} + ) + assert login.status_code == 200 + client.headers["X-CSRF-Token"] = login.json()["csrf_token"] + yield SimpleNamespace(app=app, client=client, settings=settings, provider=provider) + finally: + async with engine.begin() as c: + await c.execute(text(f"DROP DATABASE `{name}`")) + await engine.dispose() + + +@pytest_asyncio.fixture +async def wf(system): + return system diff --git a/backend/tests/mysql_v4_linux.py b/backend/tests/mysql_v4_linux.py index 431a3ee..630a7b1 100644 --- a/backend/tests/mysql_v4_linux.py +++ b/backend/tests/mysql_v4_linux.py @@ -2,6 +2,7 @@ Reuses the disposable, uniquely named database fixture; never production. """ + from mysql_v2_linux import system -from test_shared_assets import * # noqa: F403 -from test_record_deletion import * # noqa: F403 +from test_shared_assets import * +from test_record_deletion import * diff --git a/backend/tests/test_admission_clock.py b/backend/tests/test_admission_clock.py index 527eff2..0d7f6d9 100644 --- a/backend/tests/test_admission_clock.py +++ b/backend/tests/test_admission_clock.py @@ -2,33 +2,42 @@ from datetime import datetime from pathlib import Path import pytest -def stamp(value):return datetime.fromisoformat(value).timestamp() + +def stamp(value): + return datetime.fromisoformat(value).timestamp() + def test_closed_batch_window_survives_restart_and_clock_rollback(tmp_path): - from app.admission_clock import AdmissionClock - path=tmp_path/'admission-clock.json' - clock=AdmissionClock(path) - assert clock.observe(stamp('2026-11-11T07:59:59+08:00')) - assert clock.observe(stamp('2026-11-11T08:00:00+08:00')) - restarted=AdmissionClock(path) - assert not restarted.observe(stamp('2026-11-11T07:59:59+08:00')) - assert restarted.reason=='window_already_closed' - assert not restarted.observe(stamp('2026-11-11T07:55:00+08:00')) - assert restarted.reason=='clock_rollback' - assert restarted.observe(stamp('2026-11-11T21:00:00+08:00')) + from app.services.orchestration.admission_clock import AdmissionClock + + path = tmp_path / "admission-clock.json" + clock = AdmissionClock(path) + assert clock.observe(stamp("2026-11-11T07:59:59+08:00")) + assert clock.observe(stamp("2026-11-11T08:00:00+08:00")) + restarted = AdmissionClock(path) + assert not restarted.observe(stamp("2026-11-11T07:59:59+08:00")) + assert restarted.reason == "window_already_closed" + assert not restarted.observe(stamp("2026-11-11T07:55:00+08:00")) + assert restarted.reason == "clock_rollback" + assert restarted.observe(stamp("2026-11-11T21:00:00+08:00")) + def test_corrupt_clock_state_fails_closed_without_affecting_interactive(tmp_path): - from app.admission_clock import AdmissionClock - path=tmp_path/'clock.json';path.write_text('{incomplete') - clock=AdmissionClock(path) - assert not clock.observe(stamp('2026-11-11T21:00:00+08:00')) - assert clock.reason=='clock_state_invalid' + from app.services.orchestration.admission_clock import AdmissionClock -@pytest.mark.parametrize('value',['NaN','Infinity','-Infinity','1e300']) -def test_nonfinite_or_impossible_watermark_only_closes_batch_gate(tmp_path,value): - from app.admission_clock import AdmissionClock - path=tmp_path/'clock.json' - path.write_text('{"max_seen":'+value+',"closed_through":"2026-11-11"}') - clock=AdmissionClock(path) - assert not clock.observe(stamp('2026-11-11T21:00:00+08:00')) - assert clock.reason=='clock_state_invalid' + path = tmp_path / "clock.json" + path.write_text("{incomplete") + clock = AdmissionClock(path) + assert not clock.observe(stamp("2026-11-11T21:00:00+08:00")) + assert clock.reason == "clock_state_invalid" + + +@pytest.mark.parametrize("value", ["NaN", "Infinity", "-Infinity", "1e300"]) +def test_nonfinite_or_impossible_watermark_only_closes_batch_gate(tmp_path, value): + from app.services.orchestration.admission_clock import AdmissionClock + + path = tmp_path / "clock.json" + path.write_text('{"max_seen":' + value + ',"closed_through":"2026-11-11"}') + clock = AdmissionClock(path) + assert not clock.observe(stamp("2026-11-11T21:00:00+08:00")) + assert clock.reason == "clock_state_invalid" diff --git a/backend/tests/test_architecture_contract.py b/backend/tests/test_architecture_contract.py new file mode 100644 index 0000000..24aa38d --- /dev/null +++ b/backend/tests/test_architecture_contract.py @@ -0,0 +1,180 @@ +"""Refactoring must preserve the public API and existing database definition.""" + +import json +from copy import deepcopy +from pathlib import Path +import sys + + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + + +def test_routes_and_mysql_metadata_are_unchanged(): + from scripts.architecture_contract import capture_contract + + expected = json.loads( + (Path(__file__).parent / "fixtures/engineering_contract.json").read_text(encoding="utf-8") + ) + actual = capture_contract() + additions = { + "visual_shot_candidates", + "visual_shot_selections", + "visual_folders", + "visual_asset_folders", + } + assert set(actual["tables"]) == set(expected["tables"]) | additions + folder_columns = { + "visual_drafts": {"folder_id"}, + "visual_jobs": {"folder_id", "output_folder_id"}, + "visual_workflow_runs": {"folder_id", "output_folder_id"}, + } + # 007 只允许合同内的追加列;原列定义与历史fixture仍逐项比较。 + editor_columns = { + "visual_drafts": {"editor_manifest": ("JSON", True)}, + "visual_workflow_runs": { + "run_kind": ("VARCHAR(32)", False), + "output_goal": ("VARCHAR(16)", False), + "base_run_id": ("VARCHAR(32)", True), + "source_draft_version": ("INTEGER", True), + "plan_snapshot": ("JSON", True), + "result_manifest": ("JSON", True), + "apply_state": ("VARCHAR(16)", True), + }, + "visual_workflow_steps": { + name: ("JSON", True) for name in ("recipe_json", "resolved_input_json", "result_json") + }, + } + for name, old_table in expected["tables"].items(): + current = deepcopy(actual["tables"][name]) + folder_added = folder_columns.get(name, set()) + editor_added = editor_columns.get(name, {}) + added = folder_added | set(editor_added) + for column in current["columns"]: + if column["name"] in editor_added: + kind, nullable = editor_added[column["name"]] + assert column["type"] == kind + assert column["nullable"] is nullable + assert column["foreign_keys"] == [] + if column["name"] in folder_added: + assert column["nullable"] is True + assert column["foreign_keys"] == ["visual_folders.id"] + assert column["type"] == "VARCHAR(32)" + assert {c["name"] for c in current["columns"]} == { + c["name"] for c in old_table["columns"] + } | added + current["columns"] = [c for c in current["columns"] if c["name"] not in added] + current["indexes"] = [i for i in current["indexes"] if not (set(i["columns"]) & added)] + assert current == old_table + # 用户管理只精确豁免新增端点,旧的路由、响应与表结构仍按历史合同检查。 + delete_user = { + "path": "/api/auth/users/{user_id}", + "method": "DELETE", + "responses": ["204", "422"], + } + assert delete_user in actual["routes"] + change_username = { + "path": "/api/auth/username", + "method": "POST", + "responses": ["200", "422"], + } + assert change_username in actual["routes"] + editor_routes = [ + {"path": "/api/editors/{draft_id}" + suffix, "method": method, "responses": responses} + for suffix, method, responses in ( + ("", "GET", ["200", "422"]), + ("/save", "POST", ["200", "422"]), + ("/from-run", "POST", ["200", "422"]), + ("/plan", "POST", ["200", "422"]), + ("/runs", "POST", ["202", "422"]), + ("/apply", "POST", ["200", "422"]), + ("/mode", "POST", ["200", "422"]), + ) + ] + assert all(r in actual["routes"] for r in editor_routes) + assert [ + r + for r in actual["routes"] + if not r["path"].startswith(("/api/stories", "/api/folders")) + and r not in (delete_user, change_username) + and r not in editor_routes + ] == expected["routes"] + old_http, new_http = expected["http_contract"], actual["http_contract"] + for path, old_operations in old_http["operations"].items(): + current = deepcopy(new_http["operations"][path]) + if path == "/api/auth/users/{user_id}": + assert "204" in current.pop("delete")["responses"] + for method, operation in current.items(): + if ( + path in {"/api/assets", "/api/jobs", "/api/workflows", "/api/workflow-runs"} + and method == "get" + ): + extra = [p for p in operation.get("parameters", []) if p["name"] == "folder_id"] + assert len(extra) == 1 and not extra[0].get("required", False) + operation["parameters"] = [ + p for p in operation["parameters"] if p["name"] != "folder_id" + ] + if path == "/api/shared-assets/{shared_id}/import" and method == "post": + assert not operation["requestBody"].get("required", False) + variants = operation["requestBody"]["content"]["application/json"]["schema"][ + "anyOf" + ] + assert variants == [{"$ref": "#/components/schemas/SharedImport"}, {"type": "null"}] + variants[0] = {"$ref": "#/components/schemas/EmptyPayload"} + assert current == old_operations + assert set(new_http["operations"]["/api/auth/username"]) == {"post"} + assert all( + p in old_http["operations"] + or p == "/api/auth/username" + or p in {r["path"] for r in editor_routes} + or p.startswith(("/api/stories", "/api/folders")) + for p in new_http["operations"] + ) + optional_folder_fields = { + "AssetPatch": {"folder_ids"}, + "BatchJob": {"folder_id", "output_folder_id"}, + "BatchWorkflow": {"output_folder_id"}, + "Body_upload_api_assets_post": {"folder_id"}, + "DraftCreate": {"folder_id"}, + "DraftPatch": {"folder_id"}, + "RunCreate": {"output_folder_id"}, + "Submit": {"folder_id", "output_folder_id"}, + } + for group, components in old_http["components"].items(): + for name, old_component in components.items(): + current = deepcopy(new_http["components"][group][name]) + added = optional_folder_fields.get(name, set()) if group == "schemas" else set() + for field in added: + assert field in current["properties"] and field not in current.get("required", []) + current["properties"].pop(field) + assert current == old_component + + +def test_asgi_entry_uses_the_shared_application_factory(): + from app.bootstrap import create_app + from app.main import app, create_app as public_factory + + assert public_factory is create_app + assert app.title == "CMVR Visual" + + +def test_pure_domain_does_not_import_http_database_or_io_adapters(): + import ast + + directory = ROOT / "backend/app/domain" + assert directory.is_dir() + forbidden = ("fastapi", "sqlalchemy", "httpx", "app.api", "app.services", "app.adapters") + for path in directory.rglob("*.py"): + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + imports = [node.module or ""] + else: + continue + assert not any( + name == prefix or name.startswith(prefix + ".") + for name in imports + for prefix in forbidden + ), path diff --git a/backend/tests/test_asset_physical_deletion.py b/backend/tests/test_asset_physical_deletion.py new file mode 100644 index 0000000..3591d0d --- /dev/null +++ b/backend/tests/test_asset_physical_deletion.py @@ -0,0 +1,265 @@ +"""Deletion removes owned bytes and links without damaging independent copies.""" + +import os +from pathlib import Path + +import pytest +from sqlalchemy import select + +from app.models import Asset, Job, JobAsset +from app.models import AssetReference, AssetTag, Execution, SharedAsset + + +async def upload(system, png_bytes, client=None): + result = await (client or system.client).post( + "/api/assets", files={"file": ("reference.png", png_bytes, "image/png")} + ) + assert result.status_code == 201, result.text + return result.json() + + +async def files_for(system, asset_id): + async with system.app.state.db.session() as session: + asset = await session.get(Asset, asset_id) + return [ + system.settings.asset_root / key + for key in (asset.storage_key, asset.thumbnail_key) + if key + ] + + +async def test_private_delete_removes_files_and_all_asset_links(system, png_bytes): + asset = await upload(system, png_bytes) + await system.client.patch(f"/api/assets/{asset['id']}", json={"tags": ["reference"]}) + job = ( + await system.client.post( + "/api/jobs", + json={ + "task_type": "defect.generate", + "input": {"prompt": "scratch", "image_asset_id": asset["id"]}, + }, + ) + ).json()["jobs"][0] + async with system.app.state.db.session() as session: + (await session.get(Job, job["id"])).state = "failed" + row = await session.get(Asset, asset["id"]) + session.add( + AssetReference( + owner_id=row.owner_id, asset_id=row.id, ref_kind="execution", ref_id="finished" + ) + ) + await session.commit() + files = await files_for(system, asset["id"]) + assert len(files) == 2 and all(path.is_file() for path in files) + response = await system.client.delete(f"/api/assets/{asset['id']}") + assert response.status_code == 204, response.text + assert all(not path.exists() for path in files) + async with system.app.state.db.session() as session: + assert await session.get(Asset, asset["id"]) is None + for model in (JobAsset, AssetReference, AssetTag): + assert await session.scalar(select(model).where(model.asset_id == asset["id"])) is None + assert (await system.client.get("/api/assets")).json()["total"] == 0 + for url in ( + f"/api/assets/{asset['id']}", + asset["preview_url"], + asset["thumbnail_url"], + asset["download_url"], + ): + assert (await system.client.get(url)).status_code == 404 + assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 404 + + +async def test_source_and_publication_deletion_preserve_each_import( + system, other_client, png_bytes +): + source = await upload(system, png_bytes) + shared = (await system.client.post(f"/api/assets/{source['id']}/publish")).json() + imports = [] + for client in (system.client, other_client): + response = await client.post(f"/api/shared-assets/{shared['id']}/import") + assert response.status_code == 201, response.text + imports.append((client, response.json())) + async with system.app.state.db.session() as session: + snapshot_id = (await session.get(SharedAsset, shared["id"])).asset_id + source_files = await files_for(system, source["id"]) + snapshot_files = await files_for(system, snapshot_id) + imported_files = [await files_for(system, asset["id"]) for _, asset in imports] + originals = [source_files[0], snapshot_files[0], *(paths[0] for paths in imported_files)] + assert len({path.stat().st_ino for path in originals}) == 4 + assert (await other_client.delete(f"/api/assets/{source['id']}")).status_code == 404 + assert all(path.exists() for path in source_files) + assert (await system.client.delete(f"/api/assets/{source['id']}")).status_code == 204 + assert all(not path.exists() for path in source_files) + async with system.app.state.db.session() as session: + assert (await session.get(SharedAsset, shared["id"])).source_asset_id is None + assert (await other_client.get(shared["preview_url"])).content == png_bytes + assert (await other_client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404 + assert all(path.exists() for path in snapshot_files) + response = await system.client.delete(f"/api/shared-assets/{shared['id']}") + assert response.status_code == 204, response.text + assert all(not path.exists() for path in snapshot_files) + async with system.app.state.db.session() as session: + assert await session.get(SharedAsset, shared["id"]) is None + assert await session.get(Asset, snapshot_id) is None + for model in (AssetReference, AssetTag): + assert await session.scalar(select(model).where(model.asset_id == snapshot_id)) is None + assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404 + for client, asset in imports: + assert (await client.get(asset["preview_url"])).content == png_bytes + assert (await client.get(asset["thumbnail_url"])).status_code == 200 + assert (await imports[0][0].delete(f"/api/assets/{imports[0][1]['id']}")).status_code == 204 + assert all(not path.exists() for path in imported_files[0]) + assert all(path.exists() for path in imported_files[1]) + assert (await other_client.get(imports[1][1]["preview_url"])).content == png_bytes + + +async def test_missing_bytes_do_not_prevent_delete_retry(system, png_bytes): + asset = await upload(system, png_bytes) + paths = await files_for(system, asset["id"]) + paths[0].unlink() + assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 204 + assert all(not path.exists() for path in paths) + async with system.app.state.db.session() as session: + assert await session.get(Asset, asset["id"]) is None + + +@pytest.mark.parametrize("field", ["storage_key", "thumbnail_key"]) +async def test_outside_key_rejects_delete_before_any_owned_bytes_are_removed( + system, png_bytes, tmp_path, field +): + asset = await upload(system, png_bytes) + paths = await files_for(system, asset["id"]) + outside = tmp_path / "keep.png" + outside.write_bytes(b"must survive") + async with system.app.state.db.session() as session: + setattr(await session.get(Asset, asset["id"]), field, str(outside)) + await session.commit() + response = await system.client.delete(f"/api/assets/{asset['id']}") + assert response.status_code == 409, response.text + assert outside.read_bytes() == b"must survive" + assert all(path.exists() for path in paths) + + +async def test_key_for_another_asset_cannot_delete_its_files(system, png_bytes): + first, second = await upload(system, png_bytes), await upload(system, png_bytes) + paths = await files_for(system, second["id"]) + async with system.app.state.db.session() as session: + (await session.get(Asset, first["id"])).thumbnail_key = ( + await session.get(Asset, second["id"]) + ).thumbnail_key + await session.commit() + assert (await system.client.delete(f"/api/assets/{first['id']}")).status_code == 409 + assert all(path.exists() for path in paths) + + +async def test_symlink_cannot_delete_outside_bytes(system, png_bytes, tmp_path): + asset = await upload(system, png_bytes) + original, thumbnail = await files_for(system, asset["id"]) + outside = tmp_path / "keep.png" + outside.write_bytes(b"must survive") + thumbnail.unlink() + try: + thumbnail.symlink_to(outside) + except OSError as exc: + pytest.skip(f"Symlinks unavailable: {exc}") + response = await system.client.delete(f"/api/assets/{asset['id']}") + assert response.status_code == 409, response.text + assert outside.read_bytes() == b"must survive" and original.exists() + + +@pytest.mark.parametrize("key", ["", "."]) +async def test_empty_or_directory_key_cannot_remove_root(system, png_bytes, key): + asset = await upload(system, png_bytes) + paths = await files_for(system, asset["id"]) + async with system.app.state.db.session() as session: + (await session.get(Asset, asset["id"])).storage_key = key + await session.commit() + assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 409 + assert system.settings.asset_root.is_dir() and all(path.exists() for path in paths) + + +@pytest.mark.parametrize("protected", ["draft", "producer", "execution"]) +async def test_live_references_and_producer_protect_files(system, png_bytes, protected): + asset = await upload(system, png_bytes) + paths = await files_for(system, asset["id"]) + job = ( + await system.client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} + ) + ).json()["jobs"][0] + async with system.app.state.db.session() as session: + row = await session.get(Asset, asset["id"]) + if protected == "draft": + session.add( + AssetReference( + owner_id=row.owner_id, asset_id=row.id, ref_kind="draft", ref_id="draft" + ) + ) + elif protected == "producer": + row.source_job_id = job["id"] + else: + execution = Execution( + job_id=job["id"], + ordinal=1, + phase_key="execute", + resource_pool="cpu_media", + fence_token="test", + state="running", + ) + session.add(execution) + await session.flush() + session.add( + AssetReference( + owner_id=row.owner_id, + asset_id=row.id, + ref_kind="execution", + ref_id=execution.id, + ) + ) + await session.commit() + assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 409 + assert all(path.exists() for path in paths) + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows file sharing denial") +@pytest.mark.parametrize("shared", [False, True]) +async def test_windows_locked_file_returns_failure_then_retry_cleans_files( + system, png_bytes, shared +): + import ctypes + from ctypes import wintypes + + asset = await upload(system, png_bytes) + if shared: + publication = (await system.client.post(f"/api/assets/{asset['id']}/publish")).json() + route = f"/api/shared-assets/{publication['id']}" + async with system.app.state.db.session() as session: + asset_id = (await session.get(SharedAsset, publication["id"])).asset_id + else: + route, asset_id = f"/api/assets/{asset['id']}", asset["id"] + paths = await files_for(system, asset_id) + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.CreateFileW.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ] + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + # Lock the thumbnail, so a retry must also tolerate an already removed original. + handle = kernel.CreateFileW(str(paths[1]), 0x80000000, 1, None, 3, 0x80, None) + assert handle != wintypes.HANDLE(-1).value + try: + response = await system.client.delete(route) + assert response.status_code == 503, response.text + assert paths[1].exists() + async with system.app.state.db.session() as session: + assert await session.get(Asset, asset_id) is not None + finally: + kernel.CloseHandle(handle) + assert (await system.client.delete(route)).status_code == 204 + assert all(not path.exists() for path in paths) diff --git a/backend/tests/test_assets.py b/backend/tests/test_assets.py index 6b96ec7..94eeaae 100644 --- a/backend/tests/test_assets.py +++ b/backend/tests/test_assets.py @@ -1,8 +1,12 @@ from pathlib import Path -async def test_assets_are_owned_range_enabled_and_active_inputs_are_protected(system, other_client, png_bytes): - uploaded = await system.client.post("/api/assets", files={"file": ("../reference.png", png_bytes, "image/png")}) +async def test_assets_are_owned_range_enabled_and_active_inputs_are_protected( + system, other_client, png_bytes +): + uploaded = await system.client.post( + "/api/assets", files={"file": ("../reference.png", png_bytes, "image/png")} + ) assert uploaded.status_code == 201, uploaded.text asset = uploaded.json() assert asset["kind"] == "image" and asset["width"] == 16 @@ -12,41 +16,70 @@ async def test_assets_are_owned_range_enabled_and_active_inputs_are_protected(sy content = await system.client.get(asset["preview_url"], headers={"Range": "bytes=0-7"}) assert content.status_code == 206 and content.content == png_bytes[:8] assert content.headers["content-range"] == f"bytes 0-7/{len(png_bytes)}" - patched = await system.client.patch(f"/api/assets/{asset['id']}", json={"tags": ["product"], "favorite": True}) + patched = await system.client.patch( + f"/api/assets/{asset['id']}", json={"tags": ["product"], "favorite": True} + ) assert patched.json()["favorite"] and patched.json()["tags"] == ["product"] - response = await system.client.post("/api/jobs", json={"task_type": "video.generate", - "input": {"prompt": "rotate", "image_asset_id": asset["id"]}, "parameters": {}}) + response = await system.client.post( + "/api/jobs", + json={ + "task_type": "video.generate", + "input": {"prompt": "rotate", "image_asset_id": asset["id"]}, + "parameters": {}, + }, + ) assert response.status_code == 202, response.text files_before = list(system.settings.asset_root.rglob("original*")) assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 409 await system.app.state.coordinator.run_once(force=True) assert len(system.provider.accepted) == 1 - system.provider.remote["remote-1"].update(state="failed", error={"code": "test_failure", "message": "failed"}) + system.provider.remote["remote-1"].update( + state="failed", error={"code": "test_failure", "message": "failed"} + ) await system.app.state.coordinator.run_once(force=True) assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 204 - assert all(path.exists() for path in files_before) + assert all(not path.exists() for path in files_before) assert (await system.client.get(f"/api/assets/{asset['id']}/content")).status_code == 404 async def test_foreign_asset_cannot_be_used_to_create_job(system, other_client, png_bytes): - asset = (await system.client.post("/api/assets", files={"file": ("image.png", png_bytes, "image/png")})).json() - response = await other_client.post("/api/jobs", json={"task_type": "defect.generate", - "input": {"prompt": "scratch", "image_asset_id": asset["id"]}, "parameters": {}}) + asset = ( + await system.client.post( + "/api/assets", files={"file": ("image.png", png_bytes, "image/png")} + ) + ).json() + response = await other_client.post( + "/api/jobs", + json={ + "task_type": "defect.generate", + "input": {"prompt": "scratch", "image_asset_id": asset["id"]}, + "parameters": {}, + }, + ) assert response.status_code == 404 async def test_generated_asset_changes_update_source_job_version_and_sse_snapshot(system): - from app.events import event_batch - job = (await system.client.post("/api/jobs", json={"task_type": "image.generate", - "input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0] + from app.services.events import event_batch + + job = ( + await system.client.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}}, + ) + ).json()["jobs"][0] coordinator = system.app.state.coordinator await coordinator.run_once(force=True) - system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "image.png"}]}) + system.provider.remote["remote-1"].update( + state="succeeded", result={"outputs": [{"path": "image.png"}]} + ) await coordinator.run_once(force=True) old = (await system.client.get(f"/api/jobs/{job['id']}")).json() asset_id = old["result_assets"][0]["id"] cursor = (await system.client.get("/api/jobs")).json()["cursor"] - await system.client.patch(f"/api/assets/{asset_id}", json={"name": "renamed.png", "favorite": True}) + await system.client.patch( + f"/api/assets/{asset_id}", json={"name": "renamed.png", "favorite": True} + ) renamed = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert renamed["version"] > old["version"] assert renamed["result_assets"][0]["name"] == "renamed.png" diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index baba064..498c49f 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -1,55 +1,104 @@ import httpx +from pathlib import Path +from tempfile import TemporaryDirectory +import pytest from conftest import PASSWORD +@pytest.fixture +def tmp_path(): + with TemporaryDirectory(prefix="cmvr-auth-") as directory: + yield Path(directory) + + async def test_login_cookie_csrf_and_revocation(system): - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client: + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as client: assert (await client.get("/api/auth/me")).status_code == 401 - denied = await client.post("/api/auth/login", json={"username": "admin", "password": "wrong"}) + denied = await client.post( + "/api/auth/login", json={"username": "admin", "password": "wrong"} + ) assert denied.status_code == 401 - login = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) + login = await client.post( + "/api/auth/login", json={"username": "admin", "password": PASSWORD} + ) assert login.status_code == 200 and "HttpOnly" in login.headers["set-cookie"] assert (await client.post("/api/auth/logout")).status_code == 403 - assert (await client.post("/api/auth/logout", headers={"X-CSRF-Token": b"\xc3\xa9"})).status_code == 403 + assert ( + await client.post("/api/auth/logout", headers={"X-CSRF-Token": b"\xc3\xa9"}) + ).status_code == 403 csrf = login.json()["csrf_token"] assert (await client.get("/api/auth/me")).json()["csrf_token"] == csrf cookie = client.cookies.get("cmvr_session") - assert (await client.post("/api/auth/logout", headers={"X-CSRF-Token": csrf})).status_code == 204 + assert ( + await client.post("/api/auth/logout", headers={"X-CSRF-Token": csrf}) + ).status_code == 204 client.cookies.set("cmvr_session", cookie) assert (await client.get("/api/auth/me")).status_code == 401 async def test_non_admin_cannot_create_users_and_public_registration_is_absent(other_client): - assert (await other_client.post("/api/auth/users", json={"username": "bob", "password": PASSWORD})).status_code == 403 + assert ( + await other_client.post("/api/auth/users", json={"username": "bob", "password": PASSWORD}) + ).status_code == 403 assert (await other_client.post("/api/auth/register", json={})).status_code == 404 async def test_requested_initial_admin_password_is_hashed_and_not_reset_on_restart(tmp_path): from sqlalchemy import select - from app.auth import verify_password - from app.config import Settings + from app.core.security import verify_password + from app.core.config import Settings from app.main import create_app from app.models import User from conftest import FakeProvider - settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'admin.sqlite3'}", - workspace_root=tmp_path, admin_username="admin", admin_password="123456", - run_coordinator=False, cookie_secure=False) + settings = Settings( + mode="test", + database_url=f"sqlite+aiosqlite:///{tmp_path / 'admin.sqlite3'}", + workspace_root=tmp_path, + admin_username="admin", + admin_password="123456", + run_coordinator=False, + cookie_secure=False, + ) app = create_app(settings, provider=FakeProvider()) async with app.router.lifespan_context(app): - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: - login = await client.post("/api/auth/login", json={"username": "admin", "password": "123456"}) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + login = await client.post( + "/api/auth/login", json={"username": "admin", "password": "123456"} + ) assert login.status_code == 200 and login.json()["user"]["role"] == "admin" async with app.state.db.session() as session: user = await session.scalar(select(User).where(User.username == "admin")) - assert user.password_hash != "123456" and verify_password("123456", user.password_hash) + assert user.password_hash != "123456" and verify_password( + "123456", user.password_hash + ) client.headers["X-CSRF-Token"] = login.json()["csrf_token"] - denied = await client.post("/api/auth/users", json={"username": "ordinary", "password": "123456"}) - assert denied.status_code == 422 # Ordinary accounts retain their stronger password policy. + created = await client.post( + "/api/auth/users", json={"username": "ordinary", "password": "123456"} + ) + assert created.status_code == 201 + denied = await client.post( + "/api/auth/users", json={"username": "too-short", "password": "12345"} + ) + assert denied.status_code == 422 settings.admin_password = PASSWORD restarted = create_app(settings, provider=FakeProvider()) async with restarted.router.lifespan_context(restarted): - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=restarted), base_url="http://test") as client: - assert (await client.post("/api/auth/login", json={"username": "admin", "password": "123456"})).status_code == 200 - assert (await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})).status_code == 401 + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=restarted), base_url="http://test" + ) as client: + assert ( + await client.post( + "/api/auth/login", json={"username": "admin", "password": "123456"} + ) + ).status_code == 200 + assert ( + await client.post( + "/api/auth/login", json={"username": "admin", "password": PASSWORD} + ) + ).status_code == 401 diff --git a/backend/tests/test_chinese_workflow_subtitles.py b/backend/tests/test_chinese_workflow_subtitles.py new file mode 100644 index 0000000..8e922d9 --- /dev/null +++ b/backend/tests/test_chinese_workflow_subtitles.py @@ -0,0 +1,35 @@ +"""用实际 FFmpeg 证明不同中文字形能渲染,避免仅验证字幕字符串而漏掉方框。""" +import os +from pathlib import Path +import shutil +from types import SimpleNamespace + +import pytest + + +@pytest.mark.asyncio +@pytest.mark.skipif(os.name != 'nt', reason='Windows Chinese font regression') +async def test_windows_workflow_renders_distinct_chinese_glyphs(tmp_path): + from app.adapters.media import compose_workflow, run_process + ffmpeg, ffprobe = shutil.which('ffmpeg'), shutil.which('ffprobe') + if not ffmpeg or not ffprobe or not (Path(os.environ.get('WINDIR', 'C:/Windows')) / 'Fonts/msyh.ttc').exists(): + pytest.skip('Real FFmpeg and Microsoft YaHei required') + settings = SimpleNamespace(workspace_root=tmp_path, ffmpeg_bin=ffmpeg, ffprobe_bin=ffprobe, + max_output_bytes=20 * 1024 * 1024) + source = tmp_path / 'black.mp4' + await run_process([ffmpeg,'-v','error','-f','lavfi','-i','color=c=black:s=320x180:r=24', + '-frames:v','48','-c:v','libx264','-pix_fmt','yuv420p',str(source)]) + plan = SimpleNamespace(fps=24,frames=48,canvas=(1920,1080), + clips=[{'start_frame':0,'duration_frames':48,'width':320,'height':180}], + spec={'profile':'landscape_1080_v1','shots':[{}],'render':{'audio':None,'fit':'contain', + 'subtitles':[{'start_frame':0,'end_frame':24,'text':'鲲鹏'}, + {'start_frame':24,'end_frame':48,'text':'北冥'}]}}) + result = await compose_workflow(plan,tmp_path/'render',settings=settings,sources=[source]) + samples=[] + for second in ('0.5','1.5'): + raw=await run_process([ffmpeg,'-v','error','-ss',second,'-i',str(result.outputs[0]), + '-vf','crop=400:160:760:900,format=gray','-frames:v','1','-f','rawvideo','-']) + samples.append(raw) + # 缺字方框对两段等长中文产生同一幅图;真正中文字形的笔画差异明显。 + assert len(samples[0]) == len(samples[1]) == 64000 + assert sum(abs(a-b)>30 for a,b in zip(samples[0],samples[1]))>300 diff --git a/backend/tests/test_core.py b/backend/tests/test_core.py index 250dee5..cfd9edf 100644 --- a/backend/tests/test_core.py +++ b/backend/tests/test_core.py @@ -2,15 +2,20 @@ import pytest def test_production_never_silently_uses_sqlite(tmp_path): - from app.config import Settings + from app.core.config import Settings + with pytest.raises(ValueError): - Settings(mode="production", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path) + Settings( + mode="production", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path + ) def test_mysql_url_preserves_hyphen_database_and_password_special_characters(tmp_path): - from app.config import Settings - settings = Settings(mode="production", mysql_user="visual", mysql_password="p@ss:/?#&", - workspace_root=tmp_path) + from app.core.config import Settings + + settings = Settings( + mode="production", mysql_user="visual", mysql_password="p@ss:/?#&", workspace_root=tmp_path + ) assert settings.sqlalchemy_url.database == "cmvr-visual" assert settings.sqlalchemy_url.password == "p@ss:/?#&" assert settings.sqlalchemy_url.drivername == "mysql+aiomysql" @@ -18,6 +23,7 @@ def test_mysql_url_preserves_hyphen_database_and_password_special_characters(tmp async def test_application_creates_only_prefixed_tables(system): from sqlalchemy import inspect + async with system.app.state.db.engine.connect() as connection: names = await connection.run_sync(lambda sync: inspect(sync).get_table_names()) assert names and all(name.startswith("visual_") for name in names) @@ -32,8 +38,9 @@ async def test_status_discloses_preview_mode_without_connection_details(system): async def test_only_one_coordinator_can_hold_the_workspace_lock(system): - from app.coordinator import Coordinator + from app.services.orchestration.coordinator import Coordinator from filelock import Timeout + first = Coordinator(system.settings, system.app.state.db, system.provider) second = Coordinator(system.settings, system.app.state.db, system.provider) try: diff --git a/backend/tests/test_core_v2.py b/backend/tests/test_core_v2.py index ea1d8eb..f67a203 100644 --- a/backend/tests/test_core_v2.py +++ b/backend/tests/test_core_v2.py @@ -2,48 +2,78 @@ import pytest from sqlalchemy import select from app.models import Job + @pytest.mark.asyncio async def test_submission_changed_body_conflicts_and_recovers(system): - c=system.client - body={"task_type":"image.generate","input":{"prompt":"first"}} - a=await c.post("/api/jobs",json=body,headers={"Idempotency-Key":"lost-response"}) - b=await c.post("/api/jobs",json=body,headers={"Idempotency-Key":"lost-response"}) - assert a.json()["jobs"][0]["id"]==b.json()["jobs"][0]["id"] - recovered=await c.get("/api/submissions/lost-response?operation=jobs.create") - assert recovered.status_code==200 - assert recovered.json()["resource_json"]["job_ids"]==[a.json()["jobs"][0]["id"]] - body["input"]["prompt"]="different" - assert (await c.post("/api/jobs",json=body,headers={"Idempotency-Key":"lost-response"})).status_code==409 + c = system.client + body = {"task_type": "image.generate", "input": {"prompt": "first"}} + a = await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "lost-response"}) + b = await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "lost-response"}) + assert a.json()["jobs"][0]["id"] == b.json()["jobs"][0]["id"] + recovered = await c.get("/api/submissions/lost-response?operation=jobs.create") + assert recovered.status_code == 200 + assert recovered.json()["resource_json"]["job_ids"] == [a.json()["jobs"][0]["id"]] + body["input"]["prompt"] = "different" + assert ( + await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "lost-response"}) + ).status_code == 409 + @pytest.mark.asyncio async def test_paused_cpu_never_reexecuted(system): - r=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"5"}}) + r = await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "5"}} + ) async with system.app.state.db.session() as s: - job=await s.get(Job,r.json()["jobs"][0]["id"]);job.state="needs_attention";await s.commit() + job = await s.get(Job, r.json()["jobs"][0]["id"]) + job.state = "needs_attention" + await s.commit() await system.app.state.coordinator.run_once(force=True) - assert system.provider.cpu_runs==0 + assert system.provider.cpu_runs == 0 + @pytest.mark.asyncio async def test_last_admin_and_password_revoke(system): - me=(await system.client.get("/api/auth/me")).json()["user"] - assert (await system.client.patch("/api/auth/users/"+me["id"],json={"disabled":True})).status_code==409 + me = (await system.client.get("/api/auth/me")).json()["user"] + assert ( + await system.client.patch("/api/auth/users/" + me["id"], json={"disabled": True}) + ).status_code == 409 from conftest import PASSWORD - assert (await system.client.post("/api/auth/password",json={"current_password":PASSWORD,"new_password":"Different-password-123!"})).status_code==200 - assert (await system.client.get("/api/auth/me")).status_code==401 + + assert ( + await system.client.post( + "/api/auth/password", + json={"current_password": PASSWORD, "new_password": "Different-password-123!"}, + ) + ).status_code == 200 + assert (await system.client.get("/api/auth/me")).status_code == 401 @pytest.mark.asyncio -@pytest.mark.parametrize("task_type",["math.solve","audio.speech"]) -async def test_cpu_batch_accepted_with_offline_gpu_and_waits_for_window(system,monkeypatch,task_type): - from app import resource_policy - monkeypatch.setattr(resource_policy,"execution_policy",lambda now=None:{"batch_open":False}) - system.settings.tts_base_url="http://private-tts" - async def offline():raise AssertionError("CPU batch must not depend on GPU capability negotiation") - monkeypatch.setattr(system.provider,"upstream_capabilities",offline,raising=False) - response=await system.client.post("/api/jobs",json={"task_type":task_type,"input":{"prompt":"x"},"execution_mode":"batch"}) - assert response.status_code==202,response.text +@pytest.mark.parametrize("task_type", ["math.solve", "audio.speech"]) +async def test_cpu_batch_accepted_with_offline_gpu_and_waits_for_window( + system, monkeypatch, task_type +): + from app.services.orchestration import resource_policy + + monkeypatch.setattr(resource_policy, "execution_policy", lambda now=None: {"batch_open": False}) + system.settings.tts_base_url = "http://private-tts" + + async def offline(): + raise AssertionError("CPU batch must not depend on GPU capability negotiation") + + monkeypatch.setattr(system.provider, "upstream_capabilities", offline, raising=False) + response = await system.client.post( + "/api/jobs", + json={"task_type": task_type, "input": {"prompt": "x"}, "execution_mode": "batch"}, + ) + assert response.status_code == 202, response.text await system.app.state.coordinator.run_once(force=True) - assert system.provider.cpu_runs==0 + assert system.provider.cpu_runs == 0 async with system.app.state.db.session() as session: - job=await session.get(Job,response.json()["jobs"][0]["id"]) - assert job.execution_mode=="batch" and job.attempt_count==0 and job.current_execution_id is None + job = await session.get(Job, response.json()["jobs"][0]["id"]) + assert ( + job.execution_mode == "batch" + and job.attempt_count == 0 + and job.current_execution_id is None + ) diff --git a/backend/tests/test_creation_editing.py b/backend/tests/test_creation_editing.py new file mode 100644 index 0000000..a404d99 --- /dev/null +++ b/backend/tests/test_creation_editing.py @@ -0,0 +1,633 @@ +import pytest +from app.core.config import Settings +from app.adapters.provider.contracts import capabilities, validate_arguments +from app.domain.tasks import GPU_TYPES +from app.services.jobs import input_ids + + +def test_video_edit_registered_and_capabilities(tmp_path): + settings = Settings( + mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path + ) + assert {"video.people.analyze", "video.replace"} <= GPU_TYPES + info = {row["task_type"]: row for row in capabilities(settings)} + assert info["video.replace"]["available"] is False + assert info["video.replace"]["defaults"]["preserve_audio"] is True + + +def test_reference_square_and_no_duplicates(tmp_path): + from app.domain.errors import MediaError + + settings = Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=tmp_path, + reference_generation_enabled=True, + ) + validate_arguments( + "image.reference.generate", + {"prompt": "test", "reference_asset_ids": ["a"]}, + {"width": 1024, "height": 1024}, + settings, + ) + with pytest.raises(MediaError): + validate_arguments( + "image.reference.generate", + {"prompt": "test", "reference_asset_ids": ["a", "a"]}, + {}, + settings, + ) + + +def test_nested_references_protect_every_selected_actor(): + assert input_ids( + { + "video_asset_id": "video", + "replacements": [ + {"person_id": "p1", "reference_asset_id": "a"}, + {"person_id": "p2", "reference_asset_id": "b"}, + ], + }, + {}, + ) == ["video", "a", "b"] + + +@pytest.mark.asyncio +async def test_reference_four_candidates(system, png_bytes): + system.settings.reference_generation_enabled = True + response = await system.client.post( + "/api/assets", files={"file": ("ref.png", png_bytes, "image/png")} + ) + assert response.status_code == 201, response.text + response = await system.client.post( + "/api/jobs", + json={ + "task_type": "image.reference.generate", + "input": {"prompt": "edit", "reference_asset_ids": [response.json()["id"]]}, + "parameters": {"width": 1024, "height": 1024}, + "count": 4, + }, + ) + assert response.status_code == 202, response.text + assert [j["parameters"]["seed"] for j in response.json()["jobs"]] == [42, 43, 44, 45] + + +@pytest.fixture +async def video_setup(system, png_bytes, tmp_path): + from pathlib import Path + from app.adapters.media import run_process + from app.models import Job, Asset + + tools = ( + Path(__file__).resolve().parents[2] + / ".local/tools/ffmpeg/ffmpeg-9.0.2-essentials_build/bin" + ) + system.settings.ffmpeg_bin = str(tools / "ffmpeg.exe") + system.settings.ffprobe_bin = str(tools / "ffprobe.exe") + system.settings.video_edit_enabled = True + path = tmp_path / "video.mp4" + await run_process( + [ + system.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=64x48:r=24:d=1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + str(path), + ] + ) + uploaded = await system.client.post( + "/api/assets", files={"file": ("source.mp4", path.read_bytes(), "video/mp4")} + ) + assert uploaded.status_code == 201, uploaded.text + image = await system.client.post( + "/api/assets", files={"file": ("ref.png", png_bytes, "image/png")} + ) + source_id, image_id = uploaded.json()["id"], image.json()["id"] + response = await system.client.post( + "/api/jobs", + json={"task_type": "video.people.analyze", "input": {"video_asset_id": source_id}}, + ) + assert response.status_code == 202, response.text + job_id = response.json()["jobs"][0]["id"] + runtime = system.app.state + async with runtime.db.session() as session: + source = await session.get(Asset, source_id) + job = await session.get(Job, job_id) + job.state, job.upstream_id = "succeeded", "a" * 32 + job.result_json = { + "profile": "wan-animate-replace-v1", + "analysis_token": "b" * 64, + "source_sha256": source.sha256, + "video": {"width": 64, "height": 48, "frames": 24, "fps": 24, "duration_seconds": 1.0}, + "poster_output_index": 0, + "people": [ + { + "id": f"person_{i:04}", + "label": f"Person {i}", + "thumbnail_output_index": i, + "first_frame": 0, + "last_frame": 23, + "confidence": 0.9, + "samples": [ + {"frame": frame, "bbox": [0.1, 0.1, 0.4, 0.9]} for frame in (0, 12, 23) + ], + } + for i in (1, 2) + ], + "warnings": [], + } + await session.commit() + return { + "task_type": "video.replace", + "input": { + "video_asset_id": source_id, + "analysis_job_id": job_id, + "prompt": "replace both", + "replacements": [ + {"person_id": f"person_{i:04}", "reference_asset_id": image_id, "prompt": str(i)} + for i in (1, 2) + ], + }, + } + + +@pytest.mark.asyncio +async def test_replace_freezes_two_people_and_all_asset_refs(system, video_setup): + from sqlalchemy import select + from app.models import Job, JobAsset + + response = await system.client.post("/api/jobs", json=video_setup) + assert response.status_code == 202, response.text + dto = response.json()["jobs"][0] + assert "_video_edit_binding" not in dto["parameters"] + async with system.app.state.db.session() as session: + job = await session.get(Job, dto["id"]) + assert job.parameters["_video_edit_binding"]["analysis_id"] == "a" * 32 + assert len(job.input_json["replacements"]) == 2 + assert set( + ( + await session.scalars(select(JobAsset.asset_id).where(JobAsset.job_id == job.id)) + ).all() + ) == { + video_setup["input"]["video_asset_id"], + video_setup["input"]["replacements"][0]["reference_asset_id"], + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "mutation", + [ + "source", + "sha", + "deleted", + "failed", + "owner", + "unknown", + "duplicate", + "params", + "token", + "truncated", + ], +) +async def test_replace_rejects_untrusted_analysis(system, other_client, video_setup, mutation): + from app.models import Job, utcnow + + async with system.app.state.db.session() as session: + job = await session.get(Job, video_setup["input"]["analysis_job_id"]) + if mutation == "source": + job.input_json = {"video_asset_id": "different"} + elif mutation == "sha": + job.result_json = job.result_json | {"source_sha256": "0" * 64} + elif mutation == "deleted": + job.deleted_at = utcnow() + elif mutation == "failed": + job.state = "failed" + elif mutation == "owner": + from sqlalchemy import select + from app.models import User + + job.owner_id = await session.scalar(select(User.id).where(User.username == "alice")) + elif mutation == "unknown": + video_setup["input"]["replacements"][0]["person_id"] = "person_9999" + elif mutation == "duplicate": + video_setup["input"]["replacements"][1]["person_id"] = "person_0001" + elif mutation == "params": + video_setup["parameters"] = {"max_pixels": 921600} + elif mutation == "truncated": + video = job.result_json["video"] | {"frames": 12, "duration_seconds": 0.5} + people = [ + p + | { + "last_frame": 11, + "samples": [{"frame": f, "bbox": [0.1, 0.1, 0.4, 0.9]} for f in (0, 5, 11)], + } + for p in job.result_json["people"] + ] + job.result_json = job.result_json | {"video": video, "people": people} + elif mutation == "token": + video_setup["input"]["analysis_token"] = "forged" + await session.commit() + response = await system.client.post("/api/jobs", json=video_setup) + assert response.status_code in {400, 404, 422}, response.text + + +def test_analysis_rejects_missing_preview_and_drops_paths(tmp_path): + from app.domain.video_editing import safe_analysis + from app.domain.errors import MediaError + + settings = Settings( + mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path + ) + data = { + "profile": "wan-animate-replace-v1", + "analysis_token": "a" * 64, + "source_sha256": "b" * 64, + "video": {"width": 64, "height": 48, "fps": 24, "frames": 24, "duration_seconds": 1.0}, + "poster_output_index": 2, + "people": [], + "warnings": [], + "manifest_path": "/private/secret", + } + assert "manifest_path" not in safe_analysis(data, settings, output_count=3) + with pytest.raises(MediaError): + safe_analysis(data, settings, output_count=2) + + +@pytest.mark.asyncio +async def test_real_provider_sends_both_actor_mappings(system, video_setup): + import httpx + from sqlalchemy import select + from app.models import Asset, Job + from app.adapters.provider.client import Provider + from app.domain.errors import MediaError + + response = await system.client.post("/api/jobs", json=video_setup) + assert response.status_code == 202, response.text + async with system.app.state.db.session() as session: + job = await session.get(Job, response.json()["jobs"][0]["id"]) + assets = ( + await session.scalars( + select(Asset).where( + Asset.id.in_( + [ + job.input_json["video_asset_id"], + job.input_json["replacements"][0]["reference_asset_id"], + ] + ) + ) + ) + ).all() + paths = {a.id: system.settings.asset_root / a.storage_key for a in assets} + parameters = dict(job.parameters) + binding = parameters.pop("_video_edit_binding") + system.settings.inference_api_key_file = None + provider = Provider(system.settings) + await provider.client.aclose() + provider.client = httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: httpx.Response( + 200, + json={ + "video_edit": { + "available": True, + "profile": "wan-animate-replace-v1", + "max_seconds": 120, + "max_people": 12, + "max_pixels": 921600, + "fps": 24, + } + }, + ) + ) + ) + work = system.settings.job_work_root / "provider" + work.mkdir(parents=True) + try: + payload = await provider.prepare_gpu_payload( + "video.replace", job.input_json, parameters, paths, work, analysis_binding=binding + ) + assert [r["person_id"] for r in payload["input"]["replacements"]] == [ + "person_0001", + "person_0002", + ] + assert [r["prompt"] for r in payload["input"]["replacements"]] == ["1", "2"] + assert payload["input"]["analysis_id"] == "a" * 32 + assert "analysis_job_id" not in payload["input"] + with pytest.raises(MediaError): + await provider.prepare_gpu_payload( + "video.replace", + job.input_json, + parameters, + paths, + work, + analysis_binding=binding | {"source_sha256": "0" * 64}, + ) + finally: + await provider.aclose() + + +@pytest.mark.asyncio +async def test_decoded_output_type_frames_fps_audio_are_checked(system, video_setup): + from copy import deepcopy + from app.models import Job, Asset + from app.services.video_editing import validate_video_output, validate_result_metadata + + response = await system.client.post("/api/jobs", json=video_setup) + async with system.app.state.db.session() as session: + job = await session.get(Job, response.json()["jobs"][0]["id"]) + asset = await session.get(Asset, job.input_json["video_asset_id"]) + source = system.settings.asset_root / asset.storage_key + job.upstream_result = { + "outputs": [{"path": "final.mp4"}], + "metadata": { + "profile": "wan-animate-replace-v1", + "person_ids": ["person_0001", "person_0002"], + "source_frames": 24, + "output_frames": 24, + "fps": 24, + "width": 64, + "height": 48, + "final_output_indices": [0], + "warnings": [], + }, + } + await validate_video_output(job, source, system.settings) + original = deepcopy(job.upstream_result) + for key, bad in ( + ("person_ids", ["person_0002"]), + ("output_frames", 12), + ("fps", 12), + ("final_output_indices", [5]), + ): + job.upstream_result = deepcopy(original) + job.upstream_result["metadata"][key] = bad + with pytest.raises(ValueError): + validate_result_metadata(job, job.upstream_result["outputs"], system.settings) + job.upstream_result = original + job.parameters = job.parameters | { + "_video_edit_binding": job.parameters["_video_edit_binding"] | {"source_has_audio": True} + } + with pytest.raises(ValueError, match="audio"): + await validate_video_output(job, source, system.settings) + + +@pytest.mark.asyncio +async def test_analysis_requires_visible_start_middle_end_samples(system, video_setup): + from app.models import Job + from app.domain.errors import MediaError + from app.domain.video_editing import safe_analysis + + async with system.app.state.db.session() as session: + job = await session.get(Job, video_setup["input"]["analysis_job_id"]) + job.result_json["people"][0]["samples"] = job.result_json["people"][0]["samples"][:1] + with pytest.raises(MediaError): + safe_analysis(job.result_json, system.settings) + + +@pytest.mark.asyncio +async def test_nested_replacement_inputs_block_physical_deletion(system, video_setup): + response = await system.client.post("/api/jobs", json=video_setup) + assert response.status_code == 202, response.text + for asset_id in [ + video_setup["input"]["video_asset_id"], + video_setup["input"]["replacements"][0]["reference_asset_id"], + ]: + result = await system.client.delete(f"/api/assets/{asset_id}") + assert result.status_code == 409, result.text + + +@pytest.mark.asyncio +async def test_preserves_original_short_audio_duration(system, video_setup, tmp_path): + from app.models import Job + from app.adapters.media import run_process + from app.services.video_editing import validate_video_output + + response = await system.client.post("/api/jobs", json=video_setup) + async with system.app.state.db.session() as session: + job = await session.get(Job, response.json()["jobs"][0]["id"]) + output = system.settings.job_work_root / "short-audio.mp4" + await run_process( + [ + system.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=64x48:r=24:d=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=0.5", + "-c:v", + "libx264", + "-c:a", + "aac", + "-pix_fmt", + "yuv420p", + str(output), + ] + ) + job.upstream_result = { + "outputs": [{"path": "final.mp4"}], + "metadata": { + "profile": "wan-animate-replace-v1", + "person_ids": ["person_0001", "person_0002"], + "source_frames": 24, + "output_frames": 24, + "fps": 24, + "width": 64, + "height": 48, + "final_output_indices": [0], + "warnings": [], + }, + } + job.parameters = job.parameters | { + "_video_edit_binding": job.parameters["_video_edit_binding"] + | {"source_has_audio": True, "source_audio_duration": 0.5} + } + await validate_video_output(job, output, system.settings) + + +@pytest.mark.asyncio +async def test_video_timeline_ignores_longer_audio_tail(system, video_setup, tmp_path): + from hashlib import sha256 + from app.adapters.media import run_process + from app.models import Asset, Job + from app.adapters.provider.client import Provider + import httpx + + system.settings.video_edit_max_seconds = 1 + rendered = tmp_path / "long-audio.mp4" + await run_process( + [ + system.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=64x48:r=24:d=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=2", + "-c:v", + "libx264", + "-c:a", + "aac", + "-pix_fmt", + "yuv420p", + str(rendered), + ] + ) + async with system.app.state.db.session() as session: + asset = await session.get(Asset, video_setup["input"]["video_asset_id"]) + source = system.settings.asset_root / asset.storage_key + source.write_bytes(rendered.read_bytes()) + asset.sha256 = sha256(source.read_bytes()).hexdigest() + asset.duration_seconds = 2.0 + analysis = await session.get(Job, video_setup["input"]["analysis_job_id"]) + analysis.result_json = analysis.result_json | {"source_sha256": asset.sha256} + await session.commit() + response = await system.client.post("/api/jobs", json=video_setup) + assert response.status_code == 202, response.text + async with system.app.state.db.session() as session: + job = await session.get(Job, response.json()["jobs"][0]["id"]) + binding = job.parameters["_video_edit_binding"] + assert binding["video"]["duration_seconds"] == 1.0 + assert binding["source_audio_duration"] == pytest.approx(2, abs=0.05) + system.settings.inference_api_key_file = None + provider = Provider(system.settings) + await provider.client.aclose() + provider.client = httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: httpx.Response( + 200, + json={ + "video_edit": { + "available": True, + "profile": "wan-animate-replace-v1", + "max_seconds": 1, + "max_people": 12, + "max_pixels": 399360, + "fps": 24, + } + }, + ) + ) + ) + work = system.settings.job_work_root / "long-audio" + work.mkdir(parents=True) + try: + payload = await provider.prepare_gpu_payload( + "video.people.analyze", {"video_asset_id": asset.id}, {}, {asset.id: source}, work + ) + assert payload["input"]["video_path"] == str(source) + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "change", + [{"prompt": ""}, {"prompt": " \n"}, {"mask_expand_pixels": 65}, {"mask_feather_pixels": 128}], +) +async def test_business_and_provider_share_raw_prompt_mask_contract(tmp_path, change): + from app.adapters.provider.client import Provider + from app.domain.errors import MediaError + + settings = Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=tmp_path, + video_edit_enabled=True, + ) + inputs = { + "video_asset_id": "source", + "analysis_job_id": "analysis", + "prompt": "replace", + "replacements": [{"person_id": "person_0001", "reference_asset_id": "image"}], + } + parameters = {} + if "prompt" in change: + inputs.update(change) + else: + parameters.update(change) + with pytest.raises(MediaError, match="输入|参数|提示"): + validate_arguments("video.replace", inputs, parameters, settings) + provider = Provider(settings) + try: + with pytest.raises(MediaError): + await provider.prepare_gpu_payload("video.replace", inputs, parameters, {}, tmp_path) + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "local,remote,expected", + [(399360, 921600, 399360), (921600, 399360, 399360), (921600, 921600, 921600)], +) +async def test_effective_pixel_budget_is_shared_by_both_tasks(system, local, remote, expected): + from app.services.system import task_capabilities + + system.settings.video_edit_enabled = True + system.settings.video_edit_max_pixels = local + + async def capabilities(): + return { + "video_edit": { + "available": True, + "profile": "wan-animate-replace-v1", + "max_seconds": 120, + "max_people": 12, + "max_pixels": remote, + "fps": 24, + } + } + + system.provider.upstream_capabilities = capabilities + rows = {row["task_type"]: row for row in await task_capabilities(system.app.state)} + for task in ("video.people.analyze", "video.replace"): + assert rows[task]["available"] is True + assert rows[task]["constraints"]["max_pixels"] == expected + + +@pytest.mark.parametrize("pixels", [399360, 921600]) +def test_video_pixel_budget_loads_from_environment(monkeypatch, tmp_path, pixels): + monkeypatch.setenv("CMVR_MODE", "test") + monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:") + monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path)) + monkeypatch.setenv("VIDEO_EDIT_MAX_PIXELS", str(pixels)) + assert Settings.from_env().video_edit_max_pixels == pixels + + +def test_mask_upper_bound_matches_raw_protocol(tmp_path): + from app.domain.errors import MediaError + + settings = Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=tmp_path, + video_edit_enabled=True, + ) + inputs = { + "video_asset_id": "source", + "analysis_job_id": "analysis", + "prompt": "replace", + "replacements": [{"person_id": "person_0001", "reference_asset_id": "image"}], + } + validate_arguments( + "video.replace", inputs, {"mask_expand_pixels": 64, "mask_feather_pixels": 64}, settings + ) + with pytest.raises(MediaError): + validate_arguments("video.replace", inputs, {"max_pixels": 921600}, settings) diff --git a/backend/tests/test_editor_composition_real.py b/backend/tests/test_editor_composition_real.py new file mode 100644 index 0000000..956356f --- /dev/null +++ b/backend/tests/test_editor_composition_real.py @@ -0,0 +1,279 @@ +"""真实自动故事到CPU/FFmpeg的交接,模型保持离线。""" + +from copy import deepcopy +from pathlib import Path +import io +import shutil +import wave +import pytest +from sqlalchemy import select +from app.models import Asset, Job, WorkflowStep +from app.adapters.media import run_process, inspect_video_track +from app.adapters.provider.client import Provider +from app.services.orchestration.workflow_engine import advance_run + + +def ffmpeg_settings(settings): + local = Path(__file__).resolve().parents[2] / ".local" / "tools" / "ffmpeg" + for name in ("ffmpeg", "ffprobe"): + binary = shutil.which(getattr(settings, name + "_bin")) or next( + (str(p) for p in local.glob("*/bin/" + name + ".exe")), None + ) + if not binary: + pytest.skip("FFmpeg required") + setattr(settings, name + "_bin", binary) + + +async def prepare_compose(system): + ffmpeg_settings(system.settings) + for name in ( + "real-compose", + "old-retry", + "bad-sha", + "bad-width", + "bad-audio", + "bad-fps", + "short-source", + ): + (system.settings.job_work_root / name).mkdir(parents=True, exist_ok=True) + client = system.client + ids = [] + for i, (width, height) in enumerate([(1280, 704), (320, 240)]): + path = system.settings.job_work_root / f"source-{i}.mp4" + path.parent.mkdir(parents=True, exist_ok=True) + await run_process( + [ + system.settings.ffmpeg_bin, + "-nostdin", + "-v", + "error", + "-f", + "lavfi", + "-i", + f"color=c=blue:s={width}x{height}:r=24", + "-frames:v", + "24", + "-c:v", + "libx264", + "-threads", + "1", + "-pix_fmt", + "yuv420p", + str(path), + ], + timeout=20, + ) + uploaded = await client.post( + "/api/assets", files={"file": (path.name, path.read_bytes(), "video/mp4")} + ) + assert uploaded.status_code == 201, uploaded.text + ids.append(uploaded.json()["id"]) + audio = io.BytesIO() + with wave.open(audio, "wb") as stream: + stream.setnchannels(1) + stream.setsampwidth(2) + stream.setframerate(48000) + stream.writeframes(b"\0\0" * 96000) + uploaded = await client.post( + "/api/assets", files={"file": ("audio.wav", audio.getvalue(), "audio/wav")} + ) + assert uploaded.status_code == 201, uploaded.text + audio_id = uploaded.json()["id"] + response = await client.post( + "/api/stories", + json={ + "name": "Real composition", + "create_folder": False, + "spec": { + "schema_version": 3, + "shots": [ + { + "id": f"{i + 1:032x}", + "visual_prompt": "Offline source", + "edit": {"start_frame": 0, "duration_frames": 24}, + } + for i in range(2) + ], + }, + }, + ) + assert response.status_code == 201, response.text + draft = response.json()["id"] + m = (await client.get("/api/editors/" + draft)).json()["manifest"] + for sid, aid in zip(m["shot_ids"], ids): + m["bindings"]["video:" + sid] = { + "asset_id": aid, + "sha256": "0" * 64, + "kind": "video", + "source": "manual", + } + m["audio"].update( + mode="manual_track", + track={ + "asset_id": audio_id, + "source_start_ms": 0, + "source_end_ms": 2000, + "offset_frame": 0, + "short_policy": "silence", + }, + ) + saved = await client.post( + "/api/editors/" + draft + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save"}, + ) + assert saved.status_code == 200, saved.text + body = {"expected_version": 2, "output_goal": "film"} + planned = await client.post("/api/editors/" + draft + "/plan", json=body) + assert planned.status_code == 200, planned.text + body["expected_plan_hash"] = planned.json()["plan_hash"] + started = await client.post( + "/api/editors/" + draft + "/runs", json=body, headers={"Idempotency-Key": "run"} + ) + assert started.status_code == 202, started.text + rid = started.json()["run"]["id"] + async with system.app.state.db.session() as session: + await advance_run(session, rid, system.settings) + await session.commit() + job = await session.scalar(select(Job).where(Job.run_id == rid)) + assert job.task_type == "video.compose" + assets = { + a.id: system.settings.asset_root / a.storage_key + for a in ( + await session.scalars(select(Asset).where(Asset.id.in_(ids + [audio_id]))) + ).all() + } + return draft, rid, body, job, assets, planned.json() + + +async def test_auto_story_real_cpu_composition_freezes_source_facts_and_audio(system): + draft, rid, body, job, assets, plan = await prepare_compose(system) + provider = Provider(system.settings) + frozen = deepcopy(job.parameters) + try: + result = await provider.run_cpu( + "video.compose", + job.input_json, + job.parameters, + assets, + system.settings.job_work_root / "real-compose", + ) + finally: + await provider.aclose() + track = await inspect_video_track(result.outputs[0], system.settings) + assert (track["frames"], track["fps"], track["width"], track["height"]) == (48, 24, 1920, 1080) + clips = job.parameters["render_inputs"]["clips"] + assert [(c["width"], c["height"], c["fps"], c["source_frames"]) for c in clips] == [ + (1280, 704, 24, 24), + (320, 240, 24, 24), + ] + aid = job.input_json["audio_asset_id"] + assert job.parameters["render_inputs"]["audio"] == { + "asset_id": aid, + "sha256": plan["asset_sha256"][aid], + } + assert job.parameters == frozen + replay = await system.client.post( + "/api/editors/" + draft + "/runs", json=body, headers={"Idempotency-Key": "run"} + ) + assert replay.status_code == 202 and replay.json()["run"]["id"] == rid, replay.text + async with system.app.state.db.session() as session: + step = await session.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == rid, WorkflowStep.step_key == "compose" + ) + ) + assert step.resolved_input_json["parameters"] == frozen + assert step.resolved_input_json["input_sha256"][aid] == plan["asset_sha256"][aid] + + +async def test_old_frozen_story_retry_recovers_missing_dimensions_only_after_sha_check(system): + from app.domain.errors import MediaError + from app.services.orchestration.editor_engine import create_editor_child + from app.models import WorkflowRun + + _, rid, _, job, assets, _ = await prepare_compose(system) + old = deepcopy(job.parameters) + for clip in old["render_inputs"]["clips"]: + for key in ("width", "height", "fps", "source_frames"): + clip.pop(key, None) + async with system.app.state.db.session() as session: + step = await session.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == rid, WorkflowStep.step_key == "compose" + ) + ) + resolved = deepcopy(step.resolved_input_json) + resolved["parameters"] = old + step.resolved_input_json = resolved + await create_editor_child( + session, await session.get(WorkflowRun, rid), step, system.settings + ) + await session.commit() + retry = await session.get(Job, step.selected_job_id) + snapshot = deepcopy(retry.parameters) + provider = Provider(system.settings) + try: + result = await provider.run_cpu( + "video.compose", + retry.input_json, + retry.parameters, + assets, + system.settings.job_work_root / "old-retry", + ) + assert (await inspect_video_track(result.outputs[0], system.settings))["frames"] == 48 + assert retry.parameters == snapshot + bad = deepcopy(old) + bad["render_inputs"]["clips"][0]["sha256"] = "0" * 64 + with pytest.raises(MediaError, match="SHA"): + await provider.run_cpu( + "video.compose", + retry.input_json, + bad, + assets, + system.settings.job_work_root / "bad-sha", + ) + conflict = deepcopy(old) + conflict["render_inputs"]["clips"][0]["width"] = 99 + with pytest.raises(MediaError): + await provider.run_cpu( + "video.compose", + retry.input_json, + conflict, + assets, + system.settings.job_work_root / "bad-width", + ) + fps_conflict = deepcopy(old) + fps_conflict["render_inputs"]["clips"][0]["fps"] = 30 + with pytest.raises(MediaError): + await provider.run_cpu( + "video.compose", + retry.input_json, + fps_conflict, + assets, + system.settings.job_work_root / "bad-fps", + ) + short = deepcopy(old) + short["story_spec"]["shots"][0]["edit"]["duration_frames"] = 48 + short["story_spec"]["render"]["total_frames"] = 72 + short["render_inputs"]["clips"][0]["duration_frames"] = 48 + with pytest.raises(MediaError): + await provider.run_cpu( + "video.compose", + retry.input_json, + short, + assets, + system.settings.job_work_root / "short-source", + ) + audio_path = assets[retry.input_json["audio_asset_id"]] + audio_path.write_bytes(audio_path.read_bytes() + b"changed") + with pytest.raises(MediaError, match="SHA"): + await provider.run_cpu( + "video.compose", + retry.input_json, + old, + assets, + system.settings.job_work_root / "bad-audio", + ) + finally: + await provider.aclose() diff --git a/backend/tests/test_editor_engine.py b/backend/tests/test_editor_engine.py new file mode 100644 index 0000000..3557069 --- /dev/null +++ b/backend/tests/test_editor_engine.py @@ -0,0 +1,914 @@ +from types import SimpleNamespace +import pytest +from app.services.orchestration.editor_engine import build_recipes + + +def manifest(n=2): + ids = [f"{i + 1:032x}" for i in range(n)] + return dict( + schema_version=1, + source_kind="workflow", + shot_ids=ids, + bindings={}, + audio={"mode": "silent", "segments": []}, + captions={"mode": "none", "cues": []}, + spec={ + "schema_version": 2, + "profile": "landscape_1080_v1", + "shots": [ + { + "key": f"shot_{i + 1}", + "prompt": "mountain", + "duration_frames": 120, + "parameters": {"seed": 42}, + } + for i in range(n) + ], + "render": {"fps": 24, "audio": None, "subtitles": []}, + }, + ) + + +def test_media_target_ancestor_closure_and_film_compose(): + m = manifest(8) + steps = build_recipes( + m, {}, {"output_goal": "media", "targets": ["video:" + m["shot_ids"][3]]}, SimpleNamespace() + ) + assert [x["key"] for x in steps] == ["frame_0004", "video_0004"] + assert steps[-1]["dependencies"] == ["frame_0004"] + assert build_recipes(m, {}, {"output_goal": "film"}, SimpleNamespace())[-1]["key"] == "compose" + + +def test_reused_video_does_not_require_frame_or_old_job(): + m = manifest() + key = "video:" + m["shot_ids"][0] + binding = {"asset_id": "a", "sha256": "sha", "kind": "video", "source": "manual"} + steps = build_recipes( + m, {key: binding}, {"output_goal": "media", "targets": [key]}, SimpleNamespace() + ) + assert len(steps) == 1 and steps[0]["reuse"] == binding + assert steps[0]["dependencies"] == [] + + +def test_force_only_explicit_stage(): + m = manifest(1) + key = "video:" + m["shot_ids"][0] + steps = build_recipes( + m, + {key: {"asset_id": "a", "source": "manual"}}, + {"output_goal": "media", "force": [key]}, + SimpleNamespace(), + ) + assert [s["key"] for s in steps] == ["frame_0001", "video_0001"] + assert steps[-1]["forced"] is True and not steps[0]["forced"] + + +async def editor(system, n=1): + response = await system.client.post( + "/api/workflows", json={"name": "Editor", "spec": manifest(n)["spec"]} + ) + assert response.status_code == 201, response.text + id = response.json()["id"] + m = (await system.client.get("/api/editors/" + id)).json()["manifest"] + return id, m + + +async def test_media_reuse_finishes_without_jobs_or_compose_and_applies(system, png_bytes): + from sqlalchemy import select + from app.models import WorkflowRun, WorkflowStep, Job, WorkflowDraft + from app.services.orchestration.workflow_engine import advance_run + + c = system.client + id, m = await editor(system) + a = await c.post("/api/assets", files={"file": ("frame.png", png_bytes, "image/png")}) + aid = a.json()["id"] + sid = m["shot_ids"][0] + m["bindings"]["frame:" + sid] = { + "asset_id": aid, + "sha256": "0" * 64, + "kind": "image", + "source": "manual", + } + saved = await c.post( + "/api/editors/" + id + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save-frame"}, + ) + assert saved.status_code == 200, saved.text + body = {"expected_version": 2, "output_goal": "media", "targets": ["frame:" + sid]} + plan = await c.post("/api/editors/" + id + "/plan", json=body) + assert plan.status_code == 200, plan.text + assert plan.json()["steps"][0]["status"] == "reuse" + body["expected_plan_hash"] = plan.json()["plan_hash"] + run = await c.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "media"} + ) + assert run.status_code == 202, run.text + rid = run.json()["run"]["id"] + again = await c.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "media"} + ) + assert again.json()["run"]["id"] == rid + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + await s.commit() + r = await s.get(WorkflowRun, rid) + assert r.state == "succeeded" and r.apply_state == "applied" + assert r.current_output_asset_id is None + steps = (await s.scalars(select(WorkflowStep).where(WorkflowStep.run_id == rid))).all() + assert len(steps) == 1 and steps[0].selected_job_id is None + assert not (await s.scalars(select(Job).where(Job.run_id == rid))).all() + assert (await s.get(WorkflowDraft, id)).version == 3 + snapshot = await c.get("/api/workflow-runs/" + rid) + assert snapshot.status_code == 200, snapshot.text + assert snapshot.json()["run"]["output_goal"] == "media" + assert snapshot.json()["steps"][0]["result"]["asset_id"] == aid + + +async def test_direct_frame_job_frozen_input_pause_cancel_and_no_candidate(system): + from sqlalchemy import select, func + from app.models import WorkflowRun, WorkflowStep, Job, ShotCandidate + from app.services.orchestration.workflow_engine import advance_run + from app.services.workflows import control_run + + c = system.client + id, m = await editor(system) + body = { + "expected_version": 1, + "output_goal": "media", + "targets": ["frame:" + m["shot_ids"][0]], + "force": ["frame:" + m["shot_ids"][0]], + } + plan = await c.post("/api/editors/" + id + "/plan", json=body) + assert plan.status_code == 200, plan.text + body["expected_plan_hash"] = plan.json()["plan_hash"] + response = await c.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "new-frame"} + ) + assert response.status_code == 202, response.text + rid = response.json()["run"]["id"] + async with system.app.state.db.session() as s: + r = await s.get(WorkflowRun, rid) + await control_run(s, r, "pause") + await advance_run(s, rid, system.settings) + assert not (await s.scalars(select(Job).where(Job.run_id == rid))).all() + await control_run(s, r, "run") + await advance_run(s, rid, system.settings) + await s.commit() + step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) + job = await s.get(Job, step.selected_job_id) + assert job.task_type == "image.generate" and job.step_key == "frame_0001" + assert job.parameters["seed"] == step.recipe_json["parameters"]["seed"] + assert step.resolved_input_json["input"] == job.input_json + assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 0 + await control_run(s, r, "cancel") + await advance_run(s, rid, system.settings) + await s.commit() + assert r.state == "cancelled" + + +def test_generated_video_reuse_depends_on_actual_frame_and_trim_not_source_request(): + m = manifest(1) + sid = m["shot_ids"][0] + frame = {"asset_id": "f", "sha256": "a" * 64, "kind": "image", "source": "manual"} + first = build_recipes(m, {"frame:" + sid: frame}, {"output_goal": "film"}, SimpleNamespace()) + context = next(s["context_hash"] for s in first if s["key"] == "video_0001") + video = { + "asset_id": "v", + "sha256": "b" * 64, + "kind": "video", + "source": "generated", + "context_hash": context, + } + recipes = build_recipes( + m, + {"frame:" + sid: frame, "video:" + sid: video}, + {"output_goal": "media"}, + SimpleNamespace(), + ) + assert len(recipes) == 1 and recipes[0]["reuse"] + frame["sha256"] = "c" * 64 + recipes = build_recipes( + m, + {"frame:" + sid: frame, "video:" + sid: video}, + {"output_goal": "media"}, + SimpleNamespace(), + ) + assert len(recipes) == 2 and not recipes[-1]["reuse"] + + +async def start_frame(system): + id, m = await editor(system) + body = { + "expected_version": 1, + "output_goal": "media", + "targets": ["frame:" + m["shot_ids"][0]], + "force": ["frame:" + m["shot_ids"][0]], + } + p = await system.client.post("/api/editors/" + id + "/plan", json=body) + body["expected_plan_hash"] = p.json()["plan_hash"] + r = await system.client.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "frame-run"} + ) + assert r.status_code == 202, r.text + return id, r.json()["run"]["id"], body + + +async def test_retry_preserves_frozen_seed_and_ignores_late_attempt(system): + from sqlalchemy import select + from app.models import WorkflowRun, WorkflowStep, Job + from app.services.orchestration.workflow_engine import advance_run + + id, rid, body = await start_frame(system) + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) + old = await s.get(Job, step.selected_job_id) + old.state = "failed" + await advance_run(s, rid, system.settings) + await s.commit() + r = await s.get(WorkflowRun, rid) + version = r.version + old_id = old.id + frozen = step.resolved_input_json + response = await system.client.post( + f"/api/workflow-runs/{rid}/steps/frame_0001/retry", + json={"expected_run_version": version, "target_job_id": old_id}, + headers={"Idempotency-Key": "retry-frame"}, + ) + assert response.status_code == 202, response.text + async with system.app.state.db.session() as s: + step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) + new = await s.get(Job, step.selected_job_id) + assert new.id != old_id and new.parameters == frozen["parameters"] + assert step.resolved_input_json == frozen + old = await s.get(Job, old_id) + old.state = "succeeded" + await advance_run(s, rid, system.settings) + assert step.state == "ready" and step.selected_job_id == new.id + replay = await system.client.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "frame-run"} + ) + assert replay.json()["run"]["id"] == rid + + +async def test_frame_result_materialized_and_auto_apply_conflict_does_not_fail_media(system): + import io + from PIL import Image + from sqlalchemy import select + from app.models import WorkflowRun, WorkflowStep, Job, Asset, WorkflowDraft + from app.services.orchestration.workflow_engine import advance_run + + id, rid, _ = await start_frame(system) + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + await s.commit() + step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) + jid = step.selected_job_id + data = io.BytesIO() + Image.new("RGB", (1280, 704), "red").save(data, format="PNG") + response = await system.client.post( + "/api/assets", files={"file": ("result.png", data.getvalue(), "image/png")} + ) + aid = response.json()["id"] + async with system.app.state.db.session() as s: + a = await s.get(Asset, aid) + a.source_job_id = jid + a.source_output_index = 0 + j = await s.get(Job, jid) + j.state = "succeeded" + d = await s.get(WorkflowDraft, id) + d.version += 1 + await advance_run(s, rid, system.settings) + await s.commit() + r = await s.get(WorkflowRun, rid) + assert r.state == "succeeded" and r.apply_state == "conflict" + b = next(iter(r.result_manifest["bindings"].values())) + assert b["asset_id"] == aid and b["source_job_id"] == jid and b["input_hash"] + assert d.editor_manifest is None + + +def test_eight_shots_only_changed_video_and_enough_source_reused(): + from copy import deepcopy + + m = manifest(8) + reusable = {} + for sid in m["shot_ids"]: + reusable["frame:" + sid] = { + "asset_id": "f" + sid, + "sha256": "a" * 64, + "kind": "image", + "source": "manual", + } + reusable["video:" + sid] = { + "asset_id": "v" + sid, + "sha256": "b" * 64, + "kind": "video", + "source": "manual", + } + target = "video:" + m["shot_ids"][4] + recipes = build_recipes( + m, reusable, {"output_goal": "film", "force": [target]}, SimpleNamespace() + ) + assert len([s for s in recipes if s["kind"] == "video.generate" and not s["reuse"]]) == 1 + assert len([s for s in recipes if s["kind"] == "image.generate" and not s["reuse"]]) == 0 + story = deepcopy(m) + story["spec"]["shots"][0]["duration_frames"] = 72 + assert next( + s + for s in build_recipes(story, reusable, {"output_goal": "film"}, SimpleNamespace()) + if s["key"] == "video_0001" + )["reuse"] + + +async def test_legacy_patch_and_run_require_editor(system): + id, m = await editor(system) + r = await system.client.post( + "/api/editors/" + id + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save"}, + ) + assert r.status_code == 200, r.text + r = await system.client.patch( + "/api/workflows/" + id, json={"name": "legacy"}, headers={"If-Match": "2"} + ) + assert r.status_code == 409 and r.json()["detail"]["code"] == "editor_required" + r = await system.client.post( + "/api/workflows/" + id + "/runs", + json={"expected_version": 2, "draft_revision": 2}, + headers={"Idempotency-Key": "legacy"}, + ) + assert r.status_code == 409 and r.json()["detail"]["code"] == "editor_required" + + +def test_narration_typed_dag_and_models_are_frozen_before_video(): + m = manifest(1) + sid = m["shot_ids"][0] + m["audio"] = { + "mode": "generated_narration", + "voice": "test", + "speed": 1.2, + "segments": [{"id": "f" * 32, "shot_id": sid, "text": ""}], + } + m["captions"]["mode"] = "ai_script" + settings = SimpleNamespace(qwen_model="script-v1", tts_model="speech-v1") + recipes = build_recipes(m, {}, {"output_goal": "film"}, settings) + bykey = {r["key"]: r for r in recipes} + assert bykey["script"]["kind"] == "text.script.generate" + assert bykey["script"]["parameters"]["model"] == "script-v1" + assert bykey["speech_0001"]["dependencies"] == ["script"] + assert bykey["speech_0001"]["parameters"] == { + "model": "speech-v1", + "voice": "test", + "speed": 1.2, + } + assert "speech_0001" in bykey["video_0001"]["dependencies"] + assert bykey["assemble"]["dependencies"] == ["speech_0001"] + assert {"assemble", "captions", "video_0001"} == set(bykey["compose"]["dependencies"]) + + +def test_manual_frame_only_prepared_when_consumed_by_video(): + m = manifest(1) + sid = m["shot_ids"][0] + frame = { + "asset_id": "f", + "sha256": "a" * 64, + "kind": "image", + "source": "manual", + "_width": 16, + "_height": 12, + } + only = build_recipes( + m, + {"frame:" + sid: frame}, + {"output_goal": "media", "targets": ["frame:" + sid]}, + SimpleNamespace(), + ) + assert only[0]["reuse"] and "_width" not in only[0]["reuse"] + video = build_recipes(m, {"frame:" + sid: frame}, {"output_goal": "media"}, SimpleNamespace()) + assert video[0]["kind"] == "image.prepare_frame" and video[0]["reuse"] is None + assert video[0]["input"] == {"image_asset_id": "f"} + + +@pytest.mark.parametrize("timeline_frames", [25, 120]) +@pytest.mark.parametrize("source_kind", ["workflow", "story"]) +async def test_film_script_speech_captions_assemble_compose_complete_cycle( + system, monkeypatch, png_bytes, timeline_frames, source_kind +): + """模型及FFmpeg探测为边界替身,真实DB/Job准入/冻结/应用全链路。""" + import hashlib + from uuid import uuid4 + from unittest.mock import AsyncMock + from sqlalchemy import select + from app.models import WorkflowRun, WorkflowStep, WorkflowDraft, Job, Asset + from app.services.orchestration.workflow_engine import advance_run + + monkeypatch.setattr("app.services.stories.candidates.validate_video", AsyncMock()) + monkeypatch.setattr( + "app.adapters.media.inspect_video_track", + AsyncMock( + return_value={"width": 1280, "height": 704, "fps": 24, "frames": 120, "duration": 5.0} + ), + ) + system.settings.tts_base_url = "http://mock-tts" + if source_kind == "story": + response = await system.client.post( + "/api/stories", + json={ + "name": "Auto story", + "create_folder": False, + "spec": { + "schema_version": 3, + "shots": [{"id": "a" * 32, "visual_prompt": "mountain"}], + }, + }, + ) + assert response.status_code == 201, response.text + id = response.json()["id"] + m = (await system.client.get("/api/editors/" + id)).json()["manifest"] + else: + id, m = await editor(system) + sid = m["shot_ids"][0] + segment = m["audio"]["segments"][0]["id"] + m["audio"]["mode"] = "generated_narration" + m["audio"]["voice"] = system.settings.tts_voices[0] + m["captions"]["mode"] = "ai_script" + if source_kind == "story": + m["spec"]["shots"][0]["edit"]["duration_frames"] = timeline_frames + else: + m["spec"]["shots"][0]["duration_frames"] = timeline_frames + response = await system.client.post( + "/api/editors/" + id + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "narration"}, + ) + assert response.status_code == 200, response.text + body = {"expected_version": 2, "output_goal": "film"} + p = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert p.status_code == 200, p.text + body["expected_plan_hash"] = p.json()["plan_hash"] + response = await system.client.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "film"} + ) + assert response.status_code == 202, response.text + rid = response.json()["run"]["id"] + seen = [] + for tick in range(12): + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + r = await s.get(WorkflowRun, rid) + assert r.state != "blocked", r.error_json + jobs = ( + await s.scalars(select(Job).where(Job.run_id == rid, Job.state != "succeeded")) + ).all() + for j in jobs: + seen.append(j.task_type) + if j.task_type == "video.generate": + assert "audio.speech" in seen and j.input_json["image_asset_id"] + if j.task_type == "audio.speech": + assert j.input_json["prompt"] == "测试旁白" + if j.task_type == "video.compose": + assert (j.parameters.get("workflow_spec") or j.parameters["story_spec"])[ + "render" + ]["subtitles"][0]["text"] == "测试旁白" + assert j.input_json["audio_asset_id"] + key = "mock/" + uuid4().hex + ".bin" + path = system.settings.asset_root / key + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(png_bytes) + kind = { + "image.generate": "image", + "text.script.generate": "json", + "audio.speech": "audio", + "audio.assemble": "audio", + "video.generate": "video", + "video.compose": "video", + }[j.task_type] + duration = ( + 0.5 + if j.task_type == "audio.speech" + else timeline_frames / 24 + if j.task_type in {"audio.assemble", "video.compose"} + else 5.0 + ) + a = Asset( + owner_id=r.owner_id, + name="mock output", + storage_key=key, + kind=kind, + mime_type="application/octet-stream", + size_bytes=len(png_bytes), + sha256=hashlib.sha256(png_bytes).hexdigest(), + width=1280, + height=704, + duration_seconds=duration if kind in {"audio", "video"} else None, + source_job_id=j.id, + source_output_index=0, + ) + s.add(a) + j.state = "succeeded" + if j.task_type == "text.script.generate": + j.result_json = {"segments": [{"shot_id": sid, "text": "测试旁白"}]} + await s.commit() + if r.state == "succeeded": + break + async with system.app.state.db.session() as s: + r = await s.get(WorkflowRun, rid) + assert r.state == "succeeded" and r.apply_state == "applied" + assert set(seen) == { + "text.script.generate", + "image.generate", + "audio.speech", + "video.generate", + "audio.assemble", + "video.compose", + } + assert r.result_manifest["audio"]["segments"][0]["text"] == "测试旁白" + assert r.result_manifest["bindings"]["audio:" + segment]["duration_frames"] == 12 + assert r.result_manifest["captions"]["cues"][0]["segment_id"] == segment + assert (await s.get(WorkflowDraft, id)).current_run_id == rid + compose = await s.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == rid, WorkflowStep.step_key == "compose" + ) + ) + assert compose.resolved_input_json["input_sha256"] + assert ( + r.spec_snapshot["render"]["audio"] is None + and r.spec_snapshot["render"]["subtitles"] == [] + ) + + # 后续仅编辑字幕:真实产物全部恢复,配音及镜头无新的模型任务。 + current = (await system.client.get("/api/editors/" + id)).json() + edited = current["manifest"] + edited["captions"]["cues"][0].update(text="人工修改字幕", text_override=True) + saved = await system.client.post( + "/api/editors/" + id + "/save", + json={"expected_version": current["version"], "manifest": edited}, + headers={"Idempotency-Key": "caption-edit"}, + ) + assert saved.status_code == 200, saved.text + body = {"expected_version": saved.json()["version"], "output_goal": "film"} + p = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert p.status_code == 200, p.text + assert all( + x["status"] == "reuse" + for x in p.json()["steps"] + if x["kind"] in {"video.generate", "audio.speech"} + ) + body["expected_plan_hash"] = p.json()["plan_hash"] + response = await system.client.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "caption-film"} + ) + assert response.status_code == 202, response.text + newrid = response.json()["run"]["id"] + later = [] + for tick in range(8): + async with system.app.state.db.session() as s: + await advance_run(s, newrid, system.settings) + r = await s.get(WorkflowRun, newrid) + assert r.state != "blocked", r.error_json + jobs = ( + await s.scalars(select(Job).where(Job.run_id == newrid, Job.state != "succeeded")) + ).all() + for j in jobs: + later.append(j.task_type) + assert j.task_type in {"audio.assemble", "video.compose"} + if j.task_type == "video.compose": + assert (j.parameters.get("workflow_spec") or j.parameters["story_spec"])[ + "render" + ]["subtitles"][0]["text"] == "人工修改字幕" + key = "mock/" + uuid4().hex + ".bin" + path = system.settings.asset_root / key + path.write_bytes(png_bytes) + s.add( + Asset( + owner_id=r.owner_id, + name="mock reused film", + storage_key=key, + kind="audio" if j.task_type == "audio.assemble" else "video", + mime_type="application/octet-stream", + size_bytes=len(png_bytes), + sha256=hashlib.sha256(png_bytes).hexdigest(), + width=1280, + height=704, + duration_seconds=timeline_frames / 24, + source_job_id=j.id, + source_output_index=0, + ) + ) + j.state = "succeeded" + await s.commit() + if r.state == "succeeded": + break + async with system.app.state.db.session() as s: + r = await s.get(WorkflowRun, newrid) + assert r.state == "succeeded" and r.apply_state == "applied" + assert set(later) == {"audio.assemble", "video.compose"} + assert (await s.get(WorkflowDraft, id)).current_run_id == newrid + assert not any(k.startswith("_") for b in r.result_manifest["bindings"].values() for k in b) + + +def test_forced_variant_reused_by_intent_but_actual_nonseed_parameters_checked(): + from copy import deepcopy + + m = manifest(1) + sid = m["shot_ids"][0] + original = build_recipes( + m, {}, {"output_goal": "media", "targets": ["frame:" + sid]}, SimpleNamespace() + )[0] + actual = deepcopy(original["parameters"]) + actual["seed"] = 123456 + b = { + "asset_id": "f", + "sha256": "a" * 64, + "kind": "image", + "source": "generated", + "context_hash": original["context_hash"], + "generation_parameters": actual, + } + assert build_recipes( + m, + {"frame:" + sid: b}, + {"output_goal": "media", "targets": ["frame:" + sid]}, + SimpleNamespace(), + )[0]["reuse"] + b["generation_parameters"]["guidance_scale"] = 99.0 + assert not build_recipes( + m, + {"frame:" + sid: b}, + {"output_goal": "media", "targets": ["frame:" + sid]}, + SimpleNamespace(), + )[0]["reuse"] + + +async def test_cancel_waits_for_execution_cleanup_across_sessions(system): + from sqlalchemy import select + from app.models import WorkflowRun, WorkflowStep, Job, Execution + from app.services.orchestration.workflow_engine import advance_run + from app.services.workflows import control_run + + _, rid, _ = await start_frame(system) + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) + j = await s.get(Job, step.selected_job_id) + e = Execution( + job_id=j.id, + ordinal=1, + phase_key="gpu", + resource_pool="gpu", + fence_token="test", + state="running", + ) + s.add(e) + r = await s.get(WorkflowRun, rid) + await control_run(s, r, "cancel") + await s.commit() + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + r = await s.get(WorkflowRun, rid) + assert r.state == "cancelling" + e = await s.scalar( + select(Execution).join(Job, Job.id == Execution.job_id).where(Job.run_id == rid) + ) + e.state = "exited" + await s.commit() + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + r = await s.get(WorkflowRun, rid) + assert r.state == "cancelled" + + +def test_force_script_explicit_target_survives_silent_film_closure(): + m = manifest(1) + m["audio"]["segments"] = [{"id": "f" * 32, "shot_id": m["shot_ids"][0], "text": ""}] + recipes = build_recipes(m, {}, {"output_goal": "film", "force": ["script"]}, SimpleNamespace()) + assert "script" in {r["key"] for r in recipes} + assert "compose" in {r["key"] for r in recipes} + + +def test_frame_media_target_does_not_require_any_configured_tts_voice(): + m = manifest(1) + m["audio"].update( + mode="generated_narration", + voice="", + segments=[{"id": "f" * 32, "shot_id": m["shot_ids"][0], "text": "words"}], + ) + recipes = build_recipes( + m, + {}, + {"output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]]}, + SimpleNamespace(tts_voices=()), + ) + assert [r["key"] for r in recipes] == ["frame_0001"] + + +async def test_missing_tts_voice_only_blocks_speech_target_plan(system): + id, m = await editor(system) + m["audio"]["mode"] = "generated_narration" + m["audio"]["voice"] = "" + saved = await system.client.post( + "/api/editors/" + id + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save-voice"}, + ) + assert saved.status_code == 200, saved.text + system.settings.tts_voices = [] + body = {"expected_version": 2, "output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]]} + frame = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert frame.status_code == 200 and frame.json()["issues"] == [], frame.text + body["targets"] = ["audio:" + m["audio"]["segments"][0]["id"]] + speech = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert speech.status_code == 200, speech.text + assert any(i["code"] == "speech_unavailable" for i in speech.json()["issues"]) + + +async def test_forced_script_materializes_only_missing_segment_text(system): + import json, hashlib + from sqlalchemy import select + from app.models import Job, Asset, WorkflowRun + from app.services.orchestration.workflow_engine import advance_run + + id, m = await editor(system, 2) + m["audio"]["segments"][0]["text"] = "manual narration" + saved = await system.client.post( + "/api/editors/" + id + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "script-source"}, + ) + assert saved.status_code == 200, saved.text + body = { + "expected_version": 2, + "output_goal": "media", + "targets": ["script"], + "force": ["script"], + } + plan = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert plan.status_code == 200, plan.text + body["expected_plan_hash"] = plan.json()["plan_hash"] + started = await system.client.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "script"} + ) + assert started.status_code == 202, started.text + rid = started.json()["run"]["id"] + async with system.app.state.db.session() as s: + await advance_run(s, rid, system.settings) + job = await s.scalar(select(Job).where(Job.run_id == rid)) + assert job.task_type == "text.script.generate" + result = { + "segments": [{"shot_id": sid, "text": "generated narration"} for sid in m["shot_ids"]] + } + data = json.dumps(result).encode() + path = system.settings.asset_root / "script.json" + path.write_bytes(data) + s.add( + Asset( + owner_id=job.owner_id, + name="script", + storage_key="script.json", + kind="json", + mime_type="application/json", + size_bytes=len(data), + sha256=hashlib.sha256(data).hexdigest(), + source_job_id=job.id, + source_output_index=0, + ) + ) + job.result_json = result + job.state = "succeeded" + await advance_run(s, rid, system.settings) + await s.commit() + run = await s.get(WorkflowRun, rid) + assert run.state == "succeeded" + assert [x["text"] for x in run.result_manifest["audio"]["segments"]] == [ + "manual narration", + "generated narration", + ] + + +@pytest.mark.parametrize("change", ["context", "parameters", "unavailable"]) +def test_locked_binding_requires_explicit_force_when_dependency_changed(change): + from copy import deepcopy + + m = manifest(1) + key = "frame:" + m["shot_ids"][0] + original = build_recipes(m, {}, {"output_goal": "media", "targets": [key]}, SimpleNamespace())[ + 0 + ] + binding = { + "asset_id": "f", + "sha256": "a" * 64, + "kind": "image", + "source": "generated", + "locked": True, + "context_hash": original["context_hash"], + "generation_parameters": deepcopy(original["parameters"]), + } + m["bindings"][key] = binding + valid = build_recipes( + m, {key: binding}, {"output_goal": "media", "targets": [key]}, SimpleNamespace() + )[0] + assert valid["reuse"] and not valid.get("issue") + reusable = {key: binding} + if change == "context": + m["spec"]["shots"][0]["prompt"] = "changed visual" + elif change == "parameters": + binding["generation_parameters"]["guidance_scale"] = 99 + else: + reusable = {} + blocked = build_recipes( + m, reusable, {"output_goal": "media", "targets": [key]}, SimpleNamespace() + )[0] + assert blocked["issue"]["code"] == "locked_dependency_changed" + assert blocked["issue"]["unit_id"] == m["shot_ids"][0] + forced = build_recipes( + m, reusable, {"output_goal": "media", "targets": [key], "force": [key]}, SimpleNamespace() + )[0] + assert forced["reuse"] is None and not forced.get("issue") + + +def test_locked_issue_only_in_selected_target_ancestor_closure(): + m = manifest(2) + first = "frame:" + m["shot_ids"][0] + m["bindings"][first] = { + "asset_id": "missing", + "sha256": "a" * 64, + "kind": "image", + "source": "manual", + "locked": True, + } + other = build_recipes( + m, {}, {"output_goal": "media", "targets": ["frame:" + m["shot_ids"][1]]}, SimpleNamespace() + ) + assert not any(r.get("issue") for r in other) + dependent = build_recipes( + m, {}, {"output_goal": "media", "targets": ["video:" + m["shot_ids"][0]]}, SimpleNamespace() + ) + assert any(r.get("issue", {}).get("code") == "locked_dependency_changed" for r in dependent) + + +async def test_locked_corrupt_asset_reports_issue_and_media_run_cannot_replace_it( + system, png_bytes +): + from app.models import Asset + + id, m = await editor(system) + uploaded = await system.client.post( + "/api/assets", files={"file": ("locked.png", png_bytes, "image/png")} + ) + aid = uploaded.json()["id"] + key = "frame:" + m["shot_ids"][0] + m["bindings"][key] = { + "asset_id": aid, + "sha256": "a" * 64, + "kind": "image", + "source": "manual", + "locked": True, + } + saved = await system.client.post( + "/api/editors/" + id + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "locked"}, + ) + assert saved.status_code == 200, saved.text + body = {"expected_version": 2, "output_goal": "media", "targets": [key]} + valid = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert valid.status_code == 200 and not valid.json()["issues"], valid.text + async with system.app.state.db.session() as s: + asset = await s.get(Asset, aid) + (system.settings.asset_root / asset.storage_key).write_bytes(b"corrupt") + changed = await system.client.post("/api/editors/" + id + "/plan", json=body) + assert changed.status_code == 200, changed.text + assert any(i["code"] == "locked_dependency_changed" for i in changed.json()["issues"]) + body["expected_plan_hash"] = changed.json()["plan_hash"] + started = await system.client.post( + "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "locked-run"} + ) + assert started.status_code == 422, started.text + + +def test_locked_manual_frame_cannot_be_implicitly_normalized_for_video(): + m = manifest(1) + key = "frame:" + m["shot_ids"][0] + binding = { + "asset_id": "f", + "sha256": "a" * 64, + "kind": "image", + "source": "manual", + "locked": True, + "_width": 16, + "_height": 12, + } + m["bindings"][key] = {k: v for k, v in binding.items() if not k.startswith("_")} + direct = build_recipes( + m, {key: binding}, {"output_goal": "media", "targets": [key]}, SimpleNamespace() + ) + assert direct[0]["reuse"] and not direct[0].get("issue") + dependent = build_recipes( + m, + {key: binding}, + {"output_goal": "media", "targets": ["video:" + m["shot_ids"][0]]}, + SimpleNamespace(), + ) + assert dependent[0]["issue"]["code"] == "locked_dependency_changed" diff --git a/backend/tests/test_editor_media.py b/backend/tests/test_editor_media.py new file mode 100644 index 0000000..681859a --- /dev/null +++ b/backend/tests/test_editor_media.py @@ -0,0 +1,247 @@ +"""编辑媒体的实际字节和投影规则;模型仅替换 HTTP 边界。""" + +import json +import shutil +import tempfile +import unittest +import wave +import httpx +from pathlib import Path +from unittest.mock import AsyncMock + +from app.core.config import Settings +from app.adapters.provider.client import Provider, ProviderError +from app.services.editor_media import compile_captions + + +class CaptionTests(unittest.TestCase): + def manifest(self): + return { + "shot_ids": ["a" * 32, "b" * 32], + "spec": { + "shots": [{"edit": {"duration_frames": 48}}, {"edit": {"duration_frames": 72}}] + }, + "audio": { + "mode": "silent", + "segments": [ + {"id": "c" * 32, "shot_id": "a" * 32, "text": "第一句"}, + {"id": "d" * 32, "shot_id": "b" * 32, "text": "第二句"}, + ], + }, + "captions": {"mode": "script", "cues": []}, + } + + def test_script_captions_follow_stable_shot_order(self): + m = self.manifest() + self.assertEqual( + compile_captions(m, {}), + [ + {"start_frame": 0, "end_frame": 48, "text": "第一句"}, + {"start_frame": 48, "end_frame": 120, "text": "第二句"}, + ], + ) + m["shot_ids"].reverse() + m["spec"]["shots"].reverse() + self.assertEqual( + compile_captions(m, {})[0], {"start_frame": 0, "end_frame": 72, "text": "第二句"} + ) + + def test_manual_text_and_manual_time_are_separate(self): + m = self.manifest() + m["captions"]["cues"] = [ + { + "id": "e" * 32, + "anchor": "audio_segment", + "segment_id": "c" * 32, + "text": "人工改字", + "start_frame": 2, + "end_frame": 20, + "text_override": True, + "timing_override": False, + } + ] + m["audio"]["mode"] = "generated_narration" + bindings = { + "audio:" + "c" * 32: { + "sample_count": None, + "duration_frames": 12, + "duration_seconds": 0.5, + }, + "audio:" + "d" * 32: {"sample_count": 48000}, + } + self.assertEqual( + compile_captions(m, bindings)[0], + {"start_frame": 0, "end_frame": 12, "text": "人工改字"}, + ) + m["captions"]["cues"][0].update(timing_override=True, end_frame=10) + self.assertEqual( + compile_captions(m, bindings)[0], + {"start_frame": 2, "end_frame": 10, "text": "人工改字"}, + ) + + def test_none_retains_content_and_orphan_is_not_rebound(self): + m = self.manifest() + m["captions"]["mode"] = "none" + self.assertEqual(compile_captions(m, {}), []) + self.assertEqual(len(m["audio"]["segments"]), 2) + m["captions"] = { + "mode": "manual", + "cues": [ + { + "anchor": "shot", + "shot_id": "f" * 32, + "start_frame": 0, + "end_frame": 24, + "text": "孤立字幕", + "text_override": True, + "timing_override": True, + } + ], + } + with self.assertRaisesRegex(ValueError, "镜头"): + compile_captions(m, {}) + + def test_overflow_does_not_truncate_manual_cue(self): + m = self.manifest() + cue = { + "anchor": "absolute", + "start_frame": 100, + "end_frame": 130, + "text": "保留", + "text_override": True, + "timing_override": True, + } + m["captions"] = {"mode": "manual", "cues": [cue]} + with self.assertRaises(ValueError): + compile_captions(m, {}) + self.assertEqual(cue["end_frame"], 130) + + +class EditorProviderTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="em-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.settings = Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=self.root, + run_coordinator=False, + inference_api_key_file=None, + ) + self.settings.job_work_root.mkdir(parents=True) + self.settings.asset_root.mkdir(parents=True) + self.work = self.settings.job_work_root / "work" + self.work.mkdir() + self.provider = Provider(self.settings) + + async def asyncTearDown(self): + await self.provider.aclose() + + async def test_script_validates_ids_and_uses_json_output(self): + self.provider._chat = AsyncMock( + return_value=json.dumps( + {"segments": [{"shot_id": "a" * 32, "text": "山中走来一位旅人。"}]} + ) + ) + inputs = { + "shots": [ + { + "shot_id": "a" * 32, + "name": "山中", + "visual_prompt": "旅人", + "motion_prompt": "走来", + "duration_frames": 120, + } + ] + } + result = await self.provider.run_cpu("text.script.generate", inputs, {}, {}, self.work) + self.assertEqual(result.result["segments"][0]["shot_id"], "a" * 32) + self.assertEqual(json.loads(result.outputs[0].read_text(encoding="utf-8")), result.result) + self.provider._chat.return_value = json.dumps( + {"segments": [{"shot_id": "b" * 32, "text": "错误镜头"}]} + ) + with self.assertRaises(ProviderError): + await self.provider.run_cpu("text.script.generate", inputs, {}, {}, self.work) + + def wav(self, name, frames=6000): + target = self.settings.asset_root / name + with wave.open(str(target), "wb") as out: + out.setparams((1, 2, 24000, 0, "NONE", "not compressed")) + out.writeframes(b"\x00\x20" * frames) + return target + + @unittest.skipUnless(shutil.which("ffmpeg"), "FFmpeg required") + async def test_audio_assembly_is_exact_samples_and_rejects_overlap(self): + assets = {"one": self.wav("one.wav"), "two": self.wav("two.wav")} + inputs = { + "segments": [ + {"asset_id": "one", "offset_frame": 0}, + {"asset_id": "two", "offset_frame": 12}, + ], + "total_frames": 25, + } + result = await self.provider.run_cpu( + "audio.assemble", inputs, {"fps": 24}, assets, self.work + ) + with wave.open(str(result.outputs[0]), "rb") as audio: + self.assertEqual( + (audio.getframerate(), audio.getnchannels(), audio.getnframes()), (48000, 2, 50000) + ) + self.assertNotEqual(set(audio.readframes(100)), {0}) + audio.setpos(12000) + self.assertEqual(set(audio.readframes(100)), {0}) + inputs["segments"][1]["offset_frame"] = 3 + with self.assertRaises(ProviderError): + await self.provider.run_cpu("audio.assemble", inputs, {"fps": 24}, assets, self.work) + + async def test_empty_or_path_segments_are_rejected_before_processing(self): + for segments in ([], [{"asset_id": "C:/secret.wav", "offset_frame": 0}]): + with self.assertRaises(ProviderError): + await self.provider.run_cpu( + "audio.assemble", {"segments": segments, "total_frames": 24}, {}, {}, self.work + ) + + @unittest.skipUnless(shutil.which("ffprobe"), "FFprobe required") + async def test_speech_timeout_and_frozen_model_are_explicit(self): + self.settings.tts_base_url = "http://speech.test/v1" + observed = [] + source = self.wav("response.wav").read_bytes() + + def reply(request): + observed.append(request.extensions["timeout"]["read"]) + return httpx.Response(200, content=source) + + await self.provider.client.aclose() + self.provider.client = httpx.AsyncClient(transport=httpx.MockTransport(reply), timeout=1) + result = await self.provider.run_cpu( + "audio.speech", + {"prompt": "你好"}, + {"voice": "zf_xiaobei", "model": "kokoro-82m"}, + {}, + self.work, + ) + self.assertGreaterEqual(observed[0], 300) + self.assertEqual(result.result["sample_count"], 12000) + self.settings.tts_model = "replacement" + with self.assertRaises(ProviderError): + await self.provider.run_cpu( + "audio.speech", {"prompt": "你好"}, {"model": "kokoro-82m"}, {}, self.work + ) + self.assertEqual(len(observed), 1) + + async def test_speech_health_reports_reachability_without_model_execution(self): + self.settings.tts_base_url = "http://speech.test/v1" + + async def reply(request): + self.assertEqual(request.url.path, "/health") + return httpx.Response( + 200, + json={"status": "ok", "model": "kokoro-82m", "voices": ["zf_xiaobei", "zm_yunxi"]}, + ) + + await self.provider.client.aclose() + self.provider.client = httpx.AsyncClient(transport=httpx.MockTransport(reply)) + health = await self.provider.speech_health() + self.assertTrue(health["configured"] and health["reachable"]) + self.assertEqual(health["validation"], "requires_deployment_acceptance") diff --git a/backend/tests/test_editor_modes.py b/backend/tests/test_editor_modes.py new file mode 100644 index 0000000..2a2b91d --- /dev/null +++ b/backend/tests/test_editor_modes.py @@ -0,0 +1,546 @@ +from test_editors import spec +from sqlalchemy import select +from app.models import WorkflowDraft, WorkflowRun + + +async def test_mode_switch_cas_guards_and_roundtrip(system, other_client): + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Mode", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + url = f"/api/editors/{id}" + initial = await c.get(url) + assert initial.json()["editing_mode"] == "manual" + switched = await c.post( + url + "/mode", + json={"expected_version": 1, "mode": "auto"}, + headers={"Idempotency-Key": "enable"}, + ) + assert switched.status_code == 200, switched.text + assert switched.json()["editing_mode"] == "auto" + assert ( + await other_client.post( + url + "/mode", + json={"expected_version": 2, "mode": "manual"}, + headers={"Idempotency-Key": "foreign"}, + ) + ).status_code == 404 + manual = await c.post( + url + "/mode", + json={"expected_version": 2, "mode": "manual"}, + headers={"Idempotency-Key": "manual"}, + ) + assert manual.status_code == 200, manual.text + assert manual.json()["editing_mode"] == "manual" + blocked = await c.post( + url + "/save", + json={"expected_version": 3, "manifest": manual.json()["manifest"]}, + headers={"Idempotency-Key": "blocked"}, + ) + assert blocked.status_code == 409 + changed = await c.patch( + f"/api/stories/{id}", json={"name": "Renamed"}, headers={"If-Match": "3"} + ) + assert changed.status_code == 200, changed.text + assert changed.json()["editing_mode"] == "manual" + again = await c.post( + url + "/mode", + json={"expected_version": 4, "mode": "auto"}, + headers={"Idempotency-Key": "again"}, + ) + assert again.status_code == 200, again.text + assert again.json()["manifest"]["spec"] == manual.json()["manifest"]["spec"] + assert ( + await c.post( + url + "/mode", + json={"expected_version": 1, "mode": "manual"}, + headers={"Idempotency-Key": "stale"}, + ) + ).status_code == 409 + + +async def test_active_run_blocks_mode_switch(system): + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Busy", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + s.add( + WorkflowRun( + owner_id=draft.owner_id, + draft_id=id, + draft_revision=1, + spec_snapshot=draft.spec, + spec_hash="a" * 64, + ) + ) + await s.commit() + r = await c.post( + f"/api/editors/{id}/mode", + json={"expected_version": 1, "mode": "auto"}, + headers={"Idempotency-Key": "busy"}, + ) + assert r.status_code == 409, r.text + assert r.json()["detail"]["code"] == "mode_switch_busy" + + +async def test_manual_projection_selection_refs_and_narration_roundtrip(system, monkeypatch): + from test_story_studio import prepare_manual_frame + from app.models import ShotSelection, ShotCandidate, AssetReference + + c = system.client + d, candidate, _ = await prepare_manual_frame(system, monkeypatch) + id = d["id"] + url = f"/api/editors/{id}" + m = (await c.get(url)).json()["manifest"] + m["bindings"]["frame:" + ("1" * 32)] = { + "asset_id": candidate["asset"]["id"], + "kind": "image", + "source": "manual", + } + m["audio"]["voice"] = "zm_yunxi" + m["audio"]["segments"][0]["text"] = "保留的旁白" + m["audio"]["mode"] = "generated_narration" + m["captions"]["mode"] = "manual" + m["captions"]["cues"] = [ + { + "id": "a" * 32, + "anchor": "shot", + "shot_id": "1" * 32, + "start_frame": 0, + "end_frame": 24, + "text": "旧字幕", + "text_override": True, + "timing_override": True, + } + ] + saved = await c.post( + url + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save"}, + ) + assert saved.status_code == 200, saved.text + manual = await c.post( + url + "/mode", + json={"expected_version": 2, "mode": "manual"}, + headers={"Idempotency-Key": "manual"}, + ) + assert manual.status_code == 200, manual.text + assert manual.json()["story"]["spec"]["render"]["subtitles"][0]["text"] == "旧字幕" + async with system.app.state.db.session() as s: + assert not (await s.scalars(select(ShotSelection))).all() + rows = (await s.scalars(select(ShotCandidate).where(ShotCandidate.draft_id == id))).all() + assert len(rows) == 1 # 原有相同asset/hash的ready候选直接复用 + projected = manual.json()["story"]["spec"] + projected["shots"][0]["name"] = "手工编辑" + projected["render"]["subtitles"][0]["text"] = "手工字幕" + patched = await c.patch( + f"/api/stories/{id}", json={"spec": projected}, headers={"If-Match": "3"} + ) + assert patched.status_code == 200, patched.text + assert patched.json()["editor_manifest"]["audio"]["segments"][0]["text"] == "保留的旁白" + selected = await c.post( + f"/api/stories/{id}/selections", + json={ + "expected_version": 4, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": candidate["id"], + }, + headers={"Idempotency-Key": "select"}, + ) + assert selected.status_code == 200, selected.text + assert selected.json()["editor_manifest"]["bindings"]["frame:" + ("1" * 32)]["locked"] + cleared = await c.post( + f"/api/stories/{id}/selections/clear", + json={"expected_version": 5, "shot_id": "1" * 32, "kind": "frame"}, + headers={"Idempotency-Key": "clear"}, + ) + assert cleared.status_code == 200, cleared.text + assert "frame:" + ("1" * 32) not in cleared.json()["editor_manifest"]["bindings"] + auto = await c.post( + url + "/mode", + json={"expected_version": 6, "mode": "auto"}, + headers={"Idempotency-Key": "auto"}, + ) + assert auto.status_code == 200, auto.text + m = auto.json()["manifest"] + assert m["audio"]["voice"] == "zm_yunxi" and m["audio"]["segments"][0]["text"] == "保留的旁白" + assert m["captions"]["cues"][0]["text"] == "手工字幕" + assert m["spec"]["render"]["subtitles"] == [] and m["spec"]["render"]["audio"] is None + + +async def test_mode_csrf_and_candidate_batch_execution_guards(system): + from app.models import ShotCandidate, Batch, BatchItem, Job, Execution + + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Mode", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + url = f"/api/editors/{id}/mode" + body = {"expected_version": 1, "mode": "auto"} + assert ( + await c.post(url, json=body, headers={"X-CSRF-Token": "bad", "Idempotency-Key": "csrf"}) + ).status_code == 403 + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + candidate = ShotCandidate( + owner_id=draft.owner_id, + draft_id=id, + shot_id="1" * 32, + kind="frame", + source_kind="manual", + context_hash="a" * 64, + generation_hash="b" * 64, + created_revision=1, + state="queued", + ) + s.add(candidate) + await s.flush() + cid = candidate.id + owner = draft.owner_id + await s.commit() + + async def switch(key): + return await c.post(url, json=body, headers={"Idempotency-Key": key}) + + assert (await switch("candidate")).status_code == 409 + async with system.app.state.db.session() as s: + (await s.get(ShotCandidate, cid)).state = "failed" + batch = Batch(owner_id=owner, name="pending", state="queued") + s.add(batch) + await s.flush() + bid = batch.id + s.add(BatchItem(batch_id=bid, item_index=0, target_kind="candidate", target_id=cid)) + await s.commit() + assert (await switch("batch")).status_code == 409 + async with system.app.state.db.session() as s: + (await s.get(Batch, bid)).state = "succeeded" + job = Job( + owner_id=owner, + task_type="image.generate", + state="failed", + phase="failed", + input_json={}, + parameters={}, + request_hash="a" * 64, + upstream_key="mode-execution", + ) + s.add(job) + await s.flush() + jid = job.id + (await s.get(ShotCandidate, cid)).job_id = jid + ex = Execution( + job_id=jid, + ordinal=1, + phase_key="gpu", + resource_pool="new_gpu", + fence_token="a" * 32, + state="unknown", + ) + s.add(ex) + await s.flush() + eid = ex.id + await s.commit() + assert (await switch("execution")).status_code == 409 + async with system.app.state.db.session() as s: + (await s.get(Execution, eid)).state = "exited" + await s.commit() + final = await switch("drained") + assert final.status_code == 200, final.text + + +async def test_mode_real_session_and_auto_mode_cannot_be_forged(system): + import pytest + from fastapi import HTTPException + from app.models import Session + from app.core.security import Actor + from app.schemas.editors import EditorMode + from app.services.editor_modes import change_mode + + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Mode", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + url = f"/api/editors/{id}" + m = (await c.get(url)).json()["manifest"] + m["editing_mode"] = "manual" + forged = await c.post( + url + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "forge"}, + ) + assert forged.status_code == 409 + async with system.app.state.db.session() as s: + row = await s.scalar(select(Session)) + draft = await s.get(WorkflowDraft, id) + actor = Actor( + draft.owner_id, "admin", "Admin", "admin", "csrf", row.token_hash, auth_kind="bearer" + ) + with pytest.raises(HTTPException) as exc: + await change_mode( + system.app.state, actor, id, EditorMode(expected_version=1, mode="auto"), "bearer" + ) + assert exc.value.status_code == 403 + actor.auth_kind = "session" + async with system.app.state.db.session() as s: + await s.delete(await s.scalar(select(Session))) + await s.commit() + with pytest.raises(HTTPException) as exc: + await change_mode( + system.app.state, actor, id, EditorMode(expected_version=1, mode="auto"), "revoked" + ) + assert exc.value.status_code == 401 + + +async def test_manual_removing_shot_cleans_only_deleted_anchors(system): + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Two", + "spec": { + "schema_version": 3, + "shots": [ + {"id": "1" * 32, "visual_prompt": "tree"}, + {"id": "2" * 32, "visual_prompt": "river"}, + ], + }, + }, + ) + ).json() + id = d["id"] + url = f"/api/editors/{id}" + m = (await c.get(url)).json()["manifest"] + removed = m["audio"]["segments"][1]["id"] + m["captions"]["mode"] = "manual" + m["captions"]["cues"] = [ + dict( + id="a" * 32, + anchor="shot", + shot_id="2" * 32, + start_frame=0, + end_frame=24, + text="gone", + text_override=True, + timing_override=True, + ), + dict( + id="b" * 32, + anchor="absolute", + start_frame=0, + end_frame=24, + text="kept", + text_override=True, + timing_override=True, + ), + ] + saved = await c.post( + url + "/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save"}, + ) + assert saved.status_code == 200, saved.text + manual = await c.post( + url + "/mode", + json={"expected_version": 2, "mode": "manual"}, + headers={"Idempotency-Key": "manual"}, + ) + assert manual.status_code == 200, manual.text + projected = manual.json()["story"]["spec"] + projected["shots"] = projected["shots"][:1] + projected["render"]["total_frames"] = 120 + # 保持旧字幕投影不变;被删镜头锚点由桥接层按原稳定ID清理。 + projected["render"]["subtitles"] = [ + x for x in projected["render"]["subtitles"] if x["start_frame"] < 120 + ] + patched = await c.patch( + f"/api/stories/{id}", json={"spec": projected}, headers={"If-Match": "3"} + ) + assert patched.status_code == 200, patched.text + auto = await c.post( + url + "/mode", + json={"expected_version": 4, "mode": "auto"}, + headers={"Idempotency-Key": "auto"}, + ) + assert auto.status_code == 200, auto.text + result = auto.json()["manifest"] + assert len(result["audio"]["segments"]) == 1 and result["audio"]["segments"][0]["id"] != removed + assert len(result["captions"]["cues"]) == 1 and result["captions"]["cues"][0]["id"] == "b" * 32 + plan = await c.post(url + "/plan", json={"expected_version": 5, "output_goal": "film"}) + assert plan.status_code == 200, plan.text + assert not any(x["code"].startswith("orphan") for x in plan.json()["issues"]) + + +async def test_completed_run_with_pending_parent_batch_blocks_switch(system): + from app.models import Batch, BatchItem + + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Batch", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + run = WorkflowRun( + owner_id=draft.owner_id, + draft_id=id, + draft_revision=1, + spec_snapshot=draft.spec, + spec_hash="a" * 64, + state="succeeded", + ) + s.add(run) + await s.flush() + batch = Batch(owner_id=draft.owner_id, name="paused", state="paused") + s.add(batch) + await s.flush() + s.add(BatchItem(batch_id=batch.id, item_index=0, target_kind="run", target_id=run.id)) + await s.commit() + r = await c.post( + f"/api/editors/{id}/mode", + json={"expected_version": 1, "mode": "auto"}, + headers={"Idempotency-Key": "pending-parent"}, + ) + assert r.status_code == 409 and r.json()["detail"]["code"] == "mode_switch_busy" + + +async def test_deleted_unlaunched_candidate_does_not_block_mode(system): + from app.models import ShotCandidate + + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Deleted plan", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + created = await c.post( + f"/api/stories/{id}/candidates", + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + headers={"Idempotency-Key": "candidate"}, + ) + assert created.status_code == 202, created.text + candidate = created.json()["candidates"][0] + async with system.app.state.db.session() as s: + row = await s.get(ShotCandidate, candidate["id"]) + assert row.state == "queued" and row.job_id is None + deleted = await c.delete( + f"/api/stories/{id}/candidates/{candidate['id']}", + headers={"If-Match": str(candidate["version"])}, + ) + assert deleted.status_code == 200, deleted.text + switched = await c.post( + f"/api/editors/{id}/mode", + json={"expected_version": 1, "mode": "auto"}, + headers={"Idempotency-Key": "mode"}, + ) + assert switched.status_code == 200, switched.text + + +async def test_deleted_candidate_still_fences_unfinished_execution(system): + from app.models import ShotCandidate, Job, Execution + + c = system.client + d = ( + await c.post( + "/api/stories", + json={ + "name": "Deleted execution", + "spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]}, + }, + ) + ).json() + id = d["id"] + created = await c.post( + f"/api/stories/{id}/candidates", + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + headers={"Idempotency-Key": "candidate"}, + ) + assert created.status_code == 202, created.text + candidate = created.json()["candidates"][0] + deleted = await c.delete( + f"/api/stories/{id}/candidates/{candidate['id']}", + headers={"If-Match": str(candidate["version"])}, + ) + assert deleted.status_code == 200, deleted.text + async with system.app.state.db.session() as s: + row = await s.get(ShotCandidate, candidate["id"]) + assert row.deleted_at is not None and row.state == "queued" + job = Job( + owner_id=row.owner_id, + task_type="image.generate", + state="failed", + phase="failed", + input_json={}, + parameters={}, + request_hash="a" * 64, + upstream_key="deleted-mode-execution", + ) + s.add(job) + await s.flush() + row.job_id = job.id + execution = Execution( + job_id=job.id, + ordinal=1, + phase_key="gpu", + resource_pool="new_gpu", + fence_token="a" * 32, + state="unknown", + ) + s.add(execution) + await s.flush() + eid = execution.id + await s.commit() + body = {"expected_version": 1, "mode": "auto"} + blocked = await c.post( + f"/api/editors/{id}/mode", json=body, headers={"Idempotency-Key": "blocked"} + ) + assert blocked.status_code == 409 and blocked.json()["detail"]["code"] == "mode_switch_busy" + async with system.app.state.db.session() as s: + (await s.get(Execution, eid)).state = "exited" + await s.commit() + drained = await c.post( + f"/api/editors/{id}/mode", json=body, headers={"Idempotency-Key": "drained"} + ) + assert drained.status_code == 200, drained.text diff --git a/backend/tests/test_editor_names.py b/backend/tests/test_editor_names.py new file mode 100644 index 0000000..e00b12d --- /dev/null +++ b/backend/tests/test_editor_names.py @@ -0,0 +1,155 @@ +import pytest +from copy import deepcopy +from sqlalchemy import select +from app.models import WorkflowDraft, WorkflowRun, Submission + + +async def create_editor(c): + d = ( + await c.post( + "/api/stories", + json={ + "name": "未命名故事", + "spec": { + "schema_version": 3, + "shots": [{"id": "1" * 32, "name": "冻结镜头名", "visual_prompt": "tree"}], + }, + }, + ) + ).json() + enabled = await c.post( + f"/api/editors/{d['id']}/mode", + json={"expected_version": 1, "mode": "auto"}, + headers={"Idempotency-Key": "enable"}, + ) + assert enabled.status_code == 200, enabled.text + assert enabled.json()["capabilities"]["name_edit"] is True + assert enabled.json()["story"]["capabilities"]["name_edit"] is True + return enabled.json() + + +async def test_editor_name_manifest_atomic_cas_replay_and_run_frozen(system, other_client): + c = system.client + editor = await create_editor(c) + id = editor["draft_id"] + url = f"/api/editors/{id}" + m = deepcopy(editor["manifest"]) + plan_body = {"expected_version": 2, "output_goal": "media", "targets": ["frame:" + ("1" * 32)]} + plan = await c.post(url + "/plan", json=plan_body) + assert plan.status_code == 200, plan.text + run = await c.post( + url + "/runs", + json={**plan_body, "expected_plan_hash": plan.json()["plan_hash"]}, + headers={"Idempotency-Key": "run"}, + ) + assert run.status_code == 202, run.text + rid = run.json()["run"]["id"] + async with system.app.state.db.session() as s: + r = await s.get(WorkflowRun, rid) + frozen_spec = deepcopy(r.spec_snapshot) + frozen_plan = deepcopy(r.plan_snapshot) + frozen_hash = r.spec_hash + m["spec"]["shots"][0]["name"] = "编辑后的镜头名" + body = {"expected_version": 2, "manifest": m, "name": " 新故事名字 "} + saved = await c.post(url + "/save", json=body, headers={"Idempotency-Key": "rename"}) + assert saved.status_code == 200, saved.text + assert ( + saved.json()["name"] == "新故事名字" + and saved.json()["version"] == 3 + and saved.json()["revision"] == 3 + ) + assert saved.json()["manifest"]["spec"]["shots"][0]["name"] == "编辑后的镜头名" + assert ( + await c.post(url + "/save", json=body, headers={"Idempotency-Key": "rename"}) + ).json() == saved.json() + conflicting_key = await c.post( + url + "/save", json={**body, "name": "另一个名字"}, headers={"Idempotency-Key": "rename"} + ) + assert conflicting_key.status_code == 409 + assert ( + await c.post(url + "/save", json=body, headers={"Idempotency-Key": "stale"}) + ).status_code == 409 + assert ( + await other_client.post( + url + "/save", + json={**body, "expected_version": 3}, + headers={"Idempotency-Key": "foreign"}, + ) + ).status_code == 404 + async with system.app.state.db.session() as s: + r = await s.get(WorkflowRun, rid) + assert ( + r.spec_snapshot == frozen_spec + and r.plan_snapshot == frozen_plan + and r.spec_hash == frozen_hash + ) + assert r.spec_snapshot["shots"][0]["name"] == "冻结镜头名" + r.state = "succeeded" + from app.services.editors import apply_run_result + + assert not await apply_run_result(s, r, system.settings) + d = await s.get(WorkflowDraft, id) + assert d.name == "新故事名字" and d.version == 3 + + +@pytest.mark.parametrize("name", ["", " ", "x" * 256]) +async def test_editor_name_invalid_is_atomic(system, name): + editor = await create_editor(system.client) + id = editor["draft_id"] + url = f"/api/editors/{id}" + m = deepcopy(editor["manifest"]) + m["spec"]["shots"][0]["name"] = "must not save" + response = await system.client.post( + url + "/save", + json={"expected_version": 2, "manifest": m, "name": name}, + headers={"Idempotency-Key": "invalid"}, + ) + assert response.status_code == 422, response.text + unchanged = (await system.client.get(url)).json() + assert unchanged["name"] == "未命名故事" and unchanged["version"] == 2 + assert unchanged["manifest"] == editor["manifest"] + + +async def test_editor_name_omission_null_keeps_legacy_fingerprint(system): + c = system.client + editor = await create_editor(c) + id = editor["draft_id"] + url = f"/api/editors/{id}" + body = {"expected_version": 2, "manifest": editor["manifest"]} + saved = await c.post(url + "/save", json=body, headers={"Idempotency-Key": "legacy"}) + assert saved.status_code == 200, saved.text + assert saved.json()["name"] == "未命名故事" + replay = await c.post( + url + "/save", json={**body, "name": None}, headers={"Idempotency-Key": "legacy"} + ) + assert replay.status_code == 200, replay.text + assert replay.json()["version"] == 3 + async with system.app.state.db.session() as s: + sub = await s.scalar(select(Submission).where(Submission.operation == "editor.save")) + assert "name" not in sub.request_json + + +async def test_editor_name_rolls_back_when_manifest_validation_fails(system): + c = system.client + editor = await create_editor(c) + id = editor["draft_id"] + url = f"/api/editors/{id}" + broken = deepcopy(editor["manifest"]) + broken["spec"]["shots"][0]["id"] = "2" * 32 + response = await c.post( + url + "/save", + json={"expected_version": 2, "manifest": broken, "name": "must rollback"}, + headers={"Idempotency-Key": "invalid-manifest"}, + ) + assert response.status_code == 422, response.text + unchanged = (await c.get(url)).json() + assert unchanged["name"] == "未命名故事" and unchanged["version"] == 2 + async with system.app.state.db.session() as s: + assert ( + await s.scalar( + select(Submission).where( + Submission.operation == "editor.save", Submission.key == "invalid-manifest" + ) + ) + is None + ) diff --git a/backend/tests/test_editors.py b/backend/tests/test_editors.py new file mode 100644 index 0000000..0399b37 --- /dev/null +++ b/backend/tests/test_editors.py @@ -0,0 +1,474 @@ +import pytest +from sqlalchemy import select +from app.models import WorkflowDraft + + +def spec(): + return { + "schema_version": 2, + "shots": [{"key": "shot_1", "prompt": "test", "duration_frames": 120}], + } + + +async def test_editor_preview_save_cas_and_issues(system): + c = system.client + r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()}) + assert r.status_code == 201, r.text + id = r.json()["id"] + preview = await c.get(f"/api/editors/{id}") + assert preview.status_code == 200, preview.text + m = preview.json()["manifest"] + async with system.app.state.db.session() as s: + assert (await s.get(WorkflowDraft, id)).editor_manifest is None + m["captions"]["cues"] = [ + { + "id": "f" * 32, + "anchor": "absolute", + "start_frame": 0, + "end_frame": 999, + "text": "saved", + "text_override": True, + "timing_override": True, + } + ] + body = {"expected_version": 1, "manifest": m} + url = f"/api/editors/{id}/save" + saved = await c.post(url, json=body, headers={"Idempotency-Key": "save"}) + assert saved.status_code == 200, saved.text + assert saved.json()["version"] == 2 + assert saved.json()["issues"] + again = await c.post(url, json=body, headers={"Idempotency-Key": "save"}) + assert again.status_code == 200 + assert again.json()["version"] == 2 + conflict = await c.post(url, json=body, headers={"Idempotency-Key": "new"}) + assert conflict.status_code == 409 + + +async def test_editor_owner_and_csrf(system, other_client): + r = await system.client.post("/api/workflows", json={"name": "Editor", "spec": spec()}) + id = r.json()["id"] + assert (await other_client.get(f"/api/editors/{id}")).status_code == 404 + response = await system.client.post( + f"/api/editors/{id}/save", + json={"expected_version": 1, "manifest": {}}, + headers={"X-CSRF-Token": "wrong"}, + ) + assert response.status_code == 403 + + +async def test_editor_refs_server_provenance_and_frozen_restore(system, png_bytes): + from app.models import AssetReference, WorkflowRun, Submission + + c = system.client + uploaded = await c.post("/api/assets", files={"file": ("ref.png", png_bytes, "image/png")}) + assert uploaded.status_code == 201, uploaded.text + aid = uploaded.json()["id"] + r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()}) + id = r.json()["id"] + m = (await c.get(f"/api/editors/{id}")).json()["manifest"] + sid = m["shot_ids"][0] + m["bindings"]["frame:" + sid] = { + "asset_id": aid, + "kind": "image", + "source": "generated", + "input_hash": "forged", + "sample_count": 1, + "duration_frames": 999999, + "duration_seconds": 999999.0, + } + response = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save"}, + ) + assert response.status_code == 200, response.text + frozen = response.json()["manifest"] + binding = frozen["bindings"]["frame:" + sid] + assert len(binding["sha256"]) == 64 + assert binding["sha256"] != "0" * 64 + assert binding.get("input_hash") is None + assert binding["source"] == "manual" + assert binding.get("sample_count") is None + assert binding.get("duration_frames") is None + assert binding.get("duration_seconds") is None + async with system.app.state.db.session() as s: + d = await s.get(WorkflowDraft, id) + owner = d.owner_id + run = WorkflowRun( + owner_id=owner, + draft_id=id, + draft_revision=1, + spec_snapshot=frozen["spec"], + spec_hash="a" * 64, + run_kind="workflow_auto", + source_draft_version=2, + result_manifest=frozen, + ) + s.add(run) + await s.flush() + rid = run.id + await s.commit() + changed = __import__("copy").deepcopy(frozen) + changed["spec"]["shots"][0]["prompt"] = "later edit" + response = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 2, "manifest": changed}, + headers={"Idempotency-Key": "later"}, + ) + assert response.status_code == 200, response.text + stale = await c.post( + f"/api/editors/{id}/from-run", + json={"expected_version": 2, "run_id": rid}, + headers={"Idempotency-Key": "stale"}, + ) + assert stale.status_code == 409 + restore = await c.post( + f"/api/editors/{id}/from-run", + json={"expected_version": 3, "run_id": rid}, + headers={"Idempotency-Key": "restore"}, + ) + assert restore.status_code == 200, restore.text + assert restore.json()["manifest"] == {**frozen, "base_run_id": rid} + async with system.app.state.db.session() as s: + refs = ( + await s.scalars( + select(AssetReference).where( + AssetReference.ref_kind == "draft", AssetReference.ref_id == id + ) + ) + ).all() + assert {x.asset_id for x in refs} == {aid} + sub = await s.scalar(select(Submission).where(Submission.operation == "editor.from_run")) + assert sub.resource_json == {"draft_id": id} + from app.services.editors import apply_run_result + + run = await s.get(WorkflowRun, rid) + run.state = "succeeded" + assert not await apply_run_result(s, run, system.settings) + assert run.apply_state == "conflict" + run.state = "succeeded" + await s.commit() + archived = await c.delete(f"/api/workflow-runs/{rid}", headers={"If-Match": "1"}) + assert archived.status_code == 200, archived.text + protected = await c.delete(f"/api/assets/{aid}") + assert protected.status_code == 409, protected.text + assert (await c.get(f"/api/editors/{id}")).status_code == 200 + async with system.app.state.db.session() as s: + sub = await s.scalar(select(Submission).where(Submission.operation == "editor.from_run")) + assert sub.status != "purged" + + +async def test_editor_rejects_bearer_and_rechecks_revoked_session(system): + from app.models import Session + + c = system.client + r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()}) + id = r.json()["id"] + m = (await c.get(f"/api/editors/{id}")).json()["manifest"] + from app.services.editors import save_editor + from app.schemas.editors import SaveEditor + from app.core.security import Actor + from fastapi import HTTPException + + async with system.app.state.db.session() as s: + row = await s.scalar(select(Session)) + d = await s.get(WorkflowDraft, id) + actor = Actor(d.owner_id, "admin", "Admin", "admin", "csrf", row.token_hash) + await s.delete(row) + await s.commit() + with pytest.raises(HTTPException) as exc: + await save_editor( + system.app.state, actor, id, SaveEditor(expected_version=1, manifest=m), "revoked" + ) + assert exc.value.status_code == 401 + actor.auth_kind = "bearer" + with pytest.raises(HTTPException) as exc: + await save_editor( + system.app.state, actor, id, SaveEditor(expected_version=1, manifest=m), "machine" + ) + assert exc.value.status_code == 403 + + +async def test_editor_plan_run_receipt_and_legacy_guard(system): + c = system.client + r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()}) + id = r.json()["id"] + m = (await c.get(f"/api/editors/{id}")).json()["manifest"] + saved = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "save"}, + ) + assert saved.status_code == 200, saved.text + old = await c.get(f"/api/workflows/{id}") + assert old.status_code == 200, old.text + assert old.json()["editor_manifest"] is not None + legacy = await c.patch(f"/api/workflows/{id}", json={"name": "bad"}, headers={"If-Match": "2"}) + assert legacy.status_code == 409 and legacy.json()["detail"]["code"] == "editor_required" + body = { + "expected_version": 2, + "output_goal": "media", + "targets": ["frame:" + m["shot_ids"][0]], + "force": [], + "execution_mode": "interactive", + } + plan = await c.post(f"/api/editors/{id}/plan", json=body) + assert plan.status_code == 200, plan.text + body["expected_plan_hash"] = plan.json()["plan_hash"] + run = await c.post(f"/api/editors/{id}/runs", json=body, headers={"Idempotency-Key": "run"}) + assert run.status_code == 202, run.text + again = await c.post(f"/api/editors/{id}/runs", json=body, headers={"Idempotency-Key": "run"}) + assert again.status_code == 202, again.text + assert again.json()["run"]["id"] == run.json()["run"]["id"] + + +async def test_editor_imports_legacy_story_selected_frame_without_write(system, monkeypatch): + from test_story_studio import prepare_manual_frame + from app.models import ShotSelection + + d, candidate, _ = await prepare_manual_frame(system, monkeypatch) + c = system.client + selected = await c.post( + f"/api/stories/{d['id']}/selections", + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": candidate["id"], + }, + headers={"Idempotency-Key": "select"}, + ) + assert selected.status_code == 200, selected.text + before = selected.json()["version"] + editor = await c.get(f"/api/editors/{d['id']}") + assert editor.status_code == 200, editor.text + binding = editor.json()["manifest"]["bindings"]["frame:" + ("1" * 32)] + assert binding["asset_id"] == candidate["asset"]["id"] + assert binding["source"] == "manual" and binding["locked"] + assert editor.json()["version"] == before + async with system.app.state.db.session() as s: + assert (await s.get(WorkflowDraft, d["id"])).editor_manifest is None + assert len((await s.scalars(select(ShotSelection))).all()) == 1 + m = editor.json()["manifest"] + m["captions"]["cues"] = [ + dict( + id="e" * 32, + anchor="shot", + shot_id="1" * 32, + start_frame=0, + end_frame=999, + text="conflict", + text_override=True, + timing_override=True, + ) + ] + saved = await c.post( + f"/api/editors/{d['id']}/save", + json={"expected_version": before, "manifest": m}, + headers={"Idempotency-Key": "editor-save"}, + ) + assert saved.status_code == 200, saved.text + assert saved.json()["issues"] + assert (await c.get(f"/api/stories/{d['id']}")).status_code == 200 + guarded = await c.patch( + f"/api/stories/{d['id']}", json={"name": "legacy"}, headers={"If-Match": str(before + 1)} + ) + assert guarded.status_code == 409 and guarded.json()["detail"]["code"] == "editor_required" + candidate_command = await c.post( + f"/api/stories/{d['id']}/candidates", + json={"expected_version": before + 1, "shot_id": "1" * 32, "kind": "frame"}, + headers={"Idempotency-Key": "legacy-candidate"}, + ) + assert ( + candidate_command.status_code == 409 + and candidate_command.json()["detail"]["code"] == "editor_required" + ) + + +async def test_apply_requires_success_and_matching_frozen_source(system): + from app.models import WorkflowRun + + c = system.client + d = (await c.post("/api/workflows", json={"name": "Editor", "spec": spec()})).json() + id = d["id"] + m = (await c.get(f"/api/editors/{id}")).json()["manifest"] + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + run = WorkflowRun( + owner_id=draft.owner_id, + draft_id=id, + draft_revision=1, + source_draft_version=1, + result_manifest=m, + spec_snapshot=m["spec"], + spec_hash="a" * 64, + run_kind="workflow_auto", + ) + s.add(run) + await s.flush() + rid = run.id + await s.commit() + body = {"expected_version": 1, "run_id": rid} + running = await c.post( + f"/api/editors/{id}/apply", json=body, headers={"Idempotency-Key": "running"} + ) + assert running.status_code == 409 + async with system.app.state.db.session() as s: + (await s.get(WorkflowRun, rid)).state = "succeeded" + await s.commit() + saved = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "edited"}, + ) + assert saved.status_code == 200, saved.text + body["expected_version"] = 2 + conflict = await c.post( + f"/api/editors/{id}/apply", json=body, headers={"Idempotency-Key": "old-result"} + ) + assert conflict.status_code == 409 + restored = await c.post( + f"/api/editors/{id}/from-run", json=body, headers={"Idempotency-Key": "explicit-restore"} + ) + assert restored.status_code == 200, restored.text + + +async def test_from_run_save_start_preserves_validated_lineage_and_receipts(system): + from app.models import WorkflowRun, Submission + + c = system.client + d = (await c.post("/api/workflows", json={"name": "Lineage", "spec": spec()})).json() + id = d["id"] + m = (await c.get(f"/api/editors/{id}")).json()["manifest"] + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + run = WorkflowRun( + owner_id=draft.owner_id, + draft_id=id, + draft_revision=1, + source_draft_version=1, + spec_snapshot=m["spec"], + spec_hash="a" * 64, + result_manifest=m, + state="succeeded", + ) + s.add(run) + await s.flush() + rid = run.id + await s.commit() + restored = await c.post( + f"/api/editors/{id}/from-run", + json={"expected_version": 1, "run_id": rid}, + headers={"Idempotency-Key": "restore-lineage"}, + ) + assert restored.status_code == 200, restored.text + assert restored.json()["manifest"]["base_run_id"] == rid + saved = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 2, "manifest": restored.json()["manifest"]}, + headers={"Idempotency-Key": "save-lineage"}, + ) + assert saved.status_code == 200, saved.text + body = {"expected_version": 3, "output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]]} + plan = await c.post(f"/api/editors/{id}/plan", json=body) + assert plan.status_code == 200, plan.text + body["expected_plan_hash"] = plan.json()["plan_hash"] + child = await c.post( + f"/api/editors/{id}/runs", json=body, headers={"Idempotency-Key": "child-lineage"} + ) + assert child.status_code == 202, child.text + archived = await c.delete(f"/api/workflow-runs/{rid}", headers={"If-Match": "1"}) + assert archived.status_code == 200, archived.text + async with system.app.state.db.session() as s: + child_id = child.json()["run"]["id"] + assert (await s.get(WorkflowRun, child_id)).base_run_id == rid + sub = await s.scalar(select(Submission).where(Submission.operation == "editor.run")) + assert sub.resource_json == {"draft_id": id, "run_id": child_id} + assert sub.status != "purged" + from app.services.editors import apply_run_result + + child_run = await s.get(WorkflowRun, child_id) + child_run.state = "succeeded" + assert await apply_run_result(s, child_run, system.settings) + draft = await s.get(WorkflowDraft, id) + assert draft.editor_manifest["base_run_id"] == child_id + assert child_run.result_manifest["base_run_id"] == child_id + assert child_run.plan_snapshot["manifest"]["base_run_id"] == rid + assert child_run.base_run_id == rid + await s.commit() + archived_source = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 4, "manifest": restored.json()["manifest"]}, + headers={"Idempotency-Key": "archived-source"}, + ) + assert archived_source.status_code == 200, archived_source.text + # 别的同owner草稿不允许借用来源ID,也不允许通过save扩大来源读取。 + other = (await c.post("/api/workflows", json={"name": "Other", "spec": spec()})).json() + other_m = (await c.get(f"/api/editors/{other['id']}")).json()["manifest"] + other_m["base_run_id"] = rid + forged = await c.post( + f"/api/editors/{other['id']}/save", + json={"expected_version": 1, "manifest": other_m}, + headers={"Idempotency-Key": "forged-lineage"}, + ) + assert forged.status_code == 404, forged.text + + +async def test_manual_audio_binding_uses_server_duration_and_preserves_trusted_samples(system): + from app.models import Asset + + c = system.client + d = (await c.post("/api/workflows", json={"name": "Audio facts", "spec": spec()})).json() + id = d["id"] + m = (await c.get(f"/api/editors/{id}")).json()["manifest"] + segment = m["audio"]["segments"][0]["id"] + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + a = Asset( + owner_id=draft.owner_id, + name="duration.wav", + storage_key="test/duration.wav", + kind="audio", + mime_type="audio/wav", + size_bytes=1, + sha256="a" * 64, + ready=True, + duration_seconds=0.0501, + ) + s.add(a) + await s.flush() + aid = a.id + await s.commit() + key = "audio:" + segment + m["bindings"][key] = dict( + asset_id=aid, + kind="audio", + source="manual", + sample_count=1, + duration_frames=900, + duration_seconds=900.0, + ) + saved = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 1, "manifest": m}, + headers={"Idempotency-Key": "audio-facts"}, + ) + assert saved.status_code == 200, saved.text + binding = saved.json()["manifest"]["bindings"][key] + assert binding["duration_seconds"] == 0.0501 and binding["duration_frames"] == 2 + assert binding.get("sample_count") is None + async with system.app.state.db.session() as s: + draft = await s.get(WorkflowDraft, id) + trusted = __import__("copy").deepcopy(draft.editor_manifest) + trusted["bindings"][key]["sample_count"] = 2405 + draft.editor_manifest = trusted + await s.commit() + changed = saved.json()["manifest"] + changed["bindings"][key]["sample_count"] = 1 + saved = await c.post( + f"/api/editors/{id}/save", + json={"expected_version": 2, "manifest": changed}, + headers={"Idempotency-Key": "trusted-facts"}, + ) + assert saved.status_code == 200, saved.text + assert saved.json()["manifest"]["bindings"][key]["sample_count"] == 2405 diff --git a/backend/tests/test_events.py b/backend/tests/test_events.py index 7f32336..343ccd5 100644 --- a/backend/tests/test_events.py +++ b/backend/tests/test_events.py @@ -4,23 +4,31 @@ import asyncio async def test_empty_stream_immediately_sends_connection_comment(system): - from app.events import event_stream + from app.api.routes.events import event_stream + system.settings.event_heartbeat_seconds = 15 owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] + async def connected(): return False + request = SimpleNamespace(app=system.app, is_disconnected=connected) stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0) try: - assert await asyncio.wait_for(anext(stream), timeout=.1) == ": connected\n\n" + assert await asyncio.wait_for(anext(stream), timeout=0.1) == ": connected\n\n" finally: await stream.aclose() async def test_durable_events_owner_replay_and_session_revocation(system, other_client): - from app.events import event_batch, session_is_active - job = (await system.client.post("/api/jobs", json={"task_type": "image.generate", - "input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0] + from app.services.events import event_batch, session_is_active + + job = ( + await system.client.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}}, + ) + ).json()["jobs"][0] actor = (await system.client.get("/api/auth/me")).json()["user"] other = (await other_client.get("/api/auth/me")).json()["user"] events = await event_batch(system.app.state.db, actor["id"], 0) @@ -34,11 +42,17 @@ async def test_durable_events_owner_replay_and_session_revocation(system, other_ async def test_real_stream_replays_ids_heartbeats_then_stops_after_logout(system): - from app.events import event_stream - await system.client.post("/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}}) + from app.api.routes.events import event_stream + + await system.client.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}}, + ) owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] + async def connected(): return False + request = SimpleNamespace(app=system.app, is_disconnected=connected) stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0) assert await anext(stream) == ": connected\n\n" @@ -55,9 +69,11 @@ async def test_real_stream_replays_ids_heartbeats_then_stops_after_logout(system async def test_http_eventsource_last_event_id_overrides_initial_query(system, monkeypatch): - import app.events as events + import app.api.routes.events as events + async def one_event(request, owner_id, token, after): yield f"id: {after}\nevent: reset\ndata: {{}}\n\n" + monkeypatch.setattr(events, "event_stream", one_event) response = await system.client.get("/api/events?after=2", headers={"Last-Event-ID": "19"}) assert response.status_code == 200 and response.text.startswith("id: 19\n") diff --git a/backend/tests/test_execution_recovery.py b/backend/tests/test_execution_recovery.py index 2e867fc..812bffc 100644 --- a/backend/tests/test_execution_recovery.py +++ b/backend/tests/test_execution_recovery.py @@ -1,303 +1,437 @@ import asyncio import pytest from app.models import Job -from app.artifacts import write_manifest,verify_manifest -from app.executions import begin_execution,accept_manifest +from app.services.artifacts import write_manifest, verify_manifest +from app.services.orchestration.executions import begin_execution, accept_manifest + @pytest.mark.asyncio async def test_stale_fence_and_corrupt_manifest_rejected(system): - row=(await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})).json()["jobs"][0] + row = ( + await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) + ).json()["jobs"][0] async with system.app.state.db.session() as s: - first=await begin_execution(s,row["id"]) - second=await begin_execution(s,row["id"]) - assert not await accept_manifest(s,first.id,first.fence_token,{}) - assert not await accept_manifest(s,second.id,"old-fence",{}) + first = await begin_execution(s, row["id"]) + second = await begin_execution(s, row["id"]) + assert not await accept_manifest(s, first.id, first.fence_token, {}) + assert not await accept_manifest(s, second.id, "old-fence", {}) await s.commit() - root=system.settings.job_work_root - source=root/"output.txt";source.write_text("good") - manifest=write_manifest(root,root,second.id,second.fence_token,[source],{}, {}) + root = system.settings.job_work_root + source = root / "output.txt" + source.write_text("good") + manifest = write_manifest(root, root, second.id, second.fence_token, [source], {}, {}) source.write_text("changed") - with pytest.raises(ValueError,match="hash mismatch"):verify_manifest(root,manifest) + with pytest.raises(ValueError, match="hash mismatch"): + verify_manifest(root, manifest) + @pytest.mark.asyncio -async def test_cpu_failed_state_db_write_failure_does_not_replay(system,monkeypatch): - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}}) - calls=0 +async def test_cpu_failed_state_db_write_failure_does_not_replay(system, monkeypatch): + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) + calls = 0 + async def fail_provider(*args): nonlocal calls - calls+=1 + calls += 1 raise ValueError("provider failed after possible execution") - async def fail_persist(*args):raise RuntimeError("database unavailable") - monkeypatch.setattr(system.provider,"run_cpu",fail_provider) - original=c._failure - monkeypatch.setattr(c,"_failure",fail_persist) + + async def fail_persist(*args): + raise RuntimeError("database unavailable") + + monkeypatch.setattr(system.provider, "run_cpu", fail_provider) + original = c._failure + monkeypatch.setattr(c, "_failure", fail_persist) await c.run_once(force=True) await asyncio.gather(*c._cpu.values()) - monkeypatch.setattr(c,"_failure",original) + monkeypatch.setattr(c, "_failure", original) await c.run_once(force=True) - assert calls==1 + assert calls == 1 async with system.app.state.db.session() as s: - assert (await s.get(Job,response.json()["jobs"][0]["id"])).state=="needs_attention" - -@pytest.mark.asyncio -async def test_soft_window_blocks_next_batch_but_queries_running(system,monkeypatch): - from app import resource_policy - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] - await c.run_once(force=True) - async with system.app.state.db.session() as s: - job=await s.get(Job,job_id);job.execution_mode="batch";upstream=job.upstream_id;await s.commit() - system.provider.remote[upstream]["state"]="running" - monkeypatch.setattr(resource_policy,"execution_policy",lambda now=None:{"batch_open":False}) - await c.run_once(force=True) - async with system.app.state.db.session() as s:assert (await s.get(Job,job_id)).state=="running" - assert system.provider.remote[upstream]["state"]=="running" + assert (await s.get(Job, response.json()["jobs"][0]["id"])).state == "needs_attention" @pytest.mark.asyncio -async def test_pool_concurrency_and_phase_window_recheck(system,monkeypatch): - from app import resource_policy - from app.providers import enter_phase +async def test_soft_window_blocks_next_batch_but_queries_running(system, monkeypatch): + from app.services.orchestration import resource_policy + + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "x"}} + ) + job_id = response.json()["jobs"][0]["id"] + await c.run_once(force=True) + # 准备阶段在后台运行;等待其真实完成,再设置“已提交后的窗口关闭”场景。 + if c._preparing: + await asyncio.gather(*list(c._preparing.values())) + await c.run_once(force=True) + async with system.app.state.db.session() as s: + job = await s.get(Job, job_id) + job.execution_mode = "batch" + upstream = job.upstream_id + await s.commit() + system.provider.remote[upstream]["state"] = "running" + monkeypatch.setattr(resource_policy, "execution_policy", lambda now=None: {"batch_open": False}) + await c.run_once(force=True) + async with system.app.state.db.session() as s: + assert (await s.get(Job, job_id)).state == "running" + assert system.provider.remote[upstream]["state"] == "running" + + +@pytest.mark.asyncio +async def test_pool_concurrency_and_phase_window_recheck(system, monkeypatch): + from app.services.orchestration import resource_policy + from app.domain.execution import enter_phase from types import SimpleNamespace - c=system.app.state.coordinator - opened=True;entered=[];sampled=asyncio.Event() - monkeypatch.setattr(resource_policy,"execution_policy",lambda now=None:{"batch_open":opened}) - async def phased(task_type,inputs,params,assets,work): + + c = system.app.state.coordinator + opened = True + entered = [] + sampled = asyncio.Event() + monkeypatch.setattr( + resource_policy, "execution_policy", lambda now=None: {"batch_open": opened} + ) + + async def phased(task_type, inputs, params, assets, work): nonlocal opened - await enter_phase("sample_frames","cpu_media") + await enter_phase("sample_frames", "cpu_media") entered.append("sample") sampled.set() - opened=False - await enter_phase("describe_frames","qwen_http") + opened = False + await enter_phase("describe_frames", "qwen_http") entered.append("describe") - out=work/"answer.txt";out.write_text("done") - return SimpleNamespace(outputs=[out],result={},metadata={}) - monkeypatch.setattr(system.provider,"run_cpu",phased) - response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}}) + out = work / "answer.txt" + out.write_text("done") + return SimpleNamespace(outputs=[out], result={}, metadata={}) + + monkeypatch.setattr(system.provider, "run_cpu", phased) + response = await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) async with system.app.state.db.session() as session: - job=await session.get(Job,response.json()["jobs"][0]["id"]);job.execution_mode="batch";await session.commit() + job = await session.get(Job, response.json()["jobs"][0]["id"]) + job.execution_mode = "batch" + await session.commit() await c.run_once(force=True) - await asyncio.wait_for(sampled.wait(),5) - assert entered==["sample"] - assert c._pools["cpu_media"]._value==1 and c._pools["qwen_http"]._value==1 + await asyncio.wait_for(sampled.wait(), 5) + assert entered == ["sample"] + assert c._pools["cpu_media"]._value == 1 and c._pools["qwen_http"]._value == 1 # Reopening admits the next phase; current phase was allowed to finish. - opened=True - await asyncio.wait_for(asyncio.gather(*c._cpu.values()),3) - assert entered==["sample","describe"] + opened = True + await asyncio.wait_for(asyncio.gather(*c._cpu.values()), 3) + assert entered == ["sample", "describe"] @pytest.mark.asyncio -async def test_lost_asset_commit_ack_preserves_file_and_imports_once(system,monkeypatch): +async def test_lost_asset_commit_ack_preserves_file_and_imports_once(system, monkeypatch): from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.models import Asset - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] + + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "x"}} + ) + job_id = response.json()["jobs"][0]["id"] await c.run_once(force=True) - upstream=next(iter(system.provider.remote)) - system.provider.remote[upstream].update(state="succeeded",result={"outputs":[{"path":"image.png"}]}) - original=AsyncSession.commit;lost=False + upstream = next(iter(system.provider.remote)) + system.provider.remote[upstream].update( + state="succeeded", result={"outputs": [{"path": "image.png"}]} + ) + original = AsyncSession.commit + lost = False + async def uncertain(session): nonlocal lost - trigger=not lost and any(isinstance(row,Asset) and not row.ready for row in session.identity_map.values()) + trigger = not lost and any( + isinstance(row, Asset) and not row.ready for row in session.identity_map.values() + ) await original(session) if trigger: - lost=True + lost = True raise RuntimeError("commit succeeded; ACK lost") - monkeypatch.setattr(AsyncSession,"commit",uncertain) + + monkeypatch.setattr(AsyncSession, "commit", uncertain) await c.run_once(force=True) assert lost await c.run_once(force=True) async with system.app.state.db.session() as session: - assets=(await session.scalars(select(Asset).where(Asset.source_job_id==job_id))).all() - assert len(assets)==1 and assets[0].ready - assert (system.settings.asset_root/assets[0].storage_key).exists() - assert (await session.get(Job,job_id)).state=="succeeded" - assert system.provider.download_count==1 + assets = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).all() + assert len(assets) == 1 and assets[0].ready + assert (system.settings.asset_root / assets[0].storage_key).exists() + assert (await session.get(Job, job_id)).state == "succeeded" + assert system.provider.download_count == 1 + @pytest.mark.asyncio -async def test_cancel_is_sent_once_until_ack(system,monkeypatch): - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] +async def test_cancel_is_sent_once_until_ack(system, monkeypatch): + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "x"}} + ) + job_id = response.json()["jobs"][0]["id"] await c.run_once(force=True) - calls=[] + calls = [] + async def delayed_cancel(remote_id): calls.append(remote_id) - return {**system.provider.remote[remote_id],"state":"running"} - monkeypatch.setattr(system.provider,"cancel",delayed_cancel) - await system.client.post("/api/jobs/"+job_id+"/cancel") - await c.run_once(force=True);await c.run_once(force=True);await c.run_once(force=True) - assert len(calls)==1 + return {**system.provider.remote[remote_id], "state": "running"} + + monkeypatch.setattr(system.provider, "cancel", delayed_cancel) + await system.client.post("/api/jobs/" + job_id + "/cancel") + await c.run_once(force=True) + await c.run_once(force=True) + await c.run_once(force=True) + assert len(calls) == 1 @pytest.mark.asyncio -async def test_cancel_committed_after_slot_claim_never_calls_provider(system,monkeypatch): - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] - enter=c._enter_phase - async def race(job_id,phase,pool): - await enter(job_id,phase,pool) +async def test_cancel_committed_after_slot_claim_never_calls_provider(system, monkeypatch): + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) + job_id = response.json()["jobs"][0]["id"] + enter = c._enter_phase + + async def race(job_id, phase, pool): + await enter(job_id, phase, pool) async with system.app.state.db.session() as session: - job=await session.get(Job,job_id);job.cancel_requested=True;job.state="cancelling";await session.commit() - monkeypatch.setattr(c,"_enter_phase",race) + job = await session.get(Job, job_id) + job.cancel_requested = True + job.state = "cancelling" + await session.commit() + + monkeypatch.setattr(c, "_enter_phase", race) await c.run_once(force=True) await asyncio.gather(*c._cpu.values()) - assert system.provider.cpu_runs==0 - async with system.app.state.db.session() as session:assert (await session.get(Job,job_id)).state=="cancelled" + assert system.provider.cpu_runs == 0 + async with system.app.state.db.session() as session: + assert (await session.get(Job, job_id)).state == "cancelled" @pytest.mark.asyncio -async def test_waiting_qwen_job_rechecks_unknown_pool_after_acquire(system,monkeypatch): +async def test_waiting_qwen_job_rechecks_unknown_pool_after_acquire(system, monkeypatch): from conftest import BoundaryError - c=system.app.state.coordinator - first_started=asyncio.Event();second_waiting=asyncio.Event();calls=[] - acquire=c._pools["qwen_http"].acquire + + c = system.app.state.coordinator + first_started = asyncio.Event() + second_waiting = asyncio.Event() + calls = [] + acquire = c._pools["qwen_http"].acquire + async def tracked_acquire(): - if c._pools["qwen_http"].locked():second_waiting.set() + if c._pools["qwen_http"].locked(): + second_waiting.set() return await acquire() - monkeypatch.setattr(c._pools["qwen_http"],"acquire",tracked_acquire) + + monkeypatch.setattr(c._pools["qwen_http"], "acquire", tracked_acquire) + async def unknown(*args): calls.append(args[1]["prompt"]) first_started.set() await second_waiting.wait() raise BoundaryError("remote compute completion unknown") - monkeypatch.setattr(system.provider,"run_cpu",unknown) - for prompt in ("first","second"): - await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":prompt}}) + + monkeypatch.setattr(system.provider, "run_cpu", unknown) + for prompt in ("first", "second"): + await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": prompt}} + ) await c.run_once(force=True) - await asyncio.wait_for(second_waiting.wait(),3) + await asyncio.wait_for(second_waiting.wait(), 3) for _ in range(100): - if "qwen_http" in c._blocked_pools:break - await asyncio.sleep(.01) - await asyncio.sleep(.1) - assert calls==["first"] + if "qwen_http" in c._blocked_pools: + break + await asyncio.sleep(0.01) + await asyncio.sleep(0.1) + assert calls == ["first"] + @pytest.mark.asyncio -async def test_cpu_media_cancel_records_cleanup_and_allows_explicit_retry(system,monkeypatch): - from app.v2_models import Execution +async def test_cpu_media_cancel_records_cleanup_and_allows_explicit_retry(system, monkeypatch): + from app.models import Execution from sqlalchemy import select - c=system.app.state.coordinator - started=asyncio.Event();cleaned=asyncio.Event() + + c = system.app.state.coordinator + started = asyncio.Event() + cleaned = asyncio.Event() + async def cancellable(*args): started.set() - try:await asyncio.Future() - finally:cleaned.set() - monkeypatch.setattr(system.provider,"run_cpu",cancellable) - body={"task_type":"audio.speech","input":{"prompt":"x"}} - system.settings.tts_base_url="http://private-tts" - r=await system.client.post("/api/jobs",json=body);assert r.status_code==202,r.text - job_id=r.json()["jobs"][0]["id"] + try: + await asyncio.Future() + finally: + cleaned.set() + + monkeypatch.setattr(system.provider, "run_cpu", cancellable) + body = {"task_type": "audio.speech", "input": {"prompt": "x"}} + system.settings.tts_base_url = "http://private-tts" + r = await system.client.post("/api/jobs", json=body) + assert r.status_code == 202, r.text + job_id = r.json()["jobs"][0]["id"] async with system.app.state.db.session() as session: - job=await session.get(Job,job_id);job.task_type="video.compose";await session.commit() - await c.run_once(force=True);await asyncio.wait_for(started.wait(),3) - await system.client.post("/api/jobs/"+job_id+"/cancel") - await c.run_once(force=True);await asyncio.gather(*c._cpu.values()) + job = await session.get(Job, job_id) + job.task_type = "video.compose" + await session.commit() + await c.run_once(force=True) + await asyncio.wait_for(started.wait(), 3) + await system.client.post("/api/jobs/" + job_id + "/cancel") + await c.run_once(force=True) + await asyncio.gather(*c._cpu.values()) assert cleaned.is_set() async with system.app.state.db.session() as session: - execution=await session.scalar(select(Execution).where(Execution.job_id==job_id)) - assert execution.state=="exited" and execution.finished_at is not None + execution = await session.scalar(select(Execution).where(Execution.job_id == job_id)) + assert execution.state == "exited" and execution.finished_at is not None async with system.app.state.db.session() as session: - job=await session.get(Job,job_id);job.task_type="audio.speech";await session.commit() - retry=await system.client.post("/api/jobs/"+job_id+"/retry",headers={"Idempotency-Key":"after-cleanup"}) - assert retry.status_code==202,retry.text + job = await session.get(Job, job_id) + job.task_type = "audio.speech" + await session.commit() + retry = await system.client.post( + "/api/jobs/" + job_id + "/retry", headers={"Idempotency-Key": "after-cleanup"} + ) + assert retry.status_code == 202, retry.text @pytest.mark.asyncio -async def test_gpu_preparation_does_not_block_tick_behind_media_slot(system,monkeypatch): - from app.providers import enter_phase - c=system.app.state.coordinator - await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}}) +async def test_gpu_preparation_does_not_block_tick_behind_media_slot(system, monkeypatch): + from app.domain.execution import enter_phase + + c = system.app.state.coordinator + await system.client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "x"}} + ) + async def prepare(*args): - await enter_phase("extract_audio","cpu_media") + await enter_phase("extract_audio", "cpu_media") raise AssertionError("Extraction must not start behind occupied media pool") - monkeypatch.setattr(system.provider,"prepare_gpu_payload",prepare) + + monkeypatch.setattr(system.provider, "prepare_gpu_payload", prepare) await c._pools["cpu_media"].acquire() try: - await asyncio.wait_for(c.run_once(force=True),1) + await asyncio.wait_for(c.run_once(force=True), 1) assert not system.provider.accepted - finally:c._pools["cpu_media"].release() + finally: + c._pools["cpu_media"].release() + @pytest.mark.asyncio -async def test_disabled_owner_cannot_enter_new_phase_after_slot_wait(system,monkeypatch): +async def test_disabled_owner_cannot_enter_new_phase_after_slot_wait(system, monkeypatch): from app.models import User - from app.coordinator import PhaseDeferred - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] - acquire=c._pools["qwen_http"].acquire + from app.services.orchestration.coordinator import PhaseDeferred + + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) + job_id = response.json()["jobs"][0]["id"] + acquire = c._pools["qwen_http"].acquire + async def race(): - result=await acquire() + result = await acquire() async with system.app.state.db.session() as session: - job=await session.get(Job,job_id);owner=await session.get(User,job.owner_id);owner.disabled=True;await session.commit() + job = await session.get(Job, job_id) + owner = await session.get(User, job.owner_id) + owner.disabled = True + await session.commit() return result - monkeypatch.setattr(c._pools["qwen_http"],"acquire",race) - with pytest.raises(PhaseDeferred):await c._enter_phase(job_id,"solve","qwen_http",nonblocking=True) - assert c._pools["qwen_http"]._value==1 + + monkeypatch.setattr(c._pools["qwen_http"], "acquire", race) + with pytest.raises(PhaseDeferred): + await c._enter_phase(job_id, "solve", "qwen_http", nonblocking=True) + assert c._pools["qwen_http"]._value == 1 + @pytest.mark.asyncio async def test_generated_output_actual_owner_budget_stops_recollection(system): - system.settings.max_owner_asset_bytes=1 - c=system.app.state.coordinator - response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] - await c.run_once(force=True);await asyncio.gather(*c._cpu.values()) - async with system.app.state.db.session() as session: - job=await session.get(Job,job_id) - assert job.state=="failed" and job.error_json["code"]=="quota_exceeded" + system.settings.max_owner_asset_bytes = 1 + c = system.app.state.coordinator + response = await system.client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) + job_id = response.json()["jobs"][0]["id"] await c.run_once(force=True) - assert system.provider.cpu_runs==1 + await asyncio.gather(*c._cpu.values()) + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert job.state == "failed" and job.error_json["code"] == "quota_exceeded" + await c.run_once(force=True) + assert system.provider.cpu_runs == 1 assert list(system.settings.job_work_root.rglob("result-manifest.json")) @pytest.mark.asyncio -@pytest.mark.parametrize("task_type",["math.solve","audio.speech"]) -async def test_shared_http_explicit_cancel_drains_response_before_next_call(system,monkeypatch,task_type): +@pytest.mark.parametrize("task_type", ["math.solve", "audio.speech"]) +async def test_shared_http_explicit_cancel_drains_response_before_next_call( + system, monkeypatch, task_type +): from types import SimpleNamespace from sqlalchemy import select - from app.v2_models import Execution - c=system.app.state.coordinator - system.settings.tts_base_url="http://private-tts" - started=asyncio.Event();finish=asyncio.Event();calls=[] - async def http_phase(task,inputs,params,assets,work): + from app.models import Execution + + c = system.app.state.coordinator + system.settings.tts_base_url = "http://private-tts" + started = asyncio.Event() + finish = asyncio.Event() + calls = [] + + async def http_phase(task, inputs, params, assets, work): calls.append(inputs["prompt"]) - if inputs["prompt"]=="first": - started.set();await finish.wait() - output=work/"answer.txt";output.write_text("response completed") - return SimpleNamespace(outputs=[output],result={},metadata={}) - monkeypatch.setattr(system.provider,"run_cpu",http_phase) - first=await system.client.post("/api/jobs",json={"task_type":task_type,"input":{"prompt":"first"}}) - job_id=first.json()["jobs"][0]["id"] - await c.run_once(force=True);await asyncio.wait_for(started.wait(),3) - await system.client.post("/api/jobs",json={"task_type":task_type,"input":{"prompt":"second"}}) - await system.client.post("/api/jobs/"+job_id+"/cancel") - await c.run_once(force=True);await asyncio.sleep(.05) - assert calls==["first"] and not c._cpu[job_id].done() - finish.set();await asyncio.wait_for(asyncio.gather(*c._cpu.values()),5) - assert calls==["first","second"] + if inputs["prompt"] == "first": + started.set() + await finish.wait() + output = work / "answer.txt" + output.write_text("response completed") + return SimpleNamespace(outputs=[output], result={}, metadata={}) + + monkeypatch.setattr(system.provider, "run_cpu", http_phase) + first = await system.client.post( + "/api/jobs", json={"task_type": task_type, "input": {"prompt": "first"}} + ) + job_id = first.json()["jobs"][0]["id"] + await c.run_once(force=True) + await asyncio.wait_for(started.wait(), 3) + await system.client.post( + "/api/jobs", json={"task_type": task_type, "input": {"prompt": "second"}} + ) + await system.client.post("/api/jobs/" + job_id + "/cancel") + await c.run_once(force=True) + await asyncio.sleep(0.05) + assert calls == ["first"] and not c._cpu[job_id].done() + finish.set() + await asyncio.wait_for(asyncio.gather(*c._cpu.values()), 5) + assert calls == ["first", "second"] async with system.app.state.db.session() as session: - first=await session.get(Job,job_id) - execution=await session.scalar(select(Execution).where(Execution.job_id==job_id)) - assert first.state=="cancelled" and first.result_json is None - assert execution.state=="exited" + first = await session.get(Job, job_id) + execution = await session.scalar(select(Execution).where(Execution.job_id == job_id)) + assert first.state == "cancelled" and first.result_json is None + assert execution.state == "exited" + @pytest.mark.asyncio -async def test_speech_transport_unknown_quarantines_media_pool(system,monkeypatch): +async def test_speech_transport_unknown_quarantines_media_pool(system, monkeypatch): from conftest import BoundaryError from sqlalchemy import select - from app.v2_models import Execution - c=system.app.state.coordinator - system.settings.tts_base_url="http://private-tts" - async def failed(*args):raise BoundaryError("speech server completion unknown") - monkeypatch.setattr(system.provider,"run_cpu",failed) - response=await system.client.post("/api/jobs",json={"task_type":"audio.speech","input":{"prompt":"x"}}) - await c.run_once(force=True);await asyncio.gather(*c._cpu.values()) + from app.models import Execution + + c = system.app.state.coordinator + system.settings.tts_base_url = "http://private-tts" + + async def failed(*args): + raise BoundaryError("speech server completion unknown") + + monkeypatch.setattr(system.provider, "run_cpu", failed) + response = await system.client.post( + "/api/jobs", json={"task_type": "audio.speech", "input": {"prompt": "x"}} + ) + await c.run_once(force=True) + await asyncio.gather(*c._cpu.values()) async with system.app.state.db.session() as session: - job=await session.get(Job,response.json()["jobs"][0]["id"]) - execution=await session.scalar(select(Execution).where(Execution.job_id==job.id)) - assert job.state=="needs_attention" and execution.state=="unknown" + job = await session.get(Job, response.json()["jobs"][0]["id"]) + execution = await session.scalar(select(Execution).where(Execution.job_id == job.id)) + assert job.state == "needs_attention" and execution.state == "unknown" assert "cpu_media" in c._blocked_pools diff --git a/backend/tests/test_fifo_json.py b/backend/tests/test_fifo_json.py new file mode 100644 index 0000000..e37dc62 --- /dev/null +++ b/backend/tests/test_fifo_json.py @@ -0,0 +1,52 @@ +"""Prepared dispatch uses native JSON arrays on production MySQL.""" + +from sqlalchemy import event +from sqlalchemy.dialects import mysql + +from app.models import Job +from test_jobs import submit + + +async def test_prepared_fifo_uses_native_json_and_preserves_payload_and_holds(system): + jobs = [] + for prompt in ("empty", "window", "manual", "window-manual"): + jobs.append((await submit(system, task_type="video.generate", input={"prompt": prompt}))[0]) + async with system.app.state.db.session() as session: + for result, holds in zip(jobs, ([], ["window"], ["manual"], ["window", "manual"])): + job = await session.get(Job, result["id"]) + job.hold_reasons = holds + # A payload prepared on Linux before local handoff is immutable. + job.upstream_payload = { + "task_type": "video.generate", + "input": { + "prompt": job.input_json["prompt"], + "image_path": "/workspace/inputs/old-owned.png", + }, + "parameters": {}, + "timeout_seconds": 3600, + } + await session.commit() + + queries = [] + + def record_query(connection, statement, multiparams, params, options): + compiled = statement.compile(dialect=mysql.dialect()) + sql = str(compiled) + if sql.startswith("SELECT") and "hold_reasons =" in sql: + queries.append(sql) + + engine = system.app.state.db.engine.sync_engine + event.listen(engine, "before_execute", record_query) + try: + await system.app.state.coordinator.run_once(force=True) + finally: + event.remove(engine, "before_execute", record_query) + assert queries, "Exercise the actual FIFO ready query, including persisted ready payloads" + # A bare VARCHAR parameter containing [] compares as a JSON string on + # MySQL, so it cannot match a JSON array column. Both sides must be JSON. + assert all(query.count("hold_reasons = json_array(") == 2 for query in queries) + payloads = [payload for _, payload in system.provider.submitted_payloads] + assert [payload["input"]["prompt"] for payload in payloads] == ["empty", "window"] + assert all( + payload["input"]["image_path"] == "/workspace/inputs/old-owned.png" for payload in payloads + ) diff --git a/backend/tests/test_folder_propagation.py b/backend/tests/test_folder_propagation.py new file mode 100644 index 0000000..b978463 --- /dev/null +++ b/backend/tests/test_folder_propagation.py @@ -0,0 +1,743 @@ +import pytest + + +async def folder(client, name): + r = await client.post("/api/folders", json={"name": name}) + assert r.status_code == 201, r.text + return r.json()["id"] + + +@pytest.mark.asyncio +async def test_upload_patch_filter_and_foreign_folder(system, other_client, png_bytes): + c = system.client + fid = await folder(c, "素材") + foreign = await folder(other_client, "私有") + rejected = await c.post( + "/api/assets", + data={"folder_id": foreign}, + files={"file": ("x.png", png_bytes, "image/png")}, + ) + assert rejected.status_code == 404 + r = await c.post( + "/api/assets", data={"folder_id": fid}, files={"file": ("x.png", png_bytes, "image/png")} + ) + assert r.status_code == 201, r.text + asset = r.json() + assert asset["folder_ids"] == [fid] + assert (await c.get("/api/assets", params={"folder_id": "unclassified"})).json()["total"] == 0 + patched = await c.patch("/api/assets/" + asset["id"], json={"folder_ids": []}) + assert patched.status_code == 200, patched.text + assert patched.json()["folder_ids"] == [] + assert (await c.get("/api/assets", params={"folder_id": fid})).json()["total"] == 0 + assert (await c.get("/api/assets", params={"folder_id": foreign})).status_code == 404 + + +@pytest.mark.asyncio +async def test_job_targets_idempotency_retry_and_deleted_target(system): + from app.models import Job + from app.services.assets import import_output + from PIL import Image + + c = system.client + fid = await folder(c, "生成") + body = {"task_type": "image.generate", "input": {"prompt": "tree"}, "folder_id": fid} + r = await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "folder-job"}) + assert r.status_code == 202, r.text + job = r.json()["jobs"][0] + assert job["folder_id"] == job["output_folder_id"] == fid + assert (await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "folder-job"})).json()[ + "jobs" + ][0]["id"] == job["id"] + assert ( + await c.post( + "/api/jobs", + json={**body, "output_folder_id": None}, + headers={"Idempotency-Key": "folder-job"}, + ) + ).status_code == 409 + async with system.app.state.db.session() as s: + row = await s.get(Job, job["id"]) + row.state = "failed" + await s.commit() + retry = await c.post("/api/jobs/" + job["id"] + "/retry") + assert retry.status_code == 202, retry.text + assert retry.json()["jobs"][0]["output_folder_id"] == fid + assert (await c.delete("/api/folders/" + fid)).status_code == 204 + source = system.settings.job_work_root / "result.png" + source.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB", (12, 12)).save(source) + asset = await import_output(system.app.state.db, system.settings, row, source, 0) + assert ( + await c.get("/api/assets/" + asset.id) + ).status_code == 404 # publication remains coordinator-owned + async with system.app.state.db.session() as s: + from app.models import Asset + + saved = await s.get(Asset, asset.id) + assert not saved.folder_links + + +@pytest.mark.asyncio +async def test_story_default_folder_and_explicit_null(system): + from test_story_studio import story_spec + + c = system.client + first = await c.post("/api/stories", json={"name": "故事", "spec": story_spec()}) + assert first.status_code == 201, first.text + assert first.json()["folder_id"] + second = await c.post("/api/stories", json={"name": "故事", "spec": story_spec()}) + assert second.json()["folder_id"] != first.json()["folder_id"] + unc = await c.post( + "/api/stories", json={"name": "未分类", "spec": story_spec(), "folder_id": None} + ) + assert unc.status_code == 201, unc.text + assert unc.json()["folder_id"] is None + assert (await c.get("/api/stories", params={"folder_id": "unclassified"})).json()["total"] == 1 + + +@pytest.mark.asyncio +async def test_workflow_frozen_target_children(system): + from test_timeline_v2 import spec + from app.services.orchestration.workflow_engine import advance_workflows + + c = system.client + fid = await folder(c, "workflow") + response = await c.post("/api/workflows", json={"name": "w", "spec": spec(), "folder_id": fid}) + assert response.status_code == 201, response.text + d = response.json() + body = {"draft_revision": d["revision"], "expected_version": d["version"]} + started = await c.post( + "/api/workflows/" + d["id"] + "/runs", json=body, headers={"Idempotency-Key": "freeze"} + ) + assert started.status_code == 202, started.text + run = started.json()["run"] + assert run["output_folder_id"] == fid + current = (await c.get("/api/workflows/" + d["id"])).json() + assert ( + await c.patch( + "/api/workflows/" + d["id"], + json={"folder_id": None}, + headers={"If-Match": str(current["version"])}, + ) + ).status_code == 200 + await advance_workflows(system.app.state.db, system.settings, system.provider) + snap = (await c.get("/api/workflow-runs/" + run["id"])).json() + assert snap["jobs"] and all(j["output_folder_id"] == fid for j in snap["jobs"]) + + +@pytest.mark.asyncio +async def test_queued_candidate_freezes_target(system): + from test_story_studio import story_spec + from app.models import ShotCandidate, Job + from sqlalchemy import select + from app.services.stories.candidates import feed_candidates + + c = system.client + d = (await c.post("/api/stories", json={"name": "candidate", "spec": story_spec()})).json() + assert d.get("folder_id") + body = {"expected_version": d["version"], "shot_id": "1" * 32, "kind": "frame"} + r = await c.post( + "/api/stories/" + d["id"] + "/candidates", + json=body, + headers={"Idempotency-Key": "candidate-freeze"}, + ) + assert r.status_code == 202, r.text + current = (await c.get("/api/stories/" + d["id"])).json() + assert ( + await c.patch( + "/api/stories/" + d["id"], + json={"folder_id": None}, + headers={"If-Match": str(current["version"])}, + ) + ).status_code == 200 + async with system.app.state.db.session() as s: + candidate = await s.scalar(select(ShotCandidate).where(ShotCandidate.draft_id == d["id"])) + assert candidate.plan_json["output_folder_id"] == d["folder_id"] + await feed_candidates(s, system.settings) + await s.commit() + j = await s.get(Job, candidate.job_id) + assert j.output_folder_id == d["folder_id"] + + +@pytest.mark.asyncio +async def test_queued_candidate_deleted_target_falls_back(system): + from test_story_studio import story_spec + from app.models import ShotCandidate, Job + from app.services.stories.candidates import feed_candidates + from sqlalchemy import select + + c = system.client + d = (await c.post("/api/stories", json={"name": "deleted", "spec": story_spec()})).json() + r = await c.post( + "/api/stories/" + d["id"] + "/candidates", + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + headers={"Idempotency-Key": "deleted-candidate"}, + ) + assert r.status_code == 202, r.text + assert (await c.delete("/api/folders/" + d["folder_id"])).status_code == 204 + async with system.app.state.db.session() as s: + await feed_candidates(s, system.settings) + candidate = await s.scalar(select(ShotCandidate).where(ShotCandidate.draft_id == d["id"])) + assert candidate.job_id, candidate.error_json + assert (await s.get(Job, candidate.job_id)).output_folder_id is None + + +@pytest.mark.asyncio +async def test_old_job_hash_and_submission_body_remain_compatible(system): + import hashlib + import json + from app.models import Job, Submission + from app.services.submissions import body_hash + from sqlalchemy import select + + c = system.client + body = {"task_type": "image.generate", "input": {"prompt": "old"}} + response = await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "old-hash"}) + assert response.status_code == 202, response.text + legacy = {**body, "parameters": {}, "count": 1, "scheduled_at": None} + expected = hashlib.sha256( + json.dumps(legacy, sort_keys=True, ensure_ascii=False, allow_nan=False).encode() + ).hexdigest() + async with system.app.state.db.session() as s: + j = await s.get(Job, response.json()["jobs"][0]["id"]) + sub = await s.scalar(select(Submission).where(Submission.key == "old-hash")) + assert j.request_hash == expected + assert sub.body_hash == body_hash({**legacy, "execution_mode": "interactive"}, 2) + + +@pytest.mark.asyncio +async def test_shared_import_target_and_old_no_body(system, png_bytes, other_client): + c = system.client + asset = (await c.post("/api/assets", files={"file": ("x.png", png_bytes, "image/png")})).json() + pub = await c.post( + "/api/assets/" + asset["id"] + "/publish", headers={"Idempotency-Key": "publish-folder"} + ) + assert pub.status_code == 201, pub.text + shared_id = pub.json()["id"] + foreign = await folder(other_client, "foreign-import") + before_files = set(system.settings.asset_root.rglob("*")) + denied = await c.post( + "/api/shared-assets/" + shared_id + "/import", + json={"folder_id": foreign}, + headers={"Idempotency-Key": "foreign-import"}, + ) + assert denied.status_code == 404, denied.text + assert set(system.settings.asset_root.rglob("*")) == before_files + fid = await folder(c, "import") + first = await c.post( + "/api/shared-assets/" + shared_id + "/import", + json={"folder_id": fid}, + headers={"Idempotency-Key": "import-folder"}, + ) + assert first.status_code == 201, first.text + assert first.json()["folder_ids"] == [fid] + assert ( + await c.post( + "/api/shared-assets/" + shared_id + "/import", + json={}, + headers={"Idempotency-Key": "import-folder"}, + ) + ).status_code == 409 + old = await c.post("/api/shared-assets/" + shared_id + "/import") + assert old.status_code == 201, old.text + assert old.json()["folder_ids"] == [] + assert (await c.delete("/api/folders/" + fid)).status_code == 204 + replay = await c.post( + "/api/shared-assets/" + shared_id + "/import", + json={"folder_id": fid}, + headers={"Idempotency-Key": "import-folder"}, + ) + assert replay.status_code == 201, replay.text + assert replay.json()["id"] == first.json()["id"] + assert replay.json()["folder_ids"] == [] + assert ( + await c.post( + "/api/shared-assets/" + shared_id + "/import", + json={}, + headers={"Idempotency-Key": "import-folder"}, + ) + ).status_code == 409 + + +@pytest.mark.asyncio +async def test_batch_job_and_workflow_targets(system): + from test_timeline_v2 import spec + + c = system.client + fid = await folder(c, "batch") + d = ( + await c.post("/api/workflows", json={"name": "w", "spec": spec(), "folder_id": fid}) + ).json() + items = [ + { + "kind": "job", + "task_type": "image.generate", + "input": {"prompt": "tree"}, + "folder_id": fid, + "output_folder_id": None, + }, + { + "kind": "workflow", + "draft_id": d["id"], + "draft_revision": d["revision"], + "expected_version": d["version"], + "output_folder_id": None, + }, + ] + response = await c.post( + "/api/batches", json={"items": items}, headers={"Idempotency-Key": "folder-batch"} + ) + assert response.status_code == 202, response.text + from app.models import Job, WorkflowRun + + async with system.app.state.db.session() as s: + records = response.json()["items"] + job = await s.get(Job, records[0]["target_id"]) + run = await s.get(WorkflowRun, records[1]["target_id"]) + assert job.folder_id == run.folder_id == fid + assert job.output_folder_id is run.output_folder_id is None + + +@pytest.mark.asyncio +async def test_manual_source_keeps_membership_and_output_freezes(system, monkeypatch, png_bytes): + import asyncio + from app.adapters.provider.client import Provider + from test_story_studio import story_spec + + c = system.client + source_folder = await folder(c, "source") + d = (await c.post("/api/stories", json={"name": "manual", "spec": story_spec()})).json() + source = ( + await c.post( + "/api/assets", + data={"folder_id": source_folder}, + files={"file": ("x.png", png_bytes, "image/png")}, + ) + ).json() + response = await c.post( + "/api/stories/" + d["id"] + "/candidates", + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "source_kind": "manual", + "asset_id": source["id"], + }, + headers={"Idempotency-Key": "manual-folder"}, + ) + assert response.status_code == 202, response.text + assert set((await c.get("/api/assets/" + source["id"])).json()["folder_ids"]) == { + source_folder, + d["folder_id"], + } + target = await folder(c, "later") + assert ( + await c.patch( + "/api/stories/" + d["id"], json={"folder_id": target}, headers={"If-Match": "1"} + ) + ).status_code == 200 + real = Provider(system.settings) + monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) + try: + for _ in range(4): + await system.app.state.coordinator.run_once() + tasks = list(system.app.state.coordinator._cpu.values()) + if tasks: + await asyncio.gather(*tasks) + candidate = (await c.get("/api/stories/" + d["id"] + "/candidates")).json()["items"][0] + assert candidate["state"] == "ready", candidate + assert candidate["asset"]["folder_ids"] == [d["folder_id"]] + moved = await c.patch("/api/assets/" + candidate["asset"]["id"], json={"folder_ids": []}) + assert moved.status_code == 200 + assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 409 + finally: + await real.aclose() + + +@pytest.mark.asyncio +async def test_candidate_targets_do_not_change_generation_hash_and_old_plan_unclassified(system): + from test_story_studio import story_spec + from app.models import ShotCandidate, Job + from app.services.stories.candidates import feed_candidates + + c = system.client + d = (await c.post("/api/stories", json={"name": "hash", "spec": story_spec()})).json() + body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"} + first = await c.post( + "/api/stories/" + d["id"] + "/candidates", + json=body, + headers={"Idempotency-Key": "hash-first"}, + ) + second = await c.post( + "/api/stories/" + d["id"] + "/candidates", + json={**body, "output_folder_id": None}, + headers={"Idempotency-Key": "hash-second"}, + ) + assert first.status_code == second.status_code == 202 + a, b = first.json()["candidates"][0], second.json()["candidates"][0] + assert a["generation_hash"] == b["generation_hash"] + assert ( + await c.post( + "/api/stories/" + d["id"] + "/candidates", + json={**body, "output_folder_id": None}, + headers={"Idempotency-Key": "hash-first"}, + ) + ).status_code == 409 + async with system.app.state.db.session() as s: + old = await s.get(ShotCandidate, a["id"]) + old.plan_json = { + k: v for k, v in old.plan_json.items() if k not in {"folder_id", "output_folder_id"} + } + await feed_candidates(s, system.settings) + job = await s.get(Job, old.job_id) + assert job.folder_id is job.output_folder_id is None + + +@pytest.mark.asyncio +async def test_workflow_retry_reuse_and_final_output_keep_target(system): + from test_timeline_v2 import spec + from test_workflows_v2 import publish_video + from app.services.orchestration.workflow_engine import advance_workflows + from app.models import Job + from app.services.events import event_batch + + c = system.client + fid = await folder(c, "reuse-one") + target = await folder(c, "reuse-two") + d = ( + await c.post("/api/workflows", json={"name": "reuse", "spec": spec(), "folder_id": fid}) + ).json() + first = await c.post( + "/api/workflows/" + d["id"] + "/runs", + json={"draft_revision": 1, "expected_version": 1}, + headers={"Idempotency-Key": "reuse-first"}, + ) + rid = first.json()["run"]["id"] + await advance_workflows(system.app.state.db, system.settings, system.provider) + snap = (await c.get("/api/workflow-runs/" + rid)).json() + old = next(x for x in snap["steps"] if x["step_key"] == "shot_1")["selected_job_id"] + async with system.app.state.db.session() as s: + j = await s.get(Job, old) + j.state = j.phase = "failed" + await s.commit() + await advance_workflows(system.app.state.db, system.settings, system.provider) + snap = (await c.get("/api/workflow-runs/" + rid)).json() + retry = await c.post( + "/api/workflow-runs/" + rid + "/steps/shot_1/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": old}, + headers={"Idempotency-Key": "reuse-retry"}, + ) + assert retry.status_code == 202, retry.text + replacement = next( + x for x in retry.json()["jobs"] if x["id"] != old and x["step_key"] == "shot_1" + ) + assert replacement["output_folder_id"] == fid + outputs = [] + for step in retry.json()["steps"]: + if step["step_key"] != "compose": + outputs.append(await publish_video(system, step["selected_job_id"])) + await advance_workflows(system.app.state.db, system.settings, system.provider) + snap = (await c.get("/api/workflow-runs/" + rid)).json() + compose = next(x for x in snap["jobs"] if x["step_key"] == "compose") + assert compose["output_folder_id"] == fid + await publish_video(system, compose["id"], compose=True) + await advance_workflows(system.app.state.db, system.settings, system.provider) + current = (await c.get("/api/workflows/" + d["id"])).json() + owner = (await c.get("/api/auth/me")).json()["user"]["id"] + cursor = (await event_batch(system.app.state.db, owner, 0, limit=1000))[-1]["id"] + reused = await c.post( + "/api/workflows/" + d["id"] + "/runs", + json={ + "draft_revision": current["revision"], + "expected_version": current["version"], + "reuse_run_id": rid, + "output_folder_id": target, + }, + headers={"Idempotency-Key": "reuse-second"}, + ) + assert reused.status_code == 202, reused.text + assert len([x for x in reused.json()["steps"] if x["state"] == "succeeded"]) == 3 + for aid in outputs: + assert target in (await c.get("/api/assets/" + aid)).json()["folder_ids"] + events = await event_batch(system.app.state.db, owner, cursor) + updated = [e["data"]["asset"] for e in events if e["event"] == "asset.updated"] + assert {a["id"] for a in updated} == set(outputs) + assert len(updated) == len(outputs) + assert all(target in a["folder_ids"] for a in updated) + cursor = events[-1]["id"] + current = (await c.get("/api/workflows/" + d["id"])).json() + unchanged = await c.post( + "/api/workflows/" + d["id"] + "/runs", + json={ + "draft_revision": current["revision"], + "expected_version": current["version"], + "reuse_run_id": rid, + "output_folder_id": target, + "execution_mode": "batch", + }, + headers={"Idempotency-Key": "reuse-same-folder"}, + ) + assert unchanged.status_code == 202, unchanged.text + assert not [ + e + for e in await event_batch(system.app.state.db, owner, cursor) + if e["event"] == "asset.updated" + ] + + +@pytest.mark.asyncio +async def test_generated_output_archived_and_metadata_never_sent_upstream(system): + c = system.client + fid = await folder(c, "generated") + response = await c.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "tree"}, "folder_id": fid}, + ) + assert response.status_code == 202, response.text + job = response.json()["jobs"][0] + for _ in range(4): + await system.app.state.coordinator.run_once(force=True) + if system.provider.remote: + break + assert system.provider.remote + payload = system.provider.submitted_payloads[0][1] + assert "folder_id" not in payload and "output_folder_id" not in payload + assert "folder_id" not in payload["parameters"] + next(iter(system.provider.remote.values())).update( + state="succeeded", result={"outputs": [{"path": "out.png"}]} + ) + for _ in range(4): + await system.app.state.coordinator.run_once(force=True) + current = (await c.get("/api/jobs/" + job["id"])).json() + assert current["state"] == "succeeded", current + assert current["result_assets"][0]["folder_ids"] == [fid] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("destination", ["inherit", "explicit", "unclassified"]) +async def test_story_render_real_compose_freezes_output(system, monkeypatch, destination): + import asyncio + import shutil + from app.adapters.media import run_process + from app.adapters.provider.client import Provider + from test_story_studio import story_spec + + if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): + pytest.skip("FFmpeg required") + c = system.client + spec = story_spec() + spec["shots"][0]["edit"] = {"start_frame": 0, "duration_frames": 24} + spec["render"] = {"total_frames": 24} + d = (await c.post("/api/stories", json={"name": "render", "spec": spec})).json() + target = ( + await folder(c, "render-target") + if destination == "explicit" + else d["folder_id"] + if destination == "inherit" + else None + ) + video = system.settings.workspace_root / "folder-video.mp4" + await run_process( + [ + system.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=256x256:r=24", + "-frames:v", + "24", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + str(video), + ] + ) + source = await c.post( + "/api/assets", files={"file": ("video.mp4", video.read_bytes(), "video/mp4")} + ) + assert source.status_code == 201, source.text + base = "/api/stories/" + d["id"] + candidate = await c.post( + base + "/candidates", + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "video", + "source_kind": "manual", + "asset_id": source.json()["id"], + }, + headers={"Idempotency-Key": "render-video"}, + ) + assert candidate.status_code == 202, candidate.text + selected = await c.post( + base + "/selections", + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "video", + "candidate_id": candidate.json()["candidates"][0]["id"], + }, + headers={"Idempotency-Key": "render-select"}, + ) + assert selected.status_code == 200, selected.text + body = {"expected_version": selected.json()["version"]} + if destination != "inherit": + body["output_folder_id"] = target + rendered = await c.post( + base + "/renders", json=body, headers={"Idempotency-Key": "render-freeze"} + ) + assert rendered.status_code == 202, rendered.text + run = rendered.json()["run"] + assert run["output_folder_id"] == target + current = (await c.get(base)).json() + assert ( + await c.patch(base, json={"folder_id": None}, headers={"If-Match": str(current["version"])}) + ).status_code == 200 + real = Provider(system.settings) + monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) + try: + for _ in range(5): + await system.app.state.coordinator.run_once() + tasks = list(system.app.state.coordinator._cpu.values()) + if tasks: + await asyncio.gather(*tasks) + snap = (await c.get("/api/workflow-runs/" + run["id"])).json() + assert snap["run"]["state"] == "succeeded", snap + assert snap["run"]["result_assets"][0]["folder_ids"] == ([target] if target else []) + finally: + await real.aclose() + + +@pytest.mark.asyncio +async def test_foreign_folder_rejected_by_submit_drafts_candidates_and_lists(system, other_client): + from test_story_studio import story_spec + from test_timeline_v2 import spec + + c = system.client + foreign = await folder(other_client, "foreign") + assert ( + await c.post( + "/api/jobs", + json={ + "task_type": "image.generate", + "input": {"prompt": "tree"}, + "output_folder_id": foreign, + }, + ) + ).status_code == 404 + assert ( + await c.post( + "/api/stories", json={"name": "foreign", "spec": story_spec(), "folder_id": foreign} + ) + ).status_code == 404 + assert ( + await c.post( + "/api/workflows", json={"name": "foreign", "spec": spec(), "folder_id": foreign} + ) + ).status_code == 404 + d = (await c.post("/api/stories", json={"name": "own", "spec": story_spec()})).json() + assert ( + await c.post( + "/api/stories/" + d["id"] + "/candidates", + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "output_folder_id": foreign, + }, + headers={"Idempotency-Key": "foreign-output"}, + ) + ).status_code == 404 + for endpoint in ("assets", "jobs", "stories", "workflows", "workflow-runs"): + assert (await c.get("/api/" + endpoint, params={"folder_id": foreign})).status_code == 404 + assert not system.provider.submitted_payloads + + +@pytest.mark.asyncio +async def test_gpu_preparation_may_span_ticks_without_losing_folder_target(system, monkeypatch): + import asyncio + + c = system.client + target = await folder(c, "slow-prepare") + response = await c.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "tree"}, "folder_id": target}, + ) + assert response.status_code == 202, response.text + original = system.provider.prepare_gpu_payload + gate = asyncio.Event() + + async def delayed_prepare(*args, **kwargs): + await gate.wait() + return await original(*args, **kwargs) + + monkeypatch.setattr(system.provider, "prepare_gpu_payload", delayed_prepare) + await system.app.state.coordinator.run_once(force=True) + assert not system.provider.remote + pending = list(system.app.state.coordinator._preparing.values()) + assert pending and any(not task.done() for task in pending) + gate.set() + await asyncio.wait_for(asyncio.gather(*pending), timeout=5) + await system.app.state.coordinator.run_once(force=True) + assert system.provider.remote + current = (await c.get("/api/jobs/" + response.json()["jobs"][0]["id"])).json() + assert current["output_folder_id"] == target + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["reference", "manual"]) +async def test_story_membership_change_emits_asset_update_once(system, png_bytes, entry): + from test_story_studio import story_spec + from app.services.events import event_batch + + c = system.client + owner = (await c.get("/api/auth/me")).json()["user"]["id"] + original = await folder(c, "original") + target = await folder(c, "story-member") + source = ( + await c.post( + "/api/assets", + data={"folder_id": original}, + files={"file": ("x.png", png_bytes, "image/png")}, + ) + ).json() + spec = story_spec() + if entry == "reference": + spec["entities"] = [ + {"id": "2" * 32, "name": "Person", "reference_asset_ids": [source["id"]]} + ] + spec["shots"][0]["cast"] = [{"id": "3" * 32, "entity_id": "2" * 32}] + else: + story = ( + await c.post("/api/stories", json={"name": "manual", "folder_id": target, "spec": spec}) + ).json() + cursor = (await event_batch(system.app.state.db, owner, 0))[-1]["id"] + for index in range(2): + if entry == "reference": + response = await c.post( + "/api/stories", json={"name": "reference", "folder_id": target, "spec": spec} + ) + assert response.status_code == 201, response.text + else: + response = await c.post( + "/api/stories/" + story["id"] + "/candidates", + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "source_kind": "manual", + "asset_id": source["id"], + }, + headers={"Idempotency-Key": "member-" + str(index)}, + ) + assert response.status_code == 202, response.text + events = await event_batch(system.app.state.db, owner, cursor) + updates = [e["data"]["asset"] for e in events if e["event"] == "asset.updated"] + assert len(updates) == (1 if index == 0 else 0), events + if updates: + assert updates[0]["id"] == source["id"] + assert set(updates[0]["folder_ids"]) == {original, target} + cursor = events[-1]["id"] diff --git a/backend/tests/test_folder_token_scopes.py b/backend/tests/test_folder_token_scopes.py new file mode 100644 index 0000000..5675b4c --- /dev/null +++ b/backend/tests/test_folder_token_scopes.py @@ -0,0 +1,30 @@ +async def test_folder_scopes_can_be_issued_without_granting_asset_or_task_control(system): + result = await system.client.post('/api/auth/tokens', json={ + 'name': 'folder reader', 'scopes': ['folders:read']}) + assert result.status_code == 201, 'folder access needs explicit issuable token scopes' + token = result.json()['token'] + import httpx + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), + base_url='http://test', headers={'Authorization': 'Bearer ' + token}) as machine: + response = await machine.get('/api/folders') + assert response.status_code == 200 + assert (await machine.post('/api/folders', json={'name':'not allowed'})).status_code == 403 + assert (await machine.get('/api/assets')).status_code == 403 + assert (await machine.get('/api/jobs')).status_code == 403 + + +async def test_folder_write_token_cannot_submit_jobs_or_bypass_owner(system): + result = await system.client.post('/api/auth/tokens', json={ + 'name': 'folder organizer', 'scopes': ['folders:write']}) + assert result.status_code == 201, 'folder writes must not require broader execution privileges' + import httpx + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), + base_url='http://test', headers={'Authorization': 'Bearer ' + result.json()['token']}) as machine: + response = await machine.post('/api/folders', json={'name':'token folder'}) + assert response.status_code == 201 + assert (await machine.get('/api/folders')).status_code == 403 + assert (await machine.post('/api/jobs', json={'task_type':'image.generate', + 'input':{'prompt':'x'},'parameters':{}})).status_code == 403 + missing = await machine.post('/api/folders/assign', json={ + 'kind':'assets','ids':['f'*32],'folder_id':response.json()['id']}) + assert missing.status_code == 404 diff --git a/backend/tests/test_folders.py b/backend/tests/test_folders.py new file mode 100644 index 0000000..79c3a80 --- /dev/null +++ b/backend/tests/test_folders.py @@ -0,0 +1,364 @@ +import pytest +from sqlalchemy import select + + +async def folder(client, name, parent_id=None): + response = await client.post("/api/folders", json=dict(name=name, parent_id=parent_id)) + assert response.status_code == 201, response.text + return response.json() + + +@pytest.mark.asyncio +async def test_tree_unique_cycle_and_isolation(system, other_client): + c = system.client + root = await folder(c, "root") + child = await folder(c, "child", root["id"]) + assert (await c.post("/api/folders", json={"name": "root"})).status_code == 409 + assert ( + await c.patch("/api/folders/" + root["id"], json={"parent_id": child["id"]}) + ).status_code == 409 + assert ( + await other_client.post("/api/folders", json={"name": "bad", "parent_id": root["id"]}) + ).status_code == 404 + assert (await other_client.get("/api/folders")).json() == {"items": []} + assert (await c.patch("/api/folders/" + child["id"], json={"parent_id": None})).json()[ + "parent_id" + ] is None + assert (await c.patch("/api/folders/" + child["id"], json={"name": "root"})).status_code == 409 + + +@pytest.mark.asyncio +async def test_asset_membership_atomic_and_delete_preserves_content( + system, other_client, png_bytes +): + from app.models import Asset + + c = system.client + root = await folder(c, "root") + child = await folder(c, "child", root["id"]) + foreign = await folder(other_client, "foreign") + asset = (await c.post("/api/assets", files={"file": ("a.png", png_bytes, "image/png")})).json() + foreign_asset = ( + await other_client.post("/api/assets", files={"file": ("b.png", png_bytes, "image/png")}) + ).json() + body = dict(kind="assets", ids=[asset["id"]], folder_id=root["id"]) + assert (await c.post("/api/folders/assign", json=body)).status_code == 200 + body.update(folder_id=child["id"], mode="add") + assert (await c.post("/api/folders/assign", json=body)).status_code == 200 + assert set((await c.get("/api/assets/" + asset["id"])).json()["folder_ids"]) == { + root["id"], + child["id"], + } + body.update(ids=[asset["id"], foreign_asset["id"]], mode="move") + assert (await c.post("/api/folders/assign", json=body)).status_code == 404 + body.update(ids=[asset["id"]], folder_id=foreign["id"]) + assert (await c.post("/api/folders/assign", json=body)).status_code == 404 + async with system.app.state.db.session() as s: + record = await s.get(Asset, asset["id"]) + path = system.settings.asset_root / record.storage_key + assert path.exists() + assert (await c.delete("/api/folders/" + root["id"])).status_code == 204 + assert (await c.get("/api/assets/" + asset["id"])).json()["folder_ids"] == [] + assert path.exists() + assert (await c.get("/api/assets/" + foreign_asset["id"])).status_code == 404 + + +@pytest.mark.asyncio +async def test_helpers_no_commit_sync_dto_missing_and_foreign(system, other_client): + from app.models import Asset, User + from app.services.folders import create_folder, assign_asset_folders, add_asset_folder + from app.services.snapshots import asset_dto + + foreign = await folder(other_client, "foreign") + async with system.app.state.db.session() as s: + owner = await s.scalar(select(User.id).where(User.username == "admin")) + f = await create_folder(s, owner, "story") + f2 = await create_folder(s, owner, "story", unique_name=True) + assert f.name != f2.name + asset = Asset( + owner_id=owner, + name="a", + storage_key="stable.png", + kind="image", + mime_type="image/png", + size_bytes=1, + sha256="a" * 64, + ) + s.add(asset) + await s.flush() + assert asset_dto(asset)["folder_ids"] == [] + await assign_asset_folders(s, asset, [f.id]) + await add_asset_folder(s, asset, f2.id) + assert set(asset_dto(asset)["folder_ids"]) == {f.id, f2.id} + await add_asset_folder(s, asset, "missing", allow_missing=True) + from fastapi import HTTPException + + with pytest.raises(HTTPException): + await add_asset_folder(s, asset, foreign["id"], allow_missing=True) + await s.rollback() + assert (await system.client.get("/api/folders")).json()["items"] == [] + + +@pytest.mark.asyncio +async def test_classification_versions_output_freeze_and_delete_business_rows(system): + from app.models import Job, WorkflowDraft, WorkflowRun, User + + c = system.client + target = await folder(c, "target") + moved = await folder(c, "moved") + async with system.app.state.db.session() as s: + owner = await s.scalar(select(User.id).where(User.username == "admin")) + job = Job( + owner_id=owner, + task_type="image.generate", + state="queued", + phase="queued", + input_json={}, + parameters={}, + request_hash="a" * 64, + upstream_key="unique", + folder_id=target["id"], + output_folder_id=target["id"], + ) + draft = WorkflowDraft(owner_id=owner, name="story", folder_id=target["id"]) + s.add_all([job, draft]) + await s.flush() + run = WorkflowRun( + owner_id=owner, + draft_id=draft.id, + draft_revision=1, + spec_snapshot={"shots": []}, + spec_hash="b" * 64, + folder_id=target["id"], + output_folder_id=target["id"], + ) + s.add(run) + await s.commit() + ids = {"jobs": job.id, "drafts": draft.id, "runs": run.id} + for kind, record_id in ids.items(): + assert ( + await c.post( + "/api/folders/assign", json=dict(kind=kind, ids=[record_id], folder_id=moved["id"]) + ) + ).status_code == 200 + async with system.app.state.db.session() as s: + for model, key in [(Job, "jobs"), (WorkflowDraft, "drafts"), (WorkflowRun, "runs")]: + row = await s.get(model, ids[key]) + assert row.folder_id == moved["id"] + assert row.version == 2 + if model != WorkflowDraft: + assert row.output_folder_id == target["id"] + assert (await c.delete("/api/folders/" + target["id"])).status_code == 204 + assert (await c.delete("/api/folders/" + moved["id"])).status_code == 204 + async with system.app.state.db.session() as s: + for model, key in [(Job, "jobs"), (WorkflowDraft, "drafts"), (WorkflowRun, "runs")]: + row = await s.get(model, ids[key]) + assert row is not None and row.folder_id is None + assert row.version == (3 if model == WorkflowDraft else 4) + if model != WorkflowDraft: + assert row.output_folder_id is None + + +@pytest.mark.asyncio +async def test_folder_filter_and_request_validation(system, png_bytes): + from app.models import Asset, User + from app.services.folders import folder_filter + + c = system.client + target = await folder(c, "target") + asset = (await c.post("/api/assets", files={"file": ("a.png", png_bytes, "image/png")})).json() + body = dict(kind="assets", ids=[asset["id"]], folder_id=target["id"]) + assert (await c.post("/api/folders/assign", json=body)).status_code == 200 + async with system.app.state.db.session() as s: + owner = await s.scalar(select(User.id).where(User.username == "admin")) + for selected, expected in [ + ("", [asset["id"]]), + ("unclassified", []), + (target["id"], [asset["id"]]), + ]: + condition = await folder_filter(s, Asset, owner, selected) + assert list((await s.scalars(select(Asset.id).where(condition))).all()) == expected + assert (await c.post("/api/folders", json={"name": " "})).status_code == 422 + assert (await c.patch("/api/folders/" + target["id"], json={"name": None})).status_code == 422 + body.update(kind="jobs", mode="add") + assert (await c.post("/api/folders/assign", json=body)).status_code == 422 + body.update(ids=["x"] * 201) + assert (await c.post("/api/folders/assign", json=body)).status_code == 422 + headers = dict(c.headers) + del c.headers["X-CSRF-Token"] + assert (await c.delete("/api/folders/" + target["id"])).status_code == 403 + c.headers.update(headers) + (system.settings.state_root / "maintenance").write_text("on") + assert (await c.post("/api/folders", json={"name": "blocked"})).status_code == 503 + + +@pytest.mark.asyncio +async def test_assignment_run_event_keeps_existing_workflow_contract(system): + from app.models import User, WorkflowDraft, WorkflowRun, Event + + c = system.client + target = await folder(c, "target") + async with system.app.state.db.session() as s: + owner = await s.scalar(select(User.id).where(User.username == "admin")) + draft = WorkflowDraft(owner_id=owner, name="draft") + s.add(draft) + await s.flush() + run = WorkflowRun( + owner_id=owner, + draft_id=draft.id, + draft_revision=1, + spec_snapshot={"shots": []}, + spec_hash="a" * 64, + ) + s.add(run) + await s.commit() + run_id = run.id + assert ( + await c.post( + "/api/folders/assign", json=dict(kind="runs", ids=[run_id], folder_id=target["id"]) + ) + ).status_code == 200 + async with system.app.state.db.session() as s: + event = await s.scalar( + select(Event) + .where(Event.owner_id == owner, Event.event_type == "workflow.updated") + .order_by(Event.id.desc()) + ) + assert event.event_type == "workflow.updated" + assert event.data["run"]["folder_id"] == target["id"] + assert event.data["run"]["version"] == 2 + assert "steps" in event.data and "jobs" in event.data + + +async def saved_events(system, after=0): + from app.models import Event + + async with system.app.state.db.session() as s: + return list( + (await s.scalars(select(Event).where(Event.id > after).order_by(Event.id))).all() + ) + + +@pytest.mark.asyncio +async def test_folder_crud_and_assignment_emit_owner_scoped_events(system, other_client, png_bytes): + c = system.client + foreign = await folder(other_client, "foreign") + baseline = max((e.id for e in await saved_events(system)), default=0) + parent = await folder(c, "parent") + child = await folder(c, "child", parent["id"]) + assert ( + await c.patch("/api/folders/" + parent["id"], json={"name": "renamed"}) + ).status_code == 200 + asset = (await c.post("/api/assets", files={"file": ("a.png", png_bytes, "image/png")})).json() + assert ( + await c.post( + "/api/folders/assign", + json=dict(kind="assets", ids=[asset["id"]], folder_id=child["id"]), + ) + ).status_code == 200 + assert (await c.delete("/api/folders/" + parent["id"])).status_code == 204 + events = await saved_events(system, baseline) + created = [e for e in events if e.event_type == "folder.created"] + assert {e.data["folder"]["id"] for e in created} == {parent["id"], child["id"]} + owner = created[0].owner_id + assert all(e.owner_id == owner for e in events) + assert foreign["id"] not in str([e.data for e in events]) + assert any( + e.event_type == "folder.updated" and e.data["folder"]["name"] == "renamed" for e in events + ) + assert any(e.event_type == "folder.contents_changed" for e in events) + deleted = [e for e in events if e.event_type == "folder.deleted"] + assert {e.data["folder_id"] for e in deleted} == {parent["id"], child["id"]} + updates = [ + e + for e in events + if e.event_type == "asset.updated" and e.data["asset"]["id"] == asset["id"] + ] + assert updates[-1].data["asset"]["folder_ids"] == [] + assert "storage_key" not in str([e.data for e in events]) + + +@pytest.mark.asyncio +async def test_story_classification_emits_story_contract_without_revision_edit(system): + from test_story_studio import story_spec + + c = system.client + created = await c.post( + "/api/stories", json={"name": "story", "spec": story_spec(), "create_folder": False} + ) + assert created.status_code == 201, created.text + story = created.json() + target = await folder(c, "target") + baseline = max((e.id for e in await saved_events(system)), default=0) + assert ( + await c.post( + "/api/folders/assign", + json=dict(kind="drafts", ids=[story["id"]], folder_id=target["id"]), + ) + ).status_code == 200 + events = await saved_events(system, baseline) + updates = [e for e in events if e.event_type == "story.updated"] + assert len(updates) == 1 + value = updates[0].data["story"] + assert value["id"] == story["id"] and value["folder_id"] == target["id"] + assert value["version"] == story["version"] + 1 + assert value["revision"] == story["revision"] + assert not any(e.event_type == "draft.updated" for e in events) + baseline = max(e.id for e in events) + assert (await c.delete("/api/folders/" + target["id"])).status_code == 204 + events = await saved_events(system, baseline) + value = next(e.data["story"] for e in events if e.event_type == "story.updated") + assert value["folder_id"] is None and value["version"] == story["version"] + 2 + assert value["revision"] == story["revision"] + + +@pytest.mark.asyncio +async def test_folder_delete_emits_job_draft_run_current_versions(system): + from app.models import Job, WorkflowDraft, WorkflowRun, User + + c = system.client + parent = await folder(c, "parent") + target = await folder(c, "child", parent["id"]) + async with system.app.state.db.session() as s: + owner = await s.scalar(select(User.id).where(User.username == "admin")) + job = Job( + owner_id=owner, + task_type="image.generate", + state="queued", + phase="queued", + input_json={}, + parameters={}, + request_hash="a" * 64, + upstream_key="delete-event", + output_folder_id=target["id"], + ) + draft = WorkflowDraft(owner_id=owner, name="draft", folder_id=target["id"]) + s.add_all([job, draft]) + await s.flush() + run = WorkflowRun( + owner_id=owner, + draft_id=draft.id, + draft_revision=1, + spec_snapshot={"shots": []}, + spec_hash="b" * 64, + output_folder_id=target["id"], + ) + s.add(run) + await s.commit() + job_id, draft_id, run_id = job.id, draft.id, run.id + baseline = max((e.id for e in await saved_events(system)), default=0) + assert (await c.delete("/api/folders/" + parent["id"])).status_code == 204 + events = await saved_events(system, baseline) + values = {e.event_type: e.data for e in events} + job_dto = values["job.updated"]["job"] + assert ( + job_dto["id"] == job_id and job_dto["output_folder_id"] is None and job_dto["version"] == 2 + ) + draft_dto = values["draft.updated"]["draft"] + assert ( + draft_dto["id"] == draft_id and draft_dto["folder_id"] is None and draft_dto["version"] == 2 + ) + run_dto = values["workflow.updated"]["run"] + assert ( + run_dto["id"] == run_id and run_dto["output_folder_id"] is None and run_dto["version"] == 2 + ) diff --git a/backend/tests/test_gpu_executions.py b/backend/tests/test_gpu_executions.py index 27302c4..79085e5 100644 --- a/backend/tests/test_gpu_executions.py +++ b/backend/tests/test_gpu_executions.py @@ -1,120 +1,440 @@ from copy import deepcopy import pytest from sqlalchemy import select -from app.models import Job,Asset -from app.v2_models import Execution,AssetReference -from app.coordinator import Coordinator +from app.models import Job, Asset +from app.models import Execution, AssetReference +from app.services.orchestration.coordinator import Coordinator + async def queued_job(system): - response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}}) - job_id=response.json()["jobs"][0]["id"] - await system.app.state.coordinator.run_once(force=True) - async with system.app.state.db.session() as session: - job=await session.get(Job,job_id) - return job_id,job.upstream_id + import asyncio + from app.domain.tasks import TERMINAL + + response = await system.client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "x"}} + ) + assert response.status_code == 202, response.text + job_id = response.json()["jobs"][0]["id"] + observed = None + try: + async with asyncio.timeout(10): + while True: + await system.app.state.coordinator.run_once(force=True) + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert job is not None + observed = (job.state, job.phase) + if job.upstream_id: + return job_id, job.upstream_id + assert job.state not in TERMINAL, (observed, job.error_json) + # 准备在后台运行,一轮tick只观察100ms;等持久化ID而不是假定一轮即可提交。 + await asyncio.sleep(0) + except TimeoutError: + pytest.fail(f"Job {job_id} did not persist upstream_id within 10 seconds: {observed}") + @pytest.mark.asyncio async def test_gpu_attempt_observation_preempt_restart_stale_counter_and_publication(system): - job_id,upstream=await queued_job(system) - c=system.app.state.coordinator - running={"id":upstream,"execution_id":upstream+":1","attempt_count":1,"state":"running","stage":"executing","runner_pid":77} - await c._apply_remote(job_id,running) + job_id, upstream = await queued_job(system) + c = system.app.state.coordinator + running = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "running", + "stage": "executing", + "runner_pid": 77, + } + await c._apply_remote(job_id, running) async with system.app.state.db.session() as session: - first=(await session.scalars(select(Execution).where(Execution.job_id==job_id))).one() - assert first.state=="running" and first.manifest_json["upstream_attempt"]==1 - first_id=first.id + first = (await session.scalars(select(Execution).where(Execution.job_id == job_id))).one() + assert first.state == "running" and first.manifest_json["upstream_attempt"] == 1 + first_id = first.id # A queued state without a cleanup ACK cannot claim the runner is gone. - await c._apply_remote(job_id,{**running,"state":"queued","stage":"queued"}) - async with system.app.state.db.session() as session:assert (await session.get(Execution,first_id)).state=="running" - await c._apply_remote(job_id,{**running,"state":"queued","stage":"queued","runner_pid":None,"preemptions":1}) - async with system.app.state.db.session() as session:assert (await session.get(Execution,first_id)).state=="exited" - # Same closed attempt cannot be revived by a late running callback. - await c._apply_remote(job_id,running) - async with system.app.state.db.session() as session:assert (await session.get(Job,job_id)).state=="queued" - running2={**running,"execution_id":upstream+":2","attempt_count":2,"runner_pid":88} - await c._apply_remote(job_id,running2) - restarted=Coordinator(system.settings,system.app.state.db,system.provider) - await restarted._apply_remote(job_id,running2) - stale={**running,"state":"succeeded","result":{"outputs":[{"path":"old-attempt.png"}]}} - await restarted._apply_remote(job_id,stale) - assert system.provider.download_count==0 - success={**running2,"state":"succeeded","result":{"outputs":[{"path":"attempt-2/image.png"}],"metadata":{}}} - await restarted._apply_remote(job_id,success) + await c._apply_remote(job_id, {**running, "state": "queued", "stage": "queued"}) async with system.app.state.db.session() as session: - job=await session.get(Job,job_id) - rows=list((await session.scalars(select(Execution).where(Execution.job_id==job_id).order_by(Execution.ordinal))).all()) - assert len(rows)==2 and [row.state for row in rows]==["exited","results_ready"] - assert job.state=="succeeded" and job.current_execution_id==rows[1].id - assert rows[1].manifest_json["upstream_execution_id"]==upstream+":2" - asset=(await session.scalars(select(Asset).where(Asset.source_job_id==job_id))).one() + assert (await session.get(Execution, first_id)).state == "running" + await c._apply_remote( + job_id, + {**running, "state": "queued", "stage": "queued", "runner_pid": None, "preemptions": 1}, + ) + async with system.app.state.db.session() as session: + assert (await session.get(Execution, first_id)).state == "exited" + # Same closed attempt cannot be revived by a late running callback. + await c._apply_remote(job_id, running) + async with system.app.state.db.session() as session: + assert (await session.get(Job, job_id)).state == "queued" + running2 = {**running, "execution_id": upstream + ":2", "attempt_count": 2, "runner_pid": 88} + await c._apply_remote(job_id, running2) + restarted = Coordinator(system.settings, system.app.state.db, system.provider) + await restarted._apply_remote(job_id, running2) + stale = {**running, "state": "succeeded", "result": {"outputs": [{"path": "old-attempt.png"}]}} + await restarted._apply_remote(job_id, stale) + assert system.provider.download_count == 0 + success = { + **running2, + "state": "succeeded", + "result": {"outputs": [{"path": "attempt-2/image.png"}], "metadata": {}}, + } + await restarted._apply_remote(job_id, success) + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + rows = list( + ( + await session.scalars( + select(Execution).where(Execution.job_id == job_id).order_by(Execution.ordinal) + ) + ).all() + ) + assert len(rows) == 2 and [row.state for row in rows] == ["exited", "results_ready"] + assert job.state == "succeeded" and job.current_execution_id == rows[1].id + assert rows[1].manifest_json["upstream_execution_id"] == upstream + ":2" + asset = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).one() assert asset.ready - binding=await session.scalar(select(AssetReference).where(AssetReference.asset_id==asset.id,AssetReference.ref_kind=="execution")) - assert binding.ref_id==rows[1].id + binding = await session.scalar( + select(AssetReference).where( + AssetReference.asset_id == asset.id, AssetReference.ref_kind == "execution" + ) + ) + assert binding.ref_id == rows[1].id + @pytest.mark.asyncio async def test_unlaunched_deferred_claim_does_not_invent_execution(system): - job_id,upstream=await queued_job(system) - c=system.app.state.coordinator - claim={"id":upstream,"execution_id":upstream+":1","attempt_count":1,"state":"running","stage":"launching","runner_pid":None,"started_at":123} - await c._apply_remote(job_id,claim) - await c._apply_remote(job_id,{**claim,"state":"queued","stage":"batch_window_closed","started_at":None}) - await c._apply_remote(job_id,{**claim,"state":"cancelled","stage":"cancelled","started_at":None}) + job_id, upstream = await queued_job(system) + c = system.app.state.coordinator + claim = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "running", + "stage": "launching", + "runner_pid": None, + "started_at": 123, + } + await c._apply_remote(job_id, claim) + await c._apply_remote( + job_id, {**claim, "state": "queued", "stage": "batch_window_closed", "started_at": None} + ) + await c._apply_remote( + job_id, {**claim, "state": "cancelled", "stage": "cancelled", "started_at": None} + ) async with system.app.state.db.session() as session: - assert not (await session.scalars(select(Execution).where(Execution.job_id==job_id))).all() + assert not ( + await session.scalars(select(Execution).where(Execution.job_id == job_id)) + ).all() + @pytest.mark.asyncio -async def test_gpu_collection_rechecks_current_fence_before_asset_commit(system,monkeypatch): - from app.executions import begin_execution - job_id,upstream=await queued_job(system) - c=system.app.state.coordinator - download=system.provider.download +async def test_gpu_collection_rechecks_current_fence_before_asset_commit(system, monkeypatch): + from app.services.orchestration.executions import begin_execution + + job_id, upstream = await queued_job(system) + c = system.app.state.coordinator + download = system.provider.download + async def late_download(*args): await download(*args) async with system.app.state.db.session() as session: - await begin_execution(session,job_id,"gpu:2","new_gpu") + await begin_execution(session, job_id, "gpu:2", "new_gpu") await session.commit() - monkeypatch.setattr(system.provider,"download",late_download) - remote={"id":upstream,"execution_id":upstream+":1","attempt_count":1,"state":"succeeded","result":{"outputs":[{"path":"attempt-1.png"}]}} - with pytest.raises(ValueError,match="Stale GPU result import"): - await c._apply_remote(job_id,remote) + + monkeypatch.setattr(system.provider, "download", late_download) + remote = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "succeeded", + "result": {"outputs": [{"path": "attempt-1.png"}]}, + } + with pytest.raises(ValueError, match="Stale GPU result import"): + await c._apply_remote(job_id, remote) async with system.app.state.db.session() as session: - assert not (await session.scalars(select(Asset).where(Asset.source_job_id==job_id))).all() - assert (await session.get(Job,job_id)).state!="succeeded" + assert not (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).all() + assert (await session.get(Job, job_id)).state != "succeeded" @pytest.mark.asyncio async def test_gpu_terminal_observation_does_not_fabricate_missed_attempts(system): - job_id,upstream=await queued_job(system) - await system.app.state.coordinator._apply_remote(job_id,{"id":upstream,"execution_id":upstream+":3","attempt_count":3,"state":"failed"}) + job_id, upstream = await queued_job(system) + await system.app.state.coordinator._apply_remote( + job_id, + {"id": upstream, "execution_id": upstream + ":3", "attempt_count": 3, "state": "failed"}, + ) async with system.app.state.db.session() as session: - rows=list((await session.scalars(select(Execution).where(Execution.job_id==job_id))).all()) - assert len(rows)==1 and rows[0].ordinal==1 and rows[0].manifest_json["upstream_attempt"]==3 - assert rows[0].state=="exited" + rows = list( + (await session.scalars(select(Execution).where(Execution.job_id == job_id))).all() + ) + assert ( + len(rows) == 1 + and rows[0].ordinal == 1 + and rows[0].manifest_json["upstream_attempt"] == 3 + ) + assert rows[0].state == "exited" + @pytest.mark.asyncio -async def test_gpu_final_publication_rechecks_fence_after_import(system,monkeypatch): - from app.executions import begin_execution - job_id,upstream=await queued_job(system) - c=system.app.state.coordinator - complete=c._complete - async def replaced_before_publish(job_id,result,**kwargs): +async def test_gpu_final_publication_rechecks_fence_after_import(system, monkeypatch): + from app.services.orchestration.executions import begin_execution + + job_id, upstream = await queued_job(system) + c = system.app.state.coordinator + complete = c._complete + + async def replaced_before_publish(job_id, result, **kwargs): async with system.app.state.db.session() as session: - await begin_execution(session,job_id,"gpu:2","new_gpu");await session.commit() - await complete(job_id,result,**kwargs) - monkeypatch.setattr(c,"_complete",replaced_before_publish) - await c._apply_remote(job_id,{"id":upstream,"execution_id":upstream+":1","attempt_count":1,"state":"succeeded","result":{"outputs":[{"path":"attempt-1.png"}]}}) + await begin_execution(session, job_id, "gpu:2", "new_gpu") + await session.commit() + await complete(job_id, result, **kwargs) + + monkeypatch.setattr(c, "_complete", replaced_before_publish) + await c._apply_remote( + job_id, + { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "succeeded", + "result": {"outputs": [{"path": "attempt-1.png"}]}, + }, + ) async with system.app.state.db.session() as session: - assets=list((await session.scalars(select(Asset).where(Asset.source_job_id==job_id))).all()) + assets = list( + (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).all() + ) assert assets and all(not asset.ready for asset in assets) - assert (await session.get(Job,job_id)).state!="succeeded" + assert (await session.get(Job, job_id)).state != "succeeded" @pytest.mark.asyncio async def test_gpu_same_attempt_wrong_remote_fence_cannot_publish(system): - job_id,upstream=await queued_job(system) - c=system.app.state.coordinator - running={"id":upstream,"execution_id":upstream+":1","attempt_count":1,"state":"running","stage":"executing","fence_token":"current"} - await c._apply_remote(job_id,running) - await c._apply_remote(job_id,{**running,"fence_token":"stale","state":"succeeded","result":{"outputs":[{"path":"wrong.png"}]}}) - assert system.provider.download_count==0 - async with system.app.state.db.session() as session:assert (await session.get(Job,job_id)).state=="running" + job_id, upstream = await queued_job(system) + c = system.app.state.coordinator + running = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "running", + "stage": "executing", + "fence_token": "current", + } + await c._apply_remote(job_id, running) + await c._apply_remote( + job_id, + { + **running, + "fence_token": "stale", + "state": "succeeded", + "result": {"outputs": [{"path": "wrong.png"}]}, + }, + ) + assert system.provider.download_count == 0 + async with system.app.state.db.session() as session: + assert (await session.get(Job, job_id)).state == "running" + + +def _mysql_float_roundtrip(value): + """MySQL实测的相邻double变化;JSON字符串中的数字不会被数据库重编码。""" + if isinstance(value, dict): + return {key: _mysql_float_roundtrip(child) for key, child in value.items()} + if isinstance(value, list): + return [_mysql_float_roundtrip(child) for child in value] + if type(value) is float: + return { + 0.9935344827586207: 0.9935344827586208, + 0.24646226415094338: 0.24646226415094336, + }.get(value, value) + return value + + +def _real_analysis_result(): + import json + from pathlib import Path + + return json.loads( + (Path(__file__).parent / "fixtures/video_analysis_gpu_result.json").read_text( + encoding="utf-8" + ) + ) + + +@pytest.mark.asyncio +async def test_exact_gpu_result_survives_mysql_double_roundtrip(system): + from app.services.orchestration.executions import gpu_publication_matches + + job_id, upstream = await queued_job(system) + coordinator = system.app.state.coordinator + remote = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "succeeded", + "result": _real_analysis_result(), + } + await coordinator._update( + job_id, + remote_observation=remote, + state="collecting", + phase="importing_outputs", + attempt_count=1, + upstream_result=remote["result"], + ) + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + job.upstream_result = _mysql_float_roundtrip(job.upstream_result) + await session.commit() + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert await gpu_publication_matches(session, job, job.upstream_result["_visual_execution"]) + await coordinator._collect_gpu(job) + async with system.app.state.db.session() as session: + assert (await session.get(Job, job_id)).state == "succeeded" + assert len(system.provider.submitted_payloads) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "tamper", [None, "path", "attempt", "upstream_fence", "id", "state", "execution", "hash"] +) +async def test_legacy_mysql_result_recovers_same_job_only_from_original_hash(system, tamper): + from app.services.orchestration.executions import gpu_publication_matches + + job_id, upstream = await queued_job(system) + coordinator = system.app.state.coordinator + remote = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "succeeded", + "result": _real_analysis_result(), + } + await coordinator._update( + job_id, + remote_observation=remote, + state="collecting", + phase="importing_outputs", + attempt_count=1, + upstream_result=remote["result"], + ) + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + job.upstream_result = { + **_mysql_float_roundtrip(remote["result"]), + "_visual_execution": job.upstream_result["_visual_execution"], + } + await session.commit() + queried = deepcopy(remote) + if tamper == "path": + queried["result"]["outputs"][0]["path"] = "different.png" + elif tamper == "attempt": + queried["attempt_count"] = 2 + queried["execution_id"] = upstream + ":2" + if tamper == "upstream_fence": + queried["fence_token"] = "different-fence" + elif tamper == "id": + queried["id"] = "different-upstream" + elif tamper == "state": + queried["state"] = "failed" + elif tamper == "execution": + queried["execution_id"] = upstream + ":different" + elif tamper == "hash": + async with system.app.state.db.session() as session: + current = await session.get(Job, job_id) + payload = deepcopy(current.upstream_result) + payload["_visual_execution"]["result_hash"] = "0" * 64 + current.upstream_result = payload + await session.commit() + system.provider.remote[upstream] = queried + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert not await gpu_publication_matches( + session, job, job.upstream_result["_visual_execution"] + ) + if tamper: + with pytest.raises(ValueError): + await coordinator._collect_gpu(job) + assert system.provider.download_count == 0 + else: + await coordinator._collect_gpu(job) + async with system.app.state.db.session() as session: + restored = await session.get(Job, job_id) + assert restored.state == "succeeded" and restored.id == job_id + assert len(system.provider.submitted_payloads) == 1 + + +@pytest.mark.asyncio +async def test_exact_result_envelope_rejects_json_string_tampering(system): + from app.services.orchestration.executions import gpu_publication_matches + import json + + job_id, upstream = await queued_job(system) + coordinator = system.app.state.coordinator + remote = { + "id": upstream, + "execution_id": upstream + ":1", + "attempt_count": 1, + "state": "succeeded", + "result": _real_analysis_result(), + } + await coordinator._update( + job_id, + remote_observation=remote, + state="collecting", + phase="importing_outputs", + attempt_count=1, + upstream_result=remote["result"], + ) + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + payload = deepcopy(job.upstream_result) + parsed = json.loads(payload["_visual_result_json"]) + parsed["outputs"][0]["path"] = "tampered.png" + payload["_visual_result_json"] = json.dumps( + parsed, sort_keys=True, separators=(",", ":"), allow_nan=False + ) + job.upstream_result = payload + await session.commit() + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert not await gpu_publication_matches( + session, job, job.upstream_result["_visual_execution"] + ) + with pytest.raises(ValueError): + await coordinator._collect_gpu(job) + assert system.provider.download_count == 0 + + +@pytest.mark.asyncio +async def test_queued_job_waits_for_durable_upstream_after_slow_prepare(system, monkeypatch): + import asyncio + + coordinator = system.app.state.coordinator + original_prepare = system.provider.prepare_gpu_payload + original_tick = coordinator.run_once + release = asyncio.Event() + ticks = 0 + + async def deferred_prepare(*args, **kwargs): + await release.wait() + return await original_prepare(*args, **kwargs) + + async def observed_tick(*args, **kwargs): + nonlocal ticks + ticks += 1 + # 第一轮的100ms准备观察窗自然到期;只有后续tick才放行,确定性模拟慢I/O。 + if ticks == 2: + release.set() + await original_tick(*args, **kwargs) + + monkeypatch.setattr(system.provider, "prepare_gpu_payload", deferred_prepare) + monkeypatch.setattr(coordinator, "run_once", observed_tick) + try: + job_id, upstream = await asyncio.wait_for(queued_job(system), timeout=10) + finally: + release.set() + assert isinstance(upstream, str) and upstream + assert ticks >= 2 + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert job.upstream_id == upstream + assert len(system.provider.submitted_payloads) == 1 diff --git a/backend/tests/test_interactive_gpu_limit.py b/backend/tests/test_interactive_gpu_limit.py index 7c097d9..cc42de2 100644 --- a/backend/tests/test_interactive_gpu_limit.py +++ b/backend/tests/test_interactive_gpu_limit.py @@ -1,32 +1,44 @@ """The optional owner queue cap must not constrain normal video creation.""" + from datetime import datetime, timedelta, timezone import pytest -from app.config import Settings +from app.core.config import Settings from app.models import Job, new_id, utcnow -from app.v2_models import WorkflowRun, WorkflowStep +from app.models import WorkflowRun, WorkflowStep from sqlalchemy import select from test_workflows_v2 import wf, draft, run def test_interactive_gpu_limit_is_disabled_by_default(tmp_path): - settings = Settings(mode='test', database_url='sqlite+aiosqlite:///:memory:', workspace_root=tmp_path) + settings = Settings( + mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path + ) assert settings.max_interactive_gpu_jobs == 0 -@pytest.mark.parametrize('limit', [-1, -8]) +@pytest.mark.parametrize("limit", [-1, -8]) def test_negative_interactive_gpu_limit_is_rejected(tmp_path, limit): - with pytest.raises(ValueError, match='MAX_INTERACTIVE_GPU_JOBS.*non-negative'): - Settings(mode='test', database_url='sqlite+aiosqlite:///:memory:', workspace_root=tmp_path, - max_interactive_gpu_jobs=limit) + with pytest.raises(ValueError, match="MAX_INTERACTIVE_GPU_JOBS.*non-negative"): + Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=tmp_path, + max_interactive_gpu_jobs=limit, + ) async def future_video(system, index): - return await system.client.post('/api/jobs', json={ - 'task_type': 'video.generate', 'input': {'prompt': f'future video {index}'}, - 'parameters': {}, 'scheduled_at': (datetime.now(timezone.utc) + timedelta(days=1)).isoformat(), - }) + return await system.client.post( + "/api/jobs", + json={ + "task_type": "video.generate", + "input": {"prompt": f"future video {index}"}, + "parameters": {}, + "scheduled_at": (datetime.now(timezone.utc) + timedelta(days=1)).isoformat(), + }, + ) async def test_zero_limit_accepts_nine_unfinished_future_video_jobs(system): @@ -35,8 +47,8 @@ async def test_zero_limit_accepts_nine_unfinished_future_video_jobs(system): for index in range(9): response = await future_video(system, index) assert response.status_code == 202, response.text - assert response.json()['jobs'][0]['state'] == 'scheduled' - assert (await system.client.get('/api/jobs')).json()['total'] == 9 + assert response.json()["jobs"][0]["state"] == "scheduled" + assert (await system.client.get("/api/jobs")).json()["total"] == 9 await system.app.state.coordinator.run_once(force=True) assert not system.provider.accepted @@ -47,52 +59,67 @@ async def test_positive_limit_two_rejects_third_unfinished_video(system): assert (await future_video(system, 1)).status_code == 202 response = await future_video(system, 2) assert response.status_code == 429 - assert response.json()['detail']['code'] == 'quota_exceeded' - assert (await system.client.get('/api/jobs')).json()['total'] == 2 + assert response.json()["detail"]["code"] == "quota_exceeded" + assert (await system.client.get("/api/jobs")).json()["total"] == 2 assert not system.provider.accepted -def fixture_job(owner_id, *, state='scheduled', **fields): +def fixture_job(owner_id, *, state="scheduled", **fields): identifier = new_id() - return Job(id=identifier, owner_id=owner_id, task_type='video.generate', execution_mode='interactive', - state=state, phase=state, input_json={'prompt': 'future fixture video'}, parameters={}, - request_hash='fixture', upstream_key=identifier, - scheduled_at=utcnow() + timedelta(days=1), **fields) + return Job( + id=identifier, + owner_id=owner_id, + task_type="video.generate", + execution_mode="interactive", + state=state, + phase=state, + input_json={"prompt": "future fixture video"}, + parameters={}, + request_hash="fixture", + upstream_key=identifier, + scheduled_at=utcnow() + timedelta(days=1), + **fields, + ) async def test_default_limit_allows_standalone_retry_with_eight_existing_active_jobs(system): - owner = (await system.client.get('/api/auth/me')).json()['user']['id'] + owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] async with system.app.state.db.session() as session: session.add_all(fixture_job(owner) for _ in range(8)) - old = fixture_job(owner, state='failed') + old = fixture_job(owner, state="failed") session.add(old) await session.commit() - response = await system.client.post('/api/jobs/' + old.id + '/retry') + response = await system.client.post("/api/jobs/" + old.id + "/retry") assert response.status_code == 202, response.text - assert response.json()['jobs'][0]['id'] != old.id - assert (await system.client.get('/api/jobs')).json()['total'] == 10 + assert response.json()["jobs"][0]["id"] != old.id + assert (await system.client.get("/api/jobs")).json()["total"] == 10 assert not system.provider.accepted async def test_default_limit_allows_workflow_step_retry_with_eight_existing_active_jobs(wf): snapshot = await run(wf, await draft(wf)) - rid = snapshot['run']['id'] - owner = (await wf.client.get('/api/auth/me')).json()['user']['id'] + rid = snapshot["run"]["id"] + owner = (await wf.client.get("/api/auth/me")).json()["user"]["id"] async with wf.app.state.db.session() as session: session.add_all(fixture_job(owner) for _ in range(8)) - old = fixture_job(owner, state='failed', run_id=rid, step_key='shot_1', explicit_attempt=1) + old = fixture_job(owner, state="failed", run_id=rid, step_key="shot_1", explicit_attempt=1) session.add(old) - step = await session.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid, - WorkflowStep.step_key == 'shot_1')) - step.selected_job_id, step.state, step.explicit_attempt = old.id, 'blocked', 1 + step = await session.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == rid, WorkflowStep.step_key == "shot_1" + ) + ) + step.selected_job_id, step.state, step.explicit_attempt = old.id, "blocked", 1 parent = await session.get(WorkflowRun, rid) - parent.state = 'blocked' + parent.state = "blocked" await session.commit() - response = await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry', json={ - 'expected_run_version': snapshot['run']['version'], 'target_job_id': old.id}, - headers={'Idempotency-Key': 'retry-with-eight-active'}) + response = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snapshot["run"]["version"], "target_job_id": old.id}, + headers={"Idempotency-Key": "retry-with-eight-active"}, + ) assert response.status_code == 202, response.text - selected = next(step for step in response.json()['steps'] if step['step_key'] == 'shot_1') - assert selected['selected_job_id'] != old.id - assert (await wf.client.get('/api/jobs')).json()['total'] == 10 + selected = next(step for step in response.json()["steps"] if step["step_key"] == "shot_1") + assert selected["selected_job_id"] != old.id + assert (await wf.client.get("/api/jobs")).json()["total"] == 10 assert not wf.provider.accepted diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.py index 13c9ab5..3e6b406 100644 --- a/backend/tests/test_jobs.py +++ b/backend/tests/test_jobs.py @@ -12,17 +12,40 @@ async def submit(system, **changes): return response.json()["jobs"] +async def dispatch_gpu(system): + # Tick 的准备阶段有时间上限;先等待真实准备结束,再验证结果收集行为。 + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + preparing = list(coordinator._preparing.values()) + if preparing: + await asyncio.wait_for(asyncio.gather(*preparing), timeout=5) + await coordinator.run_once(force=True) + assert system.provider.remote + + async def test_batch_idempotency_and_scheduled_jobs_do_not_dispatch_early(system): future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat() - body = {"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}, "count": 3, "scheduled_at": future} - first = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) - second = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) + body = { + "task_type": "image.generate", + "input": {"prompt": "cup"}, + "parameters": {}, + "count": 3, + "scheduled_at": future, + } + first = await system.client.post( + "/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"} + ) + second = await system.client.post( + "/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"} + ) assert first.status_code == 202 and second.json() == first.json() assert len(first.json()["jobs"]) == 3 assert [job["parameters"]["seed"] for job in first.json()["jobs"]] == [42, 43, 44] assert {job["state"] for job in first.json()["jobs"]} == {"scheduled"} body["input"]["prompt"] = "changed" - assert (await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"})).status_code == 409 + assert ( + await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) + ).status_code == 409 await system.app.state.coordinator.run_once(force=True) assert not system.provider.accepted @@ -39,8 +62,12 @@ async def test_lost_submit_response_recovers_same_id_and_known_id_never_resubmit system.provider.remote["remote-1"].update(state="running", attempt_count=1) await system.app.state.coordinator.run_once(force=True) running = (await system.client.get(f"/api/jobs/{job['id']}")).json() - system.provider.remote["remote-1"].update(state="queued", attempt_count=1, preemptions=1, - last_preempted_reason="External user arrived") + system.provider.remote["remote-1"].update( + state="queued", + attempt_count=1, + preemptions=1, + last_preempted_reason="External user arrived", + ) await system.app.state.coordinator.run_once(force=True) queued = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert queued["state"] == "queued" and queued["version"] > running["version"] @@ -48,11 +75,24 @@ async def test_lost_submit_response_recovers_same_id_and_known_id_never_resubmit assert len(system.provider.submitted_payloads) == submitted -async def test_output_import_retry_does_not_generate_again_or_duplicate_assets(system): +async def test_output_import_retry_does_not_generate_again_or_duplicate_assets(system, monkeypatch): + prepare = system.provider.prepare_gpu_payload + + async def delayed_prepare(*args, **kwargs): + await asyncio.sleep(0.3) + return await prepare(*args, **kwargs) + + monkeypatch.setattr(system.provider, "prepare_gpu_payload", delayed_prepare) job = (await submit(system))[0] - await system.app.state.coordinator.run_once(force=True) - system.provider.remote["remote-1"].update(state="succeeded", attempt_count=1, - result={"outputs": [{"path": "/workspace/private/should-not-leak.png"}], "metadata": {"engine": "real"}}) + await dispatch_gpu(system) + system.provider.remote["remote-1"].update( + state="succeeded", + attempt_count=1, + result={ + "outputs": [{"path": "/workspace/private/should-not-leak.png"}], + "metadata": {"engine": "real"}, + }, + ) system.provider.fail_download_once = True await system.app.state.coordinator.run_once(force=True) collecting = (await system.client.get(f"/api/jobs/{job['id']}")).json() @@ -66,10 +106,19 @@ async def test_output_import_retry_does_not_generate_again_or_duplicate_assets(s assert assets["total"] == 1 and len(system.provider.accepted) == 1 -async def test_partial_outputs_remain_private_until_every_output_is_imported(system): +async def test_partial_outputs_remain_private_until_every_output_is_imported(system, monkeypatch): + prepare = system.provider.prepare_gpu_payload + + async def delayed_prepare(*args, **kwargs): + await asyncio.sleep(0.3) + return await prepare(*args, **kwargs) + + monkeypatch.setattr(system.provider, "prepare_gpu_payload", delayed_prepare) job = (await submit(system))[0] - await system.app.state.coordinator.run_once(force=True) - system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "one.png"}, {"path": "two.png"}]}) + await dispatch_gpu(system) + system.provider.remote["remote-1"].update( + state="succeeded", result={"outputs": [{"path": "one.png"}, {"path": "two.png"}]} + ) system.provider.fail_download_at = 1 await system.app.state.coordinator.run_once(force=True) assert (await system.client.get(f"/api/jobs/{job['id']}")).json()["state"] == "collecting" @@ -82,8 +131,11 @@ async def test_partial_outputs_remain_private_until_every_output_is_imported(sys async def test_owner_isolation_cancel_and_explicit_retry(system, other_client): job = (await submit(system))[0] - for method, path in (("get", f"/api/jobs/{job['id']}"), ("post", f"/api/jobs/{job['id']}/cancel"), - ("post", f"/api/jobs/{job['id']}/retry")): + for method, path in ( + ("get", f"/api/jobs/{job['id']}"), + ("post", f"/api/jobs/{job['id']}/cancel"), + ("post", f"/api/jobs/{job['id']}/retry"), + ): assert (await getattr(other_client, method)(path)).status_code == 404 cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel") assert cancelled.json()["state"] == "cancelled" @@ -92,8 +144,14 @@ async def test_owner_isolation_cancel_and_explicit_retry(system, other_client): async def test_unsupported_parameters_are_rejected_before_job_creation(system): - response = await system.client.post("/api/jobs", json={"task_type": "image.generate", - "input": {"prompt": "cup"}, "parameters": {"steps": 1}}) + response = await system.client.post( + "/api/jobs", + json={ + "task_type": "image.generate", + "input": {"prompt": "cup"}, + "parameters": {"steps": 1}, + }, + ) assert response.status_code == 400 assert (await system.client.get("/api/jobs")).json()["total"] == 0 @@ -104,9 +162,15 @@ async def test_definitive_upstream_input_rejection_is_terminal_not_retried_forev # Exercise definitive POST rejection with an already-ready payload; # independent background preparation need not finish within one tick. from app.models import Job + async with system.app.state.db.session() as session: - row=await session.get(Job,job['id']) - row.upstream_payload={'task_type':row.task_type,'input':row.input_json,'parameters':row.parameters,'timeout_seconds':3600} + row = await session.get(Job, job["id"]) + row.upstream_payload = { + "task_type": row.task_type, + "input": row.input_json, + "parameters": row.parameters, + "timeout_seconds": 3600, + } await session.commit() await system.app.state.coordinator.run_once(force=True) current = (await system.client.get(f"/api/jobs/{job['id']}")).json() @@ -117,7 +181,8 @@ async def test_definitive_upstream_input_rejection_is_terminal_not_retried_forev async def test_coordinator_restart_recovers_id_and_cancel_unknown_submit(system): - from app.coordinator import Coordinator + from app.services.orchestration.coordinator import Coordinator + job = (await submit(system))[0] system.provider.lost_response = True await system.app.state.coordinator.run_once(force=True) @@ -156,7 +221,7 @@ async def test_running_cpu_cancellation_waits_provider_task(system): for _ in range(100): if system.provider.cpu_runs: break - await asyncio.sleep(.01) + await asyncio.sleep(0.01) await system.client.post(f"/api/jobs/{job['id']}/cancel") tasks = list(coordinator._cpu.values()) await coordinator.run_once(force=True) @@ -169,10 +234,12 @@ async def test_cancel_during_gpu_preparation_never_starts_new_upstream_job(syste job = (await submit(system))[0] entered, release = asyncio.Event(), asyncio.Event() original = system.provider.prepare_gpu_payload + async def blocked_prepare(*args, **kwargs): entered.set() await release.wait() return await original(*args, **kwargs) + system.provider.prepare_gpu_payload = blocked_prepare task = asyncio.create_task(system.app.state.coordinator.run_once(force=True)) try: @@ -194,11 +261,13 @@ async def test_cpu_cancel_after_result_read_wins_collection_and_publication(syst coordinator = system.app.state.coordinator entered, release = asyncio.Event(), asyncio.Event() original = coordinator._update + async def blocked_collect(job_id, **changes): if changes.get("state") == "collecting": entered.set() await release.wait() return await original(job_id, **changes) + coordinator._update = blocked_collect try: await coordinator.run_once(force=True) @@ -216,14 +285,17 @@ async def test_cpu_cancel_after_result_read_wins_collection_and_publication(syst async def test_final_publication_reloads_committed_cancel_and_keeps_pending_private(system): from app.models import Job + job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] coordinator = system.app.state.coordinator entered, release = asyncio.Event(), asyncio.Event() original = coordinator._complete + async def blocked_complete(*args, **kwargs): entered.set() await release.wait() return await original(*args, **kwargs) + coordinator._complete = blocked_complete await coordinator.run_once(force=True) try: @@ -254,7 +326,8 @@ async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(syste coordinator = system.app.state.coordinator for _ in range(15): await coordinator.run_once(force=True) - if len(system.provider.accepted)==52:break + if len(system.provider.accepted) == 52: + break await asyncio.gather(*list(coordinator._cpu.values())) assert system.provider.cpu_runs == 1 and len(system.provider.accepted) == 52 assert (await system.client.get(f"/api/jobs/{cpu['id']}")).json()["state"] == "succeeded" @@ -262,4 +335,4 @@ async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(syste assert last["upstream_id"] await system.client.post(f"/api/jobs/{ids[-1]}/cancel") await coordinator.run_once(force=True) - assert (await system.client.get(f"/api/jobs/{ids[-1]}" )).json()["state"] == "cancelled" + assert (await system.client.get(f"/api/jobs/{ids[-1]}")).json()["state"] == "cancelled" diff --git a/backend/tests/test_long_shots.py b/backend/tests/test_long_shots.py index 65f06e8..f71e22e 100644 --- a/backend/tests/test_long_shots.py +++ b/backend/tests/test_long_shots.py @@ -1,4 +1,5 @@ """Native per-shot source lengths remain frozen across revisions and retries.""" + import copy import hashlib from pathlib import Path @@ -9,10 +10,10 @@ from pydantic import ValidationError from sqlalchemy import select from app.models import Asset, Job, new_id -from app.timeline import Render, WorkflowSpec, compile_timeline -from app.v2_models import WorkflowRun, WorkflowStep -from app.workflow_engine import advance_workflows -from app.workflows import digest +from app.domain.timeline import Render, WorkflowSpec, compile_timeline +from app.models import WorkflowRun, WorkflowStep +from app.services.orchestration.workflow_engine import advance_workflows +from app.services.workflows import digest from test_multishot_v3 import story from test_timeline_v2 import spec from test_workflows_v2 import wf, run, publish_video @@ -21,17 +22,24 @@ from test_workflows_v2 import wf, run, publish_video def test_mixed_native_generation_lengths_are_per_shot(): plan = compile_timeline(story(durations=[120, 240, 360]), {}) assert plan.frames == 720 and plan.shot_frames == (120, 240, 360) - assert plan.generation_parameters['num_frames'] == 121 - assert [plan.shot_generation_parameters[f'shot_{i}']['num_frames'] for i in (1, 2, 3)] == [121, 241, 361] + assert plan.generation_parameters["num_frames"] == 121 + assert [plan.shot_generation_parameters[f"shot_{i}"]["num_frames"] for i in (1, 2, 3)] == [ + 121, + 241, + 361, + ] -@pytest.mark.parametrize('frames,source', [(24,121),(48,121),(120,121),(121,125),(122,125),(240,241),(360,361)]) +@pytest.mark.parametrize( + "frames,source", + [(24, 121), (48, 121), (120, 121), (121, 125), (122, 125), (240, 241), (360, 361)], +) def test_native_source_frame_rounding(frames, source): plan = compile_timeline(story(durations=[frames]), {}) - assert plan.shot_generation_parameters['shot_1']['num_frames'] == source + assert plan.shot_generation_parameters["shot_1"]["num_frames"] == source -@pytest.mark.parametrize('frames', [23, 361]) +@pytest.mark.parametrize("frames", [23, 361]) def test_duration_bounds_remain_explicit(frames): with pytest.raises(ValidationError): WorkflowSpec.model_validate(story(durations=[frames])) @@ -41,32 +49,34 @@ def test_v1_still_freezes_three_five_second_shots(): plan = compile_timeline(spec(), {}) assert plan.frames == 360 and plan.clip_frames == 120 assert plan.shot_frames == (120, 120, 120) - assert all('duration_frames' not in shot for shot in plan.spec['shots']) - assert all(p['num_frames'] == 121 for p in plan.shot_generation_parameters.values()) - invalid = spec(); invalid['shots'][0]['duration_frames'] = 360 + assert all("duration_frames" not in shot for shot in plan.spec["shots"]) + assert all(p["num_frames"] == 121 for p in plan.shot_generation_parameters.values()) + invalid = spec() + invalid["shots"][0]["duration_frames"] = 360 with pytest.raises(ValidationError): WorkflowSpec.model_validate(invalid) -@pytest.mark.parametrize('count',[334,1000]) -@pytest.mark.parametrize('explicit',[False,True]) -def test_long_story_total_frames_roundtrips_with_or_without_explicit_total(count,explicit): - body=story(durations=[360]*count) - if explicit:body['render']={'total_frames':count*360} - accepted=WorkflowSpec.model_validate(body) - assert accepted.render.total_frames==count*360 - encoded=accepted.model_dump(mode='json') - reloaded=WorkflowSpec.model_validate(encoded) - assert reloaded.model_dump(mode='json')==encoded +@pytest.mark.parametrize("count", [334, 1000]) +@pytest.mark.parametrize("explicit", [False, True]) +def test_long_story_total_frames_roundtrips_with_or_without_explicit_total(count, explicit): + body = story(durations=[360] * count) + if explicit: + body["render"] = {"total_frames": count * 360} + accepted = WorkflowSpec.model_validate(body) + assert accepted.render.total_frames == count * 360 + encoded = accepted.model_dump(mode="json") + reloaded = WorkflowSpec.model_validate(encoded) + assert reloaded.model_dump(mode="json") == encoded def test_total_frames_above_maximum_story_is_rejected(): with pytest.raises(ValidationError): - Render.model_validate({'total_frames':360001}) + Render.model_validate({"total_frames": 360001}) -async def start(wf, durations, key='start'): - response = await wf.client.post('/api/workflows', json={'spec': story(durations=durations)}) +async def start(wf, durations, key="start"): + response = await wf.client.post("/api/workflows", json={"spec": story(durations=durations)}) assert response.status_code == 201, response.text draft = response.json() snapshot = await run(wf, draft, key) @@ -78,213 +88,381 @@ async def tick(wf): async def test_mixed_children_freeze_independent_native_frame_counts(wf): - _, snapshot = await start(wf, [120,240,360]) - rid = snapshot['run']['id'] + _, snapshot = await start(wf, [120, 240, 360]) + rid = snapshot["run"]["id"] await tick(wf) async with wf.app.state.db.session() as session: parent = await session.get(WorkflowRun, rid) - parameters = parent.spec_snapshot['compiled']['shot_generation_parameters'] - assert [parameters[f'shot_{i}']['num_frames'] for i in (1,2,3)] == [121,241,361] - jobs = (await session.scalars(select(Job).where(Job.run_id==rid).order_by(Job.step_key))).all() - assert [job.parameters['num_frames'] for job in jobs] == [121,241,361] - first = parent.spec_snapshot['shots'][0] - legacy_shot = {key:value for key,value in first.items() if key != 'duration_frames'} - legacy_hash = digest({'shot':legacy_shot, - 'generation_parameters':parent.spec_snapshot['compiled']['generation_parameters'], 'source_sha256':None}) - step = await session.scalar(select(WorkflowStep).where(WorkflowStep.run_id==rid,WorkflowStep.step_key=='shot_1')) + parameters = parent.spec_snapshot["compiled"]["shot_generation_parameters"] + assert [parameters[f"shot_{i}"]["num_frames"] for i in (1, 2, 3)] == [121, 241, 361] + jobs = ( + await session.scalars(select(Job).where(Job.run_id == rid).order_by(Job.step_key)) + ).all() + assert [job.parameters["num_frames"] for job in jobs] == [121, 241, 361] + first = parent.spec_snapshot["shots"][0] + legacy_shot = {key: value for key, value in first.items() if key != "duration_frames"} + legacy_hash = digest( + { + "shot": legacy_shot, + "generation_parameters": parent.spec_snapshot["compiled"]["generation_parameters"], + "source_sha256": None, + } + ) + step = await session.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == rid, WorkflowStep.step_key == "shot_1" + ) + ) assert step.semantic_input_hash == legacy_hash -@pytest.mark.parametrize('before,after', [(120,360),(360,240),(240,360)]) +@pytest.mark.parametrize("before,after", [(120, 360), (360, 240), (240, 360)]) async def test_source_length_revision_invalidates_reuse(wf, before, after): draft, first = await start(wf, [before]) - rid = first['run']['id'] + rid = first["run"]["id"] await tick(wf) - snapshot = (await wf.client.get('/api/workflow-runs/'+rid)).json() - jid = snapshot['steps'][0]['selected_job_id'] + snapshot = (await wf.client.get("/api/workflow-runs/" + rid)).json() + jid = snapshot["steps"][0]["selected_job_id"] assert jid is not None await publish_video(wf, jid) - await wf.client.post('/api/workflow-runs/'+rid+'/cancel', json={}, headers={'Idempotency-Key':'cancel'}) + await wf.client.post( + "/api/workflow-runs/" + rid + "/cancel", json={}, headers={"Idempotency-Key": "cancel"} + ) await tick(wf) - current = (await wf.client.get('/api/workflows/'+draft['id'])).json() - changed = await wf.client.patch('/api/workflows/'+draft['id'], json={'spec':story(durations=[after])}, - headers={'If-Match':str(current['version'])}) + current = (await wf.client.get("/api/workflows/" + draft["id"])).json() + changed = await wf.client.patch( + "/api/workflows/" + draft["id"], + json={"spec": story(durations=[after])}, + headers={"If-Match": str(current["version"])}, + ) assert changed.status_code == 200, changed.text draft = changed.json() - response = await wf.client.post('/api/workflows/'+draft['id']+'/runs', json={ - 'draft_revision':draft['revision'], 'expected_version':draft['version'], 'reuse_run_id':rid}, - headers={'Idempotency-Key':'new-source-length'}) + response = await wf.client.post( + "/api/workflows/" + draft["id"] + "/runs", + json={ + "draft_revision": draft["revision"], + "expected_version": draft["version"], + "reuse_run_id": rid, + }, + headers={"Idempotency-Key": "new-source-length"}, + ) assert response.status_code == 202, response.text second = response.json() - assert second['steps'][0]['selected_job_id'] is None - assert second['steps'][0]['semantic_input_hash'] != first['steps'][0]['semantic_input_hash'] + assert second["steps"][0]["selected_job_id"] is None + assert second["steps"][0]["semantic_input_hash"] != first["steps"][0]["semantic_input_hash"] await tick(wf) async with wf.app.state.db.session() as session: - child = await session.scalar(select(Job).where(Job.run_id==second['run']['id'])) - assert child.parameters['num_frames'] == max(121, ((after+3)//4)*4+1) + child = await session.scalar(select(Job).where(Job.run_id == second["run"]["id"])) + assert child.parameters["num_frames"] == max(121, ((after + 3) // 4) * 4 + 1) async def test_long_step_retry_keeps_frozen_length_after_draft_edit(wf): draft, first = await start(wf, [360]) - rid = first['run']['id'] + rid = first["run"]["id"] await tick(wf) async with wf.app.state.db.session() as session: - old = await session.scalar(select(Job).where(Job.run_id==rid)) - old.state='failed'; jid=old.id + old = await session.scalar(select(Job).where(Job.run_id == rid)) + old.state = "failed" + jid = old.id await session.commit() - current = (await wf.client.get('/api/workflows/'+draft['id'])).json() - changed = await wf.client.patch('/api/workflows/'+draft['id'], json={'spec':story(durations=[240])}, - headers={'If-Match':str(current['version'])}) + current = (await wf.client.get("/api/workflows/" + draft["id"])).json() + changed = await wf.client.patch( + "/api/workflows/" + draft["id"], + json={"spec": story(durations=[240])}, + headers={"If-Match": str(current["version"])}, + ) assert changed.status_code == 200 await tick(wf) - snapshot = (await wf.client.get('/api/workflow-runs/'+rid)).json() - response = await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry', json={ - 'expected_run_version':snapshot['run']['version'], 'target_job_id':jid}, - headers={'Idempotency-Key':'retry-frozen-long'}) + snapshot = (await wf.client.get("/api/workflow-runs/" + rid)).json() + response = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snapshot["run"]["version"], "target_job_id": jid}, + headers={"Idempotency-Key": "retry-frozen-long"}, + ) assert response.status_code == 202, response.text - selected = response.json()['steps'][0]['selected_job_id'] + selected = response.json()["steps"][0]["selected_job_id"] async with wf.app.state.db.session() as session: - assert (await session.get(Job, selected)).parameters['num_frames'] == 361 - assert response.json()['steps'][0]['semantic_input_hash'] == first['steps'][0]['semantic_input_hash'] + assert (await session.get(Job, selected)).parameters["num_frames"] == 361 + assert ( + response.json()["steps"][0]["semantic_input_hash"] + == first["steps"][0]["semantic_input_hash"] + ) async def test_legacy_snapshot_without_map_keeps_original_source_parameters(wf): - response = await wf.client.post('/api/workflows', json={'spec':spec()}) - draft = response.json(); first = await run(wf, draft) - rid = first['run']['id'] + response = await wf.client.post("/api/workflows", json={"spec": spec()}) + draft = response.json() + first = await run(wf, draft) + rid = first["run"]["id"] async with wf.app.state.db.session() as session: parent = await session.get(WorkflowRun, rid) frozen = copy.deepcopy(parent.spec_snapshot) - frozen['compiled'].pop('shot_generation_parameters', None) + frozen["compiled"].pop("shot_generation_parameters", None) parent.spec_snapshot = frozen await session.commit() await tick(wf) async with wf.app.state.db.session() as session: - jobs = (await session.scalars(select(Job).where(Job.run_id==rid))).all() - assert len(jobs)==3 and all(job.parameters['num_frames']==121 for job in jobs) - assert (await session.get(WorkflowRun,rid)).spec_snapshot == frozen + jobs = (await session.scalars(select(Job).where(Job.run_id == rid))).all() + assert len(jobs) == 3 and all(job.parameters["num_frames"] == 121 for job in jobs) + assert (await session.get(WorkflowRun, rid)).spec_snapshot == frozen async def test_present_but_incomplete_generation_map_never_admits_child(wf): _, first = await start(wf, [120]) - rid = first['run']['id'] + rid = first["run"]["id"] async with wf.app.state.db.session() as session: - parent = await session.get(WorkflowRun,rid) + parent = await session.get(WorkflowRun, rid) frozen = copy.deepcopy(parent.spec_snapshot) - frozen['compiled']['shot_generation_parameters'] = {} + frozen["compiled"]["shot_generation_parameters"] = {} parent.spec_snapshot = frozen await session.commit() await tick(wf) - snapshot = (await wf.client.get('/api/workflow-runs/'+rid)).json() - assert snapshot['run']['state']=='blocked' - assert snapshot['jobs']==[] + snapshot = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snapshot["run"]["state"] == "blocked" + assert snapshot["jobs"] == [] async def output_job(system, source_frames): - owner = (await system.client.get('/api/auth/me')).json()['user']['id'] - job = Job(id=new_id(),owner_id=owner,task_type='video.generate',state='collecting',phase='importing_outputs', - run_id='fixture-run',step_key='shot_1',input_json={'prompt':'fixture'}, - parameters={'num_frames':source_frames,'upscale_width':1920,'upscale_height':1056}, - request_hash='fixture',upstream_key=new_id()) + owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] + job = Job( + id=new_id(), + owner_id=owner, + task_type="video.generate", + state="collecting", + phase="importing_outputs", + run_id="fixture-run", + step_key="shot_1", + input_json={"prompt": "fixture"}, + parameters={"num_frames": source_frames, "upscale_width": 1920, "upscale_height": 1056}, + request_hash="fixture", + upstream_key=new_id(), + ) async with system.app.state.db.session() as session: - session.add(job); await session.commit() + session.add(job) + await session.commit() return job -@pytest.mark.parametrize('source_frames,decoded,accept', [(121,119,False),(121,120,True), - (241,239,False),(241,240,True),(361,121,False),(361,359,False),(361,360,True)]) -async def test_new_workflow_output_checks_frozen_decoded_length(system, monkeypatch, source_frames, decoded, accept): - from app import assets, media +@pytest.mark.parametrize( + "source_frames,decoded,accept", + [ + (121, 119, False), + (121, 120, True), + (241, 239, False), + (241, 240, True), + (361, 121, False), + (361, 359, False), + (361, 360, True), + ], +) +async def test_new_workflow_output_checks_frozen_decoded_length( + system, monkeypatch, source_frames, decoded, accept +): + from app.services import assets + from app.adapters import media + job = await output_job(system, source_frames) - source = system.settings.job_work_root/job.id/'source.mp4' - source.parent.mkdir(); source.write_bytes(b'fixture-native-video') + source = system.settings.job_work_root / job.id / "source.mp4" + source.parent.mkdir() + source.write_bytes(b"fixture-native-video") + async def track(*args): - return {'frames':decoded,'fps':24,'width':1920,'height':1056,'duration':decoded/24} - async def build(settings,owner,identifier,path,name,**fields): - data=path.read_bytes() - return Asset(id=identifier,owner_id=owner,name=name,storage_key=path.relative_to(settings.asset_root).as_posix(), - kind='video',mime_type='video/mp4',size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(), - width=1920,height=1056,duration_seconds=decoded/24,**fields) - monkeypatch.setattr(media,'inspect_video_track',track) - monkeypatch.setattr(assets,'build_asset',build) + return { + "frames": decoded, + "fps": 24, + "width": 1920, + "height": 1056, + "duration": decoded / 24, + } + + async def build(settings, owner, identifier, path, name, **fields): + data = path.read_bytes() + return Asset( + id=identifier, + owner_id=owner, + name=name, + storage_key=path.relative_to(settings.asset_root).as_posix(), + kind="video", + mime_type="video/mp4", + size_bytes=len(data), + sha256=hashlib.sha256(data).hexdigest(), + width=1920, + height=1056, + duration_seconds=decoded / 24, + **fields, + ) + + monkeypatch.setattr(media, "inspect_video_track", track) + monkeypatch.setattr(assets, "build_asset", build) if accept: - output=await assets.import_output(system.app.state.db,system.settings,job,source,0) - assert output.source_job_id==job.id + output = await assets.import_output(system.app.state.db, system.settings, job, source, 0) + assert output.source_job_id == job.id else: - with pytest.raises(ValueError,match='frozen decoded video specification'): - await assets.import_output(system.app.state.db,system.settings,job,source,0) + with pytest.raises(ValueError, match="frozen decoded video specification"): + await assets.import_output(system.app.state.db, system.settings, job, source, 0) -@pytest.mark.parametrize('source_frames,decoded,accept', [(121,120,True),(361,121,False),(361,360,True)]) -async def test_existing_output_recovery_rechecks_frozen_decoded_length(system,monkeypatch,source_frames,decoded,accept): - from app import assets, media - job=await output_job(system,source_frames) - identifier=new_id(); path=system.settings.asset_root/job.owner_id/identifier/'original.mp4' - path.parent.mkdir(parents=True); data=b'previously-imported';path.write_bytes(data) - asset=Asset(id=identifier,owner_id=job.owner_id,name='output.mp4',storage_key=path.relative_to(system.settings.asset_root).as_posix(), - kind='video',mime_type='video/mp4',size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(), - width=1920,height=1056,duration_seconds=decoded/24,source_job_id=job.id,source_output_index=0,ready=False) +@pytest.mark.parametrize( + "source_frames,decoded,accept", [(121, 120, True), (361, 121, False), (361, 360, True)] +) +async def test_existing_output_recovery_rechecks_frozen_decoded_length( + system, monkeypatch, source_frames, decoded, accept +): + from app.services import assets + from app.adapters import media + + job = await output_job(system, source_frames) + identifier = new_id() + path = system.settings.asset_root / job.owner_id / identifier / "original.mp4" + path.parent.mkdir(parents=True) + data = b"previously-imported" + path.write_bytes(data) + asset = Asset( + id=identifier, + owner_id=job.owner_id, + name="output.mp4", + storage_key=path.relative_to(system.settings.asset_root).as_posix(), + kind="video", + mime_type="video/mp4", + size_bytes=len(data), + sha256=hashlib.sha256(data).hexdigest(), + width=1920, + height=1056, + duration_seconds=decoded / 24, + source_job_id=job.id, + source_output_index=0, + ready=False, + ) async with system.app.state.db.session() as session: - session.add(asset);await session.commit() - async def track(*args):return {'frames':decoded,'fps':24,'width':1920,'height':1056,'duration':decoded/24} - monkeypatch.setattr(media,'inspect_video_track',track) - if accept: - result=await assets.import_output(system.app.state.db,system.settings,job,path,0) - assert result.id==identifier - else: - with pytest.raises(ValueError,match='frozen decoded video specification'): - await assets.import_output(system.app.state.db,system.settings,job,path,0) - - -async def test_gpu_existing_output_recovery_rejects_short_source_for_long_job(system,monkeypatch): - from app import media - job=await output_job(system,361) - identifier=new_id();path=system.settings.asset_root/job.owner_id/identifier/'original.mp4' - path.parent.mkdir(parents=True);data=b'previously-imported-short-video';path.write_bytes(data) - async with system.app.state.db.session() as session: - saved=await session.get(Job,job.id) - saved.upstream_result={'outputs':[{'path':'remote.mp4'}],'metadata':{'final_output_indices':[0]}} - session.add(Asset(id=identifier,owner_id=job.owner_id,name='short.mp4', - storage_key=path.relative_to(system.settings.asset_root).as_posix(),kind='video',mime_type='video/mp4', - size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(),width=1920,height=1056, - duration_seconds=121/24,source_job_id=job.id,source_output_index=0,ready=False)) + session.add(asset) await session.commit() - job=saved - async def track(*args):return {'frames':121,'fps':24,'width':1920,'height':1056,'duration':121/24} - published=[] - async def complete(*args,**kwargs):published.append(True) - monkeypatch.setattr(media,'inspect_video_track',track) - monkeypatch.setattr(system.app.state.coordinator,'_complete',complete) - with pytest.raises(ValueError,match='frozen decoded video specification'): + + async def track(*args): + return { + "frames": decoded, + "fps": 24, + "width": 1920, + "height": 1056, + "duration": decoded / 24, + } + + monkeypatch.setattr(media, "inspect_video_track", track) + if accept: + result = await assets.import_output(system.app.state.db, system.settings, job, path, 0) + assert result.id == identifier + else: + with pytest.raises(ValueError, match="frozen decoded video specification"): + await assets.import_output(system.app.state.db, system.settings, job, path, 0) + + +async def test_gpu_existing_output_recovery_rejects_short_source_for_long_job(system, monkeypatch): + from app.adapters import media + + job = await output_job(system, 361) + identifier = new_id() + path = system.settings.asset_root / job.owner_id / identifier / "original.mp4" + path.parent.mkdir(parents=True) + data = b"previously-imported-short-video" + path.write_bytes(data) + async with system.app.state.db.session() as session: + saved = await session.get(Job, job.id) + saved.upstream_result = { + "outputs": [{"path": "remote.mp4"}], + "metadata": {"final_output_indices": [0]}, + } + session.add( + Asset( + id=identifier, + owner_id=job.owner_id, + name="short.mp4", + storage_key=path.relative_to(system.settings.asset_root).as_posix(), + kind="video", + mime_type="video/mp4", + size_bytes=len(data), + sha256=hashlib.sha256(data).hexdigest(), + width=1920, + height=1056, + duration_seconds=121 / 24, + source_job_id=job.id, + source_output_index=0, + ready=False, + ) + ) + await session.commit() + job = saved + + async def track(*args): + return {"frames": 121, "fps": 24, "width": 1920, "height": 1056, "duration": 121 / 24} + + published = [] + + async def complete(*args, **kwargs): + published.append(True) + + monkeypatch.setattr(media, "inspect_video_track", track) + monkeypatch.setattr(system.app.state.coordinator, "_complete", complete) + with pytest.raises(ValueError, match="frozen decoded video specification"): await system.app.state.coordinator._collect_gpu(job) assert not published - assert system.provider.download_count==0 + assert system.provider.download_count == 0 -async def test_mixed_composition_uses_exact_selected_frames_without_extension(tmp_path,monkeypatch): - from app import media - plan=compile_timeline(story(durations=[120,240,360]),{}) - sources=[tmp_path/f'source-{index}.mp4' for index in range(3)] - for path in sources:path.write_bytes(b'fixture') - calls=[] - async def track(path,settings): - frames=720 if path.name=='workflow.mp4' else [121,241,361][sources.index(path)] - return {'frames':frames,'fps':24,'width':1920,'height':1080 if path.name=='workflow.mp4' else 1056,'duration':frames/24} - async def process(argv,**kwargs): - calls.append(argv);Path(argv[-1]).write_bytes(b'rendered');return b'' - monkeypatch.setattr(media,'inspect_video_track',track);monkeypatch.setattr(media,'run_process',process) - result=await media.compose_workflow(plan,tmp_path/'work',settings=SimpleNamespace( - workspace_root=tmp_path,ffmpeg_bin='ffmpeg',max_output_bytes=10**6),sources=sources) - assert [int(call[call.index('-frames:v')+1]) for call in calls]==[120,240,360,720] - assert result.result['frames']==720 and result.result['duration_seconds']==30 - assert all('tpad' not in ' '.join(call) and '-stream_loop' not in call for call in calls) +async def test_mixed_composition_uses_exact_selected_frames_without_extension( + tmp_path, monkeypatch +): + from app.adapters import media + + plan = compile_timeline(story(durations=[120, 240, 360]), {}) + sources = [tmp_path / f"source-{index}.mp4" for index in range(3)] + for path in sources: + path.write_bytes(b"fixture") + calls = [] + + async def track(path, settings): + frames = 720 if path.name == "workflow.mp4" else [121, 241, 361][sources.index(path)] + return { + "frames": frames, + "fps": 24, + "width": 1920, + "height": 1080 if path.name == "workflow.mp4" else 1056, + "duration": frames / 24, + } + + async def process(argv, **kwargs): + calls.append(argv) + Path(argv[-1]).write_bytes(b"rendered") + return b"" + + monkeypatch.setattr(media, "inspect_video_track", track) + monkeypatch.setattr(media, "run_process", process) + result = await media.compose_workflow( + plan, + tmp_path / "work", + settings=SimpleNamespace( + workspace_root=tmp_path, ffmpeg_bin="ffmpeg", max_output_bytes=10**6 + ), + sources=sources, + ) + assert [int(call[call.index("-frames:v") + 1]) for call in calls] == [120, 240, 360, 720] + assert result.result["frames"] == 720 and result.result["duration_seconds"] == 30 + assert all("tpad" not in " ".join(call) and "-stream_loop" not in call for call in calls) -async def test_composition_rejects_short_native_source_instead_of_extending(tmp_path,monkeypatch): - from app import media - plan=compile_timeline(story(durations=[360]),{}) - source=tmp_path/'source.mp4';source.write_bytes(b'fixture') - async def track(*args):return {'frames':121,'fps':24,'width':1920,'height':1056,'duration':121/24} - monkeypatch.setattr(media,'inspect_video_track',track) - with pytest.raises(media.MediaError,match='360'): - await media.compose_workflow(plan,tmp_path/'work',settings=SimpleNamespace(workspace_root=tmp_path),sources=[source]) +async def test_composition_rejects_short_native_source_instead_of_extending(tmp_path, monkeypatch): + from app.adapters import media + + plan = compile_timeline(story(durations=[360]), {}) + source = tmp_path / "source.mp4" + source.write_bytes(b"fixture") + + async def track(*args): + return {"frames": 121, "fps": 24, "width": 1920, "height": 1056, "duration": 121 / 24} + + monkeypatch.setattr(media, "inspect_video_track", track) + with pytest.raises(media.MediaError, match="360"): + await media.compose_workflow( + plan, + tmp_path / "work", + settings=SimpleNamespace(workspace_root=tmp_path), + sources=[source], + ) diff --git a/backend/tests/test_maintenance_admission.py b/backend/tests/test_maintenance_admission.py index 89bfffb..d8ad17a 100644 --- a/backend/tests/test_maintenance_admission.py +++ b/backend/tests/test_maintenance_admission.py @@ -1,18 +1,25 @@ async def test_maintenance_intent_pauses_existing_upstream_queue_and_survives_toggles(system): - response=await system.client.post('/api/jobs',json={'task_type':'image.generate','input':{'prompt':'hold existing queue'}}) - assert response.status_code==202 - coordinator=system.app.state.coordinator + response = await system.client.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "hold existing queue"}}, + ) + assert response.status_code == 202 + coordinator = system.app.state.coordinator await coordinator.run_once(force=True) - controls=[] - async def control(id,desired,command_id): - controls.append((desired,command_id)) + controls = [] + + async def control(id, desired, command_id): + controls.append((desired, command_id)) return dict(system.provider.remote[id]) - system.provider.control=control - marker=system.settings.state_root/'maintenance' - for held in (True,False,True,False): - if held:marker.write_text('hold') - else:marker.unlink() + + system.provider.control = control + marker = system.settings.state_root / "maintenance" + for held in (True, False, True, False): + if held: + marker.write_text("hold") + else: + marker.unlink() await coordinator.run_once(force=True) - assert [state for state,_ in controls]==['pause','run','pause','run'] - assert len({key for _,key in controls})==4 - assert len(system.provider.accepted)==1 + assert [state for state, _ in controls] == ["pause", "run", "pause", "run"] + assert len({key for _, key in controls}) == 4 + assert len(system.provider.accepted) == 1 diff --git a/backend/tests/test_media.py b/backend/tests/test_media.py index 908ef66..83ee234 100644 --- a/backend/tests/test_media.py +++ b/backend/tests/test_media.py @@ -22,40 +22,51 @@ class MediaTests(unittest.IsolatedAsyncioTestCase): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name).resolve() - self.settings = SimpleNamespace(workspace_root=self.root, asset_root=self.root / 'assets', - job_work_root=self.root / 'jobs', ffmpeg_bin=shutil.which('ffmpeg') or 'ffmpeg', - ffprobe_bin=shutil.which('ffprobe') or 'ffprobe', request_timeout_seconds=3, - max_output_bytes=1024 * 1024) - self.media = importlib.import_module('app.media') + self.settings = SimpleNamespace( + workspace_root=self.root, + asset_root=self.root / "assets", + job_work_root=self.root / "jobs", + ffmpeg_bin=shutil.which("ffmpeg") or "ffmpeg", + ffprobe_bin=shutil.which("ffprobe") or "ffprobe", + request_timeout_seconds=3, + max_output_bytes=1024 * 1024, + ) + self.media = importlib.import_module("app.adapters.media") async def test_image_is_decoded_and_thumbnail_really_exists(self): - source = self.root / 'source.png' - Image.new('RGB', (800, 400), 'red').save(source) + source = self.root / "source.png" + Image.new("RGB", (800, 400), "red").save(source) info = await self.media.inspect_media(source, self.settings) - self.assertEqual((info['kind'], info['mime_type'], info['width'], info['height']), - ('image', 'image/png', 800, 400)) - target = await self.media.make_thumbnail(source, self.root / 'thumb.jpg', self.settings) + self.assertEqual( + (info["kind"], info["mime_type"], info["width"], info["height"]), + ("image", "image/png", 800, 400), + ) + target = await self.media.make_thumbnail(source, self.root / "thumb.jpg", self.settings) with Image.open(target) as thumbnail: self.assertEqual(thumbnail.size, (512, 256)) async def test_generated_json_and_text_are_validated_as_assets(self): - source = self.root / 'answer.json' - source.write_text('{"text":"数学"}', encoding='utf-8') - self.assertEqual((await self.media.inspect_media(source, self.settings))['kind'], 'json') - source.write_text('{broken', encoding='utf-8') + source = self.root / "answer.json" + source.write_text('{"text":"数学"}', encoding="utf-8") + self.assertEqual((await self.media.inspect_media(source, self.settings))["kind"], "json") + source.write_text("{broken", encoding="utf-8") with self.assertRaises(self.media.MediaError): await self.media.inspect_media(source, self.settings) - source = self.root / 'answer.txt' - source.write_text('答案是 42', encoding='utf-8') - self.assertEqual((await self.media.inspect_media(source, self.settings))['mime_type'], 'text/plain') - self.assertIsNone(await self.media.make_thumbnail(source, self.root / 'unused.jpg', self.settings)) + source = self.root / "answer.txt" + source.write_text("答案是 42", encoding="utf-8") + self.assertEqual( + (await self.media.inspect_media(source, self.settings))["mime_type"], "text/plain" + ) + self.assertIsNone( + await self.media.make_thumbnail(source, self.root / "unused.jpg", self.settings) + ) async def test_outside_path_and_fake_image_fail_without_path_disclosure(self): with self.assertRaises(self.media.MediaError) as caught: - await self.media.inspect_media(self.root.parent / 'PRIVATE-SECRET.png', self.settings) - self.assertNotIn('PRIVATE-SECRET', str(caught.exception)) - broken = self.root / 'fake.png' - broken.write_bytes(b'not an image') + await self.media.inspect_media(self.root.parent / "PRIVATE-SECRET.png", self.settings) + self.assertNotIn("PRIVATE-SECRET", str(caught.exception)) + broken = self.root / "fake.png" + broken.write_bytes(b"not an image") with self.assertRaises(self.media.MediaError): await self.media.inspect_media(broken, self.settings) @@ -68,15 +79,18 @@ class MediaTests(unittest.IsolatedAsyncioTestCase): observed.append(process) return process - unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) try: - with patch.object(self.media.asyncio, 'create_subprocess_exec', side_effect=record): - task = asyncio.create_task(self.media.run_process( - [sys.executable, '-c', 'import time; time.sleep(60)'], timeout=30)) + with patch.object(self.media.asyncio, "create_subprocess_exec", side_effect=record): + task = asyncio.create_task( + self.media.run_process( + [sys.executable, "-c", "import time; time.sleep(60)"], timeout=30 + ) + ) for _ in range(100): if observed: break - await asyncio.sleep(.01) + await asyncio.sleep(0.01) self.assertTrue(observed) task.cancel() with self.assertRaises(asyncio.CancelledError): @@ -89,33 +103,70 @@ class MediaTests(unittest.IsolatedAsyncioTestCase): async def test_process_timeout_and_output_bound_are_enforced(self): with self.assertRaises(self.media.MediaError) as caught: - await self.media.run_process([sys.executable, '-c', 'import time; time.sleep(60)'], timeout=.1) - self.assertEqual(caught.exception.code, 'media_timeout') + await self.media.run_process( + [sys.executable, "-c", "import time; time.sleep(60)"], timeout=0.1 + ) + self.assertEqual(caught.exception.code, "media_timeout") with self.assertRaises(self.media.MediaError): - await self.media.run_process([sys.executable, '-c', 'print("x"*100000)'], timeout=3, max_output=256) + await self.media.run_process( + [sys.executable, "-c", 'print("x"*100000)'], timeout=3, max_output=256 + ) with warnings.catch_warnings(record=True) as captured: - warnings.simplefilter('always', ResourceWarning) + warnings.simplefilter("always", ResourceWarning) with self.assertRaises(self.media.MediaError): - await asyncio.wait_for(self.media.run_process([sys.executable, '-c', - 'import sys; sys.stdout.write("x"*10000000); sys.stdout.flush()'], timeout=3, max_output=256), 5) - await asyncio.sleep(.05) + await asyncio.wait_for( + self.media.run_process( + [ + sys.executable, + "-c", + 'import sys; sys.stdout.write("x"*10000000); sys.stdout.flush()', + ], + timeout=3, + max_output=256, + ), + 5, + ) + await asyncio.sleep(0.05) gc.collect() - self.assertFalse([warning for warning in captured if issubclass(warning.category, ResourceWarning)]) + self.assertFalse( + [warning for warning in captured if issubclass(warning.category, ResourceWarning)] + ) async def test_bounded_diagnostics_can_return_actual_frame_timestamps(self): - stdout, stderr = await self.media.run_process([sys.executable, '-c', - 'import sys; print("result"); print("pts_time:0.541667",file=sys.stderr)'], - timeout=3, return_stderr=True) - self.assertIn(b'result', stdout) - self.assertIn(b'pts_time:0.541667', stderr) + stdout, stderr = await self.media.run_process( + [ + sys.executable, + "-c", + 'import sys; print("result"); print("pts_time:0.541667",file=sys.stderr)', + ], + timeout=3, + return_stderr=True, + ) + self.assertIn(b"result", stdout) + self.assertIn(b"pts_time:0.541667", stderr) - @unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg not installed') + @unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "FFmpeg not installed") async def test_real_video_probe_and_thumbnail(self): - video = self.root / 'tiny.mp4' - await self.media.run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i', - 'color=c=blue:s=320x240:r=24:d=0.5', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(video)], timeout=30) + video = self.root / "tiny.mp4" + await self.media.run_process( + [ + self.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=320x240:r=24:d=0.5", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + str(video), + ], + timeout=30, + ) info = await self.media.inspect_media(video, self.settings) - self.assertEqual((info['kind'], info['width'], info['height']), ('video', 320, 240)) - self.assertGreater(info['duration_seconds'], .4) - thumb = await self.media.make_thumbnail(video, self.root / 'video.jpg', self.settings) + self.assertEqual((info["kind"], info["width"], info["height"]), ("video", 320, 240)) + self.assertGreater(info["duration_seconds"], 0.4) + thumb = await self.media.make_thumbnail(video, self.root / "video.jpg", self.settings) self.assertTrue(thumb.is_file()) diff --git a/backend/tests/test_multishot_v3.py b/backend/tests/test_multishot_v3.py index 4a671fa..4ea4212 100644 --- a/backend/tests/test_multishot_v3.py +++ b/backend/tests/test_multishot_v3.py @@ -1,246 +1,413 @@ """Variable story length without changing the short-clip model contract.""" + import pytest from pydantic import ValidationError from sqlalchemy import select from app.models import Job -from app.timeline import WorkflowSpec, compile_timeline +from app.domain.timeline import WorkflowSpec, compile_timeline from test_timeline_v2 import spec as legacy_spec from test_workflows_v2 import wf, run, publish_video def story(count=12, durations=None): durations = durations or [120] * count - return {'schema_version': 2, 'shots': [ - {'key': f'shot_{i + 1}', 'prompt': f'镜头{i + 1}', 'duration_frames': frames, - 'parameters': {'seed': i + 1}} - for i, frames in enumerate(durations) - ], 'profile': 'landscape_1080_v1'} + return { + "schema_version": 2, + "shots": [ + { + "key": f"shot_{i + 1}", + "prompt": f"镜头{i + 1}", + "duration_frames": frames, + "parameters": {"seed": i + 1}, + } + for i, frames in enumerate(durations) + ], + "profile": "landscape_1080_v1", + } def test_dynamic_timeline_derives_duration_and_accepts_late_audio_subtitles(): body = story(durations=[24] + [120] * 11) - body['render'] = {'audio': {'asset_id': 'voice', 'source_start_ms': 0, - 'source_end_ms': 10000, 'offset_frame': 960}, - 'subtitles': [{'start_frame': 961, 'end_frame': 1344, 'text': '乘风南迁'}]} - plan = compile_timeline(body, {'voice': {'kind': 'audio', 'duration_seconds': 10}}) + body["render"] = { + "audio": { + "asset_id": "voice", + "source_start_ms": 0, + "source_end_ms": 10000, + "offset_frame": 960, + }, + "subtitles": [{"start_frame": 961, "end_frame": 1344, "text": "乘风南迁"}], + } + plan = compile_timeline(body, {"voice": {"kind": "audio", "duration_seconds": 10}}) assert plan.frames == 1344 assert plan.shot_frames == (24,) + (120,) * 11 - assert plan.spec['render']['total_frames'] == 1344 - assert plan.generation_parameters['num_frames'] == 121 + assert plan.spec["render"]["total_frames"] == 1344 + assert plan.generation_parameters["num_frames"] == 121 -@pytest.mark.parametrize('change', ['keys', 'duplicate', 'zero', 'too_long', 'total', 'subtitle', 'audio']) +@pytest.mark.parametrize( + "change", ["keys", "duplicate", "zero", "too_long", "total", "subtitle", "audio"] +) def test_dynamic_timeline_rejects_inconsistent_order_and_bounds(change): body = story(4) - if change == 'keys': body['shots'][1]['key'] = 'shot_12' - elif change == 'duplicate': body['shots'][1]['key'] = 'shot_1' - elif change == 'zero': body['shots'][0]['duration_frames'] = 0 - elif change == 'too_long': body['shots'][0]['duration_frames'] = 361 - elif change == 'total': body['render'] = {'total_frames': 481} - elif change == 'subtitle': body['render'] = {'subtitles': [{'start_frame': 0, 'end_frame': 481, 'text': 'bad'}]} - else: body['render'] = {'audio': {'asset_id': 'a', 'source_start_ms': 0, 'source_end_ms': 20000, 'offset_frame': 1}} - with pytest.raises(ValidationError): WorkflowSpec.model_validate(body) + if change == "keys": + body["shots"][1]["key"] = "shot_12" + elif change == "duplicate": + body["shots"][1]["key"] = "shot_1" + elif change == "zero": + body["shots"][0]["duration_frames"] = 0 + elif change == "too_long": + body["shots"][0]["duration_frames"] = 361 + elif change == "total": + body["render"] = {"total_frames": 481} + elif change == "subtitle": + body["render"] = {"subtitles": [{"start_frame": 0, "end_frame": 481, "text": "bad"}]} + else: + body["render"] = { + "audio": { + "asset_id": "a", + "source_start_ms": 0, + "source_end_ms": 20000, + "offset_frame": 1, + } + } + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(body) def test_legacy_normalized_spec_and_exact_length_stay_compatible(): plan = compile_timeline(legacy_spec(), {}) assert plan.frames == 360 - assert all('duration_frames' not in shot for shot in plan.spec['shots']) - bad = legacy_spec(); bad['shots'].append({'key': 'shot_4', 'prompt': 'extra'}) - with pytest.raises(ValidationError): WorkflowSpec.model_validate(bad) + assert all("duration_frames" not in shot for shot in plan.spec["shots"]) + bad = legacy_spec() + bad["shots"].append({"key": "shot_4", "prompt": "extra"}) + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(bad) @pytest.mark.asyncio async def test_twelve_shot_run_uses_snapshot_order_then_compose(wf): - from app.workflow_engine import advance_workflows - response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story()}) + from app.services.orchestration.workflow_engine import advance_workflows + + response = await wf.client.post("/api/workflows", json={"kind": "multi_shot", "spec": story()}) assert response.status_code == 201, response.text snapshot = await run(wf, response.json()) - rid = snapshot['run']['id'] - assert snapshot['run']['total_steps'] == 13 - expected_keys = [f'shot_{i}' for i in range(1, 13)] + ['compose'] - assert [step['step_key'] for step in snapshot['steps']] == expected_keys + rid = snapshot["run"]["id"] + assert snapshot["run"]["total_steps"] == 13 + expected_keys = [f"shot_{i}" for i in range(1, 13)] + ["compose"] + assert [step["step_key"] for step in snapshot["steps"]] == expected_keys ids = [] for key in expected_keys[:-1]: await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as session: - job = await session.scalar(select(Job).where(Job.run_id == rid, Job.state != 'succeeded')) + job = await session.scalar( + select(Job).where(Job.run_id == rid, Job.state != "succeeded") + ) assert job.step_key == key jid = job.id ids.append(await publish_video(wf, jid)) await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as session: - compose = await session.scalar(select(Job).where(Job.run_id == rid, Job.step_key == 'compose')) - assert compose.input_json['asset_ids'] == ids - assert compose.parameters['workflow_spec']['render']['total_frames'] == 1440 + compose = await session.scalar( + select(Job).where(Job.run_id == rid, Job.step_key == "compose") + ) + assert compose.input_json["asset_ids"] == ids + assert compose.parameters["workflow_spec"]["render"]["total_frames"] == 1440 await publish_video(wf, compose.id, compose=True) await advance_workflows(wf.app.state.db, wf.settings, wf.provider) - snapshot = (await wf.client.get('/api/workflow-runs/' + rid)).json() - assert snapshot['run']['state'] == 'succeeded' - assert snapshot['run']['completed_steps'] == snapshot['run']['total_steps'] == 13 + snapshot = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snapshot["run"]["state"] == "succeeded" + assert snapshot["run"]["completed_steps"] == snapshot["run"]["total_steps"] == 13 @pytest.mark.asyncio async def test_trim_only_revision_reuses_generated_shot(wf): - from app.workflow_engine import advance_workflows - response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(1)}) + from app.services.orchestration.workflow_engine import advance_workflows + + response = await wf.client.post("/api/workflows", json={"kind": "multi_shot", "spec": story(1)}) assert response.status_code == 201, response.text - draft = response.json(); first = await run(wf, draft) + draft = response.json() + first = await run(wf, draft) await advance_workflows(wf.app.state.db, wf.settings, wf.provider) - first = (await wf.client.get('/api/workflow-runs/' + first['run']['id'])).json() - jid = first['steps'][0]['selected_job_id'] + first = (await wf.client.get("/api/workflow-runs/" + first["run"]["id"])).json() + jid = first["steps"][0]["selected_job_id"] await publish_video(wf, jid) - await wf.client.post('/api/workflow-runs/' + first['run']['id'] + '/cancel', json={}, headers={'Idempotency-Key': 'cancel'}) + await wf.client.post( + "/api/workflow-runs/" + first["run"]["id"] + "/cancel", + json={}, + headers={"Idempotency-Key": "cancel"}, + ) await advance_workflows(wf.app.state.db, wf.settings, wf.provider) - draft = (await wf.client.get('/api/workflows/' + draft['id'])).json() - body = story(1); body['shots'][0]['duration_frames'] = 48 - changed = await wf.client.patch('/api/workflows/' + draft['id'], json={'spec': body}, headers={'If-Match': str(draft['version'])}) + draft = (await wf.client.get("/api/workflows/" + draft["id"])).json() + body = story(1) + body["shots"][0]["duration_frames"] = 48 + changed = await wf.client.patch( + "/api/workflows/" + draft["id"], + json={"spec": body}, + headers={"If-Match": str(draft["version"])}, + ) assert changed.status_code == 200, changed.text draft = changed.json() - response = await wf.client.post('/api/workflows/' + draft['id'] + '/runs', json={ - 'draft_revision': draft['revision'], 'expected_version': draft['version'], - 'reuse_run_id': first['run']['id']}, headers={'Idempotency-Key': 'trim'}) + response = await wf.client.post( + "/api/workflows/" + draft["id"] + "/runs", + json={ + "draft_revision": draft["revision"], + "expected_version": draft["version"], + "reuse_run_id": first["run"]["id"], + }, + headers={"Idempotency-Key": "trim"}, + ) assert response.status_code == 202, response.text - assert response.json()['steps'][0]['selected_job_id'] == jid - assert response.json()['steps'][0]['state'] == 'succeeded' + assert response.json()["steps"][0]["selected_job_id"] == jid + assert response.json()["steps"][0]["state"] == "succeeded" @pytest.mark.asyncio async def test_config_cap_checks_new_save_run_but_not_frozen_children(wf, monkeypatch): - from app import workflows - from app import runtime_policy - from app.workflow_engine import advance_workflows + from app.services import workflows + from app.core import runtime_policy + from app.services.orchestration.workflow_engine import advance_workflows + limit = [12] - monkeypatch.setattr(workflows, 'read_runtime_policy', lambda settings: {'workflow_max_shots': limit[0], 'configuration_error': None}) - monkeypatch.setattr(runtime_policy, 'read_runtime_policy', workflows.read_runtime_policy) - response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(4)}) + monkeypatch.setattr( + workflows, + "read_runtime_policy", + lambda settings: {"workflow_max_shots": limit[0], "configuration_error": None}, + ) + monkeypatch.setattr(runtime_policy, "read_runtime_policy", workflows.read_runtime_policy) + response = await wf.client.post("/api/workflows", json={"kind": "multi_shot", "spec": story(4)}) assert response.status_code == 201, response.text - draft = response.json(); accepted = await run(wf, draft) + draft = response.json() + accepted = await run(wf, draft) limit[0] = 3 - rejected = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(4)}) - assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit' - current = (await wf.client.get('/api/workflows/' + draft['id'])).json() - rejected = await wf.client.patch('/api/workflows/' + draft['id'], json={'spec': story(4)}, headers={'If-Match': str(current['version'])}) + rejected = await wf.client.post("/api/workflows", json={"kind": "multi_shot", "spec": story(4)}) + assert ( + rejected.status_code == 422 and rejected.json()["detail"]["code"] == "workflow_shot_limit" + ) + current = (await wf.client.get("/api/workflows/" + draft["id"])).json() + rejected = await wf.client.patch( + "/api/workflows/" + draft["id"], + json={"spec": story(4)}, + headers={"If-Match": str(current["version"])}, + ) assert rejected.status_code == 422 - rejected = await wf.client.post('/api/workflows/' + draft['id'] + '/runs', json={ - 'draft_revision': current['revision'], 'expected_version': current['version']}, headers={'Idempotency-Key': 'over-limit'}) - assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit' - rid = accepted['run']['id'] + rejected = await wf.client.post( + "/api/workflows/" + draft["id"] + "/runs", + json={"draft_revision": current["revision"], "expected_version": current["version"]}, + headers={"Idempotency-Key": "over-limit"}, + ) + assert ( + rejected.status_code == 422 and rejected.json()["detail"]["code"] == "workflow_shot_limit" + ) + rid = accepted["run"]["id"] for i in range(4): await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as session: - job = await session.scalar(select(Job).where(Job.run_id == rid, Job.state != 'succeeded')) - assert job.step_key == f'shot_{i + 1}' + job = await session.scalar( + select(Job).where(Job.run_id == rid, Job.state != "succeeded") + ) + assert job.step_key == f"shot_{i + 1}" await publish_video(wf, job.id) await advance_workflows(wf.app.state.db, wf.settings, wf.provider) - result = (await wf.client.get('/api/workflow-runs/' + rid)).json() - assert result['steps'][-1]['step_key'] == 'compose' and result['steps'][-1]['selected_job_id'] + result = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert result["steps"][-1]["step_key"] == "compose" and result["steps"][-1]["selected_job_id"] @pytest.mark.asyncio async def test_new_manual_composition_uses_configured_clip_cap(system, monkeypatch): - from app import runtime_policy + from app.core import runtime_policy + limit = [4] - monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: { - 'workflow_max_shots': limit[0], 'configuration_error': None}) - source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}}) - aid = await publish_video(system, source.json()['jobs'][0]['id']) - body = {'task_type': 'video.compose', 'input': {'asset_ids': [aid] * 4}, - 'parameters': {'clips': [{'asset_id': aid}] * 4}} - accepted = await system.client.post('/api/jobs', json=body) + monkeypatch.setattr( + runtime_policy, + "read_runtime_policy", + lambda settings: {"workflow_max_shots": limit[0], "configuration_error": None}, + ) + source = await system.client.post( + "/api/jobs", json={"task_type": "video.generate", "input": {"prompt": "source"}} + ) + aid = await publish_video(system, source.json()["jobs"][0]["id"]) + body = { + "task_type": "video.compose", + "input": {"asset_ids": [aid] * 4}, + "parameters": {"clips": [{"asset_id": aid}] * 4}, + } + accepted = await system.client.post("/api/jobs", json=body) assert accepted.status_code == 202, accepted.text limit[0] = 3 - rejected = await system.client.post('/api/jobs', json=body) - assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit' + rejected = await system.client.post("/api/jobs", json=body) + assert ( + rejected.status_code == 422 and rejected.json()["detail"]["code"] == "workflow_shot_limit" + ) @pytest.mark.asyncio async def test_new_batch_composition_enforces_cap_and_rolls_back_atomically(system, monkeypatch): from sqlalchemy import func - from app import runtime_policy - from app.v2_models import Batch - monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: { - 'workflow_max_shots': 3, 'configuration_error': None}) - source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}}) - aid = await publish_video(system, source.json()['jobs'][0]['id']) - job = {'task_type': 'video.compose', 'input': {'asset_ids': [aid] * 4}, - 'parameters': {'clips': [{'asset_id': aid}] * 4}} - direct = await system.client.post('/api/jobs', json=job) - assert direct.status_code == 422 and direct.json()['detail']['code'] == 'workflow_shot_limit' - batch = await system.client.post('/api/batches', json={'items': [ - {'kind': 'job', 'task_type': 'math.solve', 'input': {'prompt': '2+2'}}, - {'kind': 'job', **job}]}, headers={'Idempotency-Key': 'over-cap-batch'}) - assert batch.status_code == 422 and batch.json()['detail']['code'] == 'workflow_shot_limit' + from app.core import runtime_policy + from app.models import Batch + + monkeypatch.setattr( + runtime_policy, + "read_runtime_policy", + lambda settings: {"workflow_max_shots": 3, "configuration_error": None}, + ) + source = await system.client.post( + "/api/jobs", json={"task_type": "video.generate", "input": {"prompt": "source"}} + ) + aid = await publish_video(system, source.json()["jobs"][0]["id"]) + job = { + "task_type": "video.compose", + "input": {"asset_ids": [aid] * 4}, + "parameters": {"clips": [{"asset_id": aid}] * 4}, + } + direct = await system.client.post("/api/jobs", json=job) + assert direct.status_code == 422 and direct.json()["detail"]["code"] == "workflow_shot_limit" + batch = await system.client.post( + "/api/batches", + json={ + "items": [ + {"kind": "job", "task_type": "math.solve", "input": {"prompt": "2+2"}}, + {"kind": "job", **job}, + ] + }, + headers={"Idempotency-Key": "over-cap-batch"}, + ) + assert batch.status_code == 422 and batch.json()["detail"]["code"] == "workflow_shot_limit" async with system.app.state.db.session() as session: assert await session.scalar(select(func.count()).select_from(Batch)) == 0 assert await session.scalar(select(func.count()).select_from(Job)) == 1 @pytest.mark.asyncio -async def test_accepted_batch_replays_after_cap_reduction_but_new_batch_rejected(system, monkeypatch): - from app import runtime_policy +async def test_accepted_batch_replays_after_cap_reduction_but_new_batch_rejected( + system, monkeypatch +): + from app.core import runtime_policy + limit = [4] - monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: { - 'workflow_max_shots': limit[0], 'configuration_error': None}) - source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}}) - aid = await publish_video(system, source.json()['jobs'][0]['id']) - body = {'items': [{'kind': 'job', 'task_type': 'video.compose', - 'input': {'asset_ids': [aid] * 4}, 'parameters': {'clips': [{'asset_id': aid}] * 4}}]} - accepted = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'accepted-batch'}) + monkeypatch.setattr( + runtime_policy, + "read_runtime_policy", + lambda settings: {"workflow_max_shots": limit[0], "configuration_error": None}, + ) + source = await system.client.post( + "/api/jobs", json={"task_type": "video.generate", "input": {"prompt": "source"}} + ) + aid = await publish_video(system, source.json()["jobs"][0]["id"]) + body = { + "items": [ + { + "kind": "job", + "task_type": "video.compose", + "input": {"asset_ids": [aid] * 4}, + "parameters": {"clips": [{"asset_id": aid}] * 4}, + } + ] + } + accepted = await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "accepted-batch"} + ) assert accepted.status_code == 202, accepted.text limit[0] = 3 - replay = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'accepted-batch'}) - assert replay.status_code == 202 and replay.json()['batch']['id'] == accepted.json()['batch']['id'] - rejected = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'new-batch'}) - assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit' + replay = await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "accepted-batch"} + ) + assert ( + replay.status_code == 202 and replay.json()["batch"]["id"] == accepted.json()["batch"]["id"] + ) + rejected = await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "new-batch"} + ) + assert ( + rejected.status_code == 422 and rejected.json()["detail"]["code"] == "workflow_shot_limit" + ) @pytest.mark.asyncio -async def test_manual_composition_can_exceed_twenty_four_clips_and_thirty_minutes(tmp_path, monkeypatch): +async def test_manual_composition_can_exceed_twenty_four_clips_and_thirty_minutes( + tmp_path, monkeypatch +): from types import SimpleNamespace - from app import providers - source = tmp_path / 'source.mp4'; source.write_bytes(b'x') - work = tmp_path / 'work'; work.mkdir() + from app.adapters.provider import composition + from app.adapters.provider.client import Provider + + source = tmp_path / "source.mp4" + source.write_bytes(b"x") + work = tmp_path / "work" + work.mkdir() calls = [] + async def inspect(path, settings): - return {'kind': 'video', 'has_audio': False, - 'duration_seconds': 3600 if path.name == 'composition.mp4' else 120} + return { + "kind": "video", + "has_audio": False, + "duration_seconds": 3600 if path.name == "composition.mp4" else 120, + } + async def process(argv, **kwargs): - calls.append(argv); __import__('pathlib').Path(argv[-1]).write_bytes(b'x'); return b'' - monkeypatch.setattr(providers, 'inspect_media', inspect) - monkeypatch.setattr(providers, 'run_process', process) - settings = SimpleNamespace(workspace_root=tmp_path, request_timeout_seconds=5, - ffmpeg_bin='ffmpeg', max_output_bytes=1000000) - provider = providers.Provider(settings) + calls.append(argv) + __import__("pathlib").Path(argv[-1]).write_bytes(b"x") + return b"" + + monkeypatch.setattr(composition, "inspect_media", inspect) + monkeypatch.setattr(composition, "run_process", process) + settings = SimpleNamespace( + workspace_root=tmp_path, + request_timeout_seconds=5, + ffmpeg_bin="ffmpeg", + max_output_bytes=1000000, + ) + provider = Provider(settings) try: - result = await provider._compose({'asset_ids': ['video'] * 30}, - {'clips': [{'asset_id': 'video'}] * 30}, {'video': source}, work) + result = await provider._compose( + {"asset_ids": ["video"] * 30}, + {"clips": [{"asset_id": "video"}] * 30}, + {"video": source}, + work, + ) finally: await provider.aclose() assert len(calls) == 31 - assert result.result['clip_count'] == 30 and result.result['duration_seconds'] == 3600 + assert result.result["clip_count"] == 30 and result.result["duration_seconds"] == 3600 @pytest.mark.asyncio async def test_media_variable_trims_and_total_frame_validation(tmp_path, monkeypatch): from types import SimpleNamespace - from app import media + from app.adapters import media + plan = compile_timeline(story(durations=[24, 120, 120, 120]), {}) - sources = [tmp_path / f'{i}.mp4' for i in range(4)] - for p in sources: p.write_bytes(b'x') + sources = [tmp_path / f"{i}.mp4" for i in range(4)] + for p in sources: + p.write_bytes(b"x") calls = [] + async def track(path, settings): - return {'frames': 384 if path.name == 'workflow.mp4' else 121, 'fps': 24, - 'width': 1920, 'height': 1080 if path.name == 'workflow.mp4' else 1056, - 'duration': 16 if path.name == 'workflow.mp4' else 121 / 24} + return { + "frames": 384 if path.name == "workflow.mp4" else 121, + "fps": 24, + "width": 1920, + "height": 1080 if path.name == "workflow.mp4" else 1056, + "duration": 16 if path.name == "workflow.mp4" else 121 / 24, + } + async def process(argv, **kwargs): - calls.append(argv); __import__('pathlib').Path(argv[-1]).write_bytes(b'x'); return b'' - monkeypatch.setattr(media, 'inspect_video_track', track) - monkeypatch.setattr(media, 'run_process', process) - result = await media.compose_workflow(plan, tmp_path / 'work', settings=SimpleNamespace( - workspace_root=tmp_path, ffmpeg_bin='ffmpeg', max_output_bytes=1000000), sources=sources) - assert [int(c[c.index('-frames:v') + 1]) for c in calls] == [24, 120, 120, 120, 384] - assert 'atrim=duration=16' in calls[-1] - assert result.result['duration_seconds'] == 16 - assert result.result['clip_count'] == 4 + calls.append(argv) + __import__("pathlib").Path(argv[-1]).write_bytes(b"x") + return b"" + + monkeypatch.setattr(media, "inspect_video_track", track) + monkeypatch.setattr(media, "run_process", process) + result = await media.compose_workflow( + plan, + tmp_path / "work", + settings=SimpleNamespace( + workspace_root=tmp_path, ffmpeg_bin="ffmpeg", max_output_bytes=1000000 + ), + sources=sources, + ) + assert [int(c[c.index("-frames:v") + 1]) for c in calls] == [24, 120, 120, 120, 384] + assert "atrim=duration=16" in calls[-1] + assert result.result["duration_seconds"] == 16 + assert result.result["clip_count"] == 4 diff --git a/backend/tests/test_parallel_feeder.py b/backend/tests/test_parallel_feeder.py index 930d4a2..68a4ec0 100644 --- a/backend/tests/test_parallel_feeder.py +++ b/backend/tests/test_parallel_feeder.py @@ -8,199 +8,350 @@ from test_multishot_v3 import story import pytest from test_jobs import submit + async def tick(wf): - from app.workflow_engine import advance_workflows - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + from app.services.orchestration.workflow_engine import advance_workflows + + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + async def test_three_ready_shots_and_compose_waits_all(wf): - rid=(await run(wf,await draft(wf)))['run']['id'] + rid = (await run(wf, await draft(wf)))["run"]["id"] await tick(wf) async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job).where(Job.run_id==rid).order_by(Job.created_at))).all() - assert [j.step_key for j in jobs]==['shot_1','shot_2','shot_3'] - for j in jobs[:2]: await publish_video(wf,j.id) + jobs = ( + await s.scalars(select(Job).where(Job.run_id == rid).order_by(Job.created_at)) + ).all() + assert [j.step_key for j in jobs] == ["shot_1", "shot_2", "shot_3"] + for j in jobs[:2]: + await publish_video(wf, j.id) await tick(wf) async with wf.app.state.db.session() as s: - assert not await s.scalar(select(Job.id).where(Job.run_id==rid,Job.step_key=='compose')) - await publish_video(wf,jobs[2].id) + assert not await s.scalar( + select(Job.id).where(Job.run_id == rid, Job.step_key == "compose") + ) + await publish_video(wf, jobs[2].id) await tick(wf) async with wf.app.state.db.session() as s: - assert await s.scalar(select(Job.id).where(Job.run_id==rid,Job.step_key=='compose')) + assert await s.scalar(select(Job.id).where(Job.run_id == rid, Job.step_key == "compose")) -@pytest.mark.parametrize('count',[12,20]) -async def test_many_ready_shots_replenish_eight_slot_quota(wf,count): - wf.settings.max_interactive_gpu_jobs=8 - body=story(count) - d=await wf.client.post('/api/workflows',json={'spec':body});assert d.status_code==201,d.text - rid=(await run(wf,d.json()))['run']['id'] - for expected in ([8,4] if count==12 else [8,8,4]): + +@pytest.mark.parametrize("count", [12, 20]) +async def test_many_ready_shots_replenish_eight_slot_quota(wf, count): + wf.settings.max_interactive_gpu_jobs = 8 + body = story(count) + d = await wf.client.post("/api/workflows", json={"spec": body}) + assert d.status_code == 201, d.text + rid = (await run(wf, d.json()))["run"]["id"] + for expected in [8, 4] if count == 12 else [8, 8, 4]: await tick(wf) async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job).where(Job.run_id==rid,Job.state!='succeeded'))).all() - assert len(jobs)==expected - for j in jobs: await publish_video(wf,j.id) + jobs = ( + await s.scalars(select(Job).where(Job.run_id == rid, Job.state != "succeeded")) + ).all() + assert len(jobs) == expected + for j in jobs: + await publish_video(wf, j.id) + async def test_default_limit_feeds_twenty_shots_across_ticks_without_completions(wf): - d=await wf.client.post('/api/workflows',json={'spec':story(20)});assert d.status_code==201,d.text - rid=(await run(wf,d.json()))['run']['id'] - for expected in (8,16,20): + d = await wf.client.post("/api/workflows", json={"spec": story(20)}) + assert d.status_code == 201, d.text + rid = (await run(wf, d.json()))["run"]["id"] + for expected in (8, 16, 20): await tick(wf) async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job).where(Job.run_id==rid).order_by(Job.created_at,Job.id))).all() - assert len(jobs)==expected - assert [j.step_key for j in jobs]==[f'shot_{i}' for i in range(1,expected+1)] - assert all(j.state not in {'succeeded','failed','cancelled','timed_out'} for j in jobs) - snapshot=(await wf.client.get('/api/workflow-runs/'+rid)).json() - assert 'quota' not in snapshot['run']['hold_reasons'] - assert not any(j.step_key=='compose' for j in jobs) + jobs = ( + await s.scalars( + select(Job).where(Job.run_id == rid).order_by(Job.created_at, Job.id) + ) + ).all() + assert len(jobs) == expected + assert [j.step_key for j in jobs] == [f"shot_{i}" for i in range(1, expected + 1)] + assert all(j.state not in {"succeeded", "failed", "cancelled", "timed_out"} for j in jobs) + snapshot = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert "quota" not in snapshot["run"]["hold_reasons"] + assert not any(j.step_key == "compose" for j in jobs) assert not wf.provider.accepted + async def test_two_batch_members_admitted_together(wf): - response=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':p}} for p in ('a','b')]},headers={'Idempotency-Key':'pair'}) - assert response.status_code==202,response.text + response = await wf.client.post( + "/api/batches", + json={ + "items": [ + {"kind": "job", "task_type": "image.generate", "input": {"prompt": p}} + for p in ("a", "b") + ] + }, + headers={"Idempotency-Key": "pair"}, + ) + assert response.status_code == 202, response.text await tick(wf) async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job))).all() - assert len(jobs)==2 and all('batch_wait' not in j.hold_reasons for j in jobs) + jobs = (await s.scalars(select(Job))).all() + assert len(jobs) == 2 and all("batch_wait" not in j.hold_reasons for j in jobs) + async def test_ready_fifo_ignores_poll_retry_timestamps(system): - first=(await submit(system,input={'prompt':'first'}))[0]; second=(await submit(system,input={'prompt':'second'}))[0] + first = (await submit(system, input={"prompt": "first"}))[0] + second = (await submit(system, input={"prompt": "second"}))[0] async with system.app.state.db.session() as s: - a=await s.get(Job,first['id']);b=await s.get(Job,second['id']) + a = await s.get(Job, first["id"]) + b = await s.get(Job, second["id"]) # Both payloads are already ready; preparation completion is independent # and intentionally does not define this FIFO assertion. - for j in (a,b): - j.upstream_payload={'task_type':j.task_type,'input':j.input_json,'parameters':j.parameters,'timeout_seconds':3600} - a.next_action_at=utcnow()+timedelta(hours=1);b.next_action_at=utcnow()-timedelta(hours=1) + for j in (a, b): + j.upstream_payload = { + "task_type": j.task_type, + "input": j.input_json, + "parameters": j.parameters, + "timeout_seconds": 3600, + } + a.next_action_at = utcnow() + timedelta(hours=1) + b.next_action_at = utcnow() - timedelta(hours=1) await s.commit() await system.app.state.coordinator.run_once() - assert [p[1]['input']['prompt'] for p in system.provider.submitted_payloads]==['first','second'] + assert [p[1]["input"]["prompt"] for p in system.provider.submitted_payloads] == [ + "first", + "second", + ] -async def test_slow_preparation_does_not_starve_ready_or_existing(system,monkeypatch): - first=(await submit(system))[0] - c=system.app.state.coordinator + +async def test_slow_preparation_does_not_starve_ready_or_existing(system, monkeypatch): + first = (await submit(system))[0] + c = system.app.state.coordinator for _ in range(10): await c.run_once(force=True) - existing=await c._job(first['id']) - if existing.upstream_id:break - assert existing.upstream_id,'Fixture must have an accepted remote execution' - await submit(system,input={'prompt':'slow'}) - ready=(await submit(system,input={'prompt':'ready'}))[0] + existing = await c._job(first["id"]) + if existing.upstream_id: + break + assert existing.upstream_id, "Fixture must have an accepted remote execution" + await submit(system, input={"prompt": "slow"}) + ready = (await submit(system, input={"prompt": "ready"}))[0] # The contender is explicitly ready before measuring dispatch starvation. async with system.app.state.db.session() as s: - row=await s.get(Job,ready['id']) - row.upstream_payload={'task_type':row.task_type,'input':row.input_json,'parameters':row.parameters,'timeout_seconds':3600} + row = await s.get(Job, ready["id"]) + row.upstream_payload = { + "task_type": row.task_type, + "input": row.input_json, + "parameters": row.parameters, + "timeout_seconds": 3600, + } await s.commit() - original=system.provider.prepare_gpu_payload - gate=asyncio.Event();queries=[];query=system.provider.query - async def prepare(task_type,inputs,*args): - if inputs['prompt']=='slow':await gate.wait() - return await original(task_type,inputs,*args) - async def observed(remote): queries.append(remote);return await query(remote) - monkeypatch.setattr(system.provider,'prepare_gpu_payload',prepare) - monkeypatch.setattr(system.provider,'query',observed) - try: - await asyncio.wait_for(system.app.state.coordinator.run_once(force=True),1) - assert existing.upstream_id in queries - assert any(p[1]['input']['prompt']=='ready' for p in system.provider.submitted_payloads) - finally:gate.set() + original = system.provider.prepare_gpu_payload + gate = asyncio.Event() + queries = [] + query = system.provider.query -async def test_slow_collection_does_not_starve_ready_submission(system,monkeypatch): + async def prepare(task_type, inputs, *args): + if inputs["prompt"] == "slow": + await gate.wait() + return await original(task_type, inputs, *args) + + async def observed(remote): + queries.append(remote) + return await query(remote) + + monkeypatch.setattr(system.provider, "prepare_gpu_payload", prepare) + monkeypatch.setattr(system.provider, "query", observed) + try: + await asyncio.wait_for(system.app.state.coordinator.run_once(force=True), 1) + assert existing.upstream_id in queries + assert any(p[1]["input"]["prompt"] == "ready" for p in system.provider.submitted_payloads) + finally: + gate.set() + + +async def test_slow_collection_does_not_starve_ready_submission(system, monkeypatch): await submit(system) await system.app.state.coordinator.run_once(force=True) - await submit(system,input={'prompt':'ready'}) - system.provider.remote['remote-1'].update(state='succeeded',result={'outputs':[{'path':'one.png'}]}) - gate=asyncio.Event();original=system.provider.download + # 此用例测下载收集,不把后台准备是否恰在0.1秒内结束作为测试前提。 + coordinator = system.app.state.coordinator + if coordinator._preparing: + await asyncio.gather(*list(coordinator._preparing.values())) + await coordinator.run_once(force=True) + await submit(system, input={"prompt": "ready"}) + system.provider.remote["remote-1"].update( + state="succeeded", result={"outputs": [{"path": "one.png"}]} + ) + gate = asyncio.Event() + original = system.provider.download + async def download(*args): await gate.wait() return await original(*args) - monkeypatch.setattr(system.provider,'download',download) + + monkeypatch.setattr(system.provider, "download", download) try: - await asyncio.wait_for(system.app.state.coordinator.run_once(force=True),1) - assert len(system.provider.accepted)==2 - finally:gate.set() + await asyncio.wait_for(system.app.state.coordinator.run_once(force=True), 1) + assert len(system.provider.accepted) == 2 + finally: + gate.set() + async def test_cancelling_one_child_preserves_sibling_executions(wf): - rid=(await run(wf,await draft(wf)))['run']['id'] + rid = (await run(wf, await draft(wf)))["run"]["id"] await tick(wf) for _ in range(10): await wf.app.state.coordinator.run_once(force=True) - if len(wf.provider.accepted)==3:break - assert len(wf.provider.accepted)==3 + if len(wf.provider.accepted) == 3: + break + assert len(wf.provider.accepted) == 3 async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job).where(Job.run_id==rid).order_by(Job.created_at))).all() - assert len(jobs)==3 - response=await wf.client.post('/api/jobs/'+jobs[0].id+'/cancel',json={}) - assert response.status_code==200,response.text + jobs = ( + await s.scalars(select(Job).where(Job.run_id == rid).order_by(Job.created_at)) + ).all() + assert len(jobs) == 3 + response = await wf.client.post("/api/jobs/" + jobs[0].id + "/cancel", json={}) + assert response.status_code == 200, response.text await wf.app.state.coordinator.run_once(force=True) async with wf.app.state.db.session() as s: - assert (await s.get(Job,jobs[0].id)).state=='cancelled' - assert all([(await s.get(Job,j.id)).state=='queued' for j in jobs[1:]]) + assert (await s.get(Job, jobs[0].id)).state == "cancelled" + assert all([(await s.get(Job, j.id)).state == "queued" for j in jobs[1:]]) + async def test_due_submit_retry_keeps_creation_fifo(system): - await submit(system,input={'prompt':'first'}) - system.provider.lost_response=True - await system.app.state.coordinator.run_once(force=True) - await submit(system,input={'prompt':'second'}) + await submit(system, input={"prompt": "first"}) + system.provider.lost_response = True + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + # 先确认首个请求真的到达远端并丢失响应,不依赖后台准备耗时。 + if coordinator._preparing: + await asyncio.gather(*list(coordinator._preparing.values())) + if not system.provider.submitted_payloads: + await coordinator.run_once(force=True) + assert not system.provider.lost_response + second = (await submit(system, input={"prompt": "second"}))[0] async with system.app.state.db.session() as s: - first=await s.scalar(select(Job).where(Job.input_json['prompt'].as_string()=='first')) - first.next_action_at=utcnow()-timedelta(seconds=1) + first = await s.scalar(select(Job).where(Job.input_json["prompt"].as_string() == "first")) + first.next_action_at = utcnow() - timedelta(seconds=1) + ready = await s.get(Job, second["id"]) + # 本用例的比较对象是两个均已准备、可提交的任务。 + ready.upstream_payload = await system.provider.prepare_gpu_payload( + ready.task_type, ready.input_json, ready.parameters, {}, system.settings.job_work_root + ) await s.commit() - await system.app.state.coordinator.run_once() - assert [p[1]['input']['prompt'] for p in system.provider.submitted_payloads]==['first','first','second'] + await coordinator.run_once() + assert [p[1]["input"]["prompt"] for p in system.provider.submitted_payloads] == [ + "first", + "first", + "second", + ] + async def test_held_prefix_cannot_hide_ready_fifo(system): from app.models import new_id - system.settings.max_interactive_gpu_jobs=100 - first=(await submit(system,input={'prompt':'first'}))[0] - await submit(system,input={'prompt':'second'}) + + system.settings.max_interactive_gpu_jobs = 100 + first = (await submit(system, input={"prompt": "first"}))[0] + await submit(system, input={"prompt": "second"}) async with system.app.state.db.session() as s: - owner=(await s.get(Job,first['id'])).owner_id + owner = (await s.get(Job, first["id"])).owner_id for _ in range(25): - jid=new_id() - s.add(Job(id=jid,owner_id=owner,task_type='image.generate',state='submitting',phase='waiting_dispatch',input_json={'prompt':'held'},parameters={},request_hash='fixture',upstream_key=jid,hold_reasons=['manual'],created_at=utcnow()-timedelta(days=1),next_action_at=utcnow()+timedelta(hours=1))) - for j in (await s.scalars(select(Job).where(Job.owner_id==owner,Job.hold_reasons==[]))).all(): - j.upstream_payload={'task_type':j.task_type,'input':j.input_json,'parameters':j.parameters,'timeout_seconds':3600} - (await s.get(Job,first['id'])).next_action_at=utcnow()+timedelta(hours=1) + jid = new_id() + s.add( + Job( + id=jid, + owner_id=owner, + task_type="image.generate", + state="submitting", + phase="waiting_dispatch", + input_json={"prompt": "held"}, + parameters={}, + request_hash="fixture", + upstream_key=jid, + hold_reasons=["manual"], + created_at=utcnow() - timedelta(days=1), + next_action_at=utcnow() + timedelta(hours=1), + ) + ) + for j in ( + await s.scalars(select(Job).where(Job.owner_id == owner, Job.hold_reasons == [])) + ).all(): + j.upstream_payload = { + "task_type": j.task_type, + "input": j.input_json, + "parameters": j.parameters, + "timeout_seconds": 3600, + } + (await s.get(Job, first["id"])).next_action_at = utcnow() + timedelta(hours=1) await s.commit() await system.app.state.coordinator.run_once() - assert [p[1]['input']['prompt'] for p in system.provider.submitted_payloads]==['first','second'] + assert [p[1]["input"]["prompt"] for p in system.provider.submitted_payloads] == [ + "first", + "second", + ] + async def test_prepared_overflow_never_inherits_poll_order(system): from app.models import new_id - owner=(await system.client.get('/api/auth/me')).json()['user']['id'] - expected=[f'ready-{i}' for i in range(27)] - base=utcnow()-timedelta(days=1) + + owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] + expected = [f"ready-{i}" for i in range(27)] + base = utcnow() - timedelta(days=1) async with system.app.state.db.session() as s: - for i,prompt in enumerate(expected): - jid=new_id();payload={'task_type':'image.generate','input':{'prompt':prompt},'parameters':{},'timeout_seconds':3600} - s.add(Job(id=jid,owner_id=owner,task_type='image.generate',state='submitting',phase='dispatching',input_json={'prompt':prompt},parameters={},request_hash='fixture',upstream_key=jid,upstream_payload=payload,created_at=base+timedelta(microseconds=i),next_action_at=utcnow()-timedelta(seconds=i+1))) + for i, prompt in enumerate(expected): + jid = new_id() + payload = { + "task_type": "image.generate", + "input": {"prompt": prompt}, + "parameters": {}, + "timeout_seconds": 3600, + } + s.add( + Job( + id=jid, + owner_id=owner, + task_type="image.generate", + state="submitting", + phase="dispatching", + input_json={"prompt": prompt}, + parameters={}, + request_hash="fixture", + upstream_key=jid, + upstream_payload=payload, + created_at=base + timedelta(microseconds=i), + next_action_at=utcnow() - timedelta(seconds=i + 1), + ) + ) await s.commit() for _ in range(2): await system.app.state.coordinator.run_once() - submitted=[p[1]['input']['prompt'] for p in system.provider.submitted_payloads] - assert submitted==expected[:len(submitted)] - assert len(submitted)==27 + submitted = [p[1]["input"]["prompt"] for p in system.provider.submitted_payloads] + assert submitted == expected[: len(submitted)] + assert len(submitted) == 27 + + +async def test_preparing_payload_cannot_race_dispatch_and_orphan_cancel(system, monkeypatch): + job = (await submit(system))[0] + c = system.app.state.coordinator + entered = asyncio.Event() + release = asyncio.Event() + original = c._job -async def test_preparing_payload_cannot_race_dispatch_and_orphan_cancel(system,monkeypatch): - job=(await submit(system))[0];c=system.app.state.coordinator - entered=asyncio.Event();release=asyncio.Event();original=c._job async def gated(job_id): - current=await original(job_id) - if asyncio.current_task().get_name().startswith('prepare-') and current.upstream_payload is not None: - entered.set();await release.wait() + current = await original(job_id) + if ( + asyncio.current_task().get_name().startswith("prepare-") + and current.upstream_payload is not None + ): + entered.set() + await release.wait() return await original(job_id) return current - monkeypatch.setattr(c,'_job',gated) - task=asyncio.create_task(c.run_once(force=True)) + + monkeypatch.setattr(c, "_job", gated) + task = asyncio.create_task(c.run_once(force=True)) try: - await asyncio.wait_for(entered.wait(),2) - await asyncio.wait_for(task,2) - await system.client.post('/api/jobs/'+job['id']+'/cancel') + await asyncio.wait_for(entered.wait(), 2) + await asyncio.wait_for(task, 2) + await system.client.post("/api/jobs/" + job["id"] + "/cancel") release.set() await asyncio.gather(*list(c._preparing.values())) assert not system.provider.accepted - current=await original(job['id']) - assert current.state=='cancelled' and current.upstream_id is None + current = await original(job["id"]) + assert current.state == "cancelled" and current.upstream_id is None finally: - release.set();await asyncio.gather(task,return_exceptions=True) + release.set() + await asyncio.gather(task, return_exceptions=True) diff --git a/backend/tests/test_parallel_resource_status.py b/backend/tests/test_parallel_resource_status.py index 7e6f329..0039af8 100644 --- a/backend/tests/test_parallel_resource_status.py +++ b/backend/tests/test_parallel_resource_status.py @@ -4,21 +4,35 @@ from types import SimpleNamespace import pytest -from app.providers import Provider +from app.adapters.provider.client import Provider @pytest.fixture def resource_files(tmp_path): - settings = SimpleNamespace(gpu_status_path=tmp_path / 'status.json', - gpu_scheduler_path=tmp_path / 'scheduler.json') + settings = SimpleNamespace( + gpu_status_path=tmp_path / "status.json", gpu_scheduler_path=tmp_path / "scheduler.json" + ) now = time.time() - status = {'schema_version': 1, 'generated_at': now, 'error': None, - 'container_id': 'b' * 64, 'gpus': []} + status = { + "schema_version": 1, + "generated_at": now, + "error": None, + "container_id": "b" * 64, + "gpus": [], + } for index in range(4): - status['gpus'].append({'index': index, - 'uuid': f'GPU-00000000-0000-0000-0000-{index:012d}', - 'total_gib': 79.6, 'free_gib': 79.0, 'idle_since': now - 30, - 'own_pids': [], 'external_pids': [], 'baseline_pids': [2880]}) + status["gpus"].append( + { + "index": index, + "uuid": f"GPU-00000000-0000-0000-0000-{index:012d}", + "total_gib": 79.6, + "free_gib": 79.0, + "idle_since": now - 30, + "own_pids": [], + "external_pids": [], + "baseline_pids": [2880], + } + ) settings.gpu_status_path.write_text(json.dumps(status)) provider = Provider.__new__(Provider) provider.settings = settings @@ -28,77 +42,141 @@ def resource_files(tmp_path): @pytest.mark.asyncio async def test_parallel_running_and_preempting_are_reported_per_card(resource_files): provider, settings, status = resource_files - status['gpus'][0]['external_pids'] = [99991] - status['gpus'][0]['free_gib'] = 10 + status["gpus"][0]["external_pids"] = [99991] + status["gpus"][0]["free_gib"] = 10 for index in (1, 2): - status['gpus'][index]['own_pids'] = [77770 + index] - status['gpus'][index]['free_gib'] = 30 + status["gpus"][index]["own_pids"] = [77770 + index] + status["gpus"][index]["free_gib"] = 30 settings.gpu_status_path.write_text(json.dumps(status)) - settings.gpu_scheduler_path.write_text(json.dumps({ - 'schema_version': 2, 'state': 'running', 'updated_at': time.time(), - 'queued_count': 2, 'running_count': 2, - 'active_jobs': [ - {'job_id': 'PRIVATE-OWNER-JOB-A', 'gpu_index': 1, - 'gpu_uuid': status['gpus'][1]['uuid'], 'state': 'running', - 'stage': 'executing', 'attempt_count': 1, 'reason': None}, - {'job_id': 'PRIVATE-OWNER-JOB-B', 'gpu_index': 2, - 'gpu_uuid': status['gpus'][2]['uuid'], 'state': 'preempting', - 'stage': 'cleanup', 'attempt_count': 1, 'reason': 'external user'}]})) + settings.gpu_scheduler_path.write_text( + json.dumps( + { + "schema_version": 2, + "state": "running", + "updated_at": time.time(), + "queued_count": 2, + "running_count": 2, + "active_jobs": [ + { + "job_id": "PRIVATE-OWNER-JOB-A", + "gpu_index": 1, + "gpu_uuid": status["gpus"][1]["uuid"], + "state": "running", + "stage": "executing", + "attempt_count": 1, + "reason": None, + }, + { + "job_id": "PRIVATE-OWNER-JOB-B", + "gpu_index": 2, + "gpu_uuid": status["gpus"][2]["uuid"], + "state": "preempting", + "stage": "cleanup", + "attempt_count": 1, + "reason": "external user", + }, + ], + } + ) + ) result = await provider.scheduler_status() - assert result['state'] == 'running' - assert result['running_count'] == 2 - assert result['available_count'] == 1 - assert result['queued_count'] == 2 - assert [gpu['state'] for gpu in result['gpus']] == ['external', 'running', 'preempting', 'ready'] - assert 'PRIVATE-OWNER' not in json.dumps(result) - assert '99991' not in json.dumps(result) - assert '77771' not in json.dumps(result) + assert result["state"] == "running" + assert result["running_count"] == 2 + assert result["available_count"] == 1 + assert result["queued_count"] == 2 + assert [gpu["state"] for gpu in result["gpus"]] == [ + "external", + "running", + "preempting", + "ready", + ] + assert "PRIVATE-OWNER" not in json.dumps(result) + assert "99991" not in json.dumps(result) + assert "77771" not in json.dumps(result) @pytest.mark.asyncio async def test_lease_reserves_card_before_cuda_process_appears(resource_files): provider, settings, status = resource_files - settings.gpu_scheduler_path.write_text(json.dumps({ - 'schema_version': 2, 'state': 'running', 'updated_at': time.time(), - 'queued_count': 0, 'active_jobs': [ - {'gpu_index': 1, 'gpu_uuid': status['gpus'][1]['uuid'], - 'state': 'launching', 'stage': 'launching'}]})) + settings.gpu_scheduler_path.write_text( + json.dumps( + { + "schema_version": 2, + "state": "running", + "updated_at": time.time(), + "queued_count": 0, + "active_jobs": [ + { + "gpu_index": 1, + "gpu_uuid": status["gpus"][1]["uuid"], + "state": "launching", + "stage": "launching", + } + ], + } + ) + ) result = await provider.scheduler_status() - assert result['running_count'] == 1 - assert result['gpus'][1]['busy'] is True - assert result['gpus'][1]['eligible'] is False - assert result['available_count'] == 3 + assert result["running_count"] == 1 + assert result["gpus"][1]["busy"] is True + assert result["gpus"][1]["eligible"] is False + assert result["available_count"] == 3 @pytest.mark.asyncio async def test_old_scheduler_schema_and_stale_aggregate_are_compatible(resource_files): provider, settings, status = resource_files - settings.gpu_scheduler_path.write_text(json.dumps({'state': 'leased', - 'updated_at': time.time(), 'lease': {'index': 2, 'uuid': status['gpus'][2]['uuid']}})) + settings.gpu_scheduler_path.write_text( + json.dumps( + { + "state": "leased", + "updated_at": time.time(), + "lease": {"index": 2, "uuid": status["gpus"][2]["uuid"]}, + } + ) + ) result = await provider.scheduler_status() - assert result['running_count'] == 1 - assert result['gpus'][2]['state'] == 'running' - settings.gpu_scheduler_path.write_text(json.dumps({'schema_version': 2, - 'state': 'blocked', 'updated_at': time.time() - 120, 'active_jobs': [], 'queued_count': 4})) + assert result["running_count"] == 1 + assert result["gpus"][2]["state"] == "running" + settings.gpu_scheduler_path.write_text( + json.dumps( + { + "schema_version": 2, + "state": "blocked", + "updated_at": time.time() - 120, + "active_jobs": [], + "queued_count": 4, + } + ) + ) result = await provider.scheduler_status() - assert result['available'] is True - assert result['state'] == 'ready' - assert result['queued_count'] is None + assert result["available"] is True + assert result["state"] == "ready" + assert result["queued_count"] is None @pytest.mark.asyncio async def test_executor_failure_pauses_dispatch_without_hiding_other_running_card(resource_files): provider, settings, status = resource_files - settings.gpu_scheduler_path.write_text(json.dumps({ - 'schema_version': 2, 'state': 'blocked', 'updated_at': time.time(), - 'queued_count': 1, 'active_jobs': [ - {'gpu_index': 1, 'gpu_uuid': status['gpus'][1]['uuid'], 'state': 'blocked'}, - {'gpu_index': 2, 'gpu_uuid': status['gpus'][2]['uuid'], 'state': 'running'}]})) + settings.gpu_scheduler_path.write_text( + json.dumps( + { + "schema_version": 2, + "state": "blocked", + "updated_at": time.time(), + "queued_count": 1, + "active_jobs": [ + {"gpu_index": 1, "gpu_uuid": status["gpus"][1]["uuid"], "state": "blocked"}, + {"gpu_index": 2, "gpu_uuid": status["gpus"][2]["uuid"], "state": "running"}, + ], + } + ) + ) result = await provider.scheduler_status() - assert result['dispatch_blocked'] is True - assert '管理员' in result['reason'] - assert result['running_count'] == 2 - assert result['available_count'] == 0 - assert result['gpus'][1]['state'] == 'blocked' - assert result['gpus'][2]['state'] == 'running' - assert result['gpus'][0]['eligible'] is False + assert result["dispatch_blocked"] is True + assert "管理员" in result["reason"] + assert result["running_count"] == 2 + assert result["available_count"] == 0 + assert result["gpus"][1]["state"] == "blocked" + assert result["gpus"][2]["state"] == "running" + assert result["gpus"][0]["eligible"] is False diff --git a/backend/tests/test_parent_capacity.py b/backend/tests/test_parent_capacity.py index c7c1b19..f868e86 100644 --- a/backend/tests/test_parent_capacity.py +++ b/backend/tests/test_parent_capacity.py @@ -1,42 +1,92 @@ from test_timeline_v2 import spec + async def draft(system): - response=await system.client.post('/api/workflows',json={'spec':spec()}) - assert response.status_code==201 + response = await system.client.post("/api/workflows", json={"spec": spec()}) + assert response.status_code == 201 return response.json() + def workflow_item(d): - return {'kind':'workflow','draft_id':d['id'],'draft_revision':d['revision'],'expected_version':d['version']} + return { + "kind": "workflow", + "draft_id": d["id"], + "draft_revision": d["revision"], + "expected_version": d["version"], + } + async def test_queued_workflow_parents_are_bounded_before_any_child_exists(system): - system.settings.max_owner_runs=1 - first_body={'items':[workflow_item(await draft(system))]} - first=await system.client.post('/api/batches',json=first_body,headers={'Idempotency-Key':'parent-one'}) - assert first.status_code==202 - second=await system.client.post('/api/batches',json={'items':[workflow_item(await draft(system))]},headers={'Idempotency-Key':'parent-two'}) - assert second.status_code==429 and second.json()['detail']['code']=='quota_exceeded' - replay=await system.client.post('/api/batches',json=first_body,headers={'Idempotency-Key':'parent-one'}) - assert replay.status_code==202 and replay.json()['batch']['id']==first.json()['batch']['id'] + system.settings.max_owner_runs = 1 + first_body = {"items": [workflow_item(await draft(system))]} + first = await system.client.post( + "/api/batches", json=first_body, headers={"Idempotency-Key": "parent-one"} + ) + assert first.status_code == 202 + second = await system.client.post( + "/api/batches", + json={"items": [workflow_item(await draft(system))]}, + headers={"Idempotency-Key": "parent-two"}, + ) + assert second.status_code == 429 and second.json()["detail"]["code"] == "quota_exceeded" + replay = await system.client.post( + "/api/batches", json=first_body, headers={"Idempotency-Key": "parent-one"} + ) + assert replay.status_code == 202 and replay.json()["batch"]["id"] == first.json()["batch"]["id"] + async def test_open_batch_parent_limit_and_replay(system): - system.settings.max_owner_batches=1 - body={'items':[{'kind':'job','task_type':'math.solve','input':{'prompt':'2+2'}}]} - first=await system.client.post('/api/batches',json=body,headers={'Idempotency-Key':'batch-one'}) - assert first.status_code==202 - assert (await system.client.post('/api/batches',json=body,headers={'Idempotency-Key':'batch-two'})).status_code==429 - assert (await system.client.post('/api/batches',json=body,headers={'Idempotency-Key':'batch-one'})).status_code==202 + system.settings.max_owner_batches = 1 + body = {"items": [{"kind": "job", "task_type": "math.solve", "input": {"prompt": "2+2"}}]} + first = await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "batch-one"} + ) + assert first.status_code == 202 + assert ( + await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "batch-two"} + ) + ).status_code == 429 + assert ( + await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "batch-one"} + ) + ).status_code == 202 + async def test_creation_rate_is_shared_by_run_and_job_commands(system): - system.settings.max_creation_commands_per_minute=1 - d=await draft(system) - first=await system.client.post('/api/workflows/'+d['id']+'/runs',json={'draft_revision':d['revision'],'expected_version':d['version']},headers={'Idempotency-Key':'run-one'}) - assert first.status_code==202 - second=await system.client.post('/api/jobs',json={'task_type':'math.solve','input':{'prompt':'2+2'}},headers={'Idempotency-Key':'job-two'}) - assert second.status_code==429 + system.settings.max_creation_commands_per_minute = 1 + d = await draft(system) + first = await system.client.post( + "/api/workflows/" + d["id"] + "/runs", + json={"draft_revision": d["revision"], "expected_version": d["version"]}, + headers={"Idempotency-Key": "run-one"}, + ) + assert first.status_code == 202 + second = await system.client.post( + "/api/jobs", + json={"task_type": "math.solve", "input": {"prompt": "2+2"}}, + headers={"Idempotency-Key": "job-two"}, + ) + assert second.status_code == 429 + async def test_internal_batch_children_do_not_consume_creation_command_rate(system): - system.settings.max_creation_commands_per_minute=2 - body={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':str(i)}} for i in range(3)]} - assert (await system.client.post('/api/batches',json=body,headers={'Idempotency-Key':'three-leaves'})).status_code==202 - second=await system.client.post('/api/jobs',json={'task_type':'math.solve','input':{'prompt':'2+2'}},headers={'Idempotency-Key':'next-command'}) - assert second.status_code==202 + system.settings.max_creation_commands_per_minute = 2 + body = { + "items": [ + {"kind": "job", "task_type": "image.generate", "input": {"prompt": str(i)}} + for i in range(3) + ] + } + assert ( + await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "three-leaves"} + ) + ).status_code == 202 + second = await system.client.post( + "/api/jobs", + json={"task_type": "math.solve", "input": {"prompt": "2+2"}}, + headers={"Idempotency-Key": "next-command"}, + ) + assert second.status_code == 202 diff --git a/backend/tests/test_pool_waiter_fairness.py b/backend/tests/test_pool_waiter_fairness.py index 2c3bca8..17aa005 100644 --- a/backend/tests/test_pool_waiter_fairness.py +++ b/backend/tests/test_pool_waiter_fairness.py @@ -1,34 +1,54 @@ import asyncio from types import SimpleNamespace import pytest -from app.models import Job,new_id +from app.models import Job, new_id + @pytest.mark.asyncio -async def test_quarantined_qwen_backlog_cannot_consume_cpu_media_waiter_budget(system,monkeypatch): - c=system.app.state.coordinator - owner=(await system.client.get("/api/auth/me")).json()["user"]["id"] +async def test_quarantined_qwen_backlog_cannot_consume_cpu_media_waiter_budget(system, monkeypatch): + c = system.app.state.coordinator + owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] # A scheduler backlog fixture bypasses HTTP admission caps intentionally. # Fifty durable Qwen jobs previously filled the single aggregate task cap. async with system.app.state.db.session() as session: for index in range(50): - job_id=new_id() - session.add(Job(id=job_id,owner_id=owner,task_type="math.solve",state="submitting",phase="waiting_dispatch",input_json={"prompt":str(index)},parameters={},request_hash="fixture",upstream_key="fixture:"+job_id)) + job_id = new_id() + session.add( + Job( + id=job_id, + owner_id=owner, + task_type="math.solve", + state="submitting", + phase="waiting_dispatch", + input_json={"prompt": str(index)}, + parameters={}, + request_hash="fixture", + upstream_key="fixture:" + job_id, + ) + ) await session.commit() c._blocked_pools.add("qwen_http") - started=asyncio.Event();calls=[] - async def provider_boundary(task_type,inputs,parameters,assets,work): + started = asyncio.Event() + calls = [] + + async def provider_boundary(task_type, inputs, parameters, assets, work): calls.append(task_type) - assert task_type=="audio.speech","Quarantined Qwen must not execute" + assert task_type == "audio.speech", "Quarantined Qwen must not execute" started.set() - output=work/"speech-response.txt";output.write_text("completed") - return SimpleNamespace(outputs=[output],result={},metadata={}) - monkeypatch.setattr(system.provider,"run_cpu",provider_boundary) + output = work / "speech-response.txt" + output.write_text("completed") + return SimpleNamespace(outputs=[output], result={}, metadata={}) + + monkeypatch.setattr(system.provider, "run_cpu", provider_boundary) await c.run_once(force=True) - system.settings.tts_base_url="http://fake-private-tts" - response=await system.client.post("/api/jobs",json={"task_type":"audio.speech","input":{"prompt":"independent media phase"}}) - assert response.status_code==202,response.text + system.settings.tts_base_url = "http://fake-private-tts" + response = await system.client.post( + "/api/jobs", + json={"task_type": "audio.speech", "input": {"prompt": "independent media phase"}}, + ) + assert response.status_code == 202, response.text await c.run_once(force=True) - await asyncio.wait_for(started.wait(),5) - assert calls==["audio.speech"] - assert len(c._cpu)<=50 + await asyncio.wait_for(started.wait(), 5) + assert calls == ["audio.speech"] + assert len(c._cpu) <= 50 assert "qwen_http" in c._blocked_pools diff --git a/backend/tests/test_pool_waiters.py b/backend/tests/test_pool_waiters.py index a17d8ff..768cdad 100644 --- a/backend/tests/test_pool_waiters.py +++ b/backend/tests/test_pool_waiters.py @@ -4,15 +4,19 @@ import pytest from sqlalchemy import select from app.models import Job -from app.v2_models import Execution +from app.models import Execution async def submit_jobs(system, task_type, count): jobs = [] for index in range(count): - response = await system.client.post("/api/jobs", json={ - "task_type": task_type, "input": {"prompt": f"request {index}"}, - }) + response = await system.client.post( + "/api/jobs", + json={ + "task_type": task_type, + "input": {"prompt": f"request {index}"}, + }, + ) assert response.status_code == 202, response.text jobs.append(response.json()["jobs"][0]["id"]) return jobs @@ -54,8 +58,9 @@ async def test_fifty_quarantined_qwen_jobs_cannot_block_new_speech(system, monke assert len(coordinator._cpu) <= 50 async with system.app.state.db.session() as session: assert (await session.get(Job, speech_job)).state == "succeeded" - assert not (await session.scalars(select(Execution).where( - Execution.job_id.in_(qwen_jobs)))).all() + assert not ( + await session.scalars(select(Execution).where(Execution.job_id.in_(qwen_jobs))) + ).all() @pytest.mark.asyncio diff --git a/backend/tests/test_provider_remote.py b/backend/tests/test_provider_remote.py new file mode 100644 index 0000000..6a4a51b --- /dev/null +++ b/backend/tests/test_provider_remote.py @@ -0,0 +1,526 @@ +"""The Windows business API sends bytes, never its host paths, to GPU services.""" + +from __future__ import annotations + +import asyncio +from hashlib import sha256 +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import shutil +import threading +import time +from types import SimpleNamespace +import wave + +from PIL import Image +import pytest +import pytest_asyncio + +from app.core.config import Settings +from app.adapters.provider.client import Provider, ProviderError + + +@pytest_asyncio.fixture +async def remote(tmp_path): + class Boundary: + requests = [] + reply = None + status = 200 + runtime = None + + boundary = Boundary() + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def respond(self): + body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + boundary.requests.append((self.command, self.path, dict(self.headers), body)) + if self.path == "/runtime/status": + value = boundary.runtime + else: + name = self.path.removeprefix("/inputs/") + value = { + "path": "/workspace/inputs/llm-services/" + name, + "sha256": sha256(body).hexdigest(), + "size_bytes": len(body), + } + if boundary.reply is not None: + value = boundary.reply + data = json.dumps(value).encode() + self.send_response(boundary.status) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + do_POST = do_GET = respond + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + settings = Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=tmp_path, + inference_base_url=f"http://127.0.0.1:{server.server_port}", + inference_api_key="PRIVATE-KEY", + inference_api_key_file=None, + runtime_policy_file=tmp_path / "config" / "runtime-policy.json", + request_timeout_seconds=3, + ffmpeg_bin=shutil.which("ffmpeg") or "ffmpeg", + ffprobe_bin=shutil.which("ffprobe") or "ffprobe", + ) + settings.inference_remote_files = True + settings.asset_root.mkdir(parents=True) + work = settings.job_work_root / "attempt" + work.mkdir(parents=True) + image = settings.asset_root / "image.PNG" + Image.new("RGB", (32, 24), "red").save(image) + provider = Provider(settings) + boundary.settings, boundary.provider = settings, provider + boundary.work, boundary.image = work, image + now = time.time() + boundary.runtime = { + "schema_version": 1, + "monitor": { + "schema_version": 1, + "generated_at": now, + "error": None, + "gpus": [ + { + "index": index, + "uuid": f"GPU-00000000-0000-0000-0000-{index:012d}", + "total_gib": 79.6, + "free_gib": 79.0, + "idle_since": now - 30, + "external_busy": False, + "own_busy": False, + } + for index in range(2) + ], + }, + "scheduler": { + "schema_version": 2, + "updated_at": now, + "state": "running", + "queued_count": 2, + "active_jobs": [ + { + "gpu_index": 1, + "gpu_uuid": "GPU-00000000-0000-0000-0000-000000000001", + "state": "preempting", + "stage": "cleanup", + "job_id": "PRIVATE-OWNER", + } + ], + "worker_pid": 987654, + "reason": "PRIVATE-PATH", + }, + "runtime_policy": { + "batch_window_enabled": False, + "workflow_max_shots": 240, + "configuration_error": None, + }, + } + try: + yield boundary + finally: + await provider.aclose() + server.shutdown() + server.server_close() + thread.join() + + +def test_remote_files_environment_is_opt_in(tmp_path, monkeypatch): + monkeypatch.setenv("CMVR_MODE", "test") + monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:") + monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path)) + monkeypatch.delenv("INFERENCE_REMOTE_FILES", raising=False) + assert Settings.from_env().inference_remote_files is False + monkeypatch.setenv("INFERENCE_REMOTE_FILES", "true") + assert Settings.from_env().inference_remote_files is True + + +@pytest.mark.asyncio +async def test_image_upload_replaces_windows_path_with_content_addressed_remote_path(remote): + blob = remote.image.read_bytes() + digest = sha256(blob).hexdigest() + payloads = [ + await remote.provider.prepare_gpu_payload( + "video.generate", + {"prompt": "slow shot", "image_asset_id": "owned"}, + {}, + {"owned": remote.image}, + remote.work, + ) + for _ in range(2) + ] + expected = "/workspace/inputs/llm-services/" + digest + ".png" + assert [payload["input"]["image_path"] for payload in payloads] == [expected, expected] + assert str(remote.image) not in json.dumps(payloads) + method, path, headers, sent = remote.requests[0] + assert (method, path, sent) == ("POST", "/inputs/" + digest + ".png", blob) + assert headers["Authorization"] == "Bearer PRIVATE-KEY" + assert headers["Content-Type"] == "application/octet-stream" + assert headers["Content-Length"] == str(len(blob)) + + +@pytest.mark.asyncio +async def test_jfif_reference_upload_uses_jpeg_name_without_reencoding(remote, monkeypatch): + source = remote.settings.asset_root / "reference.jfif" + Image.new("RGB", (32, 24), "blue").save(source, format="JPEG") + original = source.read_bytes() + digest = sha256(original).hexdigest() + remote.settings.reference_generation_enabled = True + + async def capabilities(): + return { + "reference_generation": { + "available": True, + "profile": remote.settings.reference_generation_profile, + "max_reference_images": 3, + } + } + + monkeypatch.setattr(remote.provider, "upstream_capabilities", capabilities) + payload = await remote.provider.prepare_gpu_payload( + "image.reference.generate", + {"prompt": "retain the reference subject", "reference_asset_ids": ["owned"]}, + {}, + {"owned": source}, + remote.work, + ) + + assert payload["input"]["image_paths"] == [f"/workspace/inputs/llm-services/{digest}.jpg"] + method, path, _, sent = remote.requests[0] + assert (method, path, sent) == ("POST", f"/inputs/{digest}.jpg", original) + assert source.read_bytes() == original + assert str(source) not in json.dumps(payload) + + +@pytest.mark.asyncio +async def test_remote_upload_still_rejects_unrecognized_extension(remote): + source = remote.settings.asset_root / "unrecognized.bin" + source.write_bytes(remote.image.read_bytes()) + with pytest.raises(ProviderError) as error: + await remote.provider.prepare_gpu_payload( + "video.generate", + {"prompt": "x", "image_asset_id": "owned"}, + {}, + {"owned": source}, + remote.work, + ) + assert error.value.code == "invalid_input" + assert remote.requests == [] + + +@pytest.mark.asyncio +async def test_local_default_and_text_generation_need_no_upload(remote): + remote.settings.inference_remote_files = False + payload = await remote.provider.prepare_gpu_payload( + "defect.generate", + {"prompt": "scratch", "image_asset_id": "owned"}, + {}, + {"owned": remote.image}, + remote.work, + ) + assert payload["input"]["image_path"] == str(remote.image) + remote.settings.inference_remote_files = True + payload = await remote.provider.prepare_gpu_payload( + "image.generate", {"prompt": "a cup"}, {}, {}, remote.work + ) + assert payload["input"]["prompt"] == "a cup" + assert remote.requests == [] + + +@pytest.mark.asyncio +async def test_invalid_task_and_oversized_asset_never_upload(remote): + for parameters in ({"width": 1250}, {"num_frames": 122}): + with pytest.raises(ProviderError): + await remote.provider.prepare_gpu_payload( + "video.generate", + {"prompt": "x", "image_asset_id": "owned"}, + parameters, + {"owned": remote.image}, + remote.work, + ) + remote.settings.max_upload_bytes = 4 + with pytest.raises(ProviderError) as error: + await remote.provider.prepare_gpu_payload( + "video.generate", + {"prompt": "x", "image_asset_id": "owned"}, + {}, + {"owned": remote.image}, + remote.work, + ) + assert error.value.code == "input_too_large" + assert remote.requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "bad_path", + [ + "C:/private/source.png", + "/workspace/inputs/llm-services/../private.png", + "/workspace/private.png", + "http://example.test/private.png", + "//example.test/inputs/llm-services/name.png", + ], +) +async def test_upload_rejects_unsafe_receipt_without_disclosing_it(remote, bad_path): + blob = remote.image.read_bytes() + remote.reply = {"path": bad_path, "sha256": sha256(blob).hexdigest(), "size_bytes": len(blob)} + with pytest.raises(ProviderError) as error: + await remote.provider.prepare_gpu_payload( + "video.generate", + {"prompt": "x", "image_asset_id": "owned"}, + {}, + {"owned": remote.image}, + remote.work, + ) + assert error.value.code == "invalid_upstream_response" + assert "private" not in error.value.message + assert "PRIVATE-KEY" not in error.value.message + + +@pytest.mark.asyncio +async def test_upload_rejects_wrong_digest_and_sanitizes_http_error(remote): + blob = remote.image.read_bytes() + digest = sha256(blob).hexdigest() + remote.reply = { + "path": "/workspace/inputs/llm-services/" + digest + ".png", + "sha256": "0" * 64, + "size_bytes": len(blob), + } + with pytest.raises(ProviderError) as error: + await remote.provider.prepare_gpu_payload( + "defect.generate", + {"prompt": "x", "image_asset_id": "owned"}, + {}, + {"owned": remote.image}, + remote.work, + ) + assert error.value.code == "invalid_upstream_response" + remote.status, remote.reply = 500, {"detail": "PRIVATE-KEY /workspace/private"} + with pytest.raises(ProviderError) as error: + await remote.provider.prepare_gpu_payload( + "defect.generate", + {"prompt": "x", "image_asset_id": "owned"}, + {}, + {"owned": remote.image}, + remote.work, + ) + assert error.value.retriable + assert "PRIVATE" not in error.value.message and "/workspace" not in error.value.message + + +@pytest.mark.asyncio +@pytest.mark.skipif(not shutil.which("ffprobe"), reason="FFprobe not installed") +async def test_audio_upload_uses_prepared_real_wav(remote): + audio = remote.settings.asset_root / "voice.wav" + with wave.open(str(audio), "wb") as stream: + stream.setnchannels(1) + stream.setsampwidth(2) + stream.setframerate(16000) + stream.writeframes(b"\x00\x00" * 1600) + payload = await remote.provider.prepare_gpu_payload( + "audio.transcribe", {"audio_asset_id": "owned"}, {}, {"owned": audio}, remote.work + ) + blob = audio.read_bytes() + assert ( + payload["input"]["audio_path"] + == "/workspace/inputs/llm-services/" + sha256(blob).hexdigest() + ".wav" + ) + assert remote.requests[0][3] == blob + + +@pytest.mark.asyncio +async def test_scheduler_uses_remote_runtime_cache_and_keeps_private_fields_out(remote): + # The local files disagree and must never determine a remote provider's display. + remote.settings.gpu_status_path = remote.work / "missing-monitor.json" + result = await remote.provider.scheduler_status() + assert result["available"] is True + assert result["running_count"] == 1 + assert result["available_count"] == 1 + assert result["queued_count"] == 2 + assert [gpu["state"] for gpu in result["gpus"]] == ["ready", "preempting"] + cached = await remote.provider.runtime_status() + assert cached["runtime_policy"] == { + "batch_window_enabled": False, + "workflow_max_shots": 240, + "configuration_error": None, + } + assert len(remote.requests) == 1 + text = json.dumps([result, cached]) + assert "PRIVATE" not in text and "987654" not in text + cached["runtime_policy"]["workflow_max_shots"] = 1 + assert (await remote.provider.runtime_status())["runtime_policy"]["workflow_max_shots"] == 240 + + +@pytest.mark.asyncio +async def test_stale_remote_monitor_and_failed_refresh_report_unavailable(remote): + remote.runtime["monitor"]["generated_at"] -= 10 + assert (await remote.provider.scheduler_status())["available"] is False + remote.provider._runtime_cache = None + remote.status = 503 + assert (await remote.provider.scheduler_status())["available"] is False + + +@pytest.mark.asyncio +async def test_malformed_remote_policy_or_busy_flags_fail_closed(remote): + remote.runtime["runtime_policy"]["batch_window_enabled"] = "false" + with pytest.raises(ProviderError) as error: + await remote.provider.runtime_status() + assert error.value.code == "invalid_upstream_response" + remote.runtime["runtime_policy"]["batch_window_enabled"] = False + remote.runtime["monitor"]["gpus"][0]["external_busy"] = [] + assert (await remote.provider.scheduler_status())["available"] is False + + +@pytest.mark.asyncio +async def test_policy_mirror_is_atomic_confined_and_preserves_last_valid_policy(remote): + policy = remote.settings.workspace_root / "config" / "runtime-policy.json" + remote.settings.runtime_policy_file = policy + await remote.provider.runtime_status() + assert json.loads(policy.read_text()) == { + "schema_version": 1, + "batch_window_enabled": False, + "workflow_max_shots": 240, + } + assert list(policy.parent.glob("*.part-*")) == [] + remote.provider._runtime_cache = None + remote.runtime["runtime_policy"]["configuration_error"] = "runtime_policy_invalid" + remote.runtime["runtime_policy"]["workflow_max_shots"] = 120 + await remote.provider.runtime_status() + assert json.loads(policy.read_text())["workflow_max_shots"] == 240 + remote.provider._runtime_cache = None + remote.status = 503 + with pytest.raises(ProviderError): + await remote.provider.runtime_status() + assert json.loads(policy.read_text())["workflow_max_shots"] == 240 + remote.provider._runtime_cache = None + remote.status = 200 + remote.runtime["runtime_policy"]["configuration_error"] = None + remote.settings.runtime_policy_file = ( + remote.settings.workspace_root.parent / "foreign-policy.json" + ) + with pytest.raises(ProviderError): + await remote.provider.runtime_status() + assert not remote.settings.runtime_policy_file.exists() + + +@pytest.mark.asyncio +async def test_local_provider_does_not_mirror_remote_policy(remote): + remote.settings.inference_remote_files = False + policy = remote.settings.workspace_root / "config" / "runtime-policy.json" + remote.settings.runtime_policy_file = policy + await remote.provider.runtime_status() + assert not policy.exists() + + +@pytest.mark.asyncio +async def test_runtime_cache_does_not_retain_private_scheduler_field_values(remote): + remote.runtime["scheduler"]["state"] = "PRIVATE-WORKER-ERROR" + remote.runtime["scheduler"]["active_jobs"][0]["stage"] = "PRIVATE-WORKSPACE-PATH" + remote.runtime["scheduler"]["active_jobs"][0]["gpu_uuid"] = "PRIVATE-LEASE" + with pytest.raises(ProviderError): + await remote.provider.runtime_status() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("schema", [True, "2", 3, None]) +async def test_remote_scheduler_schema_requires_supported_integer(remote, schema): + remote.runtime["scheduler"]["schema_version"] = schema + with pytest.raises(ProviderError): + await remote.provider.runtime_status() + + +@pytest.mark.asyncio +async def test_concurrent_runtime_readers_share_one_bounded_refresh(remote): + results = await asyncio.gather(*(remote.provider.runtime_status() for _ in range(4))) + assert len(remote.requests) == 1 + assert all(result["runtime_policy"]["workflow_max_shots"] == 240 for result in results) + + +@pytest.mark.asyncio +async def test_remote_policy_observations_fail_closed_then_recover_without_losing_file(remote): + from app.core.runtime_policy import read_runtime_policy + from app.services.orchestration.resource_policy import admits + + job = SimpleNamespace( + execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[] + ) + await remote.provider.runtime_status() + assert read_runtime_policy(remote.settings)["configuration_error"] is None + assert admits(job, settings=remote.settings) + original = remote.settings.runtime_policy_file.read_bytes() + remote.provider._runtime_cache = None + remote.runtime["runtime_policy"]["configuration_error"] = "runtime_policy_invalid" + await remote.provider.runtime_status() + assert read_runtime_policy(remote.settings)["configuration_error"] == "runtime_policy_invalid" + assert not admits(job, settings=remote.settings) + job.execution_mode = "interactive" + assert admits(job, settings=remote.settings) + assert remote.settings.runtime_policy_file.read_bytes() == original + remote.provider._runtime_cache = None + remote.status = 503 + with pytest.raises(ProviderError): + await remote.provider.runtime_status() + assert ( + read_runtime_policy(remote.settings)["configuration_error"] == "runtime_policy_unavailable" + ) + assert remote.settings.runtime_policy_file.read_bytes() == original + remote.provider._runtime_cache = None + remote.status = 200 + remote.runtime["runtime_policy"]["configuration_error"] = None + await remote.provider.runtime_status() + assert read_runtime_policy(remote.settings)["configuration_error"] is None + assert read_runtime_policy(remote.settings)["workflow_max_shots"] == 240 + + +@pytest.mark.asyncio +async def test_malformed_remote_response_invalidates_batch_policy_immediately(remote): + from app.core.runtime_policy import read_runtime_policy + + await remote.provider.runtime_status() + remote.provider._runtime_cache = None + remote.runtime["runtime_policy"]["batch_window_enabled"] = "false" + with pytest.raises(ProviderError): + await remote.provider.runtime_status() + assert read_runtime_policy(remote.settings)["configuration_error"] == "runtime_policy_invalid" + + +@pytest.mark.asyncio +async def test_remote_policy_expiry_does_not_extend_on_cached_reads(remote, monkeypatch): + from app.core import runtime_policy + + await remote.provider.runtime_status() + observed = remote.settings._remote_policy_observed_at + await remote.provider.runtime_status() + assert remote.settings._remote_policy_observed_at == observed + monkeypatch.setattr(runtime_policy, "time", SimpleNamespace(monotonic=lambda: observed + 5.01)) + result = runtime_policy.read_runtime_policy(remote.settings) + assert result["configuration_error"] == "runtime_policy_unavailable" + assert result["batch_window_enabled"] is False + assert result["workflow_max_shots"] == 240 + + +def test_never_observed_remote_policy_blocks_even_a_permissive_mirror(tmp_path): + from app.core.runtime_policy import read_runtime_policy + from app.services.orchestration.resource_policy import admits + + path = tmp_path / "runtime-policy.json" + path.write_text('{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":240}') + settings = SimpleNamespace(inference_remote_files=True, runtime_policy_file=path) + assert read_runtime_policy(settings) == { + "batch_window_enabled": False, + "workflow_max_shots": 240, + "configuration_error": "runtime_policy_unavailable", + } + job = SimpleNamespace( + execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[] + ) + assert not admits(job, settings=settings) diff --git a/backend/tests/test_providers.py b/backend/tests/test_providers.py index f429e9a..dde8d24 100644 --- a/backend/tests/test_providers.py +++ b/backend/tests/test_providers.py @@ -18,7 +18,7 @@ import wave from PIL import Image -UPSTREAM_ID = 'a' * 32 +UPSTREAM_ID = "a" * 32 class ProviderTests(unittest.IsolatedAsyncioTestCase): @@ -26,14 +26,14 @@ class ProviderTests(unittest.IsolatedAsyncioTestCase): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name).resolve() - (self.root / 'assets').mkdir() - (self.root / 'jobs').mkdir() - self.work = self.root / 'jobs' / 'attempt' + (self.root / "assets").mkdir() + (self.root / "jobs").mkdir() + self.work = self.root / "jobs" / "attempt" self.work.mkdir() self.requests = [] - self.reply = {'id': UPSTREAM_ID, 'state': 'queued'} + self.reply = {"id": UPSTREAM_ID, "state": "queued"} self.status = 200 - self.binary = b'actual-file' + self.binary = b"actual-file" owner = self class Handler(BaseHTTPRequestHandler): @@ -41,234 +41,525 @@ class ProviderTests(unittest.IsolatedAsyncioTestCase): pass def respond(self): - data = self.rfile.read(int(self.headers.get('Content-Length', '0'))) - owner.requests.append((self.command, self.path, dict(self.headers), json.loads(data) if data else None)) - blob = owner.binary if '/outputs/' in self.path or self.path.endswith('/audio/speech') else json.dumps(owner.reply).encode() + data = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + owner.requests.append( + ( + self.command, + self.path, + dict(self.headers), + json.loads(data) if data else None, + ) + ) + blob = ( + owner.binary + if "/outputs/" in self.path or self.path.endswith("/audio/speech") + else json.dumps(owner.reply).encode() + ) self.send_response(owner.status) - self.send_header('Content-Type', 'application/json') - self.send_header('Content-Length', str(len(blob))) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(blob))) self.end_headers() self.wfile.write(blob) do_GET = do_POST = respond - self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() self.addCleanup(self.server.server_close) self.addCleanup(self.server.shutdown) - url = f'http://127.0.0.1:{self.server.server_port}' - self.settings = SimpleNamespace(inference_base_url=url, inference_api_key='PRIVATE-KEY', - inference_api_key_file=None, workspace_root=self.root, asset_root=self.root / 'assets', - job_work_root=self.root / 'jobs', gpu_status_path=self.root / 'status.json', - gpu_scheduler_path=self.root / 'scheduler.json', qwen_base_url=url + '/v1', - qwen_model='existing-model', qwen_api_key='QWEN-PRIVATE', ffmpeg_bin=shutil.which('ffmpeg') or 'ffmpeg', - ffprobe_bin=shutil.which('ffprobe') or 'ffprobe', tts_base_url='', tts_model='', tts_api_key='', - request_timeout_seconds=3, max_output_bytes=1024 * 1024) - self.module = importlib.import_module('app.providers') + url = f"http://127.0.0.1:{self.server.server_port}" + self.settings = SimpleNamespace( + inference_base_url=url, + inference_api_key="PRIVATE-KEY", + inference_api_key_file=None, + workspace_root=self.root, + asset_root=self.root / "assets", + job_work_root=self.root / "jobs", + gpu_status_path=self.root / "status.json", + gpu_scheduler_path=self.root / "scheduler.json", + qwen_base_url=url + "/v1", + qwen_model="existing-model", + qwen_api_key="QWEN-PRIVATE", + ffmpeg_bin=shutil.which("ffmpeg") or "ffmpeg", + ffprobe_bin=shutil.which("ffprobe") or "ffprobe", + tts_base_url="", + tts_model="", + tts_api_key="", + request_timeout_seconds=3, + max_output_bytes=1024 * 1024, + ) + self.module = importlib.import_module("app.adapters.provider.client") self.provider = self.module.Provider(self.settings) self.addAsyncCleanup(self.provider.aclose) - self.image = self.root / 'assets' / 'source.png' - Image.new('RGB', (320, 240), 'red').save(self.image) + self.image = self.root / "assets" / "source.png" + Image.new("RGB", (320, 240), "red").save(self.image) async def test_video_payload_has_real_frame_limit_and_owned_image_path(self): - payload = await self.provider.prepare_gpu_payload('video.generate', - {'prompt': '镜头缓慢移动', 'image_asset_id': 'owned'}, {}, {'owned': self.image}, self.work) - self.assertEqual(payload['input']['image_path'], str(self.image)) - self.assertEqual((payload['parameters']['num_frames'], payload['parameters']['fps']), (121, 24)) - self.assertEqual(payload['parameters']['num_inference_steps'], 50) - for parameters in ({'num_frames': 365}, {'num_frames': 120}, {'fps': 8}, - {'width': 1280, 'height': 736}, {'unknown': True}): + payload = await self.provider.prepare_gpu_payload( + "video.generate", + {"prompt": "镜头缓慢移动", "image_asset_id": "owned"}, + {}, + {"owned": self.image}, + self.work, + ) + self.assertEqual(payload["input"]["image_path"], str(self.image)) + self.assertEqual( + (payload["parameters"]["num_frames"], payload["parameters"]["fps"]), (121, 24) + ) + self.assertEqual(payload["parameters"]["num_inference_steps"], 50) + for parameters in ( + {"num_frames": 365}, + {"num_frames": 120}, + {"fps": 8}, + {"width": 1280, "height": 736}, + {"unknown": True}, + ): with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError): - await self.provider.prepare_gpu_payload('video.generate', {'prompt': 'x'}, parameters, {}, self.work) + await self.provider.prepare_gpu_payload( + "video.generate", {"prompt": "x"}, parameters, {}, self.work + ) async def test_submission_validation_rejects_unknown_fields_before_creating_job(self): validate = self.module.validate_arguments - validate('video.generate', {'prompt': 'x'}, {'num_frames': 121}, self.settings) + validate("video.generate", {"prompt": "x"}, {"num_frames": 121}, self.settings) for task, inputs, parameters in ( - ('image.generate', {'prompt': 'x'}, {'steps': 10}), - ('math.solve', {'prompt': 'x'}, {'shell': 'evil'}), - ('media.structure', {'asset_id': 'x'}, {'frame_count': 13}), - ('audio.speech', {'prompt': 'x'}, {'voice': '/tmp/foreign.npy'}), - ('video.compose', {}, {'clips': [{'asset_id': 'x'}], 'filter': 'unsafe'}), - ('video.generate', {'prompt': 'x'}, {'num_frames': 365}), + ("image.generate", {"prompt": "x"}, {"steps": 10}), + ("math.solve", {"prompt": "x"}, {"shell": "evil"}), + ("media.structure", {"asset_id": "x"}, {"frame_count": 13}), + ("audio.speech", {"prompt": "x"}, {"voice": "/tmp/foreign.npy"}), + ("video.compose", {}, {"clips": [{"asset_id": "x"}], "filter": "unsafe"}), + ("video.generate", {"prompt": "x"}, {"num_frames": 365}), ): with self.subTest(task=task), self.assertRaises(self.module.ProviderError): validate(task, inputs, parameters, self.settings) async def test_unknown_inputs_and_foreign_paths_are_rejected(self): - for inputs, assets in (({'prompt': 'x', 'image_path': '/etc/passwd'}, {}), - ({'prompt': 'x', 'image_asset_id': 'x'}, {'x': self.root.parent / 'secret.png'})): + for inputs, assets in ( + ({"prompt": "x", "image_path": "/etc/passwd"}, {}), + ({"prompt": "x", "image_asset_id": "x"}, {"x": self.root.parent / "secret.png"}), + ): with self.assertRaises(self.module.ProviderError) as caught: - await self.provider.prepare_gpu_payload('video.generate', inputs, {}, assets, self.work) - self.assertNotIn('passwd', caught.exception.message) - self.assertNotIn('secret.png', caught.exception.message) + await self.provider.prepare_gpu_payload( + "video.generate", inputs, {}, assets, self.work + ) + self.assertNotIn("passwd", caught.exception.message) + self.assertNotIn("secret.png", caught.exception.message) with self.assertRaises(self.module.ProviderError): - await self.provider.prepare_gpu_payload('defect.generate', {'prompt': 'scratch'}, {}, {}, self.work) + await self.provider.prepare_gpu_payload( + "defect.generate", {"prompt": "scratch"}, {}, {}, self.work + ) async def test_image_and_defect_constraints_match_actual_runner(self): - payload = await self.provider.prepare_gpu_payload('defect.generate', - {'prompt': 'scratch', 'image_asset_id': 'x'}, {}, {'x': self.image}, self.work) - self.assertEqual(payload['parameters']['controlnet_conditioning_scale'], .8) - for parameters in ({'canny_low': 200, 'canny_high': 100}, {'guidance_scale': float('nan')}, - {'width': True}, {'num_inference_steps': 101}, {'mask_asset_id': 'x'}): + payload = await self.provider.prepare_gpu_payload( + "defect.generate", + {"prompt": "scratch", "image_asset_id": "x"}, + {}, + {"x": self.image}, + self.work, + ) + self.assertEqual(payload["parameters"]["controlnet_conditioning_scale"], 0.8) + for parameters in ( + {"canny_low": 200, "canny_high": 100}, + {"guidance_scale": float("nan")}, + {"width": True}, + {"num_inference_steps": 101}, + {"mask_asset_id": "x"}, + ): with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError): - await self.provider.prepare_gpu_payload('defect.generate', - {'prompt': 'scratch', 'image_asset_id': 'x'}, parameters, {'x': self.image}, self.work) + await self.provider.prepare_gpu_payload( + "defect.generate", + {"prompt": "scratch", "image_asset_id": "x"}, + parameters, + {"x": self.image}, + self.work, + ) async def test_submit_preserves_immutable_key_and_error_never_leaks_secret(self): - payload = {'task_type': 'image.generate', 'input': {'prompt': 'x'}, 'parameters': {}, 'timeout_seconds': 3600} + payload = { + "task_type": "image.generate", + "input": {"prompt": "x"}, + "parameters": {}, + "timeout_seconds": 3600, + } for _ in range(2): - await self.provider.submit(payload, 'same-key') - self.assertEqual([request[2]['Idempotency-Key'] for request in self.requests], ['same-key', 'same-key']) + await self.provider.submit(payload, "same-key") + self.assertEqual( + [request[2]["Idempotency-Key"] for request in self.requests], ["same-key", "same-key"] + ) self.assertEqual(self.requests[0][3], self.requests[1][3]) - self.status, self.reply = 500, {'detail': 'PRIVATE-KEY /workspace/private'} + self.status, self.reply = 500, {"detail": "PRIVATE-KEY /workspace/private"} with self.assertRaises(self.module.ProviderError) as caught: await self.provider.query(UPSTREAM_ID) self.assertTrue(caught.exception.retriable) - self.assertNotIn('PRIVATE', caught.exception.message) - self.assertNotIn('/workspace', caught.exception.message) + self.assertNotIn("PRIVATE", caught.exception.message) + self.assertNotIn("/workspace", caught.exception.message) + + async def test_replacing_http_client_affects_gpu_qwen_and_file_transfers(self): + import httpx + + await self.provider.client.aclose() + for marker in ("first", "replacement"): + calls = [] + + async def respond(request): + calls.append((request.url.path, request.headers.get("Authorization"))) + if request.url.path.endswith("/chat/completions"): + return httpx.Response(200, json={"choices": [{"message": {"content": marker}}]}) + if "/outputs/" in request.url.path: + return httpx.Response(200, content=marker.encode()) + return httpx.Response(200, json={"id": UPSTREAM_ID, "state": "queued"}) + + self.provider.client = httpx.AsyncClient(transport=httpx.MockTransport(respond)) + try: + await self.provider.query(UPSTREAM_ID) + answer = await self.provider.run_cpu( + "math.solve", {"prompt": "2+2"}, {}, {}, self.work + ) + target = self.work / "download.bin" + await self.provider.download(UPSTREAM_ID, 0, target) + self.assertEqual(answer.result["text"], marker) + self.assertEqual(target.read_bytes(), marker.encode()) + self.assertEqual( + [key for _, key in calls], + ["Bearer PRIVATE-KEY", "Bearer QWEN-PRIVATE", "Bearer PRIVATE-KEY"], + ) + finally: + await self.provider.client.aclose() async def test_replayed_submit_and_cancel_errors_are_sanitized(self): - self.reply = {'id': UPSTREAM_ID, 'state': 'failed', 'error': 'PRIVATE-KEY /workspace/private', - 'last_preempted_reason': 'PRIVATE /run/private'} - payload = {'task_type': 'image.generate', 'input': {'prompt': 'x'}, 'parameters': {}, 'timeout_seconds': 3600} - for value in (await self.provider.submit(payload, 'fixed'), await self.provider.cancel(UPSTREAM_ID)): - self.assertNotIn('PRIVATE', json.dumps(value)) - self.assertNotIn('/workspace', json.dumps(value)) + self.reply = { + "id": UPSTREAM_ID, + "state": "failed", + "error": "PRIVATE-KEY /workspace/private", + "last_preempted_reason": "PRIVATE /run/private", + } + payload = { + "task_type": "image.generate", + "input": {"prompt": "x"}, + "parameters": {}, + "timeout_seconds": 3600, + } + for value in ( + await self.provider.submit(payload, "fixed"), + await self.provider.cancel(UPSTREAM_ID), + ): + self.assertNotIn("PRIVATE", json.dumps(value)) + self.assertNotIn("/workspace", json.dumps(value)) async def test_download_is_real_atomic_and_bounded(self): - target = self.work / 'result.png' + target = self.work / "result.png" await self.provider.download(UPSTREAM_ID, 0, target) - self.assertEqual(target.read_bytes(), b'actual-file') + self.assertEqual(target.read_bytes(), b"actual-file") self.settings.max_output_bytes = 4 with self.assertRaises(self.module.ProviderError): - await self.provider.download(UPSTREAM_ID, 1, self.work / 'too-large.png') - self.assertFalse((self.work / 'too-large.png').exists()) - self.assertFalse(list(self.work.glob('*.part-*'))) + await self.provider.download(UPSTREAM_ID, 1, self.work / "too-large.png") + self.assertFalse((self.work / "too-large.png").exists()) + self.assertFalse(list(self.work.glob("*.part-*"))) async def test_private_key_file_is_bounded_and_not_symlink_followed(self): - key = self.root / 'private-key' - key.write_text('FILE-SECRET', encoding='utf-8') - if os.name != 'nt': + key = self.root / "private-key" + key.write_text("FILE-SECRET", encoding="utf-8") + if os.name != "nt": key.chmod(0o600) - self.settings.inference_api_key_file, self.settings.inference_api_key = key, '' + self.settings.inference_api_key_file, self.settings.inference_api_key = key, "" await self.provider.query(UPSTREAM_ID) - self.assertEqual(self.requests[-1][2]['Authorization'], 'Bearer FILE-SECRET') - key.write_text('x' * 5000) + self.assertEqual(self.requests[-1][2]["Authorization"], "Bearer FILE-SECRET") + key.write_text("x" * 5000) with self.assertRaises(self.module.ProviderError): await self.provider.query(UPSTREAM_ID) async def test_math_and_visual_structure_return_real_text_json_files(self): - self.reply = {'choices': [{'message': {'content': '答案为 4。'}, 'finish_reason': 'stop'}]} - result = await self.provider.run_cpu('math.solve', {'prompt': '2+2'}, {}, {}, self.work) - self.assertEqual(result.result, {'text': '答案为 4。'}) + self.reply = {"choices": [{"message": {"content": "答案为 4。"}, "finish_reason": "stop"}]} + result = await self.provider.run_cpu("math.solve", {"prompt": "2+2"}, {}, {}, self.work) + self.assertEqual(result.result, {"text": "答案为 4。"}) self.assertTrue(all(path.is_file() for path in result.outputs)) - self.assertNotIn('reasoning_content', result.result) - self.reply = {'choices': [{'message': {'content': '{"subjects":["红色画面"],"scene":"室内","ocr":[],"tags":["红色"]}'}}]} - result = await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work) - self.assertEqual(result.result['subjects'], ['红色画面']) - content = self.requests[-1][3]['messages'][-1]['content'] - self.assertTrue(content[0]['image_url']['url'].startswith('data:image/jpeg;base64,')) - self.assertEqual(result.result['frames'][0]['timestamp_seconds'], 0) + self.assertNotIn("reasoning_content", result.result) + self.reply = { + "choices": [ + { + "message": { + "content": '{"subjects":["红色画面"],"scene":"室内","ocr":[],"tags":["红色"]}' + } + } + ] + } + result = await self.provider.run_cpu( + "media.structure", {"asset_id": "x"}, {}, {"x": self.image}, self.work + ) + self.assertEqual(result.result["subjects"], ["红色画面"]) + content = self.requests[-1][3]["messages"][-1]["content"] + self.assertTrue(content[0]["image_url"]["url"].startswith("data:image/jpeg;base64,")) + self.assertEqual(result.result["frames"][0]["timestamp_seconds"], 0) self.assertTrue(all(path.is_file() for path in result.outputs)) async def test_math_length_finish_is_failure_and_creates_no_answer_artifacts(self): - self.reply = {'choices': [{'message': {'content': '计算尚未完成:17*3='}, 'finish_reason': 'length'}]} + self.reply = { + "choices": [{"message": {"content": "计算尚未完成:17*3="}, "finish_reason": "length"}] + } with self.assertRaises(self.module.ProviderError) as caught: - await self.provider.run_cpu('math.solve', {'prompt': '17*3?'}, {'max_tokens': 128}, {}, self.work) - self.assertEqual(caught.exception.code, 'output_truncated') - self.assertIn('提高输出长度', caught.exception.message) - self.assertFalse((self.work / 'answer.txt').exists()) - self.assertFalse((self.work / 'answer.json').exists()) + await self.provider.run_cpu( + "math.solve", {"prompt": "17*3?"}, {"max_tokens": 128}, {}, self.work + ) + self.assertEqual(caught.exception.code, "output_truncated") + self.assertIn("提高输出长度", caught.exception.message) + self.assertFalse((self.work / "answer.txt").exists()) + self.assertFalse((self.work / "answer.json").exists()) async def test_visual_length_finish_is_failure_even_when_partial_output_parses_as_json(self): - self.reply = {'choices': [{'message': {'content': '{"subjects":[],"scene":"部分内容","ocr":[],"tags":[]}'}, - 'finish_reason': 'length'}]} + self.reply = { + "choices": [ + { + "message": {"content": '{"subjects":[],"scene":"部分内容","ocr":[],"tags":[]}'}, + "finish_reason": "length", + } + ] + } with self.assertRaises(self.module.ProviderError) as caught: - await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work) - self.assertEqual(caught.exception.code, 'output_truncated') - self.assertFalse((self.work / 'structure.json').exists()) + await self.provider.run_cpu( + "media.structure", {"asset_id": "x"}, {}, {"x": self.image}, self.work + ) + self.assertEqual(caught.exception.code, "output_truncated") + self.assertFalse((self.work / "structure.json").exists()) async def test_visual_non_json_and_unconfigured_speech_are_explicit_failures(self): - self.reply = {'choices': [{'message': {'content': 'not json'}}]} + self.reply = {"choices": [{"message": {"content": "not json"}}]} with self.assertRaises(self.module.ProviderError): - await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work) + await self.provider.run_cpu( + "media.structure", {"asset_id": "x"}, {}, {"x": self.image}, self.work + ) with self.assertRaises(self.module.ProviderError) as caught: - await self.provider.run_cpu('audio.speech', {'prompt': 'hello'}, {'voice': 'zf_xiaobei'}, {}, self.work) - self.assertEqual(caught.exception.code, 'capability_unavailable') + await self.provider.run_cpu( + "audio.speech", {"prompt": "hello"}, {"voice": "zf_xiaobei"}, {}, self.work + ) + self.assertEqual(caught.exception.code, "capability_unavailable") async def test_composition_rejects_url_filter_and_invalid_subtitles_before_ffmpeg(self): - for parameters in ({'clips': [{'asset_id': 'x', 'url': 'http://evil'}]}, - {'clips': [{'asset_id': 'x'}], 'filter': 'movie=/etc/passwd'}, - {'clips': [{'asset_id': 'x', 'start_seconds': 2, 'end_seconds': 1}]}, - {'clips': [{'asset_id': 'x'}], 'subtitles': [{'start': 0, 'end': 1, 'text': '{\\p1}'}]}): + for parameters in ( + {"clips": [{"asset_id": "x", "url": "http://evil"}]}, + {"clips": [{"asset_id": "x"}], "filter": "movie=/etc/passwd"}, + {"clips": [{"asset_id": "x", "start_seconds": 2, "end_seconds": 1}]}, + {"clips": [{"asset_id": "x"}], "subtitles": [{"start": 0, "end": 1, "text": "{\\p1}"}]}, + ): with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError): - await self.provider.run_cpu('video.compose', {}, parameters, {'x': self.image}, self.work) + await self.provider.run_cpu( + "video.compose", {}, parameters, {"x": self.image}, self.work + ) async def test_capabilities_and_scheduler_do_not_overstate_or_disclose_pids(self): - items = {item['task_type']: item for item in self.module.capabilities(self.settings)} - self.assertFalse(items['audio.speech']['available']) - self.assertEqual(items['video.generate']['constraints']['num_frames'], {'min': 5, 'max': 361, 'step': 4}) - status = {'schema_version': 1, 'generated_at': time.time(), 'error': None, 'container_id': 'b' * 64, - 'gpus': [{'index': 2, 'uuid': 'GPU-00000000-0000-0000-0000-000000000002', - 'total_gib': 79.6, 'free_gib': 79.5, 'idle_since': time.time() - 20, - 'own_pids': [], 'external_pids': [], 'baseline_pids': [2880]}]} + items = {item["task_type"]: item for item in self.module.capabilities(self.settings)} + self.assertFalse(items["audio.speech"]["available"]) + self.assertEqual( + items["video.generate"]["constraints"]["num_frames"], {"min": 5, "max": 361, "step": 4} + ) + status = { + "schema_version": 1, + "generated_at": time.time(), + "error": None, + "container_id": "b" * 64, + "gpus": [ + { + "index": 2, + "uuid": "GPU-00000000-0000-0000-0000-000000000002", + "total_gib": 79.6, + "free_gib": 79.5, + "idle_since": time.time() - 20, + "own_pids": [], + "external_pids": [], + "baseline_pids": [2880], + } + ], + } self.settings.gpu_status_path.write_text(json.dumps(status)) scheduler = await self.provider.scheduler_status() - self.assertTrue(scheduler['available']) - self.assertTrue(scheduler['gpus'][0]['eligible']) - self.assertNotIn('2880', json.dumps(scheduler)) - status['generated_at'] -= 10 + self.assertTrue(scheduler["available"]) + self.assertTrue(scheduler["gpus"][0]["eligible"]) + self.assertNotIn("2880", json.dumps(scheduler)) + status["generated_at"] -= 10 self.settings.gpu_status_path.write_text(json.dumps(status)) - self.assertFalse((await self.provider.scheduler_status())['available']) + self.assertFalse((await self.provider.scheduler_status())["available"]) - @unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg not installed') + @unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "FFmpeg not installed") async def test_real_compose_preserves_order_trims_and_video_asr_prepares_wav(self): - from app.media import run_process, inspect_media - video = self.root / 'assets' / 'tiny.mp4' - await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i', - 'color=c=blue:s=320x256:r=24:d=1', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1', - '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', str(video)], timeout=30) - red = self.root / 'assets' / 'red.mp4' - await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i', - 'color=c=red:s=320x256:r=24:d=1', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(red)], timeout=30) - result = await self.provider.run_cpu('video.compose', {}, {'clips': [ - {'asset_id': 'v', 'start_seconds': 0, 'end_seconds': .25}, - {'asset_id': 'r', 'start_seconds': .5, 'end_seconds': .75}], 'width': 320, 'height': 256, - 'subtitles': [{'start': 0, 'end': .4, 'text': 'Safe & credits'}]}, {'v': video, 'r': red}, self.work) + from app.adapters.media import run_process, inspect_media + + video = self.root / "assets" / "tiny.mp4" + await run_process( + [ + self.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=320x256:r=24:d=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-shortest", + str(video), + ], + timeout=30, + ) + red = self.root / "assets" / "red.mp4" + await run_process( + [ + self.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=red:s=320x256:r=24:d=1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + str(red), + ], + timeout=30, + ) + result = await self.provider.run_cpu( + "video.compose", + {}, + { + "clips": [ + {"asset_id": "v", "start_seconds": 0, "end_seconds": 0.25}, + {"asset_id": "r", "start_seconds": 0.5, "end_seconds": 0.75}, + ], + "width": 320, + "height": 256, + "subtitles": [{"start": 0, "end": 0.4, "text": "Safe <title> & credits"}], + }, + {"v": video, "r": red}, + self.work, + ) info = await inspect_media(result.outputs[0], self.settings) - self.assertEqual((info['width'], info['height']), (320, 256)) - self.assertAlmostEqual(info['duration_seconds'], .5, delta=.15) - for timestamp, dominant in ((.1, 2), (.4, 0)): - frame = await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-ss', str(timestamp), - '-i', str(result.outputs[0]), '-frames:v', '1', '-f', 'image2pipe', '-c:v', 'png', 'pipe:1'], timeout=30) + self.assertEqual((info["width"], info["height"]), (320, 256)) + self.assertAlmostEqual(info["duration_seconds"], 0.5, delta=0.15) + for timestamp, dominant in ((0.1, 2), (0.4, 0)): + frame = await run_process( + [ + self.settings.ffmpeg_bin, + "-v", + "error", + "-ss", + str(timestamp), + "-i", + str(result.outputs[0]), + "-frames:v", + "1", + "-f", + "image2pipe", + "-c:v", + "png", + "pipe:1", + ], + timeout=30, + ) with Image.open(BytesIO(frame)) as image: - color = image.convert('RGB').getpixel((10, 10)) + color = image.convert("RGB").getpixel((10, 10)) self.assertGreater(color[dominant], 150) self.assertLess(color[2 if dominant == 0 else 0], 50) - payload = await self.provider.prepare_gpu_payload('audio.transcribe', {'audio_asset_id': 'v'}, {}, {'v': video}, self.work) - self.assertEqual(Path(payload['input']['audio_path']).suffix, '.wav') - self.assertEqual((await inspect_media(Path(payload['input']['audio_path']), self.settings))['kind'], 'audio') - self.reply = {'choices': [{'message': {'content': '{"subjects":[],"scene":"blue","ocr":[],"tags":[]}'}}]} - structure = await self.provider.run_cpu('media.structure', {'asset_id': 'v'}, {'frame_count': 2}, {'v': video}, self.work) - self.assertEqual(len(structure.result['frames']), 2) - self.assertAlmostEqual(structure.result['frames'][0]['timestamp_seconds'], .25, delta=.05) - self.assertAlmostEqual(structure.result['frames'][1]['timestamp_seconds'], .75, delta=.05) + payload = await self.provider.prepare_gpu_payload( + "audio.transcribe", {"audio_asset_id": "v"}, {}, {"v": video}, self.work + ) + self.assertEqual(Path(payload["input"]["audio_path"]).suffix, ".wav") + self.assertEqual( + (await inspect_media(Path(payload["input"]["audio_path"]), self.settings))["kind"], + "audio", + ) + self.reply = { + "choices": [ + {"message": {"content": '{"subjects":[],"scene":"blue","ocr":[],"tags":[]}'}} + ] + } + structure = await self.provider.run_cpu( + "media.structure", {"asset_id": "v"}, {"frame_count": 2}, {"v": video}, self.work + ) + self.assertEqual(len(structure.result["frames"]), 2) + self.assertAlmostEqual(structure.result["frames"][0]["timestamp_seconds"], 0.25, delta=0.05) + self.assertAlmostEqual(structure.result["frames"][1]["timestamp_seconds"], 0.75, delta=0.05) self.assertTrue(all(path.is_file() for path in structure.outputs)) - @unittest.skipUnless(shutil.which('ffprobe'), 'FFprobe not installed') + @unittest.skipUnless(shutil.which("ffprobe"), "FFprobe not installed") async def test_configured_speech_posts_only_allowed_voice_and_real_wav_output(self): stream = BytesIO() - with wave.open(stream, 'wb') as audio: + with wave.open(stream, "wb") as audio: audio.setnchannels(1) audio.setsampwidth(2) audio.setframerate(16000) - audio.writeframes(b'\x00\x00' * 1600) + audio.writeframes(b"\x00\x00" * 1600) self.binary = stream.getvalue() - self.settings.tts_base_url = self.settings.inference_base_url + '/v1' - self.settings.tts_model = 'kokoro-82m' - result = await self.provider.run_cpu('audio.speech', {'prompt': '你好'}, {'voice': 'zf_xiaobei', 'speed': 1.2}, {}, self.work) + self.settings.tts_base_url = self.settings.inference_base_url + "/v1" + self.settings.tts_model = "kokoro-82m" + result = await self.provider.run_cpu( + "audio.speech", {"prompt": "你好"}, {"voice": "zf_xiaobei", "speed": 1.2}, {}, self.work + ) self.assertEqual(result.outputs[0].read_bytes(), self.binary) - self.assertEqual(self.requests[-1][3], {'model': 'kokoro-82m', 'input': '你好', 'voice': 'zf_xiaobei', - 'speed': 1.2, 'response_format': 'wav'}) + self.assertEqual( + self.requests[-1][3], + { + "model": "kokoro-82m", + "input": "你好", + "voice": "zf_xiaobei", + "speed": 1.2, + "response_format": "wav", + }, + ) + + +class ExecutionContextTests(unittest.IsolatedAsyncioTestCase): + async def test_phase_context_is_task_scoped_and_shared_with_facade(self): + from app.adapters.provider import client + from app.domain.execution import current_phase_callback, enter_phase + from app.domain.errors import MediaError + from app.adapters import media + + self.assertIs(client.current_phase_callback, current_phase_callback) + self.assertIs(client.enter_phase, enter_phase) + self.assertIs(client.ProviderError, MediaError) + self.assertIs(media.MediaError, MediaError) + self.assertIs(media.CpuResult, client.CpuResult) + observed = [] + + async def run(label): + async def callback(phase, pool): + observed.append((label, phase, pool)) + + token = current_phase_callback.set(callback) + try: + await asyncio.sleep(0) + await client.enter_phase(label, "cpu_media") + finally: + current_phase_callback.reset(token) + + await asyncio.gather(run("one"), run("two")) + self.assertEqual( + sorted(observed), [("one", "one", "cpu_media"), ("two", "two", "cpu_media")] + ) + self.assertIsNone(current_phase_callback.get()) + + def test_execution_domain_can_import_without_http_database_or_adapters(self): + import subprocess + import sys + + script = """import sys +from app.domain.execution import CpuResult, enter_phase +from app.domain.errors import MediaError +assert not any(name == 'httpx' or name.startswith(('sqlalchemy', 'app.adapters')) for name in sys.modules) +""" + result = subprocess.run( + [sys.executable, "-B", "-c", script], + cwd=Path(__file__).resolve().parents[1], + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) diff --git a/backend/tests/test_public_preflight.py b/backend/tests/test_public_preflight.py index 5e746de..df12890 100644 --- a/backend/tests/test_public_preflight.py +++ b/backend/tests/test_public_preflight.py @@ -6,14 +6,16 @@ from conftest import PASSWORD async def test_public_preflight_refuses_insecure_cookie_and_legacy_default(system): - from app.public_preflight import require_public_ready + from app.core.public_preflight import require_public_ready + settings = system.settings settings.public_access = True with pytest.raises(ValueError, match="COOKIE_SECURE"): await require_public_ready(system.app.state.db, settings) settings.cookie_secure = True async with system.app.state.db.session() as session: - from app.auth import hash_password + from app.core.security import hash_password + user = await session.scalar(select(User).where(User.username == "admin")) user.must_change_password = False # Legacy users predate this flag. user.password_hash = hash_password("123456") @@ -24,7 +26,8 @@ async def test_public_preflight_refuses_insecure_cookie_and_legacy_default(syste async def test_public_preflight_allows_changed_admin_and_private_initial_login(system): - from app.public_preflight import require_public_ready + from app.core.public_preflight import require_public_ready + await require_public_ready(system.app.state.db, system.settings) system.settings.public_access = True system.settings.cookie_secure = True @@ -37,10 +40,11 @@ async def test_public_preflight_allows_changed_admin_and_private_initial_login(s async def test_public_mode_refuses_mysql_root_but_private_mode_remains_usable(system): - from app.public_preflight import require_public_ready - system.settings.cookie_secure=True - system.settings.database_url='mysql+aiomysql://root:unused@isolated/cmvr-visual' - await require_public_ready(system.app.state.db,system.settings) - system.settings.public_access=True - with pytest.raises(ValueError,match='dedicated MySQL'): - await require_public_ready(system.app.state.db,system.settings) + from app.core.public_preflight import require_public_ready + + system.settings.cookie_secure = True + system.settings.database_url = "mysql+aiomysql://root:unused@isolated/cmvr-visual" + await require_public_ready(system.app.state.db, system.settings) + system.settings.public_access = True + with pytest.raises(ValueError, match="dedicated MySQL"): + await require_public_ready(system.app.state.db, system.settings) diff --git a/backend/tests/test_qwen_on_demand_timeout.py b/backend/tests/test_qwen_on_demand_timeout.py new file mode 100644 index 0000000..c3083e6 --- /dev/null +++ b/backend/tests/test_qwen_on_demand_timeout.py @@ -0,0 +1,41 @@ +import asyncio +from types import SimpleNamespace + +import httpx +import pytest + +from app.adapters.provider.client import Provider +from app.domain.errors import MediaError + + +@pytest.mark.asyncio +async def test_qwen_cold_load_uses_independent_transport_and_total_timeout(): + seen = [] + async def upstream(request): + seen.append(request.extensions['timeout']['read']) + await asyncio.sleep(1.08) + return httpx.Response(200, json={'choices': [{'message': {'content': '2'}}]}) + settings = SimpleNamespace(request_timeout_seconds=.01, qwen_timeout_seconds=2, + qwen_base_url='http://qwen.test/v1', qwen_model='example', qwen_api_key='') + provider = Provider(settings) + await provider.client.aclose() + provider.client = httpx.AsyncClient(transport=httpx.MockTransport(upstream), timeout=.01) + try: + assert await provider._chat([{'role':'user', 'content':'1+1'}]) == '2' + assert seen == [2], 'Qwen must override the HTTP read timeout as well as the total deadline' + with pytest.raises(MediaError, match='超时'): + await provider._json('GET', 'http://qwen.test/slow-control') + finally: + await provider.aclose() + + +def test_qwen_timeout_config_is_separate_from_normal_api_timeout(monkeypatch): + from app.core.config import Settings + monkeypatch.setenv('CMVR_MODE', 'test') + monkeypatch.setenv('DATABASE_URL', 'sqlite+aiosqlite:///:memory:') + assert hasattr(Settings.from_env(), 'qwen_timeout_seconds'), 'Qwen cold startup needs its own configured wait' + monkeypatch.setenv('QWEN_TIMEOUT_SECONDS', '600') + monkeypatch.setenv('REQUEST_TIMEOUT_SECONDS', '3') + settings = Settings.from_env() + assert settings.qwen_timeout_seconds == 600 + assert settings.request_timeout_seconds == 3 diff --git a/backend/tests/test_readiness.py b/backend/tests/test_readiness.py index 603c1cc..f2493b6 100644 --- a/backend/tests/test_readiness.py +++ b/backend/tests/test_readiness.py @@ -1,22 +1,33 @@ async def test_readiness_distinguishes_protocol_and_drain_from_gpu_capacity(system): - assert (await system.client.get('/api/live')).status_code==200 - async def capabilities():return {'protocol_version':2,'admission_policy':True} - system.provider.upstream_capabilities=capabilities - response=await system.client.get('/api/ready') - assert response.status_code==200 - async def old_protocol():return {'protocol_version':1} - system.provider.upstream_capabilities=old_protocol - assert (await system.client.get('/api/ready')).status_code==503 - assert (await system.client.get('/api/live')).status_code==200 - system.provider.upstream_capabilities=capabilities - system.app.state.draining=True - assert (await system.client.get('/api/ready')).status_code==503 + assert (await system.client.get("/api/live")).status_code == 200 + + async def capabilities(): + return {"protocol_version": 2, "admission_policy": True} + + system.provider.upstream_capabilities = capabilities + response = await system.client.get("/api/ready") + assert response.status_code == 200 + + async def old_protocol(): + return {"protocol_version": 1} + + system.provider.upstream_capabilities = old_protocol + assert (await system.client.get("/api/ready")).status_code == 503 + assert (await system.client.get("/api/live")).status_code == 200 + system.provider.upstream_capabilities = capabilities + system.app.state.draining = True + assert (await system.client.get("/api/ready")).status_code == 503 + + +async def test_editor_capability_explicitly_advertises_compatible_schema(system): + value = (await system.client.get("/api/capabilities")).json() + assert value["editable_production"] == {"schema_version": 1} async def test_maintenance_keeps_reads_and_login_but_blocks_draft_writes(system): - marker=system.settings.state_root/'maintenance' - marker.write_text('upgrade') - assert (await system.client.get('/api/auth/me')).status_code==200 - response=await system.client.post('/api/workflows',json={}) - assert response.status_code==503 and response.json()['detail']['code']=='maintenance' - assert (await system.client.get('/api/live')).status_code==200 + marker = system.settings.state_root / "maintenance" + marker.write_text("upgrade") + assert (await system.client.get("/api/auth/me")).status_code == 200 + response = await system.client.post("/api/workflows", json={}) + assert response.status_code == 503 and response.json()["detail"]["code"] == "maintenance" + assert (await system.client.get("/api/live")).status_code == 200 diff --git a/backend/tests/test_record_deletion.py b/backend/tests/test_record_deletion.py index ad67795..3616971 100644 --- a/backend/tests/test_record_deletion.py +++ b/backend/tests/test_record_deletion.py @@ -1,38 +1,44 @@ """Owner isolation, durable tombstones, and safe archival of creative records.""" + import pytest from sqlalchemy import select -from app.events import event_batch +from app.services.events import event_batch from app.models import Asset, Job, JobAsset -from app.v2_models import AssetReference, Batch, Execution, WorkflowDraft, WorkflowRun, WorkflowStep -from app.workflow_engine import advance_workflows +from app.models import AssetReference, Batch, Execution, WorkflowDraft, WorkflowRun, WorkflowStep +from app.services.orchestration.workflow_engine import advance_workflows from test_timeline_v2 import spec async def create_job(system, key=None, **changes): body = {"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}} body.update(changes) - response = await system.client.post('/api/jobs', json=body, - headers={'Idempotency-Key': key} if key else {}) + response = await system.client.post( + "/api/jobs", json=body, headers={"Idempotency-Key": key} if key else {} + ) assert response.status_code == 202, response.text - return response.json()['jobs'] + return response.json()["jobs"] -async def create_workflow(system, key='run'): - response = await system.client.post('/api/workflows', json={'name': 'delete test', 'spec': spec()}) +async def create_workflow(system, key="run"): + response = await system.client.post( + "/api/workflows", json={"name": "delete test", "spec": spec()} + ) assert response.status_code == 201, response.text draft = response.json() - body = {'draft_revision': draft['revision'], 'expected_version': draft['version']} - response = await system.client.post(f"/api/workflows/{draft['id']}/runs", json=body, - headers={'Idempotency-Key': key}) + body = {"draft_revision": draft["revision"], "expected_version": draft["version"]} + response = await system.client.post( + f"/api/workflows/{draft['id']}/runs", json=body, headers={"Idempotency-Key": key} + ) assert response.status_code == 202, response.text return draft, response.json(), body async def cancel_workflow(system, rid): await advance_workflows(system.app.state.db, system.settings, system.provider) - response = await system.client.post(f'/api/workflow-runs/{rid}/cancel', json={}, - headers={'Idempotency-Key': 'cancel:' + rid}) + response = await system.client.post( + f"/api/workflow-runs/{rid}/cancel", json={}, headers={"Idempotency-Key": "cancel:" + rid} + ) assert response.status_code == 200, response.text await advance_workflows(system.app.state.db, system.settings, system.provider) @@ -43,201 +49,279 @@ async def test_job_delete_owner_terminal_version_and_idempotent_tombstone(system assert (await other_client.delete(path)).status_code == 404 active = await system.client.delete(path) assert active.status_code == 409, active.text - assert active.json()['detail']['code'] == 'deletion_requires_terminal' - cancelled = (await system.client.post(path + '/cancel')).json() - stale = await system.client.delete(path, headers={'If-Match': str(job['version'])}) + assert active.json()["detail"]["code"] == "deletion_requires_terminal" + cancelled = (await system.client.post(path + "/cancel")).json() + stale = await system.client.delete(path, headers={"If-Match": str(job["version"])}) assert stale.status_code == 409 - deleted = await system.client.delete(path, headers={'If-Match': str(cancelled['version'])}) + deleted = await system.client.delete(path, headers={"If-Match": str(cancelled["version"])}) assert deleted.status_code == 200, deleted.text - assert deleted.json()['deleted']['job_ids'] == [job['id']] - assert (await system.client.delete(path, headers={'If-Match': '0'})).json() == deleted.json() + assert deleted.json()["deleted"]["job_ids"] == [job["id"]] + assert (await system.client.delete(path, headers={"If-Match": "0"})).json() == deleted.json() assert (await other_client.delete(path)).status_code == 404 assert (await system.client.get(path)).status_code == 404 - assert (await system.client.get('/api/jobs')).json()['total'] == 0 - assert (await system.client.post(path + '/retry')).status_code == 404 + assert (await system.client.get("/api/jobs")).json()["total"] == 0 + assert (await system.client.post(path + "/retry")).status_code == 404 async with system.app.state.db.session() as session: - saved = await session.get(Job, job['id']) - assert saved.deleted_at is not None and saved.version == cancelled['version'] + 1 + saved = await session.get(Job, job["id"]) + assert saved.deleted_at is not None and saved.version == cancelled["version"] + 1 events = await event_batch(system.app.state.db, saved.owner_id, 0) - deleted_events = [e for e in events if e['event'] == 'job.deleted'] - assert [e['data'] for e in deleted_events] == [{'id': job['id'], 'version': saved.version}] + deleted_events = [e for e in events if e["event"] == "job.deleted"] + assert [e["data"] for e in deleted_events] == [{"id": job["id"], "version": saved.version}] async def test_deleted_job_original_submission_cannot_resurrect(system): - jobs = await create_job(system, 'original', count=2) - path = '/api/jobs/' + jobs[0]['id'] - await system.client.post(path + '/cancel') + jobs = await create_job(system, "original", count=2) + path = "/api/jobs/" + jobs[0]["id"] + await system.client.post(path + "/cancel") assert (await system.client.delete(path)).status_code == 200 - replay = await system.client.post('/api/jobs', json={'task_type': 'image.generate', - 'input': {'prompt': 'cup'}, 'parameters': {}, 'count': 2}, headers={'Idempotency-Key': 'original'}) + replay = await system.client.post( + "/api/jobs", + json={ + "task_type": "image.generate", + "input": {"prompt": "cup"}, + "parameters": {}, + "count": 2, + }, + headers={"Idempotency-Key": "original"}, + ) assert replay.status_code == 410, replay.text - recovered = await system.client.get('/api/submissions/original?operation=jobs.create') + recovered = await system.client.get("/api/submissions/original?operation=jobs.create") assert recovered.status_code == 410 - assert (await system.client.get('/api/jobs')).json()['total'] == 1 + assert (await system.client.get("/api/jobs")).json()["total"] == 1 -@pytest.mark.parametrize('state', ['allocated', 'running', 'stopping', 'unknown', 'future_unconfirmed']) +@pytest.mark.parametrize( + "state", ["allocated", "running", "stopping", "unknown", "future_unconfirmed"] +) async def test_job_delete_requires_confirmed_execution_cleanup(system, state): job = (await create_job(system))[0] - path = '/api/jobs/' + job['id'] - await system.client.post(path + '/cancel') + path = "/api/jobs/" + job["id"] + await system.client.post(path + "/cancel") async with system.app.state.db.session() as session: - execution = Execution(job_id=job['id'], ordinal=1, phase_key='execute', - resource_pool='cpu_media', fence_token='fence', state=state) + execution = Execution( + job_id=job["id"], + ordinal=1, + phase_key="execute", + resource_pool="cpu_media", + fence_token="fence", + state=state, + ) session.add(execution) await session.commit() response = await system.client.delete(path) assert response.status_code == 409, response.text - assert response.json()['detail']['code'] == 'cleanup_pending' + assert response.json()["detail"]["code"] == "cleanup_pending" async def test_run_delete_cascades_jobs_clears_draft_pointer_and_releases_refs(system): draft, snapshot, body = await create_workflow(system) - rid = snapshot['run']['id'] + rid = snapshot["run"]["id"] await cancel_workflow(system, rid) - snapshot = (await system.client.get('/api/workflow-runs/' + rid)).json() - jids = sorted(j['id'] for j in snapshot['jobs']) - assert len(jids)==3 + snapshot = (await system.client.get("/api/workflow-runs/" + rid)).json() + jids = sorted(j["id"] for j in snapshot["jobs"]) + assert len(jids) == 3 jid = jids[0] - child_delete = await system.client.delete('/api/jobs/' + jid) + child_delete = await system.client.delete("/api/jobs/" + jid) assert child_delete.status_code == 409 - assert child_delete.json()['detail']['code'] == 'parent_control_required' - response = await system.client.delete('/api/workflow-runs/' + rid) + assert child_delete.json()["detail"]["code"] == "parent_control_required" + response = await system.client.delete("/api/workflow-runs/" + rid) assert response.status_code == 200, response.text - deleted=response.json()['deleted'] - assert {**deleted,'job_ids':sorted(deleted['job_ids'])} == {'job_ids': jids, 'run_ids': [rid], 'draft_ids': [], 'batch_ids': []} - current = (await system.client.get('/api/workflows/' + draft['id'])).json() - assert current['current_run_id'] is None - assert (await system.client.get('/api/workflow-runs')).json()['total'] == 0 - assert (await system.client.get('/api/jobs')).json()['total'] == 0 - assert (await system.client.post(f"/api/workflows/{draft['id']}/runs", json=body, - headers={'Idempotency-Key': 'run'})).status_code == 410 + deleted = response.json()["deleted"] + assert {**deleted, "job_ids": sorted(deleted["job_ids"])} == { + "job_ids": jids, + "run_ids": [rid], + "draft_ids": [], + "batch_ids": [], + } + current = (await system.client.get("/api/workflows/" + draft["id"])).json() + assert current["current_run_id"] is None + assert (await system.client.get("/api/workflow-runs")).json()["total"] == 0 + assert (await system.client.get("/api/jobs")).json()["total"] == 0 + assert ( + await system.client.post( + f"/api/workflows/{draft['id']}/runs", json=body, headers={"Idempotency-Key": "run"} + ) + ).status_code == 410 async with system.app.state.db.session() as session: assert not (await session.scalars(select(JobAsset).where(JobAsset.job_id.in_(jids)))).all() - assert not (await session.scalars(select(AssetReference).where( - AssetReference.ref_kind == 'run', AssetReference.ref_id == rid))).all() + assert not ( + await session.scalars( + select(AssetReference).where( + AssetReference.ref_kind == "run", AssetReference.ref_id == rid + ) + ) + ).all() -async def test_draft_delete_atomically_refuses_active_descendants_and_archives_finished_history(system, other_client): +async def test_draft_delete_atomically_refuses_active_descendants_and_archives_finished_history( + system, other_client +): draft, snapshot, _ = await create_workflow(system) - did, rid = draft['id'], snapshot['run']['id'] - path = '/api/workflows/' + did + did, rid = draft["id"], snapshot["run"]["id"] + path = "/api/workflows/" + did assert (await other_client.delete(path)).status_code == 404 response = await system.client.delete(path) assert response.status_code == 409 - assert response.json()['detail']['code'] == 'deletion_requires_terminal' + assert response.json()["detail"]["code"] == "deletion_requires_terminal" assert (await system.client.get(path)).status_code == 200 await cancel_workflow(system, rid) response = await system.client.delete(path) assert response.status_code == 200, response.text - assert response.json()['deleted']['draft_ids'] == [did] - assert response.json()['deleted']['run_ids'] == [rid] - assert (await system.client.get('/api/workflows')).json()['total'] == 0 - assert (await system.client.get('/api/workflow-runs/' + rid)).status_code == 404 + assert response.json()["deleted"]["draft_ids"] == [did] + assert response.json()["deleted"]["run_ids"] == [rid] + assert (await system.client.get("/api/workflows")).json()["total"] == 0 + assert (await system.client.get("/api/workflow-runs/" + rid)).status_code == 404 assert (await system.client.delete(path)).json() == response.json() async def test_batch_delete_preserves_draft_and_archives_all_members(system, other_client): - response = await system.client.post('/api/workflows', json={'name': 'batch draft', 'spec': spec()}) + response = await system.client.post( + "/api/workflows", json={"name": "batch draft", "spec": spec()} + ) draft = response.json() - body = {'items': [{'kind': 'workflow', 'draft_id': draft['id'], 'draft_revision': draft['revision'], - 'expected_version': draft['version']}, {'kind': 'job', 'task_type': 'image.generate', - 'input': {'prompt': 'cup'}, 'parameters': {}, 'count': 2}]} - response = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'batch'}) + body = { + "items": [ + { + "kind": "workflow", + "draft_id": draft["id"], + "draft_revision": draft["revision"], + "expected_version": draft["version"], + }, + { + "kind": "job", + "task_type": "image.generate", + "input": {"prompt": "cup"}, + "parameters": {}, + "count": 2, + }, + ] + } + response = await system.client.post( + "/api/batches", json=body, headers={"Idempotency-Key": "batch"} + ) assert response.status_code == 202, response.text - bid = response.json()['batch']['id'] - rid = response.json()['items'][0]['target_id'] - await system.client.post('/api/batches/' + bid + '/control', json={'desired_state': 'cancel'}, - headers={'Idempotency-Key': 'stop-batch'}) + bid = response.json()["batch"]["id"] + rid = response.json()["items"][0]["target_id"] + await system.client.post( + "/api/batches/" + bid + "/control", + json={"desired_state": "cancel"}, + headers={"Idempotency-Key": "stop-batch"}, + ) await advance_workflows(system.app.state.db, system.settings, system.provider) - assert (await other_client.delete('/api/batches/' + bid)).status_code == 404 - for path in ['/api/workflow-runs/' + rid, '/api/workflows/' + draft['id']]: + assert (await other_client.delete("/api/batches/" + bid)).status_code == 404 + for path in ["/api/workflow-runs/" + rid, "/api/workflows/" + draft["id"]]: rejected = await system.client.delete(path) assert rejected.status_code == 409 - assert rejected.json()['detail']['code'] == 'parent_control_required' - response = await system.client.delete('/api/batches/' + bid) + assert rejected.json()["detail"]["code"] == "parent_control_required" + response = await system.client.delete("/api/batches/" + bid) assert response.status_code == 200, response.text - deleted = response.json()['deleted'] - assert deleted['batch_ids'] == [bid] and deleted['run_ids'] == [rid] and len(deleted['job_ids']) == 2 - assert deleted['draft_ids'] == [] - current = (await system.client.get('/api/workflows/' + draft['id'])).json() - assert current['current_run_id'] is None - assert (await system.client.get('/api/batches')).json()['total'] == 0 - assert (await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'batch'})).status_code == 410 + deleted = response.json()["deleted"] + assert ( + deleted["batch_ids"] == [bid] + and deleted["run_ids"] == [rid] + and len(deleted["job_ids"]) == 2 + ) + assert deleted["draft_ids"] == [] + current = (await system.client.get("/api/workflows/" + draft["id"])).json() + assert current["current_run_id"] is None + assert (await system.client.get("/api/batches")).json()["total"] == 0 + assert ( + await system.client.post("/api/batches", json=body, headers={"Idempotency-Key": "batch"}) + ).status_code == 410 async def test_deleting_old_run_rejects_jobs_selected_by_another_visible_run(system): - draft, first, _ = await create_workflow(system, 'first') - await cancel_workflow(system, first['run']['id']) + draft, first, _ = await create_workflow(system, "first") + await cancel_workflow(system, first["run"]["id"]) async with system.app.state.db.session() as session: - job = await session.scalar(select(Job).where(Job.run_id == first['run']['id'])) + job = await session.scalar(select(Job).where(Job.run_id == first["run"]["id"])) jid = job.id - job.state = 'succeeded' + job.state = "succeeded" await session.commit() - draft = (await system.client.get('/api/workflows/' + draft['id'])).json() - response = await system.client.post('/api/workflows/' + draft['id'] + '/runs', - json={'draft_revision': draft['revision'], 'expected_version': draft['version']}, - headers={'Idempotency-Key': 'second'}) - second = response.json()['run']['id'] + draft = (await system.client.get("/api/workflows/" + draft["id"])).json() + response = await system.client.post( + "/api/workflows/" + draft["id"] + "/runs", + json={"draft_revision": draft["revision"], "expected_version": draft["version"]}, + headers={"Idempotency-Key": "second"}, + ) + second = response.json()["run"]["id"] async with system.app.state.db.session() as session: - step = await session.scalar(select(WorkflowStep).where(WorkflowStep.run_id == second, - WorkflowStep.step_key == 'shot_1')) - step.selected_job_id, step.state = jid, 'succeeded' + step = await session.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == second, WorkflowStep.step_key == "shot_1" + ) + ) + step.selected_job_id, step.state = jid, "succeeded" await session.commit() - rejected = await system.client.delete('/api/workflow-runs/' + first['run']['id']) + rejected = await system.client.delete("/api/workflow-runs/" + first["run"]["id"]) assert rejected.status_code == 409, rejected.text - assert rejected.json()['detail']['code'] == 'resource_in_use' - assert (await system.client.get('/api/jobs/' + jid)).status_code == 200 + assert rejected.json()["detail"]["code"] == "resource_in_use" + assert (await system.client.get("/api/jobs/" + jid)).status_code == 200 async def test_deleted_job_rejects_stale_execution_fences_and_retains_generated_asset(system): - from app.executions import accept_manifest, gpu_publication_matches - jobs = await create_job(system, task_type='math.solve', input={'prompt': '2+3'}) - jid = jobs[0]['id'] + from app.services.orchestration.executions import accept_manifest, gpu_publication_matches + + jobs = await create_job(system, task_type="math.solve", input={"prompt": "2+3"}) + jid = jobs[0]["id"] coordinator = system.app.state.coordinator await coordinator.run_once(force=True) import asyncio + await asyncio.gather(*list(coordinator._cpu.values())) - result = (await system.client.get('/api/jobs/' + jid)).json() - aid = result['result_assets'][0]['id'] + result = (await system.client.get("/api/jobs/" + jid)).json() + aid = result["result_assets"][0]["id"] async with system.app.state.db.session() as session: source = await session.get(Job, jid) execution = await session.get(Execution, source.current_execution_id) - session.add(AssetReference(owner_id=source.owner_id, asset_id=aid, - ref_kind='execution', ref_id=execution.id)) + session.add( + AssetReference( + owner_id=source.owner_id, asset_id=aid, ref_kind="execution", ref_id=execution.id + ) + ) await session.commit() - response = await system.client.delete('/api/jobs/' + jid) + response = await system.client.delete("/api/jobs/" + jid) assert response.status_code == 200, response.text - assert (await system.client.get('/api/assets/' + aid + '/content')).status_code == 200 - await coordinator._update(jid, state='running') - await coordinator._complete(jid, {'stale': True}) + assert (await system.client.get("/api/assets/" + aid + "/content")).status_code == 200 + await coordinator._update(jid, state="running") + await coordinator._complete(jid, {"stale": True}) async with system.app.state.db.session() as session: source = await session.get(Job, jid) - assert source.deleted_at is not None and source.state == 'succeeded' + assert source.deleted_at is not None and source.state == "succeeded" assert not await accept_manifest(session, execution.id, execution.fence_token, {}) assert not await gpu_publication_matches(session, source, None) - assert not (await session.scalars(select(AssetReference).where( - AssetReference.ref_kind == 'execution', AssetReference.ref_id == execution.id))).all() + assert not ( + await session.scalars( + select(AssetReference).where( + AssetReference.ref_kind == "execution", AssetReference.ref_id == execution.id + ) + ) + ).all() events = await event_batch(system.app.state.db, source.owner_id, 0) - assert events[-1]['event'] == 'job.deleted' + assert events[-1]["event"] == "job.deleted" -async def test_late_failure_reloads_archived_job_before_mutating_execution_audit(system, monkeypatch): +async def test_late_failure_reloads_archived_job_before_mutating_execution_audit( + system, monkeypatch +): import asyncio - jobs = await create_job(system, task_type='math.solve', input={'prompt': '2+3'}) - jid = jobs[0]['id'] + + jobs = await create_job(system, task_type="math.solve", input={"prompt": "2+3"}) + jid = jobs[0]["id"] coordinator = system.app.state.coordinator await coordinator.run_once(force=True) await asyncio.gather(*list(coordinator._cpu.values())) original = coordinator._job + async def archive_after_read(job_id): stale = await original(job_id) - response = await system.client.delete('/api/jobs/' + job_id) + response = await system.client.delete("/api/jobs/" + job_id) assert response.status_code == 200 return stale - monkeypatch.setattr(coordinator, '_job', archive_after_read) - await coordinator._failure(jid, ValueError('late callback')) + + monkeypatch.setattr(coordinator, "_job", archive_after_read) + await coordinator._failure(jid, ValueError("late callback")) async with system.app.state.db.session() as session: row = await session.get(Job, jid) execution = await session.get(Execution, row.current_execution_id) - assert execution.state == 'results_ready' + assert execution.state == "results_ready" diff --git a/backend/tests/test_remote_policy_refresh.py b/backend/tests/test_remote_policy_refresh.py new file mode 100644 index 0000000..589b0a1 --- /dev/null +++ b/backend/tests/test_remote_policy_refresh.py @@ -0,0 +1,141 @@ +"""Remote policy admission stays correct when no browser is polling status.""" + +import asyncio +import json +import time +from types import SimpleNamespace + +import httpx +import pytest +import pytest_asyncio + +from app.adapters.provider.client import Provider +from app.core.runtime_policy import read_runtime_policy +from test_jobs import submit + + +@pytest_asyncio.fixture +async def remote_policy(system): + settings = system.settings + settings.inference_remote_files = True + settings.runtime_policy_file = settings.workspace_root / "config" / "runtime-policy.json" + settings.runtime_policy_file.parent.mkdir(parents=True) + settings.runtime_policy_file.write_text( + json.dumps({"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": 240}) + ) + boundary = SimpleNamespace( + calls=0, + status=200, + hang=False, + policy={ + "batch_window_enabled": False, + "workflow_max_shots": 240, + "configuration_error": None, + }, + ) + + async def respond(request): + assert request.url.path == "/runtime/status" + boundary.calls += 1 + if boundary.hang: + await asyncio.sleep(60) + return httpx.Response( + boundary.status, + json={ + "schema_version": 1, + "monitor": { + "schema_version": 1, + "generated_at": None, + "error": "gpu_monitor_unavailable", + "gpus": [], + }, + "scheduler": None, + "runtime_policy": boundary.policy, + }, + ) + + settings.inference_api_key_file = None + real = Provider(settings) + await real.client.aclose() + real.client = httpx.AsyncClient(transport=httpx.MockTransport(respond)) + system.provider.runtime_status = real.runtime_status + boundary.real = real + try: + yield boundary + finally: + await real.aclose() + + +async def test_tick_refreshes_remote_policy_without_browser_and_recovers_batch( + system, remote_policy +): + job = ( + await submit( + system, task_type="math.solve", input={"prompt": "2+3"}, execution_mode="batch" + ) + )[0] + remote_policy.policy["configuration_error"] = "runtime_policy_invalid" + await system.app.state.coordinator.run_once(force=True) + assert remote_policy.calls == 1 + assert system.provider.cpu_runs == 0 + assert read_runtime_policy(system.settings)["configuration_error"] == "runtime_policy_invalid" + # No HTTP status route runs between invalidation and automatic recovery. + remote_policy.policy["configuration_error"] = None + remote_policy.real._runtime_cache = None + await system.app.state.coordinator.run_once(force=True) + await system.app.state.coordinator._cpu[job["id"]] + assert remote_policy.calls == 2 + assert system.provider.cpu_runs == 1 + assert read_runtime_policy(system.settings)["configuration_error"] is None + + +async def test_unreachable_policy_keeps_file_but_only_blocks_batch_work(system, remote_policy): + await remote_policy.real.runtime_status() # Previously permissive, recently valid file. + policy_bytes = system.settings.runtime_policy_file.read_bytes() + await submit(system, task_type="math.solve", input={"prompt": "batch"}, execution_mode="batch") + interactive = (await submit(system, task_type="math.solve", input={"prompt": "interactive"}))[0] + remote_policy.real._runtime_cache = None + remote_policy.status = 503 + await system.app.state.coordinator.run_once(force=True) + await system.app.state.coordinator._cpu[interactive["id"]] + assert remote_policy.calls == 2 + assert system.provider.cpu_runs == 1 + assert system.settings.runtime_policy_file.read_bytes() == policy_bytes + assert ( + read_runtime_policy(system.settings)["configuration_error"] == "runtime_policy_unavailable" + ) + + +async def test_remote_refresh_timeout_does_not_stall_cancellation(system, remote_policy): + # Establish a remote GPU job without depending on the new refresh path. + system.settings.inference_remote_files = False + job = (await submit(system))[0] + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + current = await coordinator._job(job["id"]) + assert current.upstream_id + response = await system.client.post("/api/jobs/" + job["id"] + "/cancel") + assert response.status_code == 200 + system.settings.inference_remote_files = True + await remote_policy.real.runtime_status() + remote_policy.real._runtime_cache = None + remote_policy.hang = True + started = time.monotonic() + await asyncio.wait_for(coordinator.run_once(force=True), timeout=5) + assert time.monotonic() - started < 5 + assert (await coordinator._job(job["id"])).state == "cancelled" + assert ( + read_runtime_policy(system.settings)["configuration_error"] == "runtime_policy_unavailable" + ) + + +async def test_coordinator_shutdown_cancellation_is_not_swallowed(system, remote_policy): + remote_policy.hang = True + task = asyncio.create_task(system.app.state.coordinator.run_once(force=True)) + for _ in range(100): + if remote_policy.calls: + break + await asyncio.sleep(0.01) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task diff --git a/backend/tests/test_retention.py b/backend/tests/test_retention.py index cf2cb58..8e6fe27 100644 --- a/backend/tests/test_retention.py +++ b/backend/tests/test_retention.py @@ -1,19 +1,23 @@ from datetime import timedelta import pytest -from app.models import Asset,utcnow -from app.v2_models import AssetReference -from app.retention import collect_garbage +from app.models import Asset, utcnow +from app.models import AssetReference +from app.services.retention import collect_garbage + @pytest.mark.asyncio -async def test_referenced_soft_deleted_assets_never_gc(system,png_bytes): - c=system.client - response=await c.post("/api/assets",files={"file":("image.png",png_bytes,"image/png")}) - assert response.status_code==201 - asset_id=response.json()["id"] +async def test_referenced_soft_deleted_assets_never_gc(system, png_bytes): + c = system.client + response = await c.post("/api/assets", files={"file": ("image.png", png_bytes, "image/png")}) + assert response.status_code == 201 + asset_id = response.json()["id"] async with system.app.state.db.session() as session: - asset=await session.get(Asset,asset_id);asset.deleted_at=utcnow()-timedelta(days=30) - session.add(AssetReference(owner_id=asset.owner_id,asset_id=asset.id,ref_kind="run",ref_id="run")) + asset = await session.get(Asset, asset_id) + asset.deleted_at = utcnow() - timedelta(days=30) + session.add( + AssetReference(owner_id=asset.owner_id, asset_id=asset.id, ref_kind="run", ref_id="run") + ) await session.commit() - report=await collect_garbage(system.app.state.db,system.settings) - assert report["protected"]==[asset_id] - assert report["deleted"]==[] + report = await collect_garbage(system.app.state.db, system.settings) + assert report["protected"] == [asset_id] + assert report["deleted"] == [] diff --git a/backend/tests/test_runtime_policy.py b/backend/tests/test_runtime_policy.py index 1e4a8e3..9612849 100644 --- a/backend/tests/test_runtime_policy.py +++ b/backend/tests/test_runtime_policy.py @@ -1,4 +1,5 @@ """Operator policy is hot-loaded; browser requests cannot override scheduling.""" + from datetime import datetime import json from types import SimpleNamespace @@ -7,15 +8,22 @@ import pytest def write_policy(path, enabled, max_shots=120): - path.write_text(json.dumps({"schema_version": 1, - "batch_window_enabled": enabled, "workflow_max_shots": max_shots}), encoding="utf-8") + path.write_text( + json.dumps( + {"schema_version": 1, "batch_window_enabled": enabled, "workflow_max_shots": max_shots} + ), + encoding="utf-8", + ) def test_daytime_policy_switch_is_hot_loaded_without_changing_job_mode(tmp_path): - from app.resource_policy import admits, execution_policy + from app.services.orchestration.resource_policy import admits, execution_policy + path = tmp_path / "runtime-policy.json" settings = SimpleNamespace(runtime_policy_file=path) - job = SimpleNamespace(execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[]) + job = SimpleNamespace( + execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[] + ) noon = datetime.fromisoformat("2026-11-11T12:00:00+08:00") write_policy(path, False, 240) assert admits(job, now=noon, settings=settings) @@ -31,24 +39,31 @@ def test_daytime_policy_switch_is_hot_loaded_without_changing_job_mode(tmp_path) assert not admits(job, now=noon, settings=settings) -@pytest.mark.parametrize("value", [ - {"schema_version": 1, "batch_window_enabled": "false"}, - {"schema_version": True, "batch_window_enabled": False}, - {"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": True}, - {"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": 1001}, - {"schema_version": 1, "batch_window_enabled": False, "unexpected": True}, - [], None, -]) +@pytest.mark.parametrize( + "value", + [ + {"schema_version": 1, "batch_window_enabled": "false"}, + {"schema_version": True, "batch_window_enabled": False}, + {"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": True}, + {"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": 1001}, + {"schema_version": 1, "batch_window_enabled": False, "unexpected": True}, + [], + None, + ], +) def test_bad_runtime_policy_only_blocks_batch(tmp_path, value): - from app.runtime_policy import read_runtime_policy - from app.resource_policy import admits, execution_policy + from app.core.runtime_policy import read_runtime_policy + from app.services.orchestration.resource_policy import admits, execution_policy + path = tmp_path / "runtime-policy.json" settings = SimpleNamespace(runtime_policy_file=path) path.write_text(json.dumps(value), encoding="utf-8") result = read_runtime_policy(settings) assert result["batch_window_enabled"] is True assert result["configuration_error"] == "runtime_policy_invalid" - job = SimpleNamespace(execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[]) + job = SimpleNamespace( + execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[] + ) night = datetime.fromisoformat("2026-11-11T22:00:00+08:00") assert not admits(job, now=night, settings=settings) assert not execution_policy(night, settings=settings)["batch_open"] @@ -57,8 +72,9 @@ def test_bad_runtime_policy_only_blocks_batch(tmp_path, value): def test_missing_file_is_production_default_and_environment_selects_file(tmp_path, monkeypatch): - from app.config import Settings - from app.runtime_policy import read_runtime_policy + from app.core.config import Settings + from app.core.runtime_policy import read_runtime_policy + path = tmp_path / "missing.json" monkeypatch.setenv("CMVR_MODE", "test") monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:") @@ -66,35 +82,48 @@ def test_missing_file_is_production_default_and_environment_selects_file(tmp_pat monkeypatch.setenv("RUNTIME_POLICY_FILE", str(path)) settings = Settings.from_env() assert settings.runtime_policy_file == path - assert read_runtime_policy(settings) == {"batch_window_enabled": True, - "workflow_max_shots": 120, "configuration_error": None} + assert read_runtime_policy(settings) == { + "batch_window_enabled": True, + "workflow_max_shots": 120, + "configuration_error": None, + } -def test_empty_environment_path_keeps_shared_default_and_unreadable_file_fails_closed(tmp_path, monkeypatch): +def test_empty_environment_path_keeps_shared_default_and_unreadable_file_fails_closed( + tmp_path, monkeypatch +): from pathlib import Path - from app.config import Settings - from app.runtime_policy import read_runtime_policy + from app.core.config import Settings + from app.core.runtime_policy import read_runtime_policy + monkeypatch.setenv("CMVR_MODE", "test") monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:") monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path)) monkeypatch.setenv("RUNTIME_POLICY_FILE", "") - assert Settings.from_env().runtime_policy_file == Path("/workspace/projects/llm-services/config/runtime-policy.json") + assert Settings.from_env().runtime_policy_file == Path( + "/workspace/projects/llm-services/config/runtime-policy.json" + ) policy = read_runtime_policy(SimpleNamespace(runtime_policy_file=tmp_path)) assert policy["batch_window_enabled"] is True assert policy["configuration_error"] == "runtime_policy_unavailable" @pytest.mark.asyncio -async def test_disabled_window_drains_same_waiting_job_and_preserves_corrupt_clock(system, monkeypatch): - from app import resource_policy +async def test_disabled_window_drains_same_waiting_job_and_preserves_corrupt_clock( + system, monkeypatch +): + from app.services.orchestration import resource_policy from app.models import Job - from app.admission_clock import AdmissionClock + from app.services.orchestration.admission_clock import AdmissionClock + path = system.settings.state_root / "runtime-policy.json" system.settings.runtime_policy_file = path write_policy(path, True) monkeypatch.setattr(resource_policy, "execution_policy", lambda now=None: {"batch_open": False}) - response = await system.client.post("/api/jobs", json={"task_type": "math.solve", - "input": {"prompt": "2+3"}, "execution_mode": "batch"}) + response = await system.client.post( + "/api/jobs", + json={"task_type": "math.solve", "input": {"prompt": "2+3"}, "execution_mode": "batch"}, + ) assert response.status_code == 202, response.text job_id = response.json()["jobs"][0]["id"] coordinator = system.app.state.coordinator @@ -126,6 +155,12 @@ async def test_status_and_capabilities_share_live_policy_and_workflow_limits(sys body = response.json() assert body["execution_policy"]["batch_window_enabled"] is False assert body["execution_policy"]["configuration_error"] is None - assert body["workflow_limits"] == {"max_shots": 240, "source_frames": 121, - "default_source_frames":121,"max_source_frames":361,"default_clip_frames":120, - "max_clip_frames": 360, "fps": 24} + assert body["workflow_limits"] == { + "max_shots": 240, + "source_frames": 121, + "default_source_frames": 121, + "max_source_frames": 361, + "default_clip_frames": 120, + "max_clip_frames": 360, + "fps": 24, + } diff --git a/backend/tests/test_schema_migrations.py b/backend/tests/test_schema_migrations.py index 7ce71ad..2812803 100644 --- a/backend/tests/test_schema_migrations.py +++ b/backend/tests/test_schema_migrations.py @@ -1,53 +1,70 @@ import importlib.util from pathlib import Path import pytest -from sqlalchemy import create_engine,text -from app.schema import schema_preflight,check_schema_revision +from sqlalchemy import create_engine, text +from app.core.schema import schema_preflight, check_schema_revision + def revision(name): - path=Path(__file__).parents[1]/"alembic"/"versions"/name - spec=importlib.util.spec_from_file_location(name,path) - module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + path = Path(__file__).parents[1] / "alembic" / "versions" / name + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) return module + def test_legacy_baseline_and_drift(): - module=revision("001_legacy_baseline.py") - meta=module.metadata();engine=create_engine("sqlite://") + module = revision("001_legacy_baseline.py") + meta = module.metadata() + engine = create_engine("sqlite://") with engine.begin() as c: meta.create_all(c) - assert len(meta.tables)==6 - assert schema_preflight(c,meta).matches + assert len(meta.tables) == 6 + assert schema_preflight(c, meta).matches c.execute(text("DROP INDEX visual_jobs_dispatch")) - assert not schema_preflight(c,meta).matches + assert not schema_preflight(c, meta).matches + def test_upgrade_backfills_legacy_and_preserves_rows(tmp_path): from alembic.config import Config from alembic import command - config=Config(str(Path(__file__).parents[1]/"alembic.ini")) - db=tmp_path/"upgrade.sqlite" - config.attributes["url"]="sqlite+aiosqlite:///"+str(db) - command.upgrade(config,"001") - engine=create_engine("sqlite:///"+str(db)) + + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + db = tmp_path / "upgrade.sqlite" + config.attributes["url"] = "sqlite+aiosqlite:///" + str(db) + command.upgrade(config, "001") + engine = create_engine("sqlite:///" + str(db)) with engine.begin() as c: - c.execute(text("INSERT INTO visual_users (id,username,display_name,password_hash,role,disabled,created_at) VALUES ('owner','legacy','Legacy','UNCHANGED','admin',0,CURRENT_TIMESTAMP)")) - command.upgrade(config,"head") + c.execute( + text( + "INSERT INTO visual_users (id,username,display_name,password_hash,role,disabled,created_at) VALUES ('owner','legacy','Legacy','UNCHANGED','admin',0,CURRENT_TIMESTAMP)" + ) + ) + command.upgrade(config, "head") with engine.begin() as c: - check_schema_revision(c,{"004"}) - row=c.execute(text("SELECT password_hash,must_change_password FROM visual_users WHERE id='owner'")).one() - assert row==("UNCHANGED",0) + check_schema_revision(c, {"007"}) + row = c.execute( + text("SELECT password_hash,must_change_password FROM visual_users WHERE id='owner'") + ).one() + assert row == ("UNCHANGED", 0) + def test_unversioned_database_refuses_production(): with create_engine("sqlite://").begin() as c: - with pytest.raises(RuntimeError,match="unversioned"):check_schema_revision(c,{"003"}) + with pytest.raises(RuntimeError, match="unversioned"): + check_schema_revision(c, {"003"}) def test_mysql_reflection_normalizes_only_implicit_collation_and_boolean(): - from sqlalchemy import String,Boolean - from sqlalchemy.dialects.mysql import dialect,VARCHAR,TINYINT - from app.schema import compatible_type - mysql=dialect() - assert compatible_type(String(32),VARCHAR(32,collation="utf8mb4_unicode_ci"),mysql) - assert compatible_type(Boolean(),TINYINT(display_width=1),mysql) - assert not compatible_type(String(32),VARCHAR(64,collation="utf8mb4_unicode_ci"),mysql) - assert not compatible_type(String(32,collation="utf8mb4_bin"),VARCHAR(32,collation="utf8mb4_unicode_ci"),mysql) - assert not compatible_type(Boolean(),TINYINT(display_width=4),mysql) + from sqlalchemy import String, Boolean + from sqlalchemy.dialects.mysql import dialect, VARCHAR, TINYINT + from app.core.schema import compatible_type + + mysql = dialect() + assert compatible_type(String(32), VARCHAR(32, collation="utf8mb4_unicode_ci"), mysql) + assert compatible_type(Boolean(), TINYINT(display_width=1), mysql) + assert not compatible_type(String(32), VARCHAR(64, collation="utf8mb4_unicode_ci"), mysql) + assert not compatible_type( + String(32, collation="utf8mb4_bin"), VARCHAR(32, collation="utf8mb4_unicode_ci"), mysql + ) + assert not compatible_type(Boolean(), TINYINT(display_width=4), mysql) diff --git a/backend/tests/test_schema_v4.py b/backend/tests/test_schema_v4.py index a1ebfcf..77feca0 100644 --- a/backend/tests/test_schema_v4.py +++ b/backend/tests/test_schema_v4.py @@ -2,40 +2,65 @@ from pathlib import Path import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine,inspect,text +from sqlalchemy import create_engine, inspect, text def test_v4_preserves_private_assets_and_adds_sharing_tombstones(tmp_path): - config=Config(str(Path(__file__).parents[1]/'alembic.ini')) - path=tmp_path/'upgrade-v4.sqlite' - config.attributes['url']='sqlite+aiosqlite:///'+str(path) - command.upgrade(config,'003') - engine=create_engine('sqlite:///'+str(path)) + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + path = tmp_path / "upgrade-v4.sqlite" + config.attributes["url"] = "sqlite+aiosqlite:///" + str(path) + command.upgrade(config, "003") + engine = create_engine("sqlite:///" + str(path)) with engine.begin() as connection: - connection.execute(text("INSERT INTO visual_users(id,username,display_name,password_hash,role,disabled,must_change_password,created_at) VALUES('owner','owner','Owner','UNCHANGED','user',0,0,CURRENT_TIMESTAMP)")) - connection.execute(text("INSERT INTO visual_assets(id,owner_id,name,storage_key,kind,mime_type,size_bytes,sha256,tags,favorite,origin,ready,created_at) VALUES('asset','owner','Original','owner/asset/source.png','image','image/png',123,:sha,'[]',0,'upload',1,CURRENT_TIMESTAMP)"),{'sha':'0'*64}) - command.upgrade(config,'head') - command.upgrade(config,'head') + connection.execute( + text( + "INSERT INTO visual_users(id,username,display_name,password_hash,role,disabled,must_change_password,created_at) VALUES('owner','owner','Owner','UNCHANGED','user',0,0,CURRENT_TIMESTAMP)" + ) + ) + connection.execute( + text( + "INSERT INTO visual_assets(id,owner_id,name,storage_key,kind,mime_type,size_bytes,sha256,tags,favorite,origin,ready,created_at) VALUES('asset','owner','Original','owner/asset/source.png','image','image/png',123,:sha,'[]',0,'upload',1,CURRENT_TIMESTAMP)" + ), + {"sha": "0" * 64}, + ) + command.upgrade(config, "004") + command.upgrade(config, "004") with engine.begin() as connection: - assert connection.scalar(text('SELECT version_num FROM alembic_version'))=='004' - assert connection.execute(text("SELECT name,size_bytes,library_scope FROM visual_assets WHERE id='asset'")).one()==('Original',123,'private') - assert connection.scalar(text("SELECT password_hash FROM visual_users WHERE id='owner'"))=='UNCHANGED' - inspector=inspect(connection) - for name in ['visual_jobs','visual_drafts','visual_workflow_runs','visual_batches']: - column=next(c for c in inspector.get_columns(name) if c['name']=='deleted_at') - assert column['nullable'] - assert 'visual_shared_assets' in inspector.get_table_names() - from app.schema import check_schema_revision - check_schema_revision(connection,{'004'}) + assert connection.scalar(text("SELECT version_num FROM alembic_version")) == "004" + assert connection.execute( + text("SELECT name,size_bytes,library_scope FROM visual_assets WHERE id='asset'") + ).one() == ("Original", 123, "private") + assert ( + connection.scalar(text("SELECT password_hash FROM visual_users WHERE id='owner'")) + == "UNCHANGED" + ) + inspector = inspect(connection) + for name in ["visual_jobs", "visual_drafts", "visual_workflow_runs", "visual_batches"]: + column = next(c for c in inspector.get_columns(name) if c["name"] == "deleted_at") + assert column["nullable"] + assert "visual_shared_assets" in inspector.get_table_names() + # 历史 004 行为由上方断言保留;当前 metadata 在全部增量升级后校验。 + command.upgrade(config, "head") + with engine.begin() as connection: + from app.core.schema import schema_preflight + from app.models import Base + assert schema_preflight(connection, Base.metadata).matches + def test_v4_reruns_after_partial_ddl(tmp_path): - config=Config(str(Path(__file__).parents[1]/'alembic.ini')) - path=tmp_path/'partial-v4.sqlite';config.attributes['url']='sqlite+aiosqlite:///'+str(path) - command.upgrade(config,'003');engine=create_engine('sqlite:///'+str(path)) + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + path = tmp_path / "partial-v4.sqlite" + config.attributes["url"] = "sqlite+aiosqlite:///" + str(path) + command.upgrade(config, "003") + engine = create_engine("sqlite:///" + str(path)) with engine.begin() as connection: connection.execute(text("ALTER TABLE visual_jobs ADD COLUMN deleted_at DATETIME NULL")) - connection.execute(text("ALTER TABLE visual_assets ADD COLUMN library_scope VARCHAR(16) NOT NULL DEFAULT 'private'")) - command.upgrade(config,'head') + connection.execute( + text( + "ALTER TABLE visual_assets ADD COLUMN library_scope VARCHAR(16) NOT NULL DEFAULT 'private'" + ) + ) + command.upgrade(config, "004") with engine.begin() as connection: - assert connection.scalar(text('SELECT version_num FROM alembic_version'))=='004' + assert connection.scalar(text("SELECT version_num FROM alembic_version")) == "004" diff --git a/backend/tests/test_schema_v5.py b/backend/tests/test_schema_v5.py new file mode 100644 index 0000000..21eb620 --- /dev/null +++ b/backend/tests/test_schema_v5.py @@ -0,0 +1,38 @@ +from pathlib import Path +from alembic import command +from alembic.config import Config +from sqlalchemy import create_engine, text, inspect + + +def test_v5_is_additive_and_matches_runtime_metadata(tmp_path): + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + path = tmp_path / "story-migration.sqlite" + config.attributes["url"] = "sqlite+aiosqlite:///" + str(path) + command.upgrade(config, "004") + engine = create_engine("sqlite:///" + str(path)) + with engine.begin() as connection: + before = { + t: inspect(connection).get_columns(t) + for t in inspect(connection).get_table_names() + if t != "alembic_version" + } + command.upgrade(config, "005") + command.upgrade(config, "005") + with engine.begin() as connection: + assert connection.scalar(text("SELECT version_num FROM alembic_version")) == "005" + assert set(inspect(connection).get_table_names()) == set(before) | { + "alembic_version", + "visual_shot_candidates", + "visual_shot_selections", + } + for name, columns in before.items(): + assert [(c["name"], str(c["type"]), c["nullable"]) for c in columns] == [ + (c["name"], str(c["type"]), c["nullable"]) + for c in inspect(connection).get_columns(name) + ] + from app.core.schema import check_schema_revision + + # 历史升级断言仍验证 005;运行时 metadata 则在新增 006 后校验。 + command.upgrade(config, "head") + with engine.begin() as connection: + check_schema_revision(connection, {"007"}) diff --git a/backend/tests/test_schema_v6.py b/backend/tests/test_schema_v6.py new file mode 100644 index 0000000..846d6e8 --- /dev/null +++ b/backend/tests/test_schema_v6.py @@ -0,0 +1,42 @@ +from pathlib import Path +from alembic import command +from alembic.config import Config +from sqlalchemy import create_engine, text, inspect +from app.models import Base +from app.core.schema import schema_preflight, check_schema_revision + + +def test_v6_preserves_005_assets_and_metadata(tmp_path): + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + path = tmp_path / "folders.sqlite" + config.attributes["url"] = "sqlite+aiosqlite:///" + str(path) + command.upgrade(config, "005") + engine = create_engine("sqlite:///" + str(path)) + with engine.begin() as connection: + connection.execute( + text( + "INSERT INTO visual_users(id,username,display_name,password_hash,role,disabled,must_change_password,created_at) VALUES('owner','owner','Owner','UNCHANGED','user',0,0,CURRENT_TIMESTAMP)" + ) + ) + connection.execute( + text( + "INSERT INTO visual_assets(id,owner_id,name,storage_key,kind,mime_type,size_bytes,sha256,tags,favorite,origin,ready,library_scope,created_at) VALUES('asset','owner','Original','owner/asset/source.png','image','image/png',123,:sha,'[]',0,'upload',1,'private',CURRENT_TIMESTAMP)" + ), + {"sha": "0" * 64}, + ) + command.upgrade(config, "006") + command.upgrade(config, "head") + with engine.begin() as connection: + assert connection.execute(text("SELECT id,storage_key FROM visual_assets")).one() == ( + "asset", + "owner/asset/source.png", + ) + assert connection.scalar(text("SELECT COUNT(*) FROM visual_asset_folders")) == 0 + diff = schema_preflight(connection, Base.metadata) + assert diff.matches, diff.differences + check_schema_revision(connection, {"007"}) + for table in ("visual_jobs", "visual_drafts", "visual_workflow_runs"): + fks = inspect(connection).get_foreign_keys(table) + folder_fks = [f for f in fks if f["referred_table"] == "visual_folders"] + assert folder_fks + assert all(f["options"]["ondelete"] == "SET NULL" for f in folder_fks) diff --git a/backend/tests/test_schema_v7.py b/backend/tests/test_schema_v7.py new file mode 100644 index 0000000..e15b123 --- /dev/null +++ b/backend/tests/test_schema_v7.py @@ -0,0 +1,41 @@ +from pathlib import Path +from alembic import command +from alembic.config import Config +from sqlalchemy import create_engine, text +from app.core.schema import check_schema_revision + + +def test_007_preserves_legacy_run_and_adds_nullable_editor_fields(tmp_path): + config = Config(str(Path(__file__).parents[1] / "alembic.ini")) + path = tmp_path / "editor.sqlite" + config.attributes["url"] = "sqlite+aiosqlite:///" + str(path) + command.upgrade(config, "006") + engine = create_engine("sqlite:///" + str(path)) + try: + with engine.begin() as c: + c.execute( + text( + "INSERT INTO visual_users(id,username,display_name,password_hash,role,disabled,must_change_password,created_at) VALUES('owner','owner','Owner','unchanged','user',0,0,CURRENT_TIMESTAMP)" + ) + ) + c.execute( + text( + "INSERT INTO visual_drafts(id,owner_id,name,kind,spec,revision,version,created_at,updated_at) VALUES('draft','owner','Legacy','three_shot','{}',1,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)" + ) + ) + c.execute( + text( + "INSERT INTO visual_workflow_runs(id,owner_id,draft_id,draft_revision,spec_snapshot,spec_hash,execution_mode,state,desired_state,hold_reasons,version,created_at) VALUES('run','owner','draft',1,'{}','hash','interactive','succeeded','run','[]',1,CURRENT_TIMESTAMP)" + ) + ) + command.upgrade(config, "007") + command.upgrade(config, "head") + with engine.begin() as c: + check_schema_revision(c, {"007"}) + assert c.execute( + text("SELECT run_kind,output_goal,result_manifest FROM visual_workflow_runs") + ).one() == ("legacy", "film", None) + assert c.scalar(text("SELECT editor_manifest FROM visual_drafts")) is None + assert c.scalar(text("SELECT password_hash FROM visual_users")) == "unchanged" + finally: + engine.dispose() diff --git a/backend/tests/test_shared_assets.py b/backend/tests/test_shared_assets.py index 3929b38..b04b1d9 100644 --- a/backend/tests/test_shared_assets.py +++ b/backend/tests/test_shared_assets.py @@ -2,7 +2,7 @@ from datetime import timedelta import httpx from app.models import Asset, utcnow -from app.retention import collect_garbage +from app.services.retention import collect_garbage async def upload(client, png_bytes, name="reference.png"): @@ -17,15 +17,21 @@ async def publish(client, asset_id, **kwargs): return result.json() -async def test_publication_snapshot_and_import_have_independent_files(system, other_client, png_bytes): +async def test_publication_snapshot_and_import_have_independent_files( + system, other_client, png_bytes +): source = await upload(system.client, png_bytes) await system.client.patch(f"/api/assets/{source['id']}", json={"tags": ["reference"]}) shared = await publish(system.client, source["id"]) assert shared["is_owner"] is True assert not {"source_asset_id", "asset_id", "source_job_id", "storage_key"} & shared.keys() assert (await publish(system.client, source["id"]))["id"] == shared["id"] - await system.client.patch(f"/api/assets/{source['id']}", json={"name": "renamed.png", "tags": []}) - visible = (await other_client.get("/api/shared-assets?tag=reference&q=reference&kind=image")).json() + await system.client.patch( + f"/api/assets/{source['id']}", json={"name": "renamed.png", "tags": []} + ) + visible = ( + await other_client.get("/api/shared-assets?tag=reference&q=reference&kind=image") + ).json() assert visible["total"] == 1 and visible["items"][0]["name"] == "reference.png" assert visible["items"][0]["is_owner"] is False assert (await other_client.get("/api/shared-assets?mine=true")).json()["total"] == 0 @@ -34,14 +40,17 @@ async def test_publication_snapshot_and_import_have_independent_files(system, ot imported = imported.json() assert imported["origin"] == "shared" and imported["source_job_id"] is None assert imported["tags"] == ["reference"] and imported["id"] != source["id"] - from app.v2_models import SharedAsset + from app.models import SharedAsset + async with system.app.state.db.session() as session: publication = await session.get(SharedAsset, shared["id"]) original = await session.get(Asset, source["id"]) snapshot = await session.get(Asset, publication.asset_id) private = await session.get(Asset, imported["id"]) paths = [system.settings.asset_root / a.storage_key for a in (original, snapshot, private)] - thumbs = [system.settings.asset_root / a.thumbnail_key for a in (original, snapshot, private)] + thumbs = [ + system.settings.asset_root / a.thumbnail_key for a in (original, snapshot, private) + ] assert len(set(paths)) == len(set(thumbs)) == 3 assert snapshot.library_scope == "shared" and private.library_scope == "private" snapshot_thumbnail = thumbs[1].read_bytes() @@ -52,47 +61,75 @@ async def test_publication_snapshot_and_import_have_independent_files(system, ot assert (await system.client.get("/api/assets")).json()["total"] == 1 for client in (system.client, other_client): for suffix in ("", "/content", "/thumbnail"): - assert (await client.get(f"/api/assets/{publication.asset_id}{suffix}")).status_code == 404 + assert ( + await client.get(f"/api/assets/{publication.asset_id}{suffix}") + ).status_code == 404 assert (await system.client.delete(f"/api/assets/{source['id']}")).status_code == 204 - paths[0].unlink() - thumbs[0].unlink() + assert not paths[0].exists() and not thumbs[0].exists() assert (await other_client.get(shared["preview_url"])).content == png_bytes assert (await other_client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404 assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 204 - assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 204 + assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404 assert (await other_client.get(shared["preview_url"])).status_code == 404 assert (await other_client.post(f"/api/shared-assets/{shared['id']}/import")).status_code == 404 - paths[1].unlink() - thumbs[1].unlink() + assert not paths[1].exists() and not thumbs[1].exists() assert (await other_client.get(imported["preview_url"])).content == png_bytes assert (await other_client.get(imported["thumbnail_url"])).status_code == 200 - accepted = await other_client.post("/api/jobs", json={"task_type": "defect.generate", - "input": {"prompt": "scratch", "image_asset_id": imported["id"]}}) + accepted = await other_client.post( + "/api/jobs", + json={ + "task_type": "defect.generate", + "input": {"prompt": "scratch", "image_asset_id": imported["id"]}, + }, + ) assert accepted.status_code == 202, accepted.text -async def test_shared_assets_require_auth_and_reject_private_ids_for_jobs(system, other_client, png_bytes): +async def test_shared_assets_require_auth_and_reject_private_ids_for_jobs( + system, other_client, png_bytes +): source = await upload(system.client, png_bytes) shared = await publish(system.client, source["id"]) - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as anonymous: + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as anonymous: for path in ("/api/shared-assets", shared["preview_url"], shared["thumbnail_url"]): assert (await anonymous.get(path)).status_code == 401 - assert (await anonymous.post(f"/api/shared-assets/{shared['id']}/import")).status_code == 401 + assert ( + await anonymous.post(f"/api/shared-assets/{shared['id']}/import") + ).status_code == 401 assert (await other_client.post(f"/api/assets/{source['id']}/publish")).status_code == 404 - from app.v2_models import SharedAsset + from app.models import SharedAsset + async with system.app.state.db.session() as session: hidden_id = (await session.get(SharedAsset, shared["id"])).asset_id - for client, asset_id in ((other_client, source["id"]), (other_client, shared["id"]), - (other_client, hidden_id), (system.client, hidden_id)): - result = await client.post("/api/jobs", json={"task_type": "defect.generate", - "input": {"prompt": "scratch", "image_asset_id": asset_id}}) + for client, asset_id in ( + (other_client, source["id"]), + (other_client, shared["id"]), + (other_client, hidden_id), + (system.client, hidden_id), + ): + result = await client.post( + "/api/jobs", + json={ + "task_type": "defect.generate", + "input": {"prompt": "scratch", "image_asset_id": asset_id}, + }, + ) assert result.status_code == 404, result.text ranged = await other_client.get(shared["preview_url"], headers={"Range": "bytes=0-7"}) assert ranged.status_code == 206 and ranged.content == png_bytes[:8] assert ranged.headers["cache-control"] == "private, no-store" - token = (await other_client.post("/api/auth/tokens", json={"name": "reader", "scopes": ["assets:read"]})).json()["token"] - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test", - headers={"Authorization": "Bearer " + token}) as machine: + token = ( + await other_client.post( + "/api/auth/tokens", json={"name": "reader", "scopes": ["assets:read"]} + ) + ).json()["token"] + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + token}, + ) as machine: assert (await machine.get(shared["preview_url"])).content == png_bytes assert (await machine.post(f"/api/shared-assets/{shared['id']}/import")).status_code == 403 @@ -115,26 +152,54 @@ async def test_copy_quota_failure_does_not_create_assets_or_files(system, other_ assert set(system.settings.asset_root.rglob("original*")) == before -async def test_copy_idempotency_preserves_original_result_and_rejects_path_payloads(system, other_client, png_bytes): +async def test_copy_idempotency_preserves_original_result_and_rejects_path_payloads( + system, other_client, png_bytes +): source = await upload(system.client, png_bytes) - published = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"}) - assert (await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"}))["id"] == published["id"] + published = await publish( + system.client, source["id"], headers={"Idempotency-Key": "publication"} + ) + assert (await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"}))[ + "id" + ] == published["id"] another = await upload(system.client, png_bytes, "another.png") - assert (await system.client.post(f"/api/assets/{another['id']}/publish", headers={"Idempotency-Key": "publication"})).status_code == 409 + assert ( + await system.client.post( + f"/api/assets/{another['id']}/publish", headers={"Idempotency-Key": "publication"} + ) + ).status_code == 409 headers = {"Idempotency-Key": "import"} first = await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers) assert first.status_code == 201, first.text - assert (await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers)).json()["id"] == first.json()["id"] + assert ( + await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers) + ).json()["id"] == first.json()["id"] assert (await other_client.get("/api/assets")).json()["total"] == 1 - assert (await other_client.post(f"/api/shared-assets/{published['id']}/import", json={"path": "../../outside"})).status_code == 422 - assert (await system.client.post(f"/api/assets/{another['id']}/publish", json={"storage_key": "/etc/passwd"})).status_code == 422 + assert ( + await other_client.post( + f"/api/shared-assets/{published['id']}/import", json={"path": "../../outside"} + ) + ).status_code == 422 + assert ( + await system.client.post( + f"/api/assets/{another['id']}/publish", json={"storage_key": "/etc/passwd"} + ) + ).status_code == 422 await other_client.delete(f"/api/assets/{first.json()['id']}") - assert (await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers)).status_code == 410 + assert ( + await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers) + ).status_code == 410 await system.client.delete(f"/api/shared-assets/{published['id']}") - assert (await system.client.post(f"/api/assets/{source['id']}/publish", headers={"Idempotency-Key": "publication"})).status_code == 410 + assert ( + await system.client.post( + f"/api/assets/{source['id']}/publish", headers={"Idempotency-Key": "publication"} + ) + ).status_code == 410 -async def test_import_replay_survives_withdrawal_but_fresh_import_does_not(system, other_client, png_bytes): +async def test_import_replay_survives_withdrawal_but_fresh_import_does_not( + system, other_client, png_bytes +): source = await upload(system.client, png_bytes) shared = await publish(system.client, source["id"]) path = f"/api/shared-assets/{shared['id']}/import" @@ -146,11 +211,14 @@ async def test_import_replay_survives_withdrawal_but_fresh_import_does_not(syste assert (await other_client.post(path)).status_code == 404 -async def test_private_deletion_purges_import_recovery_and_preserves_publication_recovery(system, other_client, png_bytes): +async def test_private_deletion_purges_import_recovery_and_preserves_publication_recovery( + system, other_client, png_bytes +): source = await upload(system.client, png_bytes) shared = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"}) - imported = await other_client.post(f"/api/shared-assets/{shared['id']}/import", - headers={"Idempotency-Key": "import"}) + imported = await other_client.post( + f"/api/shared-assets/{shared['id']}/import", headers={"Idempotency-Key": "import"} + ) assert imported.status_code == 201, imported.text publication_recovery = "/api/submissions/publication?operation=assets.publish" import_recovery = "/api/submissions/import?operation=shared.import" @@ -165,22 +233,33 @@ async def test_private_deletion_purges_import_recovery_and_preserves_publication assert (await other_client.get(shared["preview_url"])).content == png_bytes -async def test_withdrawal_purges_all_publication_keys_and_preserves_independent_import_recovery(system, other_client, png_bytes): +async def test_withdrawal_purges_all_publication_keys_and_preserves_independent_import_recovery( + system, other_client, png_bytes +): source = await upload(system.client, png_bytes) - shared = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication-a"}) + shared = await publish( + system.client, source["id"], headers={"Idempotency-Key": "publication-a"} + ) same = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication-b"}) assert same["id"] == shared["id"] - imported = await other_client.post(f"/api/shared-assets/{shared['id']}/import", - headers={"Idempotency-Key": "independent-import"}) + imported = await other_client.post( + f"/api/shared-assets/{shared['id']}/import", + headers={"Idempotency-Key": "independent-import"}, + ) assert imported.status_code == 201, imported.text - own_import = await system.client.post(f"/api/shared-assets/{shared['id']}/import", - headers={"Idempotency-Key": "own-import"}) + own_import = await system.client.post( + f"/api/shared-assets/{shared['id']}/import", headers={"Idempotency-Key": "own-import"} + ) assert own_import.status_code == 201, own_import.text assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 204 for key in ("publication-a", "publication-b"): - assert (await system.client.get(f"/api/submissions/{key}?operation=assets.publish")).status_code == 410 - for client, key, asset in ((other_client, "independent-import", imported.json()), - (system.client, "own-import", own_import.json())): + assert ( + await system.client.get(f"/api/submissions/{key}?operation=assets.publish") + ).status_code == 410 + for client, key, asset in ( + (other_client, "independent-import", imported.json()), + (system.client, "own-import", own_import.json()), + ): recovery = await client.get(f"/api/submissions/{key}?operation=shared.import") assert recovery.status_code == 200 and recovery.json()["status"] == "accepted" assert recovery.json()["asset_id"] == asset["id"] @@ -191,7 +270,8 @@ async def test_retention_protects_active_publications_even_without_reference_row source = await upload(system.client, png_bytes) shared = await publish(system.client, source["id"]) from sqlalchemy import delete - from app.v2_models import AssetReference, SharedAsset + from app.models import AssetReference, SharedAsset + async with system.app.state.db.session() as session: publication = await session.get(SharedAsset, shared["id"]) snapshot = await session.get(Asset, publication.asset_id) @@ -215,18 +295,23 @@ async def test_forged_source_storage_path_is_not_copied(system, png_bytes, tmp_p async def test_physical_gc_releases_quota_only_after_files_are_removed(system, png_bytes): - response = await system.client.post("/api/assets", files={"file": ("reference.png", png_bytes, "image/png")}) + response = await system.client.post( + "/api/assets", files={"file": ("reference.png", png_bytes, "image/png")} + ) assert response.status_code == 201, response.text asset_id = response.json()["id"] system.settings.max_owner_asset_bytes = int(response.request.headers["content-length"]) - await system.client.delete(f"/api/assets/{asset_id}") async with system.app.state.db.session() as session: asset = await session.get(Asset, asset_id) + # Legacy soft-deleted rows still need the maintenance-only GC. New + # API deletes remove their files and row immediately. asset.deleted_at = utcnow() - timedelta(days=30) original = system.settings.asset_root / asset.storage_key await session.commit() assert asset_id in (await collect_garbage(system.app.state.db, system.settings))["candidates"] - blocked = await system.client.post("/api/assets", files={"file": ("reference.png", png_bytes, "image/png")}) + blocked = await system.client.post( + "/api/assets", files={"file": ("reference.png", png_bytes, "image/png")} + ) assert blocked.status_code == 429, blocked.text assert original.exists() maintenance = system.settings.state_root / "maintenance" @@ -238,5 +323,7 @@ async def test_physical_gc_releases_quota_only_after_files_are_removed(system, p assert asset_id in report["deleted"] and not original.exists() async with system.app.state.db.session() as session: assert (await session.get(Asset, asset_id)).ready is False - retry = await system.client.post("/api/assets", files={"file": ("reference.png", png_bytes, "image/png")}) + retry = await system.client.post( + "/api/assets", files={"file": ("reference.png", png_bytes, "image/png")} + ) assert retry.status_code == 201, retry.text diff --git a/backend/tests/test_shutdown_waiters.py b/backend/tests/test_shutdown_waiters.py index 9adfde6..ce2f37e 100644 --- a/backend/tests/test_shutdown_waiters.py +++ b/backend/tests/test_shutdown_waiters.py @@ -1,25 +1,29 @@ import asyncio from app.models import Job + async def test_shutdown_preserves_cpu_waiter_that_never_started_provider(system): - system.settings.tts_base_url='http://test-tts' - system.provider.cpu_wait=True - ids=[] - for prompt in ('first','second'): - response=await system.client.post('/api/jobs',json={'task_type':'audio.speech','input':{'prompt':prompt}}) - assert response.status_code==202 - ids.append(response.json()['jobs'][0]['id']) - coordinator=system.app.state.coordinator + system.settings.tts_base_url = "http://test-tts" + system.provider.cpu_wait = True + ids = [] + for prompt in ("first", "second"): + response = await system.client.post( + "/api/jobs", json={"task_type": "audio.speech", "input": {"prompt": prompt}} + ) + assert response.status_code == 202 + ids.append(response.json()["jobs"][0]["id"]) + coordinator = system.app.state.coordinator await coordinator.run_once(force=True) for _ in range(100): async with system.app.state.db.session() as session: - waiter=await session.get(Job,ids[1]) - if waiter.work_attempt and system.provider.cpu_runs==1:break - await asyncio.sleep(.01) + waiter = await session.get(Job, ids[1]) + if waiter.work_attempt and system.provider.cpu_runs == 1: + break + await asyncio.sleep(0.01) assert waiter.current_execution_id is None await coordinator.close() async with system.app.state.db.session() as session: - waiter=await session.get(Job,ids[1]) - assert waiter.state=='queued' and waiter.error_json is None + waiter = await session.get(Job, ids[1]) + assert waiter.state == "queued" and waiter.error_json is None assert waiter.current_execution_id is None - assert system.provider.cpu_runs==1 + assert system.provider.cpu_runs == 1 diff --git a/backend/tests/test_story_provider.py b/backend/tests/test_story_provider.py new file mode 100644 index 0000000..cc856d8 --- /dev/null +++ b/backend/tests/test_story_provider.py @@ -0,0 +1,186 @@ +"""真实文件/HTTP边界覆盖故事多图与CPU首帧,测试不加载GPU模型。""" + +from hashlib import sha256 + +import httpx +from PIL import Image +import pytest + +from app.adapters.provider.client import Provider +from app.adapters.provider.contracts import capabilities, validate_arguments +from app.core.config import Settings +from app.domain.errors import MediaError +from app.domain.tasks import CPU_TYPES, GPU_TYPES + + +@pytest.fixture +def configuration(tmp_path): + settings = Settings( + mode="test", + database_url="sqlite+aiosqlite:///:memory:", + workspace_root=tmp_path, + inference_api_key_file=None, + ) + settings.asset_root.mkdir(parents=True) + settings.job_work_root.mkdir(parents=True) + for name in ("attempt", "missing", "contain", "cover"): + (settings.job_work_root / name).mkdir() + return settings + + +def test_story_tasks_registered_but_reference_is_not_advertised_before_certification(configuration): + assert "image.reference.generate" in GPU_TYPES + assert "image.prepare_frame" in CPU_TYPES + info = {item["task_type"]: item for item in capabilities(configuration)} + assert info["image.reference.generate"]["available"] is False + assert info["image.reference.generate"]["defaults"]["profile"] == "qwen-image-edit-2511-v1" + assert info["image.reference.generate"]["constraints"]["max_reference_images"] == 3 + assert info["image.prepare_frame"]["available"] is True + with pytest.raises(MediaError): + validate_arguments( + "image.reference.generate", + {"prompt": "hello", "reference_asset_ids": ["a"]}, + {}, + configuration, + ) + + +@pytest.mark.asyncio +async def test_reference_uploads_all_images_in_order_and_has_separate_cfg(configuration): + configuration.reference_generation_enabled = True + configuration.inference_remote_files = True + files = {} + for name, color in (("first", "red"), ("second", "blue")): + path = configuration.asset_root / (name + ".png") + Image.new("RGB", (64, 48), color).save(path) + files[name] = path + uploads = [] + + def handle(request): + if request.url.path == "/capabilities": + return httpx.Response( + 200, + json={ + "reference_generation": { + "available": True, + "profile": "qwen-image-edit-2511-v1", + "max_reference_images": 3, + } + }, + ) + digest = sha256(request.content).hexdigest() + uploads.append(digest) + return httpx.Response( + 201, + json={ + "path": "/workspace/inputs/llm-services/" + digest + ".png", + "sha256": digest, + "size_bytes": len(request.content), + }, + ) + + provider = Provider(configuration) + await provider.client.aclose() + provider.client = httpx.AsyncClient(transport=httpx.MockTransport(handle)) + try: + payload = await provider.prepare_gpu_payload( + "image.reference.generate", + { + "prompt": "keep first character in second scene", + "reference_asset_ids": ["second", "first"], + }, + {}, + files, + configuration.job_work_root / "attempt", + ) + assert uploads == [ + sha256(files[name].read_bytes()).hexdigest() for name in ("second", "first") + ] + assert payload["input"]["image_paths"] == [ + "/workspace/inputs/llm-services/" + digest + ".png" for digest in uploads + ] + assert payload["parameters"]["guidance_scale"] == 1.0 + assert payload["parameters"]["true_cfg_scale"] == 4.0 + assert (payload["parameters"]["width"], payload["parameters"]["height"]) == (1280, 704) + uploads.clear() + with pytest.raises(MediaError): + await provider.prepare_gpu_payload( + "image.reference.generate", + {"prompt": "test", "reference_asset_ids": ["first", "missing"]}, + {}, + files, + configuration.job_work_root / "missing", + ) + assert uploads == [] # 缺一张不能部分提交或降级文生图。 + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "remote", + [ + {}, + {"available": False}, + {"available": True, "profile": "qwen-image-edit-2509-v1", "max_reference_images": 3}, + {"available": True, "profile": "qwen-image-edit-2511-v1", "max_reference_images": 0}, + ], +) +async def test_upstream_must_certify_the_same_profile_before_upload(configuration, remote): + configuration.reference_generation_enabled = True + provider = Provider(configuration) + await provider.client.aclose() + provider.client = httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: httpx.Response(200, json={"reference_generation": remote}) + ) + ) + try: + with pytest.raises(MediaError) as error: + await provider.prepare_gpu_payload( + "image.reference.generate", + {"prompt": "a", "reference_asset_ids": ["missing"]}, + {}, + {}, + configuration.job_work_root / "attempt", + ) + assert error.value.code == "capability_unavailable" + finally: + await provider.aclose() + + +@pytest.mark.parametrize("ids", [[], ["a"] * 4, "a", [1], ["a", ""]]) +def test_reference_rejects_missing_invalid_and_excess_images(configuration, ids): + configuration.reference_generation_enabled = True + with pytest.raises(MediaError): + validate_arguments( + "image.reference.generate", + {"prompt": "x", "reference_asset_ids": ids}, + {}, + configuration, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fit", ["contain", "cover"]) +async def test_prepare_frame_writes_new_exact_rgb_image_without_changing_source(configuration, fit): + source = configuration.asset_root / "source.png" + Image.new("RGBA", (20, 40), (255, 0, 0, 128)).save(source) + original = source.read_bytes() + provider = Provider(configuration) + try: + result = await provider.run_cpu( + "image.prepare_frame", + {"image_asset_id": "source"}, + {"width": 1280, "height": 704, "fit": fit}, + {"source": source}, + configuration.job_work_root / fit, + ) + assert result.outputs[0] != source + with Image.open(result.outputs[0]) as output: + assert output.size == (1280, 704) + assert output.mode == "RGB" + assert result.metadata["fit"] == fit + assert source.read_bytes() == original + finally: + await provider.aclose() diff --git a/backend/tests/test_story_reference_bindings.py b/backend/tests/test_story_reference_bindings.py new file mode 100644 index 0000000..7c8bfe5 --- /dev/null +++ b/backend/tests/test_story_reference_bindings.py @@ -0,0 +1,310 @@ +"""参考图片编号必须与实际模型输入及稳定实体/形态引用对应。""" + +import copy +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + + +def referenced_spec(asset_ids): + scene, entity, appearance = asset_ids + return { + "schema_version": 3, + "scenes": [{"id": "2" * 32, "name": "Palace", "reference_asset_ids": [scene]}], + "entities": [ + { + "id": "3" * 32, + "name": "Mira", + "description": "Silver-haired guard", + "reference_asset_ids": [entity, scene], + "forms": [{"id": "4" * 32, "name": "Battle form", "reference_asset_ids": [scene]}], + "appearances": [ + {"id": "5" * 32, "name": "Red cloak", "reference_asset_ids": [appearance]} + ], + }, + { + "id": "7" * 32, + "name": "Mira", + "description": "Unselected impostor", + "reference_asset_ids": ["unused"], + }, + ], + "shots": [ + { + "id": "1" * 32, + "scene_id": "2" * 32, + "cast": [ + { + "id": "6" * 32, + "entity_id": "3" * 32, + "form_id": "4" * 32, + "appearance_id": "5" * 32, + } + ], + "visual_prompt": "Mira stands near the gate.", + } + ], + } + + +def test_compiled_reference_bindings_number_unique_images_scene_first_and_keep_all_roles(): + from app.domain.stories import compile_story + + assets = {id: {"sha256": id * 64} for id in "abc"} + shot = compile_story(referenced_spec(list("abc")), assets)["shots"][0] + lines = [line for line in shot["frame_prompt"].splitlines() if line.startswith("Picture ")] + assert len(lines) == 3 + assert ( + lines[0] + == 'Picture 1: scene "Scene 1 / Palace"; entity "Character 1 / Mira"; form "Character 1 / Mira / Battle form".' + ) + assert lines[1] == 'Picture 2: entity "Character 1 / Mira".' + assert lines[2] == 'Picture 3: appearance "Character 1 / Mira / Red cloak".' + assert [ref["asset_id"] for ref in shot["references"]] == ["a", "b", "a", "a", "c"] + assert "Unselected impostor" not in shot["frame_prompt"] + assert shot["errors"] == [] + + +def test_reference_bindings_resolve_stable_cast_ids_after_entity_and_shot_reordering(): + from app.domain.stories import compile_story + + spec = referenced_spec(list("abc")) + spec["shots"].append({"id": "8" * 32, "visual_prompt": "Another shot"}) + spec["scenes"].insert( + 0, {"id": "9" * 32, "name": "Unselected scene", "reference_asset_ids": ["unused"]} + ) + spec["entities"][0]["forms"].insert( + 0, {"id": "a" * 32, "name": "Unselected form", "reference_asset_ids": ["unused"]} + ) + spec["entities"][0]["appearances"].insert( + 0, {"id": "b" * 32, "name": "Unselected appearance", "reference_asset_ids": ["unused"]} + ) + assets = {id: {"sha256": id * 64} for id in "abc"} + before = compile_story(spec, assets)["shots"][0] + changed = copy.deepcopy(spec) + # @选择/按钮保存的是cast.entity_id,不能在同名实体或展示序号变化后改绑图片。 + changed["entities"].reverse() + changed["scenes"].reverse() + changed["entities"][1]["forms"].reverse() + changed["entities"][1]["appearances"].reverse() + changed["shots"].reverse() + after = next(s for s in compile_story(changed, assets)["shots"] if s["shot_id"] == "1" * 32) + assert after["frame_prompt"] == before["frame_prompt"] + assert after["context_hash"] == before["context_hash"] + assert 'Picture 3: appearance "Character 1 / Mira / Red cloak".' in after["frame_prompt"] + next(form for form in changed["entities"][1]["forms"] if form["id"] == "4" * 32)["name"] = ( + "Wolf form" + ) + renamed = next(s for s in compile_story(changed, assets)["shots"] if s["shot_id"] == "1" * 32) + assert 'form "Character 1 / Mira / Wolf form"' in renamed["frame_prompt"] + assert renamed["context_hash"] != before["context_hash"] + + +def test_no_reference_story_keeps_original_prompt_and_visual_hash(): + from app.domain.stories import compile_story, digest + + spec = {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "A tree"}]} + shot = compile_story(spec, {})["shots"][0] + assert shot["frame_prompt"] == "A tree" + assert shot["context_hash"] == digest( + { + "prompt": "A tree", + "settings": { + "era": "", + "style": "", + "palette": "", + "lighting": "", + "negative_prompt": "", + }, + "references": [], + "profile": "landscape_1080_v1", + } + ) + + +def test_same_named_cast_members_have_unique_aliases_for_description_position_and_picture_binding(): + from app.domain.stories import compile_story + + spec = { + "schema_version": 3, + "entities": [ + { + "id": "3" * 32, + "name": "Mira", + "description": "Silver-haired guard", + "reference_asset_ids": ["a"], + }, + { + "id": "7" * 32, + "name": "Mira", + "description": "Dark-haired scholar", + "reference_asset_ids": ["b"], + }, + { + "id": "9" * 32, + "name": "Mira", + "description": "Unselected impostor", + "reference_asset_ids": ["unused"], + }, + ], + "shots": [ + { + "id": "1" * 32, + "cast": [ + { + "id": "4" * 32, + "entity_id": "3" * 32, + "position": "on the left", + "action": "holds a lantern", + }, + { + "id": "8" * 32, + "entity_id": "7" * 32, + "position": "on the right", + "action": "waves", + }, + ], + "visual_prompt": "Both subjects face the camera.", + } + ], + } + for index, asset_id in enumerate("ab"): + variant_id = asset_id * 32 + spec["entities"][index]["forms"] = [ + { + "id": variant_id, + "name": "Wolf", + "description": "White fur" if index == 0 else "Black fur", + "reference_asset_ids": [asset_id], + } + ] + spec["shots"][0]["cast"][index]["form_id"] = variant_id + assets = {id: {"sha256": id * 64} for id in "ab"} + before = compile_story(spec, assets)["shots"][0] + prompt = before["frame_prompt"] + assert 'entity "Character 1 / Mira": Silver-haired guard' in prompt + assert 'entity "Character 2 / Mira": Dark-haired scholar' in prompt + assert '"Character 1 / Mira" position: on the left' in prompt + assert '"Character 2 / Mira" position: on the right' in prompt + assert '"Character 1 / Mira" action: holds a lantern' in prompt + assert 'form "Character 1 / Mira / Wolf": White fur' in prompt + assert 'form "Character 2 / Mira / Wolf": Black fur' in prompt + assert 'Picture 1: entity "Character 1 / Mira"; form "Character 1 / Mira / Wolf".' in prompt + assert 'Picture 2: entity "Character 2 / Mira"; form "Character 2 / Mira / Wolf".' in prompt + assert "Unselected impostor" not in prompt + reordered = copy.deepcopy(spec) + reordered["entities"].reverse() + reordered["entities"][0]["name"] = "Uncast renamed person" + after = compile_story(reordered, assets)["shots"][0] + assert after["frame_prompt"] == prompt and after["context_hash"] == before["context_hash"] + renamed = copy.deepcopy(spec) + renamed["entities"][1]["name"] = "Nora" + changed = compile_story(renamed, assets)["shots"][0] + assert ( + 'Picture 2: entity "Character 2 / Nora"; form "Character 2 / Nora / Wolf".' + in changed["frame_prompt"] + ) + assert changed["context_hash"] != before["context_hash"] + + +def test_repeated_cast_of_same_entity_reuses_alias_and_variant_parent_binding(): + from app.domain.stories import compile_story + + spec = referenced_spec(list("abc")) + spec["shots"][0]["cast"].append( + { + "id": "d" * 32, + "entity_id": "3" * 32, + "form_id": "4" * 32, + "position": "in the reflection", + } + ) + prompt = compile_story(spec, {id: {"sha256": id * 64} for id in "abc"})["shots"][0][ + "frame_prompt" + ] + assert "Character 2" not in prompt + assert '"Character 1 / Mira" position: in the reflection' in prompt + assert 'form "Character 1 / Mira / Battle form"' in prompt + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reference_mode", ["reference", "text"]) +async def test_candidate_prompt_binding_matches_preview_and_actual_provider_image_order( + system, png_bytes, monkeypatch, reference_mode +): + from app.adapters.provider.client import Provider + from app.models import Asset, ShotCandidate + + c = system.client + ids = [ + ( + await c.post("/api/assets", files={"file": (f"image-{i}.png", png_bytes, "image/png")}) + ).json()["id"] + for i in range(3) + ] + # 未出现实体的参考不属于此镜头,但仍须是可访问的故事基准素材。 + spec = referenced_spec(ids) + spec["entities"][1]["reference_asset_ids"] = [ids[2]] + d = (await c.post("/api/stories", json={"name": "Picture bindings", "spec": spec})).json() + path = f"/api/stories/{d['id']}" + preview = (await c.get(path + "/preview")).json()["shots"][0] + assert ( + 'Picture 1: scene "Scene 1 / Palace"; entity "Character 1 / Mira"; form "Character 1 / Mira / Battle form".' + in preview["frame_prompt"] + ) + assert 'Picture 3: appearance "Character 1 / Mira / Red cloak".' in preview["frame_prompt"] + caps = { + "reference_generation": { + "available": True, + "profile": system.settings.reference_generation_profile, + "max_reference_images": 3, + } + } + system.settings.reference_generation_enabled = True + monkeypatch.setattr( + system.provider, "upstream_capabilities", AsyncMock(return_value=caps), raising=False + ) + accepted = await c.post( + path + "/candidates", + headers={"Idempotency-Key": "bound"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "reference_mode": reference_mode, + }, + ) + assert accepted.status_code == 202, accepted.text + candidate = accepted.json()["candidates"][0] + expected_ids = ids if reference_mode == "reference" else [] + assert candidate["context_hash"] == preview["context_hash"] + assert candidate["input_summary"]["actual_reference_asset_ids"] == expected_ids + async with system.app.state.db.session() as s: + plan = (await s.get(ShotCandidate, candidate["id"])).plan_json + assets = { + id: system.settings.asset_root / (await s.get(Asset, id)).storage_key for id in ids + } + if reference_mode == "text": + assert "Picture " not in plan["input"]["prompt"] + assert "Silver-haired guard" in plan["input"]["prompt"] + assert plan["input"].get("reference_asset_ids", []) == [] + return + assert plan["input"]["prompt"] == preview["frame_prompt"] + assert plan["input"]["reference_asset_ids"] == ids + real = Provider(system.settings) + monkeypatch.setattr(real, "upstream_capabilities", AsyncMock(return_value=caps)) + try: + work = system.settings.job_work_root / "mapping-check" + work.mkdir(parents=True) + payload = await real.prepare_gpu_payload( + plan["task_type"], + plan["input"], + plan["parameters"], + assets, + work, + ) + assert payload["input"]["prompt"] == preview["frame_prompt"] + assert payload["input"]["image_paths"] == [str(assets[id]) for id in ids] + finally: + await real.aclose() diff --git a/backend/tests/test_story_render_policy.py b/backend/tests/test_story_render_policy.py new file mode 100644 index 0000000..c27002b --- /dev/null +++ b/backend/tests/test_story_render_policy.py @@ -0,0 +1,85 @@ +"""长镜头校验持有事务锁时,最终合成准入仍须读取真实且新鲜的远程策略。""" +import time + +import pytest +from sqlalchemy import func, select + +from test_story_studio import story_spec + + +@pytest.mark.asyncio +@pytest.mark.parametrize('refresh_result', ['ready', 'unavailable', 'invalid']) +async def test_render_refreshes_policy_after_slow_clip_validation(system, monkeypatch, refresh_result): + from app.domain.errors import MediaError + from app.models import Asset, QuotaReservation, ShotCandidate, ShotSelection, WorkflowDraft, WorkflowRun + from app.services.stories.common import current_hash + + c = system.client + created = await c.post('/api/stories', json={'name': 'Slow clip validation', 'spec': story_spec()}) + assert created.status_code == 201, created.text + draft = created.json() + owner = (await c.get('/api/auth/me')).json()['user']['id'] + async with system.app.state.db.session() as s: + d = await s.get(WorkflowDraft, draft['id']) + asset = Asset(owner_id=owner, name='approved.mp4', kind='video', mime_type='video/mp4', + storage_key='approved.mp4', size_bytes=3, sha256='a' * 64, + width=1920, height=1080, duration_seconds=5, ready=True) + s.add(asset) + await s.flush() + context = await current_hash(s, d, '1' * 32, 'video', source_kind='manual', source_sha256=asset.sha256) + candidate = ShotCandidate(owner_id=owner, draft_id=d.id, shot_id='1' * 32, kind='video', + source_kind='manual', asset_id=asset.id, asset_sha256=asset.sha256, + context_hash=context, generation_hash='b' * 64, + created_revision=1, state='ready') + s.add(candidate) + await s.flush() + s.add(ShotSelection(owner_id=owner, draft_id=d.id, shot_id='1' * 32, kind='video', + candidate_id=candidate.id, asset_id=asset.id, context_hash=context, + decision_json={'asset_sha256':asset.sha256, 'source_kind':'manual'})) + await s.commit() + + settings = system.settings + settings.inference_remote_files = True + settings._remote_policy_error = None + settings._remote_policy_observed_at = time.monotonic() + calls = [] + + async def slow_validation(*args, **kwargs): + # 模拟多片段真实解码耗时,不延长测试或修改事件循环的时钟。 + settings._remote_policy_observed_at = time.monotonic() - 6 + + async def refresh(): + calls.append('refresh') + if refresh_result == 'unavailable': + raise MediaError('upstream_unavailable', 'Unavailable', True) + settings._remote_policy_observed_at = time.monotonic() + settings._remote_policy_error = 'runtime_policy_invalid' if refresh_result == 'invalid' else None + return {'runtime_policy': {'configuration_error': settings._remote_policy_error}} + + monkeypatch.setattr('app.services.stories.api.validate_video', slow_validation) + monkeypatch.setattr(system.provider, 'runtime_status', refresh, raising=False) + path = f"/api/stories/{draft['id']}/renders" + headers = {'Idempotency-Key':'slow-render'} + body = {'expected_version':1, 'execution_mode':'interactive'} + response = await c.post(path, headers=headers, json=body) + assert calls == ['refresh'] + if refresh_result == 'ready': + assert response.status_code == 202, response.text + settings._remote_policy_observed_at = time.monotonic() - 6 + replay = await c.post(path, headers=headers, json=body) + assert replay.status_code == 202 and replay.json() == response.json() + assert calls == ['refresh'] # 已接纳结果重放不依赖外部服务再次可用。 + else: + assert response.status_code == 503, response.text + assert response.json()['detail']['code'] == 'runtime_policy_unavailable' + async with system.app.state.db.session() as s: + count = await s.scalar(select(func.count()).select_from(WorkflowRun)) + assert count == (1 if refresh_result == 'ready' else 0) + reservations = await s.scalar(select(func.count()).select_from(QuotaReservation).where( + QuotaReservation.operation == 'story.render')) + assert reservations == (1 if refresh_result == 'ready' else 0) + if refresh_result != 'ready': + refresh_result = 'ready' + recovered = await c.post(path, headers=headers, json=body) + assert recovered.status_code == 202, recovered.text + assert calls == ['refresh', 'refresh'] diff --git a/backend/tests/test_story_review_repairs.py b/backend/tests/test_story_review_repairs.py new file mode 100644 index 0000000..1f3b795 --- /dev/null +++ b/backend/tests/test_story_review_repairs.py @@ -0,0 +1,723 @@ +"""独立审查的可复现回归:引用生命周期、真实模型输入和共享接纳预算。""" + +import copy + +import httpx +import pytest +from sqlalchemy import select, func + +from test_story_studio import prepare_manual_frame, story_spec + + +@pytest.mark.asyncio +async def test_removed_shot_releases_selection_refs_without_losing_audit_or_other_refs( + system, monkeypatch +): + from app.models import AssetReference, ShotCandidate, ShotSelection, WorkflowDraft + + spec = story_spec() + spec["shots"].append({"id": "2" * 32, "visual_prompt": "A river"}) + c = system.client + d = (await c.post("/api/stories", json={"name": "Remove selected shot", "spec": spec})).json() + d, candidate, _ = await prepare_manual_frame(system, monkeypatch, d) + path = f"/api/stories/{d['id']}" + selected = await c.post( + path + "/selections", + headers={"Idempotency-Key": "select"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": candidate["id"], + }, + ) + assert selected.status_code == 200, selected.text + chosen = selected.json()["selections"][0] + actor = (await c.get("/api/auth/me")).json()["user"]["id"] + async with system.app.state.db.session() as s: + # 独立引用只用于断言PATCH不能笼统释放同素材的Run/候选/其他镜头保护。 + for kind, id in (("run", "historical-run"), ("selection", "other-shot-selection")): + s.add( + AssetReference( + owner_id=actor, asset_id=candidate["asset"]["id"], ref_kind=kind, ref_id=id + ) + ) + await s.commit() + changed = copy.deepcopy(selected.json()["spec"]) + changed["shots"].pop(0) + changed["render"]["total_frames"] = 120 + patched = await c.patch(path, headers={"If-Match": "2"}, json={"spec": changed}) + assert patched.status_code == 200, patched.text + # 即使客户端随后显式重加同一个稳定ID,也只能看见新的空选择,不能恢复旧审批。 + restored = await c.patch( + path, headers={"If-Match": "3"}, json={"spec": selected.json()["spec"]} + ) + assert restored.status_code == 200, restored.text + cleared = next( + x + for x in restored.json()["selections"] + if x["shot_id"] == "1" * 32 and x["kind"] == "frame" + ) + assert cleared["candidate_id"] is None and cleared["asset"] is None + assert cleared["version"] == chosen["version"] + 1 and cleared["id"] != chosen["id"] + await system.app.state.coordinator.run_once() + assert ( + next(x for x in (await c.get(path)).json()["selections"] if x["shot_id"] == "1" * 32)[ + "candidate_id" + ] + is None + ) + removed_again = await c.patch(path, headers={"If-Match": "4"}, json={"spec": changed}) + assert removed_again.status_code == 200 + async with system.app.state.db.session() as s: + refs = ( + await s.execute( + select(AssetReference.ref_kind, AssetReference.ref_id).where( + AssetReference.asset_id == candidate["asset"]["id"] + ) + ) + ).all() + assert ("selection", chosen["id"]) not in refs + assert ("candidate", candidate["id"]) in refs + assert ("run", "historical-run") in refs + assert ("selection", "other-shot-selection") in refs + approval = await s.get(ShotSelection, chosen["id"]) + assert ( + approval.candidate_id == candidate["id"] + and approval.asset_id == candidate["asset"]["id"] + ) + history = ( + await s.scalars( + select(ShotSelection) + .where( + ShotSelection.draft_id == d["id"], + ShotSelection.shot_id == "1" * 32, + ShotSelection.kind == "frame", + ) + .order_by(ShotSelection.version) + ) + ).all() + assert len(history) == 2 and history[-1].candidate_id is None + assert history[-1].decision_json["clear_reason"] == "shot_removed" + assert (await s.get(ShotCandidate, candidate["id"])).deleted_at is None + # 只撤掉本测试模拟的独立消费者,确认真实孤立产物此后可以释放。 + from sqlalchemy import delete + + await s.execute( + delete(AssetReference).where( + AssetReference.ref_id.in_(["historical-run", "other-shot-selection"]) + ) + ) + await s.commit() + deleted = await c.delete( + path + "/candidates/" + candidate["id"], headers={"If-Match": str(candidate["version"])} + ) + assert deleted.status_code == 200, deleted.text + assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 204 + # 已完成旧Job的再次协调也不能恢复被删镜头或可信选择。 + await system.app.state.coordinator.run_once() + current = (await c.get(path)).json() + assert [x["id"] for x in current["spec"]["shots"]] == ["2" * 32] + async with system.app.state.db.session() as s: + assert len((await s.get(WorkflowDraft, d["id"])).spec["shots"]) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("distinct", [False, True]) +async def test_reference_roles_preserved_but_model_inputs_are_ordered_unique( + system, png_bytes, monkeypatch, distinct +): + from app.models import ShotCandidate + from unittest.mock import AsyncMock + + c = system.client + assets = [ + ( + await c.post("/api/assets", files={"file": (f"ref-{i}.png", png_bytes, "image/png")}) + ).json()["id"] + for i in range(3) + ] + a, b, z = assets if distinct else [assets[0]] * 3 + spec = story_spec() + spec["scenes"] = [{"id": "2" * 32, "reference_asset_ids": [a]}] + spec["entities"] = [ + { + "id": "3" * 32, + "reference_asset_ids": [a, b] if distinct else [a], + "forms": [{"id": "4" * 32, "reference_asset_ids": [a]}], + "appearances": [ + {"id": "5" * 32, "reference_asset_ids": [b, z, a] if distinct else [a]} + ], + } + ] + spec["shots"][0].update( + scene_id="2" * 32, + cast=[ + {"id": "6" * 32, "entity_id": "3" * 32, "form_id": "4" * 32, "appearance_id": "5" * 32} + ], + ) + d = (await c.post("/api/stories", json={"name": "Reference roles", "spec": spec})).json() + path = f"/api/stories/{d['id']}" + preview = (await c.get(path + "/preview")).json()["shots"][0] + roles = preview["references"] + assert len(roles) == (7 if distinct else 4) + assert {x["role"] for x in roles} == {"scene", "entity", "form", "appearance"} + maximum = 3 if distinct else 1 + system.settings.reference_generation_enabled = True + system.settings.reference_max_images = maximum + monkeypatch.setattr( + system.provider, + "upstream_capabilities", + AsyncMock( + return_value={ + "reference_generation": { + "available": True, + "profile": system.settings.reference_generation_profile, + "max_reference_images": maximum, + } + } + ), + raising=False, + ) + response = await c.post( + path + "/candidates", + headers={"Idempotency-Key": "reference"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "reference_mode": "reference", + }, + ) + assert response.status_code == 202, response.text + candidate = response.json()["candidates"][0] + expected = [a, b, z] if distinct else [a] + assert candidate["input_summary"]["actual_reference_asset_ids"] == expected + async with system.app.state.db.session() as s: + plan = (await s.get(ShotCandidate, candidate["id"])).plan_json + assert plan["input"]["reference_asset_ids"] == expected + assert plan["input_snapshot"]["actual_image_refs"] == expected + assert plan["references"] == roles + assert candidate["context_hash"] == preview["context_hash"] + + +@pytest.mark.asyncio +async def test_workflow_machine_scopes_cover_story_commands_and_recovery(system): + c = system.client + made = await c.post( + "/api/auth/tokens", + json={ + "name": "Story machine", + "scopes": ["workflows:read", "workflows:write", "interactive:write"], + }, + ) + assert made.status_code == 201 + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + made.json()["token"]}, + ) as machine: + assert (await machine.get("/api/stories/capabilities")).status_code == 200 + created = await machine.post( + "/api/stories", json={"name": "Machine story", "spec": story_spec()} + ) + assert created.status_code == 201, created.text + d = created.json() + assert (await machine.get("/api/stories")).json()["total"] == 1 + path = f"/api/stories/{d['id']}" + accepted = await machine.post( + path + "/candidates", + headers={"Idempotency-Key": "machine-candidate"}, + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + ) + assert accepted.status_code == 202, accepted.text + recovered = await machine.get( + "/api/submissions/machine-candidate?operation=story.candidate.create" + ) + assert recovered.status_code == 200, recovered.text + assert recovered.json()["candidate_ids"] == [accepted.json()["candidates"][0]["id"]] + assert (await machine.get("/api/jobs")).status_code == 403 + + +@pytest.mark.asyncio +async def test_candidate_commands_share_creation_rate_and_replay_does_not_charge(system): + from app.models import QuotaReservation, ShotCandidate + from app.services.orchestration.workflow_engine import advance_workflows + + c = system.client + d = (await c.post("/api/stories", json={"name": "Rate", "spec": story_spec()})).json() + path = f"/api/stories/{d['id']}" + body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "count": 4} + system.settings.max_creation_commands_per_minute = 1 + first = await c.post(path + "/candidates", headers={"Idempotency-Key": "rate-one"}, json=body) + assert first.status_code == 202, first.text + assert ( + await c.post(path + "/candidates", headers={"Idempotency-Key": "rate-one"}, json=body) + ).json() == first.json() + blocked = await c.post(path + "/candidates", headers={"Idempotency-Key": "rate-two"}, json=body) + assert blocked.status_code == 429, blocked.text + assert ( + await c.post( + "/api/jobs", + headers={"Idempotency-Key": "legacy-next"}, + json={"task_type": "math.solve", "input": {"prompt": "2+2"}}, + ) + ).status_code == 429 + await advance_workflows(system.app.state.db, system.settings, system.provider) + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 4 + assert ( + await s.scalar( + select(func.count()) + .select_from(QuotaReservation) + .where(QuotaReservation.operation.like("story.%")) + ) + == 1 + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["single", "batch"]) +async def test_candidate_plans_cannot_bypass_parent_or_leaf_capacity(system, kind): + from app.models import ShotCandidate + + c = system.client + d = (await c.post("/api/stories", json={"name": "Bounded", "spec": story_spec()})).json() + path = f"/api/stories/{d['id']}" + ("/candidates" if kind == "single" else "/candidate-batches") + body = {"expected_version": 1, "kind": "frame", "count": 2} + body.update( + {"shot_id": "1" * 32} + if kind == "single" + else {"shot_ids": ["1" * 32], "execution_mode": "batch"} + ) + system.settings.max_owner_batches = 1 + system.settings.max_owner_jobs = 1 + system.settings.max_owner_story_candidates = 3 + first = await c.post(path, headers={"Idempotency-Key": "plan-one"}, json=body) + assert first.status_code == 202, first.text + second = await c.post(path, headers={"Idempotency-Key": "plan-two"}, json=body) + assert second.status_code == 429, second.text + system.settings.max_owner_batches = 10 + leaf_limited = await c.post(path, headers={"Idempotency-Key": "plan-three"}, json=body) + assert leaf_limited.status_code == 429, leaf_limited.text + assert ( + await c.post(path, headers={"Idempotency-Key": "plan-one"}, json=body) + ).status_code == 202 + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 2 + + +@pytest.mark.asyncio +async def test_running_candidate_batch_progress_changes_version_and_emits_event(system): + from app.models import BatchItem, Event, ShotCandidate + from app.services.orchestration.workflow_engine import advance_workflows + from app.services.stories.candidates import advance_candidate_batches + + c = system.client + d = (await c.post("/api/stories", json={"name": "Progress", "spec": story_spec()})).json() + response = await c.post( + f"/api/stories/{d['id']}/candidate-batches", + headers={"Idempotency-Key": "progress"}, + json={ + "expected_version": 1, + "shot_ids": ["1" * 32], + "kind": "frame", + "count": 2, + "execution_mode": "batch", + }, + ) + assert response.status_code == 202 + bid = response.json()["batch_id"] + await advance_workflows(system.app.state.db, system.settings, system.provider) + before = (await c.get("/api/batches/" + bid)).json()["batch"] + assert before["state"] == "running" and before["completed_items"] == 0 + async with system.app.state.db.session() as s: + rows = ( + await s.scalars( + select(ShotCandidate) + .where(ShotCandidate.batch_id == bid) + .order_by(ShotCandidate.id) + ) + ).all() + rows[0].state, rows[1].state = "ready", "running" + assert ( + await s.scalar(select(BatchItem).where(BatchItem.target_id == rows[0].id)) + ).state != "succeeded" + old_event = await s.scalar(select(func.max(Event.id))) + await advance_candidate_batches(s, system.settings) + await s.commit() + emitted = ( + await s.scalars( + select(Event).where(Event.id > old_event, Event.event_type == "batch.updated") + ) + ).all() + after = (await c.get("/api/batches/" + bid)).json()["batch"] + assert after["state"] == "running" and after["completed_items"] == 1 + assert after["version"] > before["version"] + assert len(emitted) == 1 and emitted[0].data["batch"]["completed_items"] == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["single", "batch", "retry", "render"]) +async def test_story_creation_zero_rate_rejects_new_intents_and_keeps_no_partial_records( + system, operation +): + from app.models import ShotCandidate, QuotaReservation + + c = system.client + d = (await c.post("/api/stories", json={"name": "Zero budget", "spec": story_spec()})).json() + path = f"/api/stories/{d['id']}" + body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"} + route = path + "/candidates" + previous = 0 + if operation == "retry": + accepted = await c.post(route, headers={"Idempotency-Key": "original"}, json=body) + assert accepted.status_code == 202 + cid = accepted.json()["candidates"][0]["id"] + async with system.app.state.db.session() as s: + (await s.get(ShotCandidate, cid)).state = "failed" + await s.commit() + route, body, previous = route + "/" + cid + "/retry", {"expected_version": 1}, 1 + elif operation == "batch": + route, body = ( + path + "/candidate-batches", + {"expected_version": 1, "shot_ids": ["1" * 32], "kind": "frame"}, + ) + elif operation == "render": + route, body = path + "/renders", {"expected_version": 1, "execution_mode": "interactive"} + system.settings.max_creation_commands_per_minute = 0 + rejected = await c.post(route, headers={"Idempotency-Key": "zero"}, json=body) + assert rejected.status_code == 429, rejected.text + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == previous + assert ( + await s.scalar( + select(func.count()) + .select_from(QuotaReservation) + .where(QuotaReservation.operation.like("story.%")) + ) + == previous + ) + + +def test_story_candidate_settings_limits_are_independent_and_environment_configurable( + monkeypatch, tmp_path +): + from app.core.config import Settings + + monkeypatch.setenv("CMVR_MODE", "test") + monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:") + monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path)) + monkeypatch.setenv("MAX_OWNER_STORY_CANDIDATES", "4200") + monkeypatch.setenv("MAX_GLOBAL_STORY_CANDIDATES", "17000") + settings = Settings.from_env() + assert settings.max_owner_story_candidates == 4200 + assert settings.max_global_story_candidates == 17000 + assert ( + Settings( + mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path + ).max_owner_story_candidates + == 4000 + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("shot_count", [126, 1000]) +async def test_large_candidate_plan_is_accepted_before_any_jobs_despite_active_job_limit( + system, monkeypatch, shot_count +): + from app.models import Job, ShotCandidate + + monkeypatch.setattr( + "app.services.stories.common.read_runtime_policy", + lambda settings: {"configuration_error": None, "workflow_max_shots": 1000}, + ) + system.settings.max_owner_jobs = 1 + system.settings.max_owner_batches = 1 + spec = { + "schema_version": 3, + "shots": [{"id": f"{i:032x}", "visual_prompt": "A tree"} for i in range(1, shot_count + 1)], + } + c = system.client + created = await c.post("/api/stories", json={"name": "Large plan", "spec": spec}) + assert created.status_code == 201, created.text + d = created.json() + response = await c.post( + f"/api/stories/{d['id']}/candidate-batches", + headers={"Idempotency-Key": "large-plan"}, + json={ + "expected_version": 1, + "shot_ids": [s["id"] for s in spec["shots"]], + "kind": "frame", + "count": 4, + "execution_mode": "batch", + }, + ) + assert response.status_code == 202, response.text + assert len(response.json()["candidates"]) == shot_count * 4 + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == shot_count * 4 + assert await s.scalar(select(func.count()).select_from(Job)) == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "visual_prompt,source_seconds,source_frames,duration_frames", + [("A tree", 5, 48, 24), ("", 5, 48, 24), ("A tree", 1, 360, 240), ("A tree", 5, 360, 240)], +) +async def test_manual_video_only_can_confirm_and_render_without_unused_frame_dependencies( + system, monkeypatch, visual_prompt, source_seconds, source_frames, duration_frames +): + import asyncio + import shutil + from app.adapters.media import run_process + from app.adapters.provider.client import Provider + from app.models import ShotSelection + + if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): + pytest.skip("FFmpeg and ffprobe required for manual video composition") + system.settings.ffmpeg_bin, system.settings.ffprobe_bin = ( + shutil.which("ffmpeg"), + shutil.which("ffprobe"), + ) + c = system.client + spec = story_spec() + spec["shots"][0]["visual_prompt"] = visual_prompt + spec["shots"][0]["video_parameters"] = {"source_seconds": source_seconds} + spec["shots"][0]["edit"] = {"start_frame": 24, "duration_frames": duration_frames} + created = await c.post("/api/stories", json={"name": "Manual video only", "spec": spec}) + assert created.status_code == 201, created.text + d = created.json() + path = f"/api/stories/{d['id']}" + source = system.settings.workspace_root / "manual-only.mp4" + await run_process( + [ + system.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=green:s=256x256:r=24", + "-frames:v", + str(source_frames), + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + str(source), + ] + ) + uploaded = await c.post( + "/api/assets", files={"file": ("manual.mp4", source.read_bytes(), "video/mp4")} + ) + assert uploaded.status_code == 201, uploaded.text + accepted = await c.post( + path + "/candidates", + headers={"Idempotency-Key": "manual-video"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "video", + "source_kind": "manual", + "asset_id": uploaded.json()["id"], + }, + ) + assert accepted.status_code == 202, accepted.text + candidate = accepted.json()["candidates"][0] + confirmed = await c.post( + path + "/selections", + headers={"Idempotency-Key": "select-video"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "video", + "candidate_id": candidate["id"], + }, + ) + assert confirmed.status_code == 200, confirmed.text + assert confirmed.json()["readiness"]["ready"], confirmed.json()["readiness"] + async with system.app.state.db.session() as s: + assert not await s.scalar( + select(ShotSelection.id).where( + ShotSelection.draft_id == d["id"], ShotSelection.kind == "frame" + ) + ) + # 人工片未使用Wan源长度/seed;修改这些参数或清除无关首帧不应使其过期。 + changed = confirmed.json()["spec"] + changed["shots"][0]["video_parameters"].update(source_seconds=15, seed=987) + patched = await c.patch(path, headers={"If-Match": "2"}, json={"spec": changed}) + assert patched.status_code == 200 and patched.json()["readiness"]["ready"] + cleared = await c.post( + path + "/selections/clear", + headers={"Idempotency-Key": "unused-frame"}, + json={"expected_version": 3, "shot_id": "1" * 32, "kind": "frame"}, + ) + assert cleared.status_code == 200 and cleared.json()["readiness"]["ready"] + after = (await c.get(path + "/candidates")).json()["items"][0] + assert not after["stale"] and after["context_hash"] == candidate["context_hash"] + rendered = await c.post( + path + "/renders", + headers={"Idempotency-Key": "render-manual"}, + json={"expected_version": 4, "execution_mode": "interactive"}, + ) + assert rendered.status_code == 202, rendered.text + real = Provider(system.settings) + monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) + try: + for _ in range(5): + await system.app.state.coordinator.run_once() + tasks = list(system.app.state.coordinator._cpu.values()) + if tasks: + await asyncio.gather(*tasks) + run = (await c.get("/api/workflow-runs/" + rendered.json()["run"]["id"])).json()["run"] + assert run["state"] == "succeeded" and run["result_assets"], run + changed["shots"][0]["motion_prompt"] = "Different action" + stale = await c.patch(path, headers={"If-Match": "5"}, json={"spec": changed}) + assert stale.status_code == 200 + video_selection = next(x for x in stale.json()["selections"] if x["kind"] == "video") + assert video_selection["stale"] + finally: + await real.aclose() + + +@pytest.mark.asyncio +async def test_generated_video_readiness_keeps_approved_frame_dependency(): + from types import SimpleNamespace + from app.domain.stories import StorySpecV3, compile_story + from app.models import Asset, ShotSelection + from app.services.stories.common import current_hash, readiness + + parsed = StorySpecV3.model_validate(story_spec()) + d = SimpleNamespace(id="story", owner_id="owner", spec=parsed.model_dump(mode="json")) + compiled = compile_story(parsed, {}) + assets = { + "frame": Asset( + id="frame", + owner_id="owner", + kind="image", + name="Frame", + mime_type="image/png", + size_bytes=1, + sha256="a" * 64, + ready=True, + ), + "video": Asset( + id="video", + owner_id="owner", + kind="video", + name="Video", + mime_type="video/mp4", + size_bytes=1, + sha256="b" * 64, + duration_seconds=5, + ready=True, + ), + } + + async def get(model, id): + return assets[id] + + s = SimpleNamespace(get=get) + frame = ShotSelection( + id="sf", + draft_id=d.id, + shot_id="1" * 32, + kind="frame", + candidate_id="cf", + asset_id="frame", + context_hash=compiled["shots"][0]["context_hash"], + decision_json={"asset_sha256": "a" * 64}, + version=1, + ) + latest = {("1" * 32, "frame"): frame} + video_hash = await current_hash(s, d, "1" * 32, "video", compiled, latest) + latest[("1" * 32, "video")] = ShotSelection( + id="sv", + draft_id=d.id, + shot_id="1" * 32, + kind="video", + candidate_id="cv", + asset_id="video", + context_hash=video_hash, + decision_json={"asset_sha256": "b" * 64, "source_kind": "generated"}, + version=1, + ) + assert (await readiness(s, d, compiled, latest))["ready"] + without_frame = {key: value for key, value in latest.items() if key[1] != "frame"} + unavailable = await readiness(s, d, compiled, without_frame) + assert not unavailable["ready"] + assert {issue["code"] for issue in unavailable["issues"]} == { + "frame_selection_required", + "video_selection_stale", + } + d.spec["shots"][0]["video_parameters"]["source_seconds"] = 15 + assert await current_hash(s, d, "1" * 32, "video", compiled, latest) != video_hash + + +@pytest.mark.asyncio +async def test_global_standalone_parent_and_pending_candidate_limits_include_other_owners( + system, other_client +): + c = system.client + system.settings.max_global_batches = 1 + system.settings.max_global_story_candidates = 3 + stories = [] + for client in (c, other_client): + response = await client.post("/api/stories", json={"name": "Private", "spec": story_spec()}) + assert response.status_code == 201 + stories.append(response.json()) + body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "count": 2} + first = await c.post( + f"/api/stories/{stories[0]['id']}/candidates", + headers={"Idempotency-Key": "first"}, + json=body, + ) + assert first.status_code == 202 + second_path = f"/api/stories/{stories[1]['id']}/candidates" + assert ( + await other_client.post( + second_path, headers={"Idempotency-Key": "global-parent"}, json=body + ) + ).status_code == 429 + system.settings.max_global_batches = 20 + assert ( + await other_client.post( + second_path, headers={"Idempotency-Key": "global-pending"}, json=body + ) + ).status_code == 429 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("source_seconds", [1, 5]) +async def test_generated_video_range_exceeding_generation_source_is_rejected_before_dispatch( + system, source_seconds +): + from app.models import Job, ShotCandidate + + spec = story_spec() + spec["shots"][0].update( + video_parameters={"source_seconds": source_seconds}, + edit={"start_frame": 24, "duration_frames": 240}, + ) + c = system.client + created = await c.post("/api/stories", json={"name": "Independent trim", "spec": spec}) + assert created.status_code == 201, created.text + d = created.json() + response = await c.post( + f"/api/stories/{d['id']}/candidates", + headers={"Idempotency-Key": "too-short"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "video", + "source_kind": "generated", + }, + ) + assert ( + response.status_code == 422 + and response.json()["detail"]["code"] == "generation_source_too_short" + ), response.text + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 0 + assert await s.scalar(select(func.count()).select_from(Job)) == 0 diff --git a/backend/tests/test_story_studio.py b/backend/tests/test_story_studio.py new file mode 100644 index 0000000..321e560 --- /dev/null +++ b/backend/tests/test_story_studio.py @@ -0,0 +1,650 @@ +import copy + +import pytest +from pydantic import ValidationError + + +def story_spec(): + return { + "schema_version": 3, + "shots": [{"id": "1" * 32, "name": "Shot", "visual_prompt": "A tree"}], + } + + +def test_v3_visual_hash_ignores_seed_trim_motion_and_order(): + from app.domain.stories import StorySpecV3, compile_story + + spec = StorySpecV3.model_validate(story_spec()) + before = compile_story(spec, {})["shots"][0] + changed = spec.model_dump(mode="json") + changed["shots"][0]["frame_parameters"]["seed"] = 99 + changed["shots"][0]["motion_prompt"] = "pan right" + changed["shots"][0]["edit"]["duration_frames"] = 24 + changed["render"]["total_frames"] = 24 + after = compile_story(StorySpecV3.model_validate(changed), {})["shots"][0] + assert before["context_hash"] == after["context_hash"] + changed["shots"][0]["visual_prompt"] = "A river" + assert ( + compile_story(StorySpecV3.model_validate(changed), {})["shots"][0]["context_hash"] + != before["context_hash"] + ) + + +def test_v3_rejects_forged_selection_and_dangling_cast(): + from app.domain.stories import StorySpecV3 + + forged = {**story_spec(), "selections": []} + with pytest.raises(ValidationError): + StorySpecV3.model_validate(forged) + spec = copy.deepcopy(story_spec()) + spec["shots"][0]["cast"] = [{"id": "2" * 32, "entity_id": "3" * 32}] + with pytest.raises(ValidationError): + StorySpecV3.model_validate(spec) + + +@pytest.mark.asyncio +async def test_story_crud_isolation_cas_and_no_legacy_leak(system, other_client): + c = system.client + response = await c.post("/api/stories", json={"name": "Story", "spec": story_spec()}) + assert response.status_code == 201, response.text + d = response.json() + assert d["kind"] == "story_v3" and d["selections"] == [] + assert not d["readiness"]["ready"] + assert (await other_client.get(f"/api/stories/{d['id']}")).status_code == 404 + assert all(x["id"] != d["id"] for x in (await c.get("/api/workflows")).json()["items"]) + path = f"/api/stories/{d['id']}" + assert ( + await c.patch(path, headers={"If-Match": "999"}, json={"name": "bad"}) + ).status_code == 409 + preview = (await c.get(path + "/preview")).json() + assert preview["shots"][0]["shot_id"] == "1" * 32 + assert preview["shots"][0]["context_hash"] + assert ( + await c.patch(path, headers={"If-Match": "1"}, json={"selections": []}) + ).status_code == 422 + + +@pytest.mark.asyncio +async def test_clear_is_append_only_idempotent_and_versioned(system): + c = system.client + d = (await c.post("/api/stories", json={"name": "Story", "spec": story_spec()})).json() + path = f"/api/stories/{d['id']}/selections/clear" + body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"} + response = await c.post(path, headers={"Idempotency-Key": "clear-1"}, json=body) + assert response.status_code == 200, response.text + first = response.json() + assert first["version"] == 2 and first["revision"] == 2 + assert first["selections"][0]["candidate_id"] is None + assert (await c.post(path, headers={"Idempotency-Key": "clear-1"}, json=body)).json() == first + body["expected_version"] = 2 + second = (await c.post(path, headers={"Idempotency-Key": "clear-2"}, json=body)).json() + assert second["selections"][0]["version"] == 2 + + +async def prepare_manual_frame(system, monkeypatch, story=None, key="manual"): + from app.adapters.provider.client import Provider + import asyncio + import io + from PIL import Image + + c = system.client + story = ( + story or (await c.post("/api/stories", json={"name": "Story", "spec": story_spec()})).json() + ) + content = io.BytesIO() + Image.new("RGB", (60, 30), "red").save(content, "PNG") + asset = ( + await c.post("/api/assets", files={"file": ("input.png", content.getvalue(), "image/png")}) + ).json() + response = await c.post( + f"/api/stories/{story['id']}/candidates", + headers={"Idempotency-Key": key}, + json={ + "expected_version": story["version"], + "shot_id": "1" * 32, + "kind": "frame", + "source_kind": "manual", + "asset_id": asset["id"], + }, + ) + assert response.status_code == 202, response.text + candidate = response.json()["candidates"][0] + assert candidate["state"] == "queued" and candidate["asset"] is None + real = Provider(system.settings) + monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) + try: + for _ in range(4): + await system.app.state.coordinator.run_once() + tasks = list(system.app.state.coordinator._cpu.values()) + if tasks: + await asyncio.gather(*tasks) + result = await c.get(f"/api/stories/{story['id']}/candidates") + assert result.status_code == 200, result.text + ready = result.json()["items"][0] + assert ready["state"] == "ready", ready + assert ready["asset"]["id"] != asset["id"] + assert (ready["asset"]["width"], ready["asset"]["height"]) == (1280, 704) + return story, ready, asset + finally: + await real.aclose() + + +@pytest.mark.asyncio +async def test_manual_frame_real_cpu_confirm_cas_refs_and_clear(system, monkeypatch, other_client): + story, candidate, source = await prepare_manual_frame(system, monkeypatch) + c = system.client + path = f"/api/stories/{story['id']}" + body = { + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": candidate["id"], + } + assert ( + await other_client.post( + path + "/selections", headers={"Idempotency-Key": "foreign"}, json=body + ) + ).status_code == 404 + first = await c.post(path + "/selections", headers={"Idempotency-Key": "confirm"}, json=body) + assert first.status_code == 200, first.text + assert first.json()["version"] == 2 + assert ( + await c.post(path + "/selections", headers={"Idempotency-Key": "late-window"}, json=body) + ).status_code == 409 + assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 409 + response = await c.delete( + path + "/candidates/" + candidate["id"], headers={"If-Match": str(candidate["version"])} + ) + assert response.status_code == 200, response.text + # 删除候选只释放候选引用,当前选择仍保护其素材。 + assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 409 + body.pop("candidate_id") + body["expected_version"] = 2 + cleared = await c.post( + path + "/selections/clear", headers={"Idempotency-Key": "clear"}, json=body + ) + assert cleared.status_code == 200 + assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 204 + + +@pytest.mark.asyncio +async def test_candidate_batch_lazy_feeder_seed_hash_and_stale(system): + from app.services.orchestration.workflow_engine import advance_workflows + from app.models import Job, ShotCandidate + from sqlalchemy import select, func + + c = system.client + system.settings.inference_base_url = "http://fake" + spec = story_spec() + spec["shots"] += [{"id": f"{i:032x}", "visual_prompt": "tree"} for i in range(2, 7)] + d = (await c.post("/api/stories", json={"name": "Batch", "spec": spec})).json() + response = await c.post( + f"/api/stories/{d['id']}/candidate-batches", + headers={"Idempotency-Key": "batch"}, + json={ + "expected_version": 1, + "shot_ids": [x["id"] for x in spec["shots"]], + "kind": "frame", + "count": 2, + "execution_mode": "batch", + }, + ) + assert response.status_code == 202, response.text + candidates = response.json()["candidates"] + assert len(candidates) == 12 and all(x["job_id"] is None for x in candidates) + assert candidates[0]["context_hash"] == candidates[1]["context_hash"] + assert candidates[0]["generation_hash"] != candidates[1]["generation_hash"] + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(Job)) == 0 + await advance_workflows(system.app.state.db, system.settings, system.provider) + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(Job)) == 8 + await advance_workflows(system.app.state.db, system.settings, system.provider) + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(Job)) == 12 + rows = (await s.scalars(select(ShotCandidate))).all() + assert all(x.job_id for x in rows) + + +@pytest.mark.asyncio +async def test_seed_and_trim_changes_preserve_frame_selection_visual_change_stales( + system, monkeypatch +): + d, candidate, _ = await prepare_manual_frame(system, monkeypatch) + c = system.client + path = f"/api/stories/{d['id']}" + spec = copy.deepcopy(d["spec"]) + spec["shots"][0]["frame_parameters"]["seed"] = 987 + spec["shots"][0]["edit"]["duration_frames"] = 24 + spec["render"]["total_frames"] = 24 + changed = await c.patch(path, headers={"If-Match": "1"}, json={"spec": spec}) + assert changed.status_code == 200, changed.text + selected = await c.post( + path + "/selections", + headers={"Idempotency-Key": "after-seed"}, + json={ + "expected_version": 2, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": candidate["id"], + }, + ) + assert selected.status_code == 200, selected.text + spec["shots"][0]["visual_prompt"] = "A river" + changed = await c.patch(path, headers={"If-Match": "3"}, json={"spec": spec}) + assert changed.status_code == 200 + assert changed.json()["selections"][0]["stale"] + + +@pytest.mark.asyncio +async def test_reference_unavailable_never_silently_generates_text(system, png_bytes): + c = system.client + a = (await c.post("/api/assets", files={"file": ("ref.png", png_bytes, "image/png")})).json() + spec = story_spec() + spec["entities"] = [{"id": "2" * 32, "name": "Person", "reference_asset_ids": [a["id"]]}] + spec["shots"][0]["cast"] = [{"id": "3" * 32, "entity_id": "2" * 32}] + d = (await c.post("/api/stories", json={"name": "Ref", "spec": spec})).json() + path = f"/api/stories/{d['id']}/candidates" + body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "source_kind": "generated"} + response = await c.post(path, headers={"Idempotency-Key": "ref-disabled"}, json=body) + assert ( + response.status_code == 503 + and response.json()["detail"]["code"] == "reference_generation_unavailable" + ) + system.settings.inference_base_url = "" + response = await c.post( + path, headers={"Idempotency-Key": "force-text"}, json={**body, "reference_mode": "text"} + ) + assert response.status_code == 503 # 文字服务也须真实可用,不能伪造能力。 + system.settings.inference_base_url = "http://fake" + response = await c.post( + path, headers={"Idempotency-Key": "explicit-text"}, json={**body, "reference_mode": "text"} + ) + assert response.status_code == 202, response.text + summary = response.json()["candidates"][0]["input_summary"] + assert summary["reference_mode"] == "text" and summary["actual_reference_asset_ids"] == [] + + +@pytest.mark.asyncio +async def test_deleting_shot_before_dispatch_does_not_recreate_it(system): + from app.services.orchestration.workflow_engine import advance_workflows + from app.models import Job + from sqlalchemy import select, func + + c = system.client + system.settings.inference_base_url = "http://fake" + spec = story_spec() + spec["shots"].append({"id": "2" * 32, "visual_prompt": "River"}) + d = (await c.post("/api/stories", json={"name": "Delete", "spec": spec})).json() + path = f"/api/stories/{d['id']}" + candidate = ( + await c.post( + path + "/candidates", + headers={"Idempotency-Key": "pending"}, + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + ) + ).json()["candidates"][0] + spec["shots"].pop(0) + assert (await c.patch(path, headers={"If-Match": "1"}, json={"spec": spec})).status_code == 200 + await advance_workflows(system.app.state.db, system.settings, system.provider) + row = (await c.get(path + "/candidates")).json()["items"][0] + assert row["id"] == candidate["id"] and row["stale"] and row["state"] == "failed" + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(Job)) == 0 + assert len((await c.get(path)).json()["spec"]["shots"]) == 1 + + +@pytest.mark.asyncio +async def test_story_cannot_be_mutated_or_started_through_legacy_workflow_api(system): + c = system.client + d = (await c.post("/api/stories", json={"name": "Story", "spec": story_spec()})).json() + path = f"/api/workflows/{d['id']}" + assert (await c.get(path)).status_code == 404 + assert ( + await c.patch(path, headers={"If-Match": "1"}, json={"name": "bypass"}) + ).status_code == 404 + assert (await c.delete(path, headers={"If-Match": "1"})).status_code == 404 + response = await c.post( + path + "/runs", + headers={"Idempotency-Key": "old-run"}, + json={"expected_version": 1, "draft_revision": 1}, + ) + assert response.status_code == 404 + + +@pytest.mark.asyncio +async def test_story_delete_releases_candidates_and_selection_refs(system, monkeypatch): + from sqlalchemy import select + from app.models import ShotCandidate, ShotSelection, AssetReference, Job + + d, candidate, source = await prepare_manual_frame(system, monkeypatch) + c = system.client + path = f"/api/stories/{d['id']}" + selected = await c.post( + path + "/selections", + headers={"Idempotency-Key": "select-delete"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": candidate["id"], + }, + ) + assert selected.status_code == 200 + deleted = await c.delete(path, headers={"If-Match": "2"}) + assert deleted.status_code == 200, deleted.text + assert (await c.get(path)).status_code == 404 + async with system.app.state.db.session() as s: + row = await s.get(ShotCandidate, candidate["id"]) + assert row.deleted_at is not None + assert (await s.get(Job, candidate["job_id"])).deleted_at is not None + selection_ids = select(ShotSelection.id).where(ShotSelection.draft_id == d["id"]) + assert not await s.scalar( + select(AssetReference.id).where( + AssetReference.ref_kind == "selection", AssetReference.ref_id.in_(selection_ids) + ) + ) + assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 204 + + +@pytest.mark.asyncio +async def test_manual_video_frozen_compose_history_and_nonzero_trim(system, monkeypatch): + import asyncio + from app.adapters.media import run_process, inspect_video_track + from app.adapters.provider.client import Provider + from app.models import Asset + import shutil + + if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): + pytest.skip("FFmpeg and ffprobe are required for the decoded video integration test") + system.settings.ffmpeg_bin = shutil.which("ffmpeg") + system.settings.ffprobe_bin = shutil.which("ffprobe") + + c = system.client + spec = story_spec() + spec["shots"][0]["edit"] = {"start_frame": 24, "duration_frames": 24} + spec["render"] = {"total_frames": 24} + d = (await c.post("/api/stories", json={"name": "Frozen", "spec": spec})).json() + d, frame, _ = await prepare_manual_frame(system, monkeypatch, d) + path = f"/api/stories/{d['id']}" + selected = await c.post( + path + "/selections", + headers={"Idempotency-Key": "frame"}, + json={ + "expected_version": 1, + "shot_id": "1" * 32, + "kind": "frame", + "candidate_id": frame["id"], + }, + ) + assert selected.status_code == 200 + video = system.settings.workspace_root / "source.mp4" + await run_process( + [ + system.settings.ffmpeg_bin, + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=256x256:r=24", + "-frames:v", + "48", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + str(video), + ] + ) + uploaded = await c.post( + "/api/assets", files={"file": ("source.mp4", video.read_bytes(), "video/mp4")} + ) + assert uploaded.status_code == 201, uploaded.text + candidate = await c.post( + path + "/candidates", + headers={"Idempotency-Key": "manual-video"}, + json={ + "expected_version": 2, + "shot_id": "1" * 32, + "kind": "video", + "source_kind": "manual", + "asset_id": uploaded.json()["id"], + }, + ) + assert candidate.status_code == 202, candidate.text + candidate = candidate.json()["candidates"][0] + assert candidate["state"] == "ready" and candidate["job_id"] is None + selected = await c.post( + path + "/selections", + headers={"Idempotency-Key": "video"}, + json={ + "expected_version": 2, + "shot_id": "1" * 32, + "kind": "video", + "candidate_id": candidate["id"], + }, + ) + assert selected.status_code == 200, selected.text + assert selected.json()["readiness"]["ready"] + # 已接纳的首帧/人工视频各扣一次,此次合成达到共享创建命令预算上限。 + system.settings.max_creation_commands_per_minute = 3 + response = await c.post( + path + "/renders", + headers={"Idempotency-Key": "render"}, + json={"expected_version": 3, "execution_mode": "interactive"}, + ) + assert response.status_code == 202, response.text + snap = response.json() + replay = await c.post( + path + "/renders", + headers={"Idempotency-Key": "render"}, + json={"expected_version": 3, "execution_mode": "interactive"}, + ) + assert replay.status_code == 202 and replay.json() == snap + blocked = await c.post( + path + "/renders", + headers={"Idempotency-Key": "render-second"}, + json={"expected_version": 4, "execution_mode": "interactive"}, + ) + assert blocked.status_code == 429 + assert [s["step_key"] for s in snap["steps"]] == ["compose"] + assert len(snap["run"]["render_inputs"]["selections"]) == 2 + assert snap["run"]["render_inputs"]["clips"][0]["start_frame"] == 24 + latest = (await c.get(path)).json() + changed = latest["spec"] + changed["shots"][0]["visual_prompt"] = "A different story" + assert ( + await c.patch(path, headers={"If-Match": str(latest["version"])}, json={"spec": changed}) + ).status_code == 200 + real = Provider(system.settings) + monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) + try: + for _ in range(5): + await system.app.state.coordinator.run_once() + tasks = list(system.app.state.coordinator._cpu.values()) + if tasks: + await asyncio.gather(*tasks) + current = (await c.get("/api/workflow-runs/" + snap["run"]["id"])).json() + assert current["draft"]["spec"]["shots"][0]["visual_prompt"] == "A tree" + assert current["run"]["state"] == "succeeded", current + output = current["run"]["result_assets"][0] + async with system.app.state.db.session() as s: + asset = await s.get(Asset, output["id"]) + track = await inspect_video_track( + system.settings.asset_root / asset.storage_key, system.settings + ) + assert track["frames"] == 24 and track["fps"] == 24 + assert (track["width"], track["height"]) == (1920, 1080) + finally: + await real.aclose() + + +def test_override_inheritance_and_only_selected_entity_references(): + from app.domain.stories import compile_story, StorySpecV3 + + spec = story_spec() + spec["context"] = {"lighting": "sunlight", "palette": "warm"} + spec["scenes"] = [{"id": "2" * 32, "lighting": "moonlight"}] + spec["entities"] = [{"id": "3" * 32, "name": "Unused", "reference_asset_ids": ["unused"]}] + spec["shots"][0].update(scene_id="2" * 32, overrides={"lighting": ""}) + parsed = StorySpecV3.model_validate(spec) + output = compile_story(parsed, {})["shots"][0] + assert output["effective_settings"]["lighting"] == "" + assert output["references"] == [] + assert parsed.model_dump()["shots"][0]["overrides"] == {"lighting": ""} + spec["shots"][0]["overrides"] = {} + assert compile_story(spec, {})["shots"][0]["effective_settings"]["lighting"] == "moonlight" + + +@pytest.mark.asyncio +async def test_retry_keeps_frozen_generation_input_and_never_selects_automatically(system): + from app.models import ShotCandidate, Job + from app.services.orchestration.workflow_engine import advance_workflows + + c = system.client + d = (await c.post("/api/stories", json={"name": "Retry", "spec": story_spec()})).json() + path = f"/api/stories/{d['id']}" + response = await c.post( + path + "/candidates", + headers={"Idempotency-Key": "candidate"}, + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + ) + assert response.status_code == 202, response.text + old = response.json()["candidates"][0] + await advance_workflows(system.app.state.db, system.settings, system.provider) + async with system.app.state.db.session() as s: + candidate = await s.get(ShotCandidate, old["id"]) + job = await s.get(Job, candidate.job_id) + job.state = "failed" + frozen = candidate.plan_json + await s.commit() + retry = await c.post( + path + "/candidates/" + old["id"] + "/retry", + headers={"Idempotency-Key": "retry"}, + json={"expected_version": 1}, + ) + assert retry.status_code == 202, retry.text + new = retry.json()["candidates"][0] + assert new["id"] != old["id"] and new["generation_hash"] == old["generation_hash"] + async with system.app.state.db.session() as s: + retried = (await s.get(ShotCandidate, new["id"])).plan_json + assert {k: v for k, v in retried.items() if k != "parent_plan_id"} == { + k: v for k, v in frozen.items() if k != "parent_plan_id" + } + assert retried["parent_plan_id"] != frozen["parent_plan_id"] + assert (await c.get(path)).json()["selections"] == [] + + +@pytest.mark.asyncio +async def test_cancel_undispatched_candidate_batch_is_terminal_and_emits_events(system): + from app.services.orchestration.workflow_engine import advance_workflows + from app.models import Event, Job + from sqlalchemy import select, func + + c = system.client + d = (await c.post("/api/stories", json={"name": "Cancel", "spec": story_spec()})).json() + response = await c.post( + f"/api/stories/{d['id']}/candidate-batches", + headers={"Idempotency-Key": "cancel-batch"}, + json={ + "expected_version": 1, + "shot_ids": ["1" * 32], + "kind": "frame", + "count": 2, + "execution_mode": "batch", + }, + ) + assert response.status_code == 202, response.text + bid = response.json()["batch_id"] + cancelled = await c.post( + "/api/batches/" + bid + "/control", + headers={"Idempotency-Key": "cancel"}, + json={"desired_state": "cancel"}, + ) + assert cancelled.status_code == 200 + await advance_workflows(system.app.state.db, system.settings, system.provider) + assert (await c.get("/api/batches/" + bid)).json()["batch"]["state"] == "cancelled" + candidates = (await c.get(f"/api/stories/{d['id']}/candidates")).json()["items"] + assert all(x["state"] == "failed" and x["error"]["code"] == "cancelled" for x in candidates) + async with system.app.state.db.session() as s: + assert await s.scalar(select(func.count()).select_from(Job)) == 0 + events = (await s.scalars(select(Event.event_type))).all() + assert ( + "story.updated" in events + and "candidate.updated" in events + and "batch.updated" in events + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("upscale", [False, True]) +async def test_candidate_video_validator_checks_native_and_enhanced_profiles( + system, monkeypatch, upscale +): + from app.services.assets import validate_workflow_output + from types import SimpleNamespace + from unittest.mock import AsyncMock + + p = dict( + num_frames=121, + width=1280, + height=704, + upscale=upscale, + upscale_width=1920, + upscale_height=1056, + ) + job = SimpleNamespace( + request_key="candidate:one", task_type="video.generate", run_id=None, parameters=p + ) + track = { + "frames": 121, + "fps": 24, + "width": 1920 if upscale else 1280, + "height": 1056 if upscale else 704, + } + mock = AsyncMock(return_value=track) + monkeypatch.setattr("app.adapters.media.inspect_video_track", mock) + await validate_workflow_output(job, "source.mp4", system.settings) + for invalid in ({**track, "fps": 25}, {**track, "frames": 119}, {**track, "width": 256}): + mock.return_value = invalid + with pytest.raises(ValueError): + await validate_workflow_output(job, "source.mp4", system.settings) + + +@pytest.mark.asyncio +async def test_candidate_retry_requires_confirmed_execution_cleanup(system): + from app.models import ShotCandidate, Job, Execution + from app.services.orchestration.workflow_engine import advance_workflows + + c = system.client + d = (await c.post("/api/stories", json={"name": "Cleanup", "spec": story_spec()})).json() + path = f"/api/stories/{d['id']}" + response = await c.post( + path + "/candidates", + headers={"Idempotency-Key": "candidate"}, + json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, + ) + cid = response.json()["candidates"][0]["id"] + await advance_workflows(system.app.state.db, system.settings, system.provider) + async with system.app.state.db.session() as s: + candidate = await s.get(ShotCandidate, cid) + job = await s.get(Job, candidate.job_id) + job.state = "failed" + s.add( + Execution( + job_id=job.id, + ordinal=1, + phase_key="execute", + resource_pool="new_gpu", + fence_token="fence", + state="running", + ) + ) + await s.commit() + retry = await c.post( + path + "/candidates/" + cid + "/retry", + headers={"Idempotency-Key": "retry"}, + json={"expected_version": 1}, + ) + assert retry.status_code == 409 and retry.json()["detail"]["code"] == "cleanup_pending" diff --git a/backend/tests/test_story_user_suspension.py b/backend/tests/test_story_user_suspension.py new file mode 100644 index 0000000..21952c0 --- /dev/null +++ b/backend/tests/test_story_user_suspension.py @@ -0,0 +1,121 @@ +import pytest +from sqlalchemy import func, select + +from app.models import Batch, Job, ShotCandidate, WorkflowDraft +from app.services.stories.candidates import feed_candidates + + +async def create_plan(system, client, *, batch): + system.settings.inference_base_url = "http://fake" + response = await client.post( + "/api/stories", + json={ + "name": "Suspended story", + "spec": { + "schema_version": 3, + "shots": [{"id": "1" * 32, "visual_prompt": "A tree"}], + }, + }, + ) + assert response.status_code == 201, response.text + draft = response.json() + body = {"expected_version": 1, "kind": "frame", "count": 2} + body.update( + {"shot_ids": ["1" * 32], "execution_mode": "batch"} if batch else {"shot_id": "1" * 32} + ) + response = await client.post( + f"/api/stories/{draft['id']}/" + ("candidate-batches" if batch else "candidates"), + headers={"Idempotency-Key": "suspended-plan"}, + json=body, + ) + assert response.status_code == 202, response.text + return draft, response.json() + + +async def tick(system): + async with system.app.state.db.session() as session: + await feed_candidates(session, system.settings) + await session.commit() + + +@pytest.mark.parametrize("batch", [False, True]) +async def test_disabled_owner_keeps_candidate_plan_and_enable_resumes(system, other_client, batch): + owner = (await other_client.get("/api/auth/me")).json()["user"] + draft, plan = await create_plan(system, other_client, batch=batch) + path = f"/api/auth/users/{owner['id']}" + response = await system.client.patch(path, json={"disabled": True}) + assert response.status_code == 200, response.text + + await tick(system) + async with system.app.state.db.session() as session: + candidates = (await session.scalars(select(ShotCandidate))).all() + assert len(candidates) == 2 + assert all(c.state == "queued" and c.job_id is None for c in candidates) + assert all(c.error_json is None and c.version == 1 for c in candidates) + assert {c.id: c.generation_hash for c in candidates} == { + c["id"]: c["generation_hash"] for c in plan["candidates"] + } + assert await session.scalar(select(func.count()).select_from(Job)) == 0 + assert await session.get(WorkflowDraft, draft["id"]) is not None + + response = await system.client.patch(path, json={"disabled": False}) + assert response.status_code == 200, response.text + await tick(system) + async with system.app.state.db.session() as session: + candidates = (await session.scalars(select(ShotCandidate))).all() + assert all(c.job_id is not None and c.error_json is None for c in candidates) + assert await session.scalar(select(func.count()).select_from(Job)) == 2 + + +@pytest.mark.parametrize("control", ["manual", "admin_suspend", "pause"]) +async def test_candidate_batch_controls_preserve_plan_until_released(system, control): + _, plan = await create_plan(system, system.client, batch=True) + async with system.app.state.db.session() as session: + batch = await session.get(Batch, plan["batch_id"]) + if control == "pause": + batch.desired_state = "pause" + else: + batch.hold_reasons = [control] + await session.commit() + + await tick(system) + async with system.app.state.db.session() as session: + assert await session.scalar(select(func.count()).select_from(Job)) == 0 + batch = await session.get(Batch, plan["batch_id"]) + assert batch.state == "paused" + assert batch.desired_state == ("pause" if control == "pause" else "run") + assert batch.hold_reasons == ([] if control == "pause" else [control]) + candidates = (await session.scalars(select(ShotCandidate))).all() + assert all(c.state == "queued" and c.error_json is None for c in candidates) + batch.desired_state = "run" + batch.hold_reasons = [] + await session.commit() + + await tick(system) + async with system.app.state.db.session() as session: + assert await session.scalar(select(func.count()).select_from(Job)) == 2 + + +@pytest.mark.parametrize("control", ["manual", "pause"]) +async def test_enable_keeps_candidate_batch_manual_control(system, other_client, control): + owner = (await other_client.get("/api/auth/me")).json()["user"] + _, plan = await create_plan(system, other_client, batch=True) + async with system.app.state.db.session() as session: + batch = await session.get(Batch, plan["batch_id"]) + if control == "pause": + batch.desired_state = "pause" + else: + batch.hold_reasons = ["manual"] + await session.commit() + + path = f"/api/auth/users/{owner['id']}" + assert (await system.client.patch(path, json={"disabled": True})).status_code == 200 + await tick(system) + assert (await system.client.patch(path, json={"disabled": False})).status_code == 200 + await tick(system) + async with system.app.state.db.session() as session: + assert await session.scalar(select(func.count()).select_from(Job)) == 0 + batch = await session.get(Batch, plan["batch_id"]) + assert batch.state == "paused" + assert batch.desired_state == ("pause" if control == "pause" else "run") + assert batch.hold_reasons == ([] if control == "pause" else ["manual"]) diff --git a/backend/tests/test_structure_phase_review.py b/backend/tests/test_structure_phase_review.py index 15b2db8..3c5f4ea 100644 --- a/backend/tests/test_structure_phase_review.py +++ b/backend/tests/test_structure_phase_review.py @@ -1,4 +1,5 @@ """Every visual request is a separate finish-current admission boundary.""" + import json import httpx @@ -7,36 +8,63 @@ from PIL import Image @pytest.mark.asyncio -@pytest.mark.parametrize('reason',['window_closed','explicit_cancel']) -async def test_structure_rechecks_admission_before_each_http_request(system,monkeypatch,reason): - from app import providers - provider=providers.Provider(system.settings) +@pytest.mark.parametrize("reason", ["window_closed", "explicit_cancel"]) +async def test_structure_rechecks_admission_before_each_http_request(system, monkeypatch, reason): + from app.adapters.provider import client as providers + from app.adapters.provider import qwen + + provider = providers.Provider(system.settings) await provider.client.aclose() - requests=[] + requests = [] + async def respond(request): requests.append(request) - return httpx.Response(200,json={'choices':[{'message':{'content':json.dumps( - {'scene':'frame','subjects':[],'ocr':[],'tags':[]})}}]}) - provider.client=httpx.AsyncClient(transport=httpx.MockTransport(respond)) - source=system.settings.asset_root/'video.mp4';source.write_bytes(b'video') - work=system.settings.job_work_root/'sample';work.mkdir() - async def inspect(*args):return {'kind':'video','duration_seconds':2} - async def extract(argv,**kwargs): - Image.new('RGB',(8,8),'red').save(argv[-1]) - return b'',b'pts_time:0.5' - monkeypatch.setattr(providers,'inspect_media',inspect) - monkeypatch.setattr(providers,'run_process',extract) - admissions=[] - async def gate(phase,pool): - admissions.append((phase,pool)) - if pool=='qwen_http' and requests:raise RuntimeError(reason) - token=providers.current_phase_callback.set(gate) + return httpx.Response( + 200, + json={ + "choices": [ + { + "message": { + "content": json.dumps( + {"scene": "frame", "subjects": [], "ocr": [], "tags": []} + ) + } + } + ] + }, + ) + + provider.client = httpx.AsyncClient(transport=httpx.MockTransport(respond)) + source = system.settings.asset_root / "video.mp4" + source.write_bytes(b"video") + work = system.settings.job_work_root / "sample" + work.mkdir() + + async def inspect(*args): + return {"kind": "video", "duration_seconds": 2} + + async def extract(argv, **kwargs): + Image.new("RGB", (8, 8), "red").save(argv[-1]) + return b"", b"pts_time:0.5" + + monkeypatch.setattr(qwen, "inspect_media", inspect) + monkeypatch.setattr(qwen, "run_process", extract) + admissions = [] + + async def gate(phase, pool): + admissions.append((phase, pool)) + if pool == "qwen_http" and requests: + raise RuntimeError(reason) + + token = providers.current_phase_callback.set(gate) try: - with pytest.raises(RuntimeError,match=reason): - await provider.run_cpu('media.structure',{'asset_id':'v'},{'frame_count':2},{'v':source},work) - assert len(requests)==1 - assert len([x for x in admissions if x[1]=='qwen_http'])==2 - assert not (work/'structure.json').exists() + with pytest.raises(RuntimeError, match=reason): + await provider.run_cpu( + "media.structure", {"asset_id": "v"}, {"frame_count": 2}, {"v": source}, work + ) + assert len(requests) == 1 + assert len([x for x in admissions if x[1] == "qwen_http"]) == 2 + assert not (work / "structure.json").exists() finally: providers.current_phase_callback.reset(token) await provider.aclose() diff --git a/backend/tests/test_timeline_v2.py b/backend/tests/test_timeline_v2.py index e06900b..e3f6432 100644 --- a/backend/tests/test_timeline_v2.py +++ b/backend/tests/test_timeline_v2.py @@ -1,112 +1,235 @@ import copy import pytest from pydantic import ValidationError -from app.timeline import WorkflowSpec, compile_timeline +from app.domain.timeline import WorkflowSpec, compile_timeline def spec(): - return {'shots': [{'key': f'shot_{i}', 'prompt': f'镜头{i}', 'parameters': {'seed': i}} for i in range(1,4)], 'profile': 'landscape_1080_v1'} + return { + "shots": [ + {"key": f"shot_{i}", "prompt": f"镜头{i}", "parameters": {"seed": i}} + for i in range(1, 4) + ], + "profile": "landscape_1080_v1", + } def test_exact_keys_and_unknown_fields(): - body = spec(); body['shots'][1]['key'] = 'shot_1' - with pytest.raises(ValidationError): WorkflowSpec.model_validate(body) - body = spec(); body['render'] = {'filter': 'movie=http://bad'} - with pytest.raises(ValidationError): WorkflowSpec.model_validate(body) - body = spec(); body['shots'][0]['parameters']['width'] = 256 - with pytest.raises(ValidationError): WorkflowSpec.model_validate(body) + body = spec() + body["shots"][1]["key"] = "shot_1" + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(body) + body = spec() + body["render"] = {"filter": "movie=http://bad"} + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(body) + body = spec() + body["shots"][0]["parameters"]["width"] = 256 + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(body) def test_freezes_profiles_and_frame_boundaries(): - body = spec(); body['render'] = {'subtitles': [{'start_frame':119, 'end_frame':241, 'text':'跨镜头'}]} + body = spec() + body["render"] = {"subtitles": [{"start_frame": 119, "end_frame": 241, "text": "跨镜头"}]} plan = compile_timeline(body, {}) - assert plan.generation_parameters['width'] == 1280 - assert plan.generation_parameters['upscale_height'] == 1056 - assert plan.canvas == (1920,1080) + assert plan.generation_parameters["width"] == 1280 + assert plan.generation_parameters["upscale_height"] == 1056 + assert plan.canvas == (1920, 1080) assert plan.frames == 360 and plan.clip_frames == 120 - body['profile'] = 'portrait_1080_v1' + body["profile"] = "portrait_1080_v1" plan = compile_timeline(body, {}) - assert plan.canvas == (1080,1920) - assert plan.generation_parameters['upscale_width'] == 1056 + assert plan.canvas == (1080, 1920) + assert plan.generation_parameters["upscale_width"] == 1056 -@pytest.mark.parametrize('offset,valid', [(120,True),(121,False)]) +@pytest.mark.parametrize("offset,valid", [(120, True), (121, False)]) def test_explicit_audio_cut_and_offset(offset, valid): - body = spec(); body['render'] = {'audio': {'asset_id':'audio','source_start_ms':0,'source_end_ms':10000,'offset_frame':offset,'short_policy':'silence'}} + body = spec() + body["render"] = { + "audio": { + "asset_id": "audio", + "source_start_ms": 0, + "source_end_ms": 10000, + "offset_frame": offset, + "short_policy": "silence", + } + } if valid: - compile_timeline(body, {'audio': {'kind':'audio','duration_seconds':10}}) + compile_timeline(body, {"audio": {"kind": "audio", "duration_seconds": 10}}) else: - with pytest.raises(ValidationError): WorkflowSpec.model_validate(body) + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(body) def test_audio_source_bounds_and_subtitle_controls(): - body = spec(); body['render'] = {'audio': {'asset_id':'audio','source_start_ms':3000,'source_end_ms':18000,'offset_frame':0}} - with pytest.raises(ValueError): compile_timeline(body, {'audio': {'kind':'audio','duration_seconds':17}}) - compile_timeline(body, {'audio': {'kind':'audio','duration_seconds':18}}) - body = spec(); body['render'] = {'subtitles':[{'start_frame':0,'end_frame':360,'text':r'{\an8}bad'}]} - with pytest.raises(ValidationError): WorkflowSpec.model_validate(body) + body = spec() + body["render"] = { + "audio": { + "asset_id": "audio", + "source_start_ms": 3000, + "source_end_ms": 18000, + "offset_frame": 0, + } + } + with pytest.raises(ValueError): + compile_timeline(body, {"audio": {"kind": "audio", "duration_seconds": 17}}) + compile_timeline(body, {"audio": {"kind": "audio", "duration_seconds": 18}}) + body = spec() + body["render"] = {"subtitles": [{"start_frame": 0, "end_frame": 360, "text": r"{\an8}bad"}]} + with pytest.raises(ValidationError): + WorkflowSpec.model_validate(body) + @pytest.mark.asyncio -async def test_media_short_source_rejected_before_encoding(tmp_path,monkeypatch): +async def test_media_short_source_rejected_before_encoding(tmp_path, monkeypatch): from types import SimpleNamespace - from app import media - from app.media import MediaError - plan=compile_timeline(spec(),{}) - paths=[] + from app.adapters import media + from app.adapters.media import MediaError + + plan = compile_timeline(spec(), {}) + paths = [] for i in range(3): - p=tmp_path/f'{i}.mp4';p.write_bytes(b'not decoded');paths.append(p) - async def inspect(*args):return {'frames':119,'fps':24,'width':1920,'height':1056,'duration':119/24} - monkeypatch.setattr(media,'inspect_video_track',inspect) - with pytest.raises(MediaError,match='120'): - await media.compose_workflow(plan,tmp_path/'work',None,settings=SimpleNamespace(workspace_root=tmp_path),sources=paths) + p = tmp_path / f"{i}.mp4" + p.write_bytes(b"not decoded") + paths.append(p) + + async def inspect(*args): + return {"frames": 119, "fps": 24, "width": 1920, "height": 1056, "duration": 119 / 24} + + monkeypatch.setattr(media, "inspect_video_track", inspect) + with pytest.raises(MediaError, match="120"): + await media.compose_workflow( + plan, + tmp_path / "work", + None, + settings=SimpleNamespace(workspace_root=tmp_path), + sources=paths, + ) + @pytest.mark.asyncio -async def test_media_fixed_frame_argv_and_audio_offset(tmp_path,monkeypatch): +async def test_media_fixed_frame_argv_and_audio_offset(tmp_path, monkeypatch): from types import SimpleNamespace - from app import media - body=spec();body['render']={'audio':{'asset_id':'audio','source_start_ms':3000,'source_end_ms':13000,'offset_frame':120},'subtitles':[{'start_frame':119,'end_frame':241,'text':'镜头'}]} - plan=compile_timeline(body,{'audio':{'kind':'audio','duration_seconds':13}}) - paths=[] + from app.adapters import media + + body = spec() + body["render"] = { + "audio": { + "asset_id": "audio", + "source_start_ms": 3000, + "source_end_ms": 13000, + "offset_frame": 120, + }, + "subtitles": [{"start_frame": 119, "end_frame": 241, "text": "镜头"}], + } + plan = compile_timeline(body, {"audio": {"kind": "audio", "duration_seconds": 13}}) + paths = [] for i in range(3): - p=tmp_path/f'{i}.mp4';p.write_bytes(b'x');paths.append(p) - audio=tmp_path/'audio.wav';audio.write_bytes(b'x');calls=[] - async def track(path,settings):return {'frames':360 if path.name=='workflow.mp4' else 121,'fps':24,'width':1920,'height':1080 if path.name=='workflow.mp4' else 1056,'duration':15} - async def inspect(*args):return {'kind':'audio','duration_seconds':13} - async def process(argv,**kwargs):calls.append(argv);__import__('pathlib').Path(argv[-1]).write_bytes(b'x');return b'' - monkeypatch.setattr(media,'inspect_video_track',track);monkeypatch.setattr(media,'inspect_media',inspect);monkeypatch.setattr(media,'run_process',process) - result=await media.compose_workflow(plan,tmp_path/'work',None,settings=SimpleNamespace(workspace_root=tmp_path,ffmpeg_bin='ffmpeg',max_output_bytes=1000000),sources=paths,audio=audio) - assert len(calls)==4 - assert all('120'==c[c.index('-frames:v')+1] for c in calls[:3]) - assert calls[-1][calls[-1].index('-frames:v')+1]=='360' - assert any('adelay=5000' in value and 'atrim=start=3.000:end=13.000' in value for value in calls[-1]) - assert result.result['frames']==360 + p = tmp_path / f"{i}.mp4" + p.write_bytes(b"x") + paths.append(p) + audio = tmp_path / "audio.wav" + audio.write_bytes(b"x") + calls = [] + + async def track(path, settings): + return { + "frames": 360 if path.name == "workflow.mp4" else 121, + "fps": 24, + "width": 1920, + "height": 1080 if path.name == "workflow.mp4" else 1056, + "duration": 15, + } + + async def inspect(*args): + return {"kind": "audio", "duration_seconds": 13} + + async def process(argv, **kwargs): + calls.append(argv) + __import__("pathlib").Path(argv[-1]).write_bytes(b"x") + return b"" + + monkeypatch.setattr(media, "inspect_video_track", track) + monkeypatch.setattr(media, "inspect_media", inspect) + monkeypatch.setattr(media, "run_process", process) + result = await media.compose_workflow( + plan, + tmp_path / "work", + None, + settings=SimpleNamespace( + workspace_root=tmp_path, ffmpeg_bin="ffmpeg", max_output_bytes=1000000 + ), + sources=paths, + audio=audio, + ) + assert len(calls) == 4 + assert all("120" == c[c.index("-frames:v") + 1] for c in calls[:3]) + assert calls[-1][calls[-1].index("-frames:v") + 1] == "360" + assert any( + "adelay=5000" in value and "atrim=start=3.000:end=13.000" in value for value in calls[-1] + ) + assert result.result["frames"] == 360 + @pytest.mark.asyncio -async def test_upstream_capabilities_cache_and_control_envelope(monkeypatch,tmp_path): +async def test_upstream_capabilities_cache_and_control_envelope(monkeypatch, tmp_path): from types import SimpleNamespace - from app.providers import Provider - p=Provider(SimpleNamespace(request_timeout_seconds=5,inference_base_url='http://inference',inference_api_key='')) - calls=[] - async def call(method,url,**kwargs): - calls.append((method,url,kwargs)) - return {'protocol_version':2,'features':{'scheduling':True,'admission_pause':True}} if method=='GET' else {'desired_state':'pause'} - monkeypatch.setattr(p,'_json',call) + from app.adapters.provider.client import Provider + + p = Provider( + SimpleNamespace( + request_timeout_seconds=5, inference_base_url="http://inference", inference_api_key="" + ) + ) + calls = [] + + async def call(method, url, **kwargs): + calls.append((method, url, kwargs)) + return ( + {"protocol_version": 2, "features": {"scheduling": True, "admission_pause": True}} + if method == "GET" + else {"desired_state": "pause"} + ) + + monkeypatch.setattr(p, "_json", call) try: - a=await p.upstream_capabilities();b=await p.upstream_capabilities() - assert a['admission_policy'] is True and a==b and len(calls)==1 - await p.control('a'*32,'pause','cmd-1',expected_version=2,expected_execution_id='e'*32) - assert calls[-1][0]=='PUT' and calls[-1][2]['payload']=={'desired_state':'pause','command_id':'cmd-1','expected_version':2,'expected_execution_id':'e'*32} - finally:await p.aclose() + a = await p.upstream_capabilities() + b = await p.upstream_capabilities() + assert a["admission_policy"] is True and a == b and len(calls) == 1 + await p.control( + "a" * 32, "pause", "cmd-1", expected_version=2, expected_execution_id="e" * 32 + ) + assert calls[-1][0] == "PUT" and calls[-1][2]["payload"] == { + "desired_state": "pause", + "command_id": "cmd-1", + "expected_version": 2, + "expected_execution_id": "e" * 32, + } + finally: + await p.aclose() + @pytest.mark.asyncio async def test_phase_callback_is_context_local(): import asyncio - from app.providers import current_phase_callback, enter_phase - seen=[] + from app.domain.execution import current_phase_callback, enter_phase + + seen = [] + async def one(name): - async def hook(key,pool):seen.append((name,key,pool)) - token=current_phase_callback.set(hook) - try:await asyncio.sleep(0);await enter_phase('sample_frames','cpu_media') - finally:current_phase_callback.reset(token) - await asyncio.gather(one('first'),one('second')) - assert sorted(seen)==[('first','sample_frames','cpu_media'),('second','sample_frames','cpu_media')] + async def hook(key, pool): + seen.append((name, key, pool)) + + token = current_phase_callback.set(hook) + try: + await asyncio.sleep(0) + await enter_phase("sample_frames", "cpu_media") + finally: + current_phase_callback.reset(token) + + await asyncio.gather(one("first"), one("second")) + assert sorted(seen) == [ + ("first", "sample_frames", "cpu_media"), + ("second", "sample_frames", "cpu_media"), + ] diff --git a/backend/tests/test_tokens_quotas.py b/backend/tests/test_tokens_quotas.py index 8befba7..3748c65 100644 --- a/backend/tests/test_tokens_quotas.py +++ b/backend/tests/test_tokens_quotas.py @@ -1,58 +1,99 @@ import httpx import pytest + @pytest.mark.asyncio -async def test_token_scope_owner_revoke_and_no_admin(system,other_client): - made=await other_client.post("/api/auth/tokens",json={"name":"reader","scopes":["jobs:read","assets:read"]}) - assert made.status_code==201 - token=made.json()["token"] - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app),base_url="http://test",headers={"Authorization":"Bearer "+token}) as machine: - assert (await machine.get("/api/jobs")).json()["total"]==0 - assert (await machine.get("/api/auth/users")).status_code==403 - assert (await machine.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})).status_code==403 - await other_client.delete("/api/auth/tokens/"+made.json()["record"]["id"]) - assert (await machine.get("/api/jobs")).status_code==401 - from app.v2_models import ApiToken +async def test_token_scope_owner_revoke_and_no_admin(system, other_client): + made = await other_client.post( + "/api/auth/tokens", json={"name": "reader", "scopes": ["jobs:read", "assets:read"]} + ) + assert made.status_code == 201 + token = made.json()["token"] + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + token}, + ) as machine: + assert (await machine.get("/api/jobs")).json()["total"] == 0 + assert (await machine.get("/api/auth/users")).status_code == 403 + assert ( + await machine.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "x"}} + ) + ).status_code == 403 + await other_client.delete("/api/auth/tokens/" + made.json()["record"]["id"]) + assert (await machine.get("/api/jobs")).status_code == 401 + from app.models import ApiToken from sqlalchemy import select + async with system.app.state.db.session() as session: - row=await session.scalar(select(ApiToken)) - assert row.token_hash!=token and not hasattr(row,"token") + row = await session.scalar(select(ApiToken)) + assert row.token_hash != token and not hasattr(row, "token") + @pytest.mark.asyncio async def test_quota_replay_does_not_charge_twice(system): - system.settings.max_owner_jobs=1 - body={"task_type":"image.generate","input":{"prompt":"x"}} - one=await system.client.post("/api/jobs",json=body,headers={"Idempotency-Key":"one"}) - assert one.status_code==202 - assert (await system.client.post("/api/jobs",json=body,headers={"Idempotency-Key":"one"})).status_code==202 - assert (await system.client.post("/api/jobs",json=body,headers={"Idempotency-Key":"two"})).status_code==429 + system.settings.max_owner_jobs = 1 + body = {"task_type": "image.generate", "input": {"prompt": "x"}} + one = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "one"}) + assert one.status_code == 202 + assert ( + await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "one"}) + ).status_code == 202 + assert ( + await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "two"}) + ).status_code == 429 @pytest.mark.asyncio async def test_workflow_read_only_token_can_recover_own_workflow_submission(system): - from app.v2_models import Submission - actor=(await system.client.get("/api/auth/me")).json()["user"] + from app.models import Submission + + actor = (await system.client.get("/api/auth/me")).json()["user"] async with system.app.state.db.session() as session: - session.add(Submission(owner_id=actor["id"],operation="workflows.run",key="run-key",payload_schema=2,body_hash="x",request_json={},resource_json={"run_id":"known"})) + session.add( + Submission( + owner_id=actor["id"], + operation="workflows.run", + key="run-key", + payload_schema=2, + body_hash="x", + request_json={}, + resource_json={"run_id": "known"}, + ) + ) await session.commit() - made=await system.client.post("/api/auth/tokens",json={"name":"workflow-reader","scopes":["workflows:read"]}) - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app),base_url="http://test",headers={"Authorization":"Bearer "+made.json()["token"]}) as machine: - r=await machine.get("/api/submissions/run-key?operation=workflows.run") - assert r.status_code==200 and r.json()["run_id"]=="known" - assert (await machine.get("/api/submissions/run-key?operation=jobs.create")).status_code==403 + made = await system.client.post( + "/api/auth/tokens", json={"name": "workflow-reader", "scopes": ["workflows:read"]} + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + made.json()["token"]}, + ) as machine: + r = await machine.get("/api/submissions/run-key?operation=workflows.run") + assert r.status_code == 200 and r.json()["run_id"] == "known" + assert ( + await machine.get("/api/submissions/run-key?operation=jobs.create") + ).status_code == 403 @pytest.mark.asyncio -async def test_storage_budget_includes_own_tmp_sibling(system,monkeypatch): +async def test_storage_budget_includes_own_tmp_sibling(system, monkeypatch): from types import SimpleNamespace from fastapi import HTTPException - from app import quotas - actor=(await system.client.get("/api/auth/me")).json()["user"] - temporary=system.settings.asset_root.parent/"tmp" + from app.services import quotas + + actor = (await system.client.get("/api/auth/me")).json()["user"] + temporary = system.settings.asset_root.parent / "tmp" temporary.mkdir(exist_ok=True) - (temporary/"encoded.part").write_bytes(b"abc") - system.settings.mode="production";system.settings.max_data_bytes=2 - monkeypatch.setattr(quotas.shutil,"disk_usage",lambda path:SimpleNamespace(total=10**12,free=10**12)) + (temporary / "encoded.part").write_bytes(b"abc") + system.settings.mode = "production" + system.settings.max_data_bytes = 2 + monkeypatch.setattr( + quotas.shutil, "disk_usage", lambda path: SimpleNamespace(total=10**12, free=10**12) + ) async with system.app.state.db.session() as session: - with pytest.raises(HTTPException) as caught:await quotas.check_storage_budget(session,system.settings,actor["id"]) - assert caught.value.detail["code"]=="storage_insufficient" + with pytest.raises(HTTPException) as caught: + await quotas.check_storage_budget(session, system.settings, actor["id"]) + assert caught.value.detail["code"] == "storage_insufficient" diff --git a/backend/tests/test_upload_guard.py b/backend/tests/test_upload_guard.py index 631d187..ce68bc3 100644 --- a/backend/tests/test_upload_guard.py +++ b/backend/tests/test_upload_guard.py @@ -2,49 +2,75 @@ import httpx import asyncio from types import SimpleNamespace + async def test_unauthenticated_upload_does_not_consume_or_parse_body(system): - consumed=[] + consumed = [] + async def body(): consumed.append(True) - yield b'x'*1024 - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app),base_url='http://test') as client: - response=await client.post('/api/assets',content=body(),headers={'Content-Type':'multipart/form-data; boundary=test'}) - assert response.status_code==401 - assert consumed==[] + yield b"x" * 1024 + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as client: + response = await client.post( + "/api/assets", + content=body(), + headers={"Content-Type": "multipart/form-data; boundary=test"}, + ) + assert response.status_code == 401 + assert consumed == [] -async def test_chunked_upload_is_bounded_before_multipart_parser(system,monkeypatch): +async def test_chunked_upload_is_bounded_before_multipart_parser(system, monkeypatch): from starlette.requests import Request - called=[] - original=Request._get_form - async def form(self,*args,**kwargs): - called.append(True) - return await original(self,*args,**kwargs) - monkeypatch.setattr(Request,'_get_form',form) - system.settings.max_upload_bytes=16 - async def body(): - for _ in range(18):yield b'x'*(64*1024) - response=await system.client.post('/api/assets',content=body(),headers={'Content-Type':'multipart/form-data; boundary=test'}) - assert response.status_code==413 - assert called==[] - assert list((system.settings.asset_root.parent/'tmp').glob('*'))==[] -async def test_two_owners_share_reserved_upload_capacity(system,other_client,monkeypatch): - system.settings.mode='production' - system.settings.max_data_bytes=127 - system.settings.min_free_bytes=0 - monkeypatch.setattr('app.quotas.shutil.disk_usage',lambda _:SimpleNamespace(total=1000,free=1000)) - entered,release=asyncio.Event(),asyncio.Event() + called = [] + original = Request._get_form + + async def form(self, *args, **kwargs): + called.append(True) + return await original(self, *args, **kwargs) + + monkeypatch.setattr(Request, "_get_form", form) + system.settings.max_upload_bytes = 16 + + async def body(): + for _ in range(18): + yield b"x" * (64 * 1024) + + response = await system.client.post( + "/api/assets", + content=body(), + headers={"Content-Type": "multipart/form-data; boundary=test"}, + ) + assert response.status_code == 413 + assert called == [] + assert list((system.settings.asset_root.parent / "tmp").glob("*")) == [] + + +async def test_two_owners_share_reserved_upload_capacity(system, other_client, monkeypatch): + system.settings.mode = "production" + system.settings.max_data_bytes = 127 + system.settings.min_free_bytes = 0 + monkeypatch.setattr( + "app.services.quotas.shutil.disk_usage", lambda _: SimpleNamespace(total=1000, free=1000) + ) + entered, release = asyncio.Event(), asyncio.Event() + async def held(): entered.set() await release.wait() - yield b'x'*32 - headers={'Content-Type':'multipart/form-data; boundary=test','Content-Length':'32'} - first=asyncio.create_task(system.client.post('/api/assets',content=held(),headers=headers)) + yield b"x" * 32 + + headers = {"Content-Type": "multipart/form-data; boundary=test", "Content-Length": "32"} + first = asyncio.create_task(system.client.post("/api/assets", content=held(), headers=headers)) try: - await asyncio.wait_for(entered.wait(),2) - second=await other_client.post('/api/assets',content=b'x'*32,headers=headers) - assert second.status_code==503 and second.json()['detail']['code']=='storage_insufficient' + await asyncio.wait_for(entered.wait(), 2) + second = await other_client.post("/api/assets", content=b"x" * 32, headers=headers) + assert ( + second.status_code == 503 and second.json()["detail"]["code"] == "storage_insufficient" + ) finally: release.set() await first diff --git a/backend/tests/test_user_deletion.py b/backend/tests/test_user_deletion.py new file mode 100644 index 0000000..98c84f1 --- /dev/null +++ b/backend/tests/test_user_deletion.py @@ -0,0 +1,429 @@ +"""管理员删除账号必须清理全部自有数据,并等待执行与上传停止。""" + +import asyncio +import io +import os +from pathlib import Path +from tempfile import TemporaryDirectory + +import httpx +import pytest +from sqlalchemy import select +from starlette.datastructures import UploadFile + +from app.core.security import Actor +from app.models import ( + ApiToken, + Asset, + AssetFolder, + AssetReference, + AssetTag, + Base, + Batch, + BatchItem, + Event, + Execution, + Folder, + Job, + JobAsset, + QuotaReservation, + Session, + SharedAsset, + ShotCandidate, + ShotSelection, + Submission, + User, + WorkflowDraft, + WorkflowRun, + WorkflowStep, +) +from conftest import PASSWORD + + +@pytest.fixture +def tmp_path(): + # 本模块覆盖pytest默认保留目录,隔离DB/媒体/锁文件在fixture退出时立即清理。 + with TemporaryDirectory(prefix="cmvr-user-deletion-") as directory: + yield Path(directory) + + +async def account(client): + return (await client.get("/api/auth/me")).json()["user"] + + +async def upload(client, png_bytes): + response = await client.post( + "/api/assets", files={"file": ("picture.png", png_bytes, "image/png")} + ) + assert response.status_code == 201, response.text + return response.json() + + +async def test_delete_user_requires_admin_session_csrf_and_forbids_self(system, other_client): + target = await account(other_client) + url = f"/api/auth/users/{target['id']}" + assert (await other_client.delete(url)).status_code == 403 + assert (await system.client.delete(url, headers={"X-CSRF-Token": "wrong"})).status_code == 403 + own = await account(system.client) + denied = await system.client.delete(f"/api/auth/users/{own['id']}") + assert denied.status_code == 409, denied.text + assert (await system.client.delete("/api/auth/users/missing")).status_code == 404 + + +async def test_delete_user_removes_complete_tree_and_preserves_other_import( + system, other_client, png_bytes +): + target = await account(other_client) + admin = await account(system.client) + owner = target["id"] + source = await upload(other_client, png_bytes) + shared = (await other_client.post(f"/api/assets/{source['id']}/publish")).json() + imported = await system.client.post(f"/api/shared-assets/{shared['id']}/import") + assert imported.status_code == 201, imported.text + imported_id = imported.json()["id"] + token = await other_client.post( + "/api/auth/tokens", json={"name": "machine", "scopes": ["jobs:read"]} + ) + assert token.status_code == 201, token.text + token_value = token.json()["token"] + async with system.app.state.db.session() as session: + folder = Folder(owner_id=owner, name="root") + session.add(folder) + await session.flush() + child = Folder(owner_id=owner, name="child", parent_id=folder.id, parent_key=folder.id) + draft = WorkflowDraft(owner_id=owner, name="story", kind="story_v3", spec={}) + batch = Batch(owner_id=owner, name="batch", state="succeeded") + session.add_all([child, draft, batch]) + await session.flush() + run = WorkflowRun( + owner_id=owner, + draft_id=draft.id, + draft_revision=1, + spec_hash="hash", + state="succeeded", + batch_id=batch.id, + ) + session.add(run) + await session.flush() + job = Job( + owner_id=owner, + task_type="image.generate", + state="succeeded", + phase="done", + input_json={}, + parameters={}, + request_hash="hash", + upstream_key="tree-job", + run_id=run.id, + batch_id=batch.id, + folder_id=child.id, + ) + session.add(job) + await session.flush() + job_id = job.id + source_row = await session.get(Asset, source["id"]) + source_row.source_job_id = job.id + session.add_all( + [ + AssetFolder(asset_id=source_row.id, folder_id=child.id), + JobAsset(job_id=job.id, asset_id=source_row.id), + AssetTag(owner_id=owner, asset_id=source_row.id, tag="mine"), + AssetReference( + owner_id=owner, asset_id=source_row.id, ref_kind="draft", ref_id=draft.id + ), + WorkflowStep( + run_id=run.id, + step_key="shot", + kind="image.generate", + semantic_input_hash="hash", + selected_job_id=job.id, + ), + BatchItem(batch_id=batch.id, item_index=0, target_kind="run", target_id=run.id), + Execution( + job_id=job.id, + ordinal=1, + phase_key="execute", + resource_pool="cpu_media", + fence_token="fence", + state="exited", + ), + ShotCandidate( + owner_id=owner, + draft_id=draft.id, + shot_id="s1", + kind="image", + source_kind="generated", + job_id=job.id, + asset_id=source_row.id, + context_hash="hash", + generation_hash="hash", + created_revision=1, + ), + ShotSelection( + owner_id=owner, + draft_id=draft.id, + shot_id="s1", + kind="image", + asset_id=source_row.id, + context_hash="hash", + ), + Submission(owner_id=owner, operation="story.render", key="key", body_hash="hash"), + QuotaReservation(owner_id=owner, operation="story.render"), + Event(owner_id=owner, event_type="test", data={}), + ] + ) + imported_row = await session.get(Asset, imported_id) + preserved = system.settings.asset_root / imported_row.storage_key + await session.commit() + work = system.settings.job_work_root / job_id / "attempt-0001" + work.mkdir(parents=True) + (work / "output.bin").write_bytes(b"output") + # 中断上传或已软删素材遗留的字节也只能在本账号目录内清理。 + leftover = system.settings.asset_root / owner / "orphan" / "upload.part" + leftover.parent.mkdir(parents=True) + leftover.write_bytes(b"partial") + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 204, response.text + assert not (system.settings.asset_root / owner).exists() + assert not (system.settings.job_work_root / job_id).exists() + assert preserved.read_bytes() == png_bytes + assert (await other_client.get("/api/auth/me")).status_code == 401 + assert ( + await other_client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) + ).status_code == 401 + assert (await system.client.get(imported.json()["preview_url"])).content == png_bytes + assert (await system.client.get(shared["preview_url"])).status_code == 404 + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as machine: + assert ( + await machine.get("/api/jobs", headers={"Authorization": "Bearer " + token_value}) + ).status_code == 401 + async with system.app.state.db.session() as session: + assert await session.get(User, owner) is None + assert await session.get(User, admin["id"]) is not None + assert await session.get(Asset, imported_id) is not None + for table in Base.metadata.tables.values(): + field = table.c.get("owner_id") + if field is None: + field = table.c.get("publisher_id") + if field is None: + field = table.c.get("user_id") + if field is not None: + assert ( + await session.execute(select(table).where(field == owner)) + ).first() is None, table.name + for model in (JobAsset, AssetFolder, WorkflowStep, BatchItem, Execution): + assert await session.scalar(select(model)) is None + + +@pytest.mark.parametrize("state", ["allocated", "running", "stopping", "unknown", "future"]) +async def test_delete_waits_for_execution_cleanup(system, other_client, png_bytes, state): + owner = (await account(other_client))["id"] + asset = await upload(other_client, png_bytes) + response = await other_client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} + ) + job_id = response.json()["jobs"][0]["id"] + async with system.app.state.db.session() as session: + (await session.get(Job, job_id)).state = "cancelled" + execution = Execution( + job_id=job_id, + ordinal=1, + phase_key="execute", + resource_pool="cpu_media", + fence_token="fence", + state=state, + ) + session.add(execution) + await session.commit() + execution_id = execution.id + path = system.settings.asset_root / owner + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "cleanup_pending" + assert path.exists() + assert (await other_client.get("/api/auth/me")).status_code == 401 + async with system.app.state.db.session() as session: + assert (await session.get(User, owner)).disabled + assert await session.get(Asset, asset["id"]) is not None + assert await session.scalar(select(Session).where(Session.user_id == owner)) is None + (await session.get(Execution, execution_id)).state = "exited" + await session.commit() + assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 + + +async def test_delete_persists_cancellation_before_removing_active_gpu_files( + system, other_client, png_bytes +): + owner = (await account(other_client))["id"] + await upload(other_client, png_bytes) + response = await other_client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} + ) + job_id = response.json()["jobs"][0]["id"] + await system.app.state.coordinator.run_once(force=True) + preparing = list(system.app.state.coordinator._preparing.values()) + if preparing: + await asyncio.gather(*preparing) + await system.app.state.coordinator.run_once(force=True) + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "cleanup_pending" + assert (system.settings.asset_root / owner).exists() + async with system.app.state.db.session() as session: + job = await session.get(Job, job_id) + assert job.cancel_requested and job.desired_state == "cancel" + await system.app.state.coordinator.run_once(force=True) + assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 + + +async def test_delete_preflights_all_paths_before_unlinking(system, other_client, png_bytes): + owner = (await account(other_client))["id"] + good = await upload(other_client, png_bytes) + bad = await upload(other_client, png_bytes) + other = await upload(system.client, png_bytes) + async with system.app.state.db.session() as session: + good_path = system.settings.asset_root / (await session.get(Asset, good["id"])).storage_key + other_path = ( + system.settings.asset_root / (await session.get(Asset, other["id"])).storage_key + ) + (await session.get(Asset, bad["id"])).storage_key = ( + other_path.relative_to(system.settings.asset_root).as_posix() + ".unsafe" + ) + await session.commit() + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "unsafe_user_path" + assert good_path.exists() and other_path.read_bytes() == png_bytes + + +async def test_delete_waits_for_inflight_upload_and_prevents_new_upload( + system, other_client, png_bytes, monkeypatch +): + from app.services import assets + + owner = (await account(other_client))["id"] + user = await account(other_client) + actor = Actor(owner, user["username"], user["display_name"], "user", "", "") + started, release = asyncio.Event(), asyncio.Event() + real_build = assets.build_asset + + async def paused_build(*args, **kwargs): + started.set() + await release.wait() + return await real_build(*args, **kwargs) + + monkeypatch.setattr(assets, "build_asset", paused_build) + task = asyncio.create_task( + assets.upload( + runtime=system.app.state, + file=UploadFile(io.BytesIO(png_bytes), filename="picture.png"), + actor=actor, + ) + ) + try: + await asyncio.wait_for(started.wait(), timeout=5) + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "cleanup_pending" + finally: + release.set() + outcome = await asyncio.gather(task, return_exceptions=True) + assert isinstance(outcome[0], Exception), "禁用后的在途上传不可提交新素材" + assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 + assert not (system.settings.asset_root / owner).exists() + + +async def test_delete_filesystem_failure_retains_rows_for_retry( + system, other_client, png_bytes, monkeypatch +): + owner = (await account(other_client))["id"] + asset = await upload(other_client, png_bytes) + real_unlink = Path.unlink + + def fail_unlink(path, *args, **kwargs): + if owner in path.parts: + raise PermissionError("busy file") + return real_unlink(path, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(Path, "unlink", fail_unlink) + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 503, response.text + async with system.app.state.db.session() as session: + assert await session.get(User, owner) is not None + assert await session.get(Asset, asset["id"]) is not None + assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 + + +async def test_delete_waits_for_execution_reference_not_owned_job(system, other_client, png_bytes): + owner = (await account(other_client))["id"] + asset = await upload(other_client, png_bytes) + async with system.app.state.db.session() as session: + execution = Execution( + job_id="foreign-job", + ordinal=1, + phase_key="execute", + resource_pool="cpu_media", + fence_token="fence", + state="running", + ) + session.add(execution) + await session.flush() + session.add( + AssetReference( + owner_id=owner, asset_id=asset["id"], ref_kind="execution", ref_id=execution.id + ) + ) + await session.commit() + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "cleanup_pending" + assert (system.settings.asset_root / owner).is_dir() + + +async def test_delete_waits_for_background_writer_after_job_terminal( + system, other_client, png_bytes +): + owner = (await account(other_client))["id"] + await upload(other_client, png_bytes) + response = await other_client.post( + "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}} + ) + job_id = response.json()["jobs"][0]["id"] + async with system.app.state.db.session() as session: + (await session.get(Job, job_id)).state = "succeeded" + await session.commit() + release = asyncio.Event() + writer = asyncio.create_task(release.wait()) + system.app.state.coordinator._collecting[job_id] = writer + try: + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "cleanup_pending" + assert (system.settings.asset_root / owner).is_dir() + finally: + release.set() + await writer + assert (await system.client.delete(f"/api/auth/users/{owner}")).status_code == 204 + + +async def test_delete_refuses_link_inside_user_tree(system, other_client, png_bytes, tmp_path): + owner = (await account(other_client))["id"] + await upload(other_client, png_bytes) + external = tmp_path / "other-account-secret" + external.mkdir() + (external / "keep.bin").write_bytes(b"keep") + link = system.settings.asset_root / owner / "linked" + try: + os.symlink(external, link, target_is_directory=True) + except OSError as exc: + pytest.skip(f"OS does not permit test symlink: {exc}") + try: + response = await system.client.delete(f"/api/auth/users/{owner}") + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "unsafe_user_path" + assert (external / "keep.bin").read_bytes() == b"keep" + finally: + link.unlink() diff --git a/backend/tests/test_user_deletion_thread_safety.py b/backend/tests/test_user_deletion_thread_safety.py new file mode 100644 index 0000000..f66dfcc --- /dev/null +++ b/backend/tests/test_user_deletion_thread_safety.py @@ -0,0 +1,149 @@ +"""删除账号须等待实际写文件的线程退出,取消其等待协程不算停止确认。""" + +import asyncio +import io +from pathlib import Path +from tempfile import TemporaryDirectory +from threading import Event as ThreadEvent + +import pytest +from PIL import Image +from starlette.datastructures import UploadFile + +from app.adapters.provider.cpu import run_cpu as actual_cpu +from app.core.security import Actor +from app.services.assets import upload +from conftest import PASSWORD + + +@pytest.fixture +def tmp_path(): + with TemporaryDirectory(prefix="cmvr-delete-thread-") as directory: + yield Path(directory) + + +async def test_delete_waits_for_cancelled_real_cpu_file_thread( + system, other_client, png_bytes, monkeypatch +): + owner = (await other_client.get("/api/auth/me")).json()["user"]["id"] + uploaded = await other_client.post( + "/api/assets", files={"file": ("input.png", png_bytes, "image/png")} + ) + assert uploaded.status_code == 201, uploaded.text + asset_id = uploaded.json()["id"] + response = await other_client.post( + "/api/jobs", + json={ + "task_type": "image.prepare_frame", + "input": {"image_asset_id": asset_id}, + "parameters": {"width": 704, "height": 1280, "fit": "contain"}, + }, + ) + assert response.status_code == 202, response.text + job_id = response.json()["jobs"][0]["id"] + + # 仅替换网络边界,运行生产 normalize/to_thread 与真实协调器取消路径。 + provider = system.provider + monkeypatch.setattr(provider, "settings", system.settings, raising=False) + monkeypatch.setattr(provider, "_work", lambda path: path, raising=False) + monkeypatch.setattr( + provider, "_asset", lambda identity, assets: assets[identity], raising=False + ) + + async def run_cpu(task_type, inputs, parameters, assets, work_dir): + return await actual_cpu(provider, task_type, inputs, parameters, assets, work_dir) + + monkeypatch.setattr(provider, "run_cpu", run_cpu) + entered, release, finished = ThreadEvent(), ThreadEvent(), ThreadEvent() + real_open = Image.open + + def paused_open(*args, **kwargs): + entered.set() + try: + if not release.wait(10): + raise TimeoutError("test did not release CPU image thread") + return real_open(*args, **kwargs) + finally: + finished.set() + + monkeypatch.setattr(Image, "open", paused_open) + coordinator = system.app.state.coordinator + worker = None + try: + await coordinator.run_once(force=True) + assert await asyncio.to_thread(entered.wait, 5), "CPU file thread did not start" + worker = coordinator._cpu[job_id] + first = await system.client.delete("/api/auth/users/" + owner) + assert first.status_code == 409, first.text + assert first.json()["detail"]["code"] == "cleanup_pending" + + await coordinator.run_once(force=True) + # 给取消处理机会;不得取消本次wait,否则会给被测任务额外发cancel。 + await asyncio.wait({worker}, timeout=0.1) + assert not worker.done(), "等待协程取消不能冒充底层线程已退出" + worker.cancel() + await asyncio.wait({worker}, timeout=0.1) + assert not worker.done(), "重复取消也不能跳过真实线程的结束确认" + assert not finished.is_set() + second = await system.client.delete("/api/auth/users/" + owner) + assert second.status_code == 409, second.text + assert second.json()["detail"]["code"] == "cleanup_pending" + assert (system.settings.asset_root / owner).is_dir() + assert (system.settings.job_work_root / job_id).is_dir() + finally: + release.set() + if worker is not None: + await asyncio.wait_for(asyncio.gather(worker, return_exceptions=True), 5) + await asyncio.to_thread(finished.wait, 5) + + assert finished.is_set() + final = await system.client.delete("/api/auth/users/" + owner) + assert final.status_code == 204, final.text + assert not (system.settings.asset_root / owner).exists() + assert not (system.settings.job_work_root / job_id).exists() + assert ( + await other_client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) + ).status_code == 401 + + +async def test_upload_thumbnail_thread_retains_delete_guard_on_repeated_cancel( + system, other_client, png_bytes, monkeypatch +): + user = (await other_client.get("/api/auth/me")).json()["user"] + owner = user["id"] + actor = Actor(owner, user["username"], user["display_name"], "user", "", "") + entered, release = ThreadEvent(), ThreadEvent() + real_save = Image.Image.save + + def paused_save(image, target, *args, **kwargs): + if kwargs.get("format") == "JPEG": + entered.set() + if not release.wait(10): + raise TimeoutError("test did not release thumbnail thread") + return real_save(image, target, *args, **kwargs) + + monkeypatch.setattr(Image.Image, "save", paused_save) + worker = asyncio.create_task( + upload( + runtime=system.app.state, + actor=actor, + file=UploadFile(io.BytesIO(png_bytes), filename="input.png"), + ) + ) + try: + assert await asyncio.to_thread(entered.wait, 5) + for _ in range(2): + worker.cancel() + await asyncio.wait({worker}, timeout=0.1) + assert not worker.done(), "缩略图线程未退出时上传保护不能释放" + assert system.app.state.owner_uploads[owner] == 1 + response = await system.client.delete("/api/auth/users/" + owner) + assert response.status_code == 409, response.text + assert response.json()["detail"]["code"] == "cleanup_pending" + finally: + release.set() + await asyncio.wait_for(asyncio.gather(worker, return_exceptions=True), 5) + assert not system.app.state.owner_uploads + response = await system.client.delete("/api/auth/users/" + owner) + assert response.status_code == 204, response.text + assert not (system.settings.asset_root / owner).exists() diff --git a/backend/tests/test_user_status.py b/backend/tests/test_user_status.py new file mode 100644 index 0000000..a05d83e --- /dev/null +++ b/backend/tests/test_user_status.py @@ -0,0 +1,181 @@ +import httpx +from pathlib import Path +from tempfile import TemporaryDirectory +import pytest +from sqlalchemy import delete + +from conftest import PASSWORD +from app.models import Batch, Job, Session, User, WorkflowDraft, WorkflowRun +from app.services.events import session_is_active + + +@pytest.fixture +def tmp_path(): + with TemporaryDirectory(prefix="cmvr-user-status-") as directory: + yield Path(directory) + + +async def test_disable_and_enable_preserve_resources_and_remove_only_admin_holds( + system, other_client, png_bytes +): + owner = (await other_client.get("/api/auth/me")).json()["user"]["id"] + cookie = other_client.cookies.get("cmvr_session") + asset = ( + await other_client.post( + "/api/assets", files={"file": ("owned.png", png_bytes, "image/png")} + ) + ).json() + token = ( + await other_client.post( + "/api/auth/tokens", json={"name": "existing reader", "scopes": ["assets:read"]} + ) + ).json()["token"] + jobs = ( + await other_client.post( + "/api/jobs", + json={"task_type": "image.generate", "input": {"prompt": "preserve"}, "count": 2}, + ) + ).json()["jobs"] + async with system.app.state.db.session() as session: + draft = WorkflowDraft(owner_id=owner, name="preserve draft", spec={"shots": []}) + session.add(draft) + await session.flush() + run = WorkflowRun( + owner_id=owner, + draft_id=draft.id, + draft_revision=1, + spec_snapshot={"shots": []}, + spec_hash="hash", + hold_reasons=["manual"], + ) + batch = Batch(owner_id=owner, name="preserve batch", hold_reasons=["batch_pause"]) + session.add_all([run, batch]) + (await session.get(Job, jobs[0]["id"])).hold_reasons = ["manual"] + await session.commit() + run_id, batch_id = run.id, batch.id + response = await system.client.patch("/api/auth/users/" + owner, json={"disabled": True}) + assert response.status_code == 200 + assert not await session_is_active(system.app.state.db, cookie) + assert not await session_is_active(system.app.state.db, "Bearer " + token) + assert (await other_client.get("/api/assets")).status_code == 401 + assert (await other_client.post("/api/jobs", json={})).status_code == 401 + assert ( + await other_client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) + ).status_code == 401 + async with system.app.state.db.session() as session: + assert "admin_suspend" in (await session.get(Job, jobs[0]["id"])).hold_reasons + assert "admin_suspend" in (await session.get(WorkflowRun, run_id)).hold_reasons + assert "admin_suspend" in (await session.get(Batch, batch_id)).hold_reasons + assert ( + await system.client.patch("/api/auth/users/" + owner, json={"disabled": False}) + ).status_code == 200 + # 旧 Cookie 保持失效;已有机器令牌随账号启用恢复,资源不需要重建。 + assert (await other_client.get("/api/auth/me")).status_code == 401 + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + token}, + ) as machine: + assert (await machine.get("/api/assets")).status_code == 200 + login = await other_client.post( + "/api/auth/login", json={"username": "alice", "password": PASSWORD} + ) + assert login.status_code == 200 + assert (await other_client.get(asset["preview_url"])).status_code == 200 + assert asset["id"] in [a["id"] for a in (await other_client.get("/api/assets")).json()["items"]] + async with system.app.state.db.session() as session: + assert (await session.get(Job, jobs[0]["id"])).hold_reasons == ["manual"] + assert (await session.get(Job, jobs[1]["id"])).hold_reasons == [] + assert (await session.get(WorkflowRun, run_id)).hold_reasons == ["manual"] + assert (await session.get(Batch, batch_id)).hold_reasons == ["batch_pause"] + + +async def test_reenabled_unheld_cpu_task_can_continue(system, other_client): + owner = (await other_client.get("/api/auth/me")).json()["user"]["id"] + created = await other_client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "resume"}} + ) + assert created.status_code == 202 + jid = created.json()["jobs"][0]["id"] + await system.client.patch("/api/auth/users/" + owner, json={"disabled": True}) + await system.app.state.coordinator.run_once(force=True) + assert system.provider.cpu_runs == 0 + await system.client.patch("/api/auth/users/" + owner, json={"disabled": False}) + import asyncio + + for _ in range(4): + await system.app.state.coordinator.run_once(force=True) + pending = list(system.app.state.coordinator._cpu.values()) + if pending: + await asyncio.gather(*pending) + assert system.provider.cpu_runs == 1 + async with system.app.state.db.session() as session: + assert (await session.get(Job, jid)).state == "succeeded" + + +async def test_admin_cannot_disable_their_own_account_even_with_another_admin(system): + admin = (await system.client.get("/api/auth/me")).json()["user"]["id"] + async with system.app.state.db.session() as session: + first = await session.get(User, admin) + session.add( + User( + username="backup-admin", + display_name="Backup", + role="admin", + password_hash=first.password_hash, + ) + ) + await session.commit() + response = await system.client.patch("/api/auth/users/" + admin, json={"disabled": True}) + assert response.status_code == 409 + assert (await system.client.get("/api/auth/me")).status_code == 200 + + +async def test_stale_authenticated_admin_cannot_reenable_or_create_users(system, other_client): + from app.api.dependencies import current_actor + from app.core.security import Actor, token_hash + + me = (await system.client.get("/api/auth/me")).json()["user"] + target = (await other_client.get("/api/auth/me")).json()["user"]["id"] + actor = Actor( + me["id"], + me["username"], + me["display_name"], + "admin", + system.client.headers["X-CSRF-Token"], + token_hash(system.client.cookies.get("cmvr_session")), + ) + async with system.app.state.db.session() as session: + admin = await session.get(User, actor.id) + admin.disabled = True + await session.execute(delete(Session).where(Session.user_id == actor.id)) + await session.commit() + # 模拟鉴权已完成、业务事务尚未开始时,管理员被另一请求停用。 + system.app.dependency_overrides[current_actor] = lambda: actor + try: + assert ( + await system.client.patch("/api/auth/users/" + actor.id, json={"disabled": False}) + ).status_code in {401, 403} + assert ( + await system.client.post( + "/api/auth/users", json={"username": "stale-admin-created", "password": PASSWORD} + ) + ).status_code in {401, 403} + assert (await system.client.get("/api/auth/users")).status_code in {401, 403} + assert (await system.client.delete("/api/auth/users/" + target)).status_code in {401, 403} + async with system.app.state.db.session() as session: + assert (await session.get(User, actor.id)).disabled + # 即使稍后重新启用,旧的已撤销会话也不能恢复操作。 + (await session.get(User, actor.id)).disabled = False + await session.commit() + assert ( + await system.client.patch("/api/auth/users/" + target, json={"disabled": True}) + ).status_code in {401, 403} + assert ( + await system.client.post( + "/api/auth/password", + json={"current_password": PASSWORD, "new_password": PASSWORD + "-new"}, + ) + ).status_code in {401, 403} + finally: + system.app.dependency_overrides.clear() diff --git a/backend/tests/test_username_change.py b/backend/tests/test_username_change.py new file mode 100644 index 0000000..3c8cd60 --- /dev/null +++ b/backend/tests/test_username_change.py @@ -0,0 +1,396 @@ +"""登录名变更只修改当前用户;重启不得恢复旧管理员和初始密码。""" + +import asyncio +from datetime import timedelta +from pathlib import Path +from tempfile import TemporaryDirectory + +import httpx +import pytest +from sqlalchemy import delete, select + +from app.api.dependencies import current_actor +from app.core.security import Actor, hash_password, token_hash +from app.models import ( + ApiToken, + Asset, + Batch, + Job, + Session, + User, + WorkflowDraft, + WorkflowRun, + utcnow, +) +from app.services.auth import bootstrap_admin +from conftest import FakeProvider, PASSWORD + + +@pytest.fixture +def tmp_path(): + with TemporaryDirectory(prefix="cmvr-username-") as directory: + yield Path(directory) + + +async def test_rename_preserves_identity_resources_password_and_existing_sessions( + system, other_client, png_bytes +): + client = other_client + before = (await client.get("/api/auth/me")).json() + owner = before["user"]["id"] + cookie = client.cookies.get("cmvr_session") + asset = await client.post("/api/assets", files={"file": ("owned.png", png_bytes, "image/png")}) + assert asset.status_code == 201 + job = await client.post( + "/api/jobs", json={"task_type": "math.solve", "input": {"prompt": "preserve"}} + ) + assert job.status_code == 202 + made = await client.post( + "/api/auth/tokens", json={"name": "keep reader", "scopes": ["assets:read"]} + ) + assert made.status_code == 201 + token_id = made.json()["record"]["id"] + async with system.app.state.db.session() as session: + password_hash = (await session.get(User, owner)).password_hash + draft = WorkflowDraft(owner_id=owner, name="keep draft", spec={"shots": []}) + session.add(draft) + await session.flush() + run = WorkflowRun( + owner_id=owner, + draft_id=draft.id, + draft_revision=1, + spec_snapshot={"shots": []}, + spec_hash="preserve", + ) + batch = Batch(owner_id=owner, name="keep batch") + session.add_all([run, batch]) + await session.commit() + draft_id, run_id, batch_id = draft.id, run.id, batch.id + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as second: + login = await second.post( + "/api/auth/login", json={"username": "alice", "password": PASSWORD} + ) + assert login.status_code == 200 + response = await client.post( + "/api/auth/username", + json={"username": " Alice.New-1_ ", "current_password": PASSWORD}, + ) + assert response.status_code == 200, response.text + assert response.json() == {**before["user"], "username": "alice.new-1_", "disabled": False} + assert client.cookies.get("cmvr_session") == cookie + assert (await client.get("/api/auth/me")).json() == { + **before, + "user": {**before["user"], "username": "alice.new-1_"}, + } + assert (await second.get("/api/auth/me")).json()["user"]["username"] == "alice.new-1_" + assert ( + await second.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) + ).status_code == 401 + fresh = await second.post( + "/api/auth/login", json={"username": " ALICE.NEW-1_ ", "password": PASSWORD} + ) + assert fresh.status_code == 200 and fresh.json()["user"]["id"] == owner + + assert (await client.get(asset.json()["preview_url"])).status_code == 200 + assert (await client.get("/api/jobs/" + job.json()["jobs"][0]["id"])).status_code == 200 + assert (await client.get("/api/auth/users")).status_code == 403 + async with system.app.state.db.session() as session: + user = await session.get(User, owner) + assert user.password_hash == password_hash and user.role == "user" + for model, identity in ( + (Asset, asset.json()["id"]), + (Job, job.json()["jobs"][0]["id"]), + (WorkflowDraft, draft_id), + (WorkflowRun, run_id), + (Batch, batch_id), + (ApiToken, token_id), + ): + assert (await session.get(model, identity)).owner_id == owner + assert await session.get(Session, token_hash(cookie)) is not None + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + made.json()["token"]}, + ) as machine: + assert (await machine.get(asset.json()["preview_url"])).status_code == 200 + + +async def test_admin_rename_survives_restart_without_recreating_bootstrap_account(tmp_path): + from app.core.config import Settings + from app.main import create_app + + settings = Settings( + mode="test", + database_url=f"sqlite+aiosqlite:///{tmp_path / 'restart.sqlite3'}", + workspace_root=tmp_path, + admin_username="admin", + admin_password="123456", + run_coordinator=False, + cookie_secure=False, + ) + app = create_app(settings, provider=FakeProvider()) + async with app.router.lifespan_context(app): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + login = await client.post( + "/api/auth/login", json={"username": "admin", "password": "123456"} + ) + before = login.json()["user"] + owner = before["id"] + cookie = client.cookies.get("cmvr_session") + csrf = login.json()["csrf_token"] + client.headers["X-CSRF-Token"] = csrf + async with app.state.db.session() as session: + password_hash = (await session.get(User, owner)).password_hash + draft = WorkflowDraft(owner_id=owner, name="keep admin draft", spec={}) + session.add(draft) + await session.commit() + draft_id = draft.id + response = await client.post( + "/api/auth/username", json={"username": "new-admin", "current_password": "123456"} + ) + assert response.status_code == 200, response.text + assert response.json() == {**before, "username": "new-admin"} + + settings.admin_password = PASSWORD + restarted = create_app(settings, provider=FakeProvider()) + async with restarted.router.lifespan_context(restarted): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=restarted), base_url="http://test" + ) as client: + client.cookies.set("cmvr_session", cookie) + assert (await client.get("/api/auth/me")).json() == { + "user": { + k: v for k, v in {**before, "username": "new-admin"}.items() if k != "disabled" + }, + "csrf_token": csrf, + } + for password in ("123456", PASSWORD): + assert ( + await client.post( + "/api/auth/login", json={"username": "admin", "password": password} + ) + ).status_code == 401 + assert ( + await client.post( + "/api/auth/login", json={"username": "new-admin", "password": "123456"} + ) + ).json()["user"]["id"] == owner + async with restarted.state.db.session() as session: + users = (await session.scalars(select(User))).all() + assert len(users) == 1 + assert users[0].id == owner and users[0].role == "admin" + assert users[0].password_hash == password_hash + assert (await session.get(WorkflowDraft, draft_id)).owner_id == owner + + +@pytest.mark.parametrize("disabled", [False, True]) +async def test_bootstrap_does_not_create_configured_name_when_any_admin_exists(system, disabled): + async with system.app.state.db.session() as session: + admin = await session.scalar(select(User).where(User.username == "admin")) + admin.username = "renamed-admin" + admin.disabled = disabled + await session.commit() + owner = admin.id + await bootstrap_admin(system.app.state.db, system.settings) + async with system.app.state.db.session() as session: + users = (await session.scalars(select(User))).all() + assert [(u.id, u.username, u.disabled) for u in users] == [ + (owner, "renamed-admin", disabled) + ] + + +async def test_bootstrap_preserves_existing_non_admin_with_configured_name(system): + async with system.app.state.db.session() as session: + user = await session.scalar(select(User).where(User.username == "admin")) + user.role = "user" + password_hash = user.password_hash + await session.commit() + owner = user.id + await bootstrap_admin(system.app.state.db, system.settings) + async with system.app.state.db.session() as session: + users = (await session.scalars(select(User))).all() + assert len(users) == 1 + assert (users[0].id, users[0].role, users[0].password_hash) == ( + owner, + "user", + password_hash, + ) + + +@pytest.mark.parametrize("username", ["", "ab", "a" * 65, "用户一", "bad/name", "bad name"]) +async def test_rename_rejects_invalid_username_without_mutation(system, username): + response = await system.client.post( + "/api/auth/username", json={"username": username, "current_password": PASSWORD} + ) + assert response.status_code == 422, response.text + assert (await system.client.get("/api/auth/me")).json()["user"]["username"] == "admin" + + +@pytest.mark.parametrize("username", ["a_1", "a" * 64]) +async def test_rename_accepts_username_length_boundaries(system, username): + response = await system.client.post( + "/api/auth/username", json={"username": username, "current_password": PASSWORD} + ) + assert response.status_code == 200, response.text + assert response.json()["username"] == username + + +async def test_rename_requires_password_even_for_same_name_and_handles_duplicates( + system, other_client +): + for username in ("admin", "new-admin"): + response = await system.client.post( + "/api/auth/username", json={"username": username, "current_password": "wrong"} + ) + assert response.status_code == 403, response.text + assert response.json()["detail"]["code"] == "invalid_password" + conflict = await system.client.post( + "/api/auth/username", json={"username": " ALICE ", "current_password": PASSWORD} + ) + assert conflict.status_code == 409 and conflict.json()["detail"]["code"] == "username_exists" + same = await system.client.post( + "/api/auth/username", json={"username": " ADMIN ", "current_password": PASSWORD} + ) + assert same.status_code == 200 and same.json()["username"] == "admin" + + +async def test_regular_user_only_renames_self_even_with_other_user_id(system, other_client): + admin = (await system.client.get("/api/auth/me")).json()["user"] + alice = (await other_client.get("/api/auth/me")).json()["user"] + response = await other_client.post( + "/api/auth/username", + json={ + "username": "renamed-alice", + "current_password": PASSWORD, + "user_id": admin["id"], + "role": "admin", + }, + ) + assert response.status_code == 200, response.text + assert response.json()["id"] == alice["id"] and response.json()["role"] == "user" + assert (await system.client.get("/api/auth/me")).json()["user"] == admin + + +async def test_rename_requires_session_and_csrf(system): + body = {"username": "new-admin", "current_password": PASSWORD} + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), base_url="http://test" + ) as client: + assert (await client.post("/api/auth/username", json=body)).status_code == 401 + client.cookies.set("cmvr_session", system.client.cookies.get("cmvr_session")) + assert (await client.post("/api/auth/username", json=body)).status_code == 403 + assert ( + await client.post("/api/auth/username", json=body, headers={"X-CSRF-Token": "wrong"}) + ).status_code == 403 + assert ( + await system.client.post( + "/api/auth/username", json=body, headers={"sec-fetch-site": "cross-site"} + ) + ).status_code == 403 + assert (await system.client.get("/api/auth/me")).json()["user"]["username"] == "admin" + + +@pytest.mark.parametrize("stale", ["disabled", "revoked", "expired", "password_changed", "bearer"]) +async def test_rename_rechecks_actor_in_transaction(system, stale): + user = (await system.client.get("/api/auth/me")).json()["user"] + actor = Actor( + user["id"], + user["username"], + user["display_name"], + user["role"], + system.client.headers["X-CSRF-Token"], + token_hash(system.client.cookies.get("cmvr_session")), + auth_kind="bearer" if stale == "bearer" else "session", + ) + async with system.app.state.db.session() as session: + if stale == "disabled": + (await session.get(User, actor.id)).disabled = True + elif stale == "revoked": + await session.execute(delete(Session).where(Session.user_id == actor.id)) + elif stale == "expired": + (await session.get(Session, actor.token_hash)).expires_at = utcnow() - timedelta( + seconds=1 + ) + elif stale == "password_changed": + (await session.get(User, actor.id)).password_hash = hash_password( + "Updated-password-194!" + ) + await session.commit() + # 只替换先前已经通过的鉴权,真实业务事务仍须复核数据库,不能信任旧 Actor。 + system.app.dependency_overrides[current_actor] = lambda: actor + try: + response = await system.client.post( + "/api/auth/username", json={"username": "new-admin", "current_password": PASSWORD} + ) + assert response.status_code == (403 if stale in {"bearer", "password_changed"} else 401), ( + response.text + ) + finally: + system.app.dependency_overrides.clear() + async with system.app.state.db.session() as session: + assert (await session.get(User, actor.id)).username == "admin" + + +async def test_machine_token_cannot_rename_login(system): + made = await system.client.post( + "/api/auth/tokens", json={"name": "writer", "scopes": ["assets:write", "jobs:write"]} + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=system.app), + base_url="http://test", + headers={"Authorization": "Bearer " + made.json()["token"]}, + ) as machine: + response = await machine.post( + "/api/auth/username", json={"username": "new-admin", "current_password": PASSWORD} + ) + assert response.status_code == 403, response.text + + +async def test_concurrent_rename_conflict_leaves_both_accounts_and_sessions_valid( + system, other_client +): + before = [ + (await client.get("/api/auth/me")).json()["user"] + for client in (system.client, other_client) + ] + responses = await asyncio.gather( + *( + client.post( + "/api/auth/username", json={"username": "same-name", "current_password": PASSWORD} + ) + for client in (system.client, other_client) + ) + ) + assert sorted(response.status_code for response in responses) == [200, 409] + for client, previous, response in zip((system.client, other_client), before, responses): + me = (await client.get("/api/auth/me")).json()["user"] + assert me == { + **previous, + "username": "same-name" if response.status_code == 200 else previous["username"], + } + async with system.app.state.db.session() as session: + assert ( + len((await session.scalars(select(User).where(User.username == "same-name"))).all()) + == 1 + ) + + +@pytest.mark.parametrize("length,status", [(6, 422), (11, 422), (12, 200), (256, 200), (257, 422)]) +async def test_self_password_change_keeps_stronger_length_policy(system, length, status): + response = await system.client.post( + "/api/auth/password", json={"current_password": PASSWORD, "new_password": "x" * length} + ) + assert response.status_code == status, response.text + + +@pytest.mark.parametrize("length,status", [(5, 422), (6, 201), (256, 201), (257, 422)]) +async def test_admin_created_user_initial_password_length_limits(system, length, status): + response = await system.client.post( + "/api/auth/users", json={"username": "new-user", "password": "x" * length} + ) + assert response.status_code == status, response.text diff --git a/backend/tests/test_video_duration.py b/backend/tests/test_video_duration.py index 44ae7ca..0d0205d 100644 --- a/backend/tests/test_video_duration.py +++ b/backend/tests/test_video_duration.py @@ -1,37 +1,53 @@ """The public contract and adapter must agree on native fifteen-second shots.""" + import pytest -from app.providers import Provider, ProviderError, capabilities, validate_arguments +from app.adapters.provider.client import Provider, ProviderError, capabilities, validate_arguments def test_video_capability_exposes_fifteen_seconds_with_legacy_default(system): - video = next(row for row in capabilities(system.settings) if row['task_type'] == 'video.generate') - assert video['defaults']['num_frames'] == 121 - assert video['constraints']['num_frames'] == {'min': 5, 'max': 361, 'step': 4} + video = next( + row for row in capabilities(system.settings) if row["task_type"] == "video.generate" + ) + assert video["defaults"]["num_frames"] == 121 + assert video["constraints"]["num_frames"] == {"min": 5, "max": 361, "step": 4} -@pytest.mark.parametrize('frames', [241, 361]) +@pytest.mark.parametrize("frames", [241, 361]) async def test_native_long_video_is_accepted_and_forwarded_without_shortening(system, frames): - parameters = {'num_frames': frames, 'upscale': False} - validate_arguments('video.generate', {'prompt': 'one continuous shot'}, parameters, system.settings) - response = await system.client.post('/api/jobs', json={ - 'task_type': 'video.generate', 'input': {'prompt': 'one continuous shot'}, 'parameters': parameters}) + parameters = {"num_frames": frames, "upscale": False} + validate_arguments( + "video.generate", {"prompt": "one continuous shot"}, parameters, system.settings + ) + response = await system.client.post( + "/api/jobs", + json={ + "task_type": "video.generate", + "input": {"prompt": "one continuous shot"}, + "parameters": parameters, + }, + ) assert response.status_code == 202, response.text - assert response.json()['jobs'][0]['parameters']['num_frames'] == frames + assert response.json()["jobs"][0]["parameters"]["num_frames"] == frames provider = Provider(system.settings) - work = system.settings.job_work_root / 'longshot' + work = system.settings.job_work_root / "longshot" work.mkdir(parents=True) try: - payload = await provider.prepare_gpu_payload('video.generate', {'prompt': 'one continuous shot'}, - parameters, {}, work) - assert payload['parameters']['num_frames'] == frames - assert payload['parameters']['fps'] == 24 + payload = await provider.prepare_gpu_payload( + "video.generate", {"prompt": "one continuous shot"}, parameters, {}, work + ) + assert payload["parameters"]["num_frames"] == frames + assert payload["parameters"]["fps"] == 24 finally: await provider.aclose() -@pytest.mark.parametrize('frames', [362, 365]) +@pytest.mark.parametrize("frames", [362, 365]) def test_out_of_contract_video_frames_remain_rejected(system, frames): with pytest.raises(ProviderError): - validate_arguments('video.generate', {'prompt': 'one continuous shot'}, - {'num_frames': frames}, system.settings) + validate_arguments( + "video.generate", + {"prompt": "one continuous shot"}, + {"num_frames": frames}, + system.settings, + ) diff --git a/backend/tests/test_workflow_output_contract.py b/backend/tests/test_workflow_output_contract.py index 3935d30..036333d 100644 --- a/backend/tests/test_workflow_output_contract.py +++ b/backend/tests/test_workflow_output_contract.py @@ -2,27 +2,139 @@ from types import SimpleNamespace from unittest.mock import AsyncMock from sqlalchemy import select from app.models import Job +import pytest -async def test_workflow_imports_only_final_enhanced_output(system, monkeypatch): - response = await system.client.post('/api/jobs', json={ - 'task_type':'video.generate','input':{'prompt':'three-shot source'},'parameters':{}}, - headers={'Idempotency-Key':'dual-stage-output'}) +@pytest.mark.parametrize("candidate", [False, True]) +async def test_workflow_imports_only_final_enhanced_output(system, monkeypatch, candidate): + response = await system.client.post( + "/api/jobs", + json={ + "task_type": "video.generate", + "input": {"prompt": "three-shot source"}, + "parameters": {}, + }, + headers={"Idempotency-Key": "dual-stage-output"}, + ) assert response.status_code == 202 - job_id=response.json()['jobs'][0]['id'] + job_id = response.json()["jobs"][0]["id"] async with system.app.state.db.session() as session: - job=await session.get(Job,job_id) - job.run_id='run';job.step_key='shot_1';job.upstream_id='gpu-result' - job.upstream_result={'outputs':[{'path':'native.mp4'},{'path':'enhanced.mp4'}], - 'metadata':{'final_output_indices':[1]}} + job = await session.get(Job, job_id) + if candidate: + job.request_key = "candidate:test" + else: + job.run_id = "run" + job.step_key = "shot_1" + job.upstream_id = "gpu-result" + job.upstream_result = { + "outputs": [{"path": "native.mp4"}, {"path": "enhanced.mp4"}], + "metadata": {"final_output_indices": [1]}, + } await session.commit() - imported=[] - async def import_one(db,settings,job,path,index,**kwargs): + imported = [] + + async def import_one(db, settings, job, path, index, **kwargs): imported.append(index) - return SimpleNamespace(kind='video') - monkeypatch.setattr('app.coordinator.import_output',import_one) - coordinator=system.app.state.coordinator - monkeypatch.setattr(coordinator,'_complete',AsyncMock()) + return SimpleNamespace(kind="video") + + monkeypatch.setattr("app.services.orchestration.coordinator.import_output", import_one) + coordinator = system.app.state.coordinator + monkeypatch.setattr(coordinator, "_complete", AsyncMock()) await coordinator._collect_gpu(job) - assert imported==[1] - assert system.provider.download_count==1 + assert imported == [1] + assert system.provider.download_count == 1 + + +@pytest.mark.parametrize( + "run_kind,upscale", [("workflow_auto", False), ("story_auto", True), ("legacy", False)] +) +async def test_real_short_auto_video_import_respects_frozen_native_or_upscaled_profile( + system, run_kind, upscale +): + import shutil + from app.adapters.media import run_process, inspect_video_track + from app.models import WorkflowDraft, WorkflowRun, User + from app.services.assets import import_output + from pathlib import Path + + ffmpeg = shutil.which(system.settings.ffmpeg_bin) + ffprobe = shutil.which(system.settings.ffprobe_bin) + local = Path(__file__).resolve().parents[2] / ".local" / "tools" / "ffmpeg" + ffmpeg = ffmpeg or next((str(p) for p in local.glob("*/bin/ffmpeg.exe")), None) + ffprobe = ffprobe or next((str(p) for p in local.glob("*/bin/ffprobe.exe")), None) + if not ffmpeg or not ffprobe: + pytest.skip("FFmpeg required") + system.settings.ffmpeg_bin = ffmpeg + system.settings.ffprobe_bin = ffprobe + async with system.app.state.db.session() as s: + owner = await s.scalar(select(User)) + draft = WorkflowDraft(owner_id=owner.id, name="import boundary", spec={}) + s.add(draft) + await s.flush() + run = WorkflowRun( + owner_id=owner.id, + draft_id=draft.id, + draft_revision=1, + spec_snapshot={}, + spec_hash="a" * 64, + run_kind=run_kind, + ) + s.add(run) + await s.flush() + job = Job( + owner_id=owner.id, + task_type="video.generate", + request_hash="a" * 64, + upstream_key="test:" + run.id, + run_id=run.id, + step_key="video_0001", + state="collecting", + phase="collecting", + input_json={"prompt": "mock"}, + parameters={ + "num_frames": 25, + "fps": 24, + "upscale": upscale, + "width": 640 if upscale else 1280, + "height": 352 if upscale else 704, + "upscale_width": 1280 if upscale else 1920, + "upscale_height": 704 if upscale else 1056, + }, + ) + s.add(job) + await s.commit() + source = system.settings.job_work_root / "short.mp4" + source.parent.mkdir(parents=True, exist_ok=True) + await run_process( + [ + ffmpeg, + "-nostdin", + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=blue:s=1280x704:r=24", + "-frames:v", + "25", + "-c:v", + "libx264", + "-threads", + "1", + "-pix_fmt", + "yuv420p", + str(source), + ], + timeout=20, + ) + track = await inspect_video_track(source, system.settings) + assert track["frames"] == 25 and track["fps"] == 24 + if run_kind == "legacy": + with pytest.raises(ValueError, match="Workflow shot"): + await import_output(system.app.state.db, system.settings, job, source, 0) + else: + asset = await import_output(system.app.state.db, system.settings, job, source, 0) + assert asset.kind == "video" and (asset.width, asset.height) == (1280, 704) + assert asset.duration_seconds < 1.1 + replay = await import_output(system.app.state.db, system.settings, job, source, 0) + assert replay.id == asset.id diff --git a/backend/tests/test_workflow_review_repairs.py b/backend/tests/test_workflow_review_repairs.py index 1c2a9db..f5782c9 100644 --- a/backend/tests/test_workflow_review_repairs.py +++ b/backend/tests/test_workflow_review_repairs.py @@ -1,23 +1,37 @@ """Regression tests for independent workflow orchestration review findings.""" + import httpx import pytest from sqlalchemy import select from app.models import Asset, Job -from app.v2_models import ApiToken, Batch, WorkflowRun, WorkflowStep +from app.models import ApiToken, Batch, WorkflowRun, WorkflowStep from test_workflows_v2 import wf, draft, run, publish_video async def tick(wf): - from app.workflow_engine import advance_workflows + from app.services.orchestration.workflow_engine import advance_workflows + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) -async def workflow_batch(wf, key='batch', extra=()): +async def workflow_batch(wf, key="batch", extra=()): d = await draft(wf) - response = await wf.client.post('/api/batches', json={'items':[ - {'kind':'workflow','draft_id':d['id'],'draft_revision':d['revision'],'expected_version':d['version']}, *extra - ]}, headers={'Idempotency-Key':key}) + response = await wf.client.post( + "/api/batches", + json={ + "items": [ + { + "kind": "workflow", + "draft_id": d["id"], + "draft_revision": d["revision"], + "expected_version": d["version"], + }, + *extra, + ] + }, + headers={"Idempotency-Key": key}, + ) assert response.status_code == 202, response.text return response.json() @@ -25,261 +39,410 @@ async def workflow_batch(wf, key='batch', extra=()): @pytest.mark.asyncio async def test_batch_cancel_before_children_reconciles_to_terminal(wf): batch = await workflow_batch(wf) - response = await wf.client.post('/api/batches/'+batch['batch']['id']+'/control', - json={'desired_state':'cancel'}, headers={'Idempotency-Key':'cancel'}) + response = await wf.client.post( + "/api/batches/" + batch["batch"]["id"] + "/control", + json={"desired_state": "cancel"}, + headers={"Idempotency-Key": "cancel"}, + ) assert response.status_code == 200 await tick(wf) - result = (await wf.client.get('/api/batches/'+batch['batch']['id'])).json() - assert result['batch']['state'] == 'cancelled' - assert result['items'][0]['state'] == 'cancelled' + result = (await wf.client.get("/api/batches/" + batch["batch"]["id"])).json() + assert result["batch"]["state"] == "cancelled" + assert result["items"][0]["state"] == "cancelled" @pytest.mark.asyncio async def test_held_batch_reconciles_finished_compose_without_new_admission(wf): batch = await workflow_batch(wf) - rid = batch['items'][0]['target_id'] + rid = batch["items"][0]["target_id"] for _ in range(3): await tick(wf) async with wf.app.state.db.session() as s: - selected = await s.scalar(select(Job.id).where(Job.run_id==rid, Job.state!='succeeded')) + selected = await s.scalar( + select(Job.id).where(Job.run_id == rid, Job.state != "succeeded") + ) await publish_video(wf, selected) await tick(wf) async with wf.app.state.db.session() as s: - compose = await s.scalar(select(Job.id).where(Job.run_id==rid, Job.step_key=='compose')) - b = await s.get(Batch,batch['batch']['id']); b.desired_state='pause'; b.hold_reasons=['admin_suspend'] + compose = await s.scalar(select(Job.id).where(Job.run_id == rid, Job.step_key == "compose")) + b = await s.get(Batch, batch["batch"]["id"]) + b.desired_state = "pause" + b.hold_reasons = ["admin_suspend"] await s.commit() - await publish_video(wf,compose,compose=True) + await publish_video(wf, compose, compose=True) await tick(wf) - result = (await wf.client.get('/api/workflow-runs/'+rid)).json() - assert result['run']['state'] == 'succeeded' - assert len(result['jobs']) == 4 + result = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert result["run"]["state"] == "succeeded" + assert len(result["jobs"]) == 4 @pytest.mark.asyncio async def test_retry_inherits_pause_manual_and_admin_holds(wf): - snap = await run(wf,await draft(wf)); rid=snap['run']['id'] + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] await tick(wf) async with wf.app.state.db.session() as s: - job = await s.scalar(select(Job).where(Job.run_id==rid)); job.state='failed'; jid=job.id + job = await s.scalar(select(Job).where(Job.run_id == rid)) + job.state = "failed" + jid = job.id await s.commit() - await wf.client.post('/api/workflow-runs/'+rid+'/pause',json={},headers={'Idempotency-Key':'pause'}) + await wf.client.post( + "/api/workflow-runs/" + rid + "/pause", json={}, headers={"Idempotency-Key": "pause"} + ) async with wf.app.state.db.session() as s: - r=await s.get(WorkflowRun,rid); r.hold_reasons=['manual','admin_suspend']; await s.commit() - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - response=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={ - 'expected_run_version':snap['run']['version'],'target_job_id':jid},headers={'Idempotency-Key':'retry'}) - assert response.status_code==202,response.text + r = await s.get(WorkflowRun, rid) + r.hold_reasons = ["manual", "admin_suspend"] + await s.commit() + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + response = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": jid}, + headers={"Idempotency-Key": "retry"}, + ) + assert response.status_code == 202, response.text async with wf.app.state.db.session() as s: - new=await s.get(Job,next(x['selected_job_id'] for x in response.json()['steps'] if x['step_key']=='shot_1')) - assert new.desired_state=='pause' - assert {'manual','admin_suspend'} <= set(new.hold_reasons) + new = await s.get( + Job, + next( + x["selected_job_id"] for x in response.json()["steps"] if x["step_key"] == "shot_1" + ), + ) + assert new.desired_state == "pause" + assert {"manual", "admin_suspend"} <= set(new.hold_reasons) @pytest.mark.asyncio async def test_retry_old_batch_member_can_coexist_with_later_member(wf): - batch=await workflow_batch(wf,extra=[{'kind':'job','task_type':'image.generate','input':{'prompt':'later'}}]) - rid=batch['items'][0]['target_id']; later_id=batch['items'][1]['target_id'] + batch = await workflow_batch( + wf, extra=[{"kind": "job", "task_type": "image.generate", "input": {"prompt": "later"}}] + ) + rid = batch["items"][0]["target_id"] + later_id = batch["items"][1]["target_id"] await tick(wf) async with wf.app.state.db.session() as s: - job=await s.scalar(select(Job).where(Job.run_id==rid)); job.state='failed'; jid=job.id; await s.commit() + job = await s.scalar(select(Job).where(Job.run_id == rid)) + job.state = "failed" + jid = job.id + await s.commit() await tick(wf) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - response=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={ - 'expected_run_version':snap['run']['version'],'target_job_id':jid},headers={'Idempotency-Key':'retry'}) - assert response.status_code==202,response.text - new_id=next(x['selected_job_id'] for x in response.json()['steps'] if x['step_key']=='shot_1') + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + response = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": jid}, + headers={"Idempotency-Key": "retry"}, + ) + assert response.status_code == 202, response.text + new_id = next( + x["selected_job_id"] for x in response.json()["steps"] if x["step_key"] == "shot_1" + ) for _ in range(2): await tick(wf) async with wf.app.state.db.session() as s: - assert 'batch_wait' not in (await s.get(Job,new_id)).hold_reasons - assert 'batch_wait' not in (await s.get(Job,later_id)).hold_reasons + assert "batch_wait" not in (await s.get(Job, new_id)).hold_reasons + assert "batch_wait" not in (await s.get(Job, later_id)).hold_reasons async with wf.app.state.db.session() as s: - later=await s.get(Job,later_id);later.state='succeeded';await s.commit() + later = await s.get(Job, later_id) + later.state = "succeeded" + await s.commit() await tick(wf) async with wf.app.state.db.session() as s: - assert 'batch_wait' not in (await s.get(Job,new_id)).hold_reasons + assert "batch_wait" not in (await s.get(Job, new_id)).hold_reasons @pytest.mark.asyncio async def test_two_accepted_batches_preserve_first_child_and_retry_quota_hold(wf): - wf.settings.max_owner_jobs=1 - one=await workflow_batch(wf,'one');two=await workflow_batch(wf,'two') + wf.settings.max_owner_jobs = 1 + one = await workflow_batch(wf, "one") + two = await workflow_batch(wf, "two") await tick(wf) async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job))).all() - assert len(jobs)==1 - held=await s.get(WorkflowRun,two['items'][0]['target_id']) - assert 'quota' in held.hold_reasons and held.error_json['code']=='quota_exceeded' - jobs[0].state='failed';await s.commit() + jobs = (await s.scalars(select(Job))).all() + assert len(jobs) == 1 + held = await s.get(WorkflowRun, two["items"][0]["target_id"]) + assert "quota" in held.hold_reasons and held.error_json["code"] == "quota_exceeded" + jobs[0].state = "failed" + await s.commit() await tick(wf) async with wf.app.state.db.session() as s: - assert await s.scalar(select(Job.id).where(Job.run_id==two['items'][0]['target_id'])) - assert 'quota' in (await s.get(WorkflowRun,two['items'][0]['target_id'])).hold_reasons - admitted=await s.scalar(select(Job).where(Job.run_id==two['items'][0]['target_id'])) - assert 'quota' not in admitted.hold_reasons + assert await s.scalar(select(Job.id).where(Job.run_id == two["items"][0]["target_id"])) + assert "quota" in (await s.get(WorkflowRun, two["items"][0]["target_id"])).hold_reasons + admitted = await s.scalar(select(Job).where(Job.run_id == two["items"][0]["target_id"])) + assert "quota" not in admitted.hold_reasons @pytest.mark.asyncio async def test_retry_coexists_with_active_sibling_when_representative_finished(wf): - batch=await workflow_batch(wf,extra=[{'kind':'job','task_type':'image.generate','input':{'prompt':'pair'},'count':2}]) - rid=batch['items'][0]['target_id'];bid=batch['batch']['id'] + batch = await workflow_batch( + wf, + extra=[ + {"kind": "job", "task_type": "image.generate", "input": {"prompt": "pair"}, "count": 2} + ], + ) + rid = batch["items"][0]["target_id"] + bid = batch["batch"]["id"] await tick(wf) async with wf.app.state.db.session() as s: - first=await s.scalar(select(Job).where(Job.run_id==rid));first.state='failed';jid=first.id - representative=await s.get(Job,batch['items'][1]['target_id']);representative.state='cancelled' + first = await s.scalar(select(Job).where(Job.run_id == rid)) + first.state = "failed" + jid = first.id + representative = await s.get(Job, batch["items"][1]["target_id"]) + representative.state = "cancelled" await s.commit() await tick(wf) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - response=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={ - 'expected_run_version':snap['run']['version'],'target_job_id':jid},headers={'Idempotency-Key':'retry'}) - assert response.status_code==202,response.text - retried=next(x['selected_job_id'] for x in response.json()['steps'] if x['step_key']=='shot_1') + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + response = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": jid}, + headers={"Idempotency-Key": "retry"}, + ) + assert response.status_code == 202, response.text + retried = next( + x["selected_job_id"] for x in response.json()["steps"] if x["step_key"] == "shot_1" + ) await tick(wf) async with wf.app.state.db.session() as s: - assert 'batch_wait' not in (await s.get(Job,retried)).hold_reasons - sibling=await s.scalar(select(Job).where(Job.batch_id==bid,Job.batch_item_index==1,Job.state!='cancelled')) - assert 'batch_wait' not in sibling.hold_reasons + assert "batch_wait" not in (await s.get(Job, retried)).hold_reasons + sibling = await s.scalar( + select(Job).where( + Job.batch_id == bid, Job.batch_item_index == 1, Job.state != "cancelled" + ) + ) + assert "batch_wait" not in sibling.hold_reasons @pytest.mark.asyncio -async def test_storage_admission_failure_isolated_and_retried(wf,monkeypatch): - from app import workflows - from app.errors import fail - first=await workflow_batch(wf,'one'); second=await workflow_batch(wf,'two') - original=workflows.create_jobs - held_owner_run=first['items'][0]['target_id'] - calls=0 - async def storage_once(*args,**kwargs): +async def test_storage_admission_failure_isolated_and_retried(wf, monkeypatch): + from app.services import workflows + from app.core.errors import fail + + first = await workflow_batch(wf, "one") + second = await workflow_batch(wf, "two") + original = workflows.create_jobs + held_owner_run = first["items"][0]["target_id"] + calls = 0 + + async def storage_once(*args, **kwargs): nonlocal calls - calls+=1 - if calls==1:fail(503,'storage_insufficient','Full') - return await original(*args,**kwargs) - monkeypatch.setattr(workflows,'create_jobs',storage_once) + calls += 1 + if calls == 1: + fail(503, "storage_insufficient", "Full") + return await original(*args, **kwargs) + + monkeypatch.setattr(workflows, "create_jobs", storage_once) await tick(wf) async with wf.app.state.db.session() as s: - assert 'storage' in (await s.get(WorkflowRun,held_owner_run)).hold_reasons - assert await s.scalar(select(Job.id).where(Job.run_id==second['items'][0]['target_id'])) + assert "storage" in (await s.get(WorkflowRun, held_owner_run)).hold_reasons + assert await s.scalar(select(Job.id).where(Job.run_id == second["items"][0]["target_id"])) await tick(wf) async with wf.app.state.db.session() as s: - assert await s.scalar(select(Job.id).where(Job.run_id==held_owner_run)) + assert await s.scalar(select(Job.id).where(Job.run_id == held_owner_run)) @pytest.mark.asyncio async def test_interactive_retry_scope_checked_on_new_request_and_accepted_replay(wf): - snap=await run(wf,await draft(wf));rid=snap['run']['id'];await tick(wf) + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + await tick(wf) async with wf.app.state.db.session() as s: - job=await s.scalar(select(Job).where(Job.run_id==rid));job.state='failed';jid=job.id;await s.commit() - await tick(wf);snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - issued=await wf.client.post('/api/auth/tokens',json={'name':'retry','scopes':['workflows:write']}) - token=issued.json()['token'];tid=issued.json()['record']['id'] - body={'expected_run_version':snap['run']['version'],'target_job_id':jid} - async with httpx.AsyncClient(transport=httpx.ASGITransport(app=wf.app),base_url='http://test',headers={'Authorization':'Bearer '+token}) as client: - url=f'/api/workflow-runs/{rid}/steps/shot_1/retry' - rejected=await client.post(url,json=body,headers={'Idempotency-Key':'retry'}) - assert rejected.status_code==403 + job = await s.scalar(select(Job).where(Job.run_id == rid)) + job.state = "failed" + jid = job.id + await s.commit() + await tick(wf) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + issued = await wf.client.post( + "/api/auth/tokens", json={"name": "retry", "scopes": ["workflows:write"]} + ) + token = issued.json()["token"] + tid = issued.json()["record"]["id"] + body = {"expected_run_version": snap["run"]["version"], "target_job_id": jid} + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=wf.app), + base_url="http://test", + headers={"Authorization": "Bearer " + token}, + ) as client: + url = f"/api/workflow-runs/{rid}/steps/shot_1/retry" + rejected = await client.post(url, json=body, headers={"Idempotency-Key": "retry"}) + assert rejected.status_code == 403 async with wf.app.state.db.session() as s: - row=await s.get(ApiToken,tid);row.scopes=['workflows:write','interactive:write'];await s.commit() - accepted=await client.post(url,json=body,headers={'Idempotency-Key':'retry'}) - assert accepted.status_code==202,accepted.text + row = await s.get(ApiToken, tid) + row.scopes = ["workflows:write", "interactive:write"] + await s.commit() + accepted = await client.post(url, json=body, headers={"Idempotency-Key": "retry"}) + assert accepted.status_code == 202, accepted.text async with wf.app.state.db.session() as s: - row=await s.get(ApiToken,tid);row.scopes=['workflows:write'];await s.commit() - replay=await client.post(url,json=body,headers={'Idempotency-Key':'retry'}) - assert replay.status_code==403 + row = await s.get(ApiToken, tid) + row.scopes = ["workflows:write"] + await s.commit() + replay = await client.post(url, json=body, headers={"Idempotency-Key": "retry"}) + assert replay.status_code == 403 @pytest.mark.asyncio -@pytest.mark.parametrize('task',['math.solve','media.structure','audio.speech']) -async def test_cpu_only_batch_accepted_without_gpu_capabilities(wf,png_bytes,monkeypatch,task): - checks=[] - async def offline():checks.append(True);raise RuntimeError('GPU offline') - monkeypatch.setattr(wf.provider,'upstream_capabilities',offline,raising=False) - wf.settings.tts_base_url='http://tts/v1';wf.settings.tts_model='kokoro' - inputs={'prompt':'hello'} - if task=='media.structure': - image=await wf.client.post('/api/assets',files={'file':('ref.png',png_bytes,'image/png')}) - inputs={'asset_id':image.json()['id']} - response=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':task,'input':inputs}]},headers={'Idempotency-Key':'cpu'}) - assert response.status_code==202,response.text - assert checks==[] +@pytest.mark.parametrize("task", ["math.solve", "media.structure", "audio.speech"]) +async def test_cpu_only_batch_accepted_without_gpu_capabilities(wf, png_bytes, monkeypatch, task): + checks = [] + + async def offline(): + checks.append(True) + raise RuntimeError("GPU offline") + + monkeypatch.setattr(wf.provider, "upstream_capabilities", offline, raising=False) + wf.settings.tts_base_url = "http://tts/v1" + wf.settings.tts_model = "kokoro" + inputs = {"prompt": "hello"} + if task == "media.structure": + image = await wf.client.post( + "/api/assets", files={"file": ("ref.png", png_bytes, "image/png")} + ) + inputs = {"asset_id": image.json()["id"]} + response = await wf.client.post( + "/api/batches", + json={"items": [{"kind": "job", "task_type": task, "input": inputs}]}, + headers={"Idempotency-Key": "cpu"}, + ) + assert response.status_code == 202, response.text + assert checks == [] @pytest.mark.asyncio async def test_admin_held_batch_propagates_to_standalone_and_run_members(wf): - batch=await workflow_batch(wf,extra=[{'kind':'job','task_type':'image.generate','input':{'prompt':'later'}}]) + batch = await workflow_batch( + wf, extra=[{"kind": "job", "task_type": "image.generate", "input": {"prompt": "later"}}] + ) async with wf.app.state.db.session() as s: - b=await s.get(Batch,batch['batch']['id']);b.hold_reasons=['admin_suspend'];await s.commit() + b = await s.get(Batch, batch["batch"]["id"]) + b.hold_reasons = ["admin_suspend"] + await s.commit() await tick(wf) async with wf.app.state.db.session() as s: - r=await s.get(WorkflowRun,batch['items'][0]['target_id']) - assert not await s.scalar(select(Job.id).where(Job.run_id==r.id)) - j=await s.get(Job,batch['items'][1]['target_id']) - assert 'admin_suspend' in j.hold_reasons - result=(await wf.client.get('/api/batches/'+batch['batch']['id'])).json() - assert result['batch']['hold_reasons']==['admin_suspend'] + r = await s.get(WorkflowRun, batch["items"][0]["target_id"]) + assert not await s.scalar(select(Job.id).where(Job.run_id == r.id)) + j = await s.get(Job, batch["items"][1]["target_id"]) + assert "admin_suspend" in j.hold_reasons + result = (await wf.client.get("/api/batches/" + batch["batch"]["id"])).json() + assert result["batch"]["hold_reasons"] == ["admin_suspend"] @pytest.mark.asyncio -@pytest.mark.parametrize('corruption',['missing','same_size','wrong_size','outside_root','foreign_owner']) -async def test_reuse_requires_owned_verified_file(wf,corruption,tmp_path): - d=await draft(wf);snap=await run(wf,d);rid=snap['run']['id'];await tick(wf) - async with wf.app.state.db.session() as s: - jid=await s.scalar(select(Job.id).where(Job.run_id==rid)) - aid=await publish_video(wf,jid) - await tick(wf) - await wf.client.post('/api/workflow-runs/'+rid+'/cancel',json={},headers={'Idempotency-Key':'cancel'}) +@pytest.mark.parametrize( + "corruption", ["missing", "same_size", "wrong_size", "outside_root", "foreign_owner"] +) +async def test_reuse_requires_owned_verified_file(wf, corruption, tmp_path): + d = await draft(wf) + snap = await run(wf, d) + rid = snap["run"]["id"] await tick(wf) async with wf.app.state.db.session() as s: - a=await s.get(Asset,aid);path=wf.settings.asset_root/a.storage_key - if corruption=='missing':path.unlink(missing_ok=True) - elif corruption=='same_size':path.write_bytes(b'x'*a.size_bytes) - elif corruption=='wrong_size':path.write_bytes(b'bad size') - elif corruption=='outside_root': - escape=tmp_path/'outside.mp4';escape.write_bytes(b'v');a.storage_key=str(escape) + jid = await s.scalar(select(Job.id).where(Job.run_id == rid)) + aid = await publish_video(wf, jid) + await tick(wf) + await wf.client.post( + "/api/workflow-runs/" + rid + "/cancel", json={}, headers={"Idempotency-Key": "cancel"} + ) + await tick(wf) + async with wf.app.state.db.session() as s: + a = await s.get(Asset, aid) + path = wf.settings.asset_root / a.storage_key + if corruption == "missing": + path.unlink(missing_ok=True) + elif corruption == "same_size": + path.write_bytes(b"x" * a.size_bytes) + elif corruption == "wrong_size": + path.write_bytes(b"bad size") + elif corruption == "outside_root": + escape = tmp_path / "outside.mp4" + escape.write_bytes(b"v") + a.storage_key = str(escape) else: from app.models import User - foreign=User(username='foreign',display_name='Other',password_hash='unused');s.add(foreign);await s.flush();a.owner_id=foreign.id + + foreign = User(username="foreign", display_name="Other", password_hash="unused") + s.add(foreign) + await s.flush() + a.owner_id = foreign.id await s.commit() - current=(await wf.client.get('/api/workflows/'+d['id'])).json() - response=await wf.client.post('/api/workflows/'+d['id']+'/runs',json={ - 'draft_revision':current['revision'],'expected_version':current['version'],'reuse_run_id':rid},headers={'Idempotency-Key':'reuse'}) - assert response.status_code==202,response.text - shot=next(x for x in response.json()['steps'] if x['step_key']=='shot_1') - assert shot['selected_job_id'] is None and shot['state']=='waiting' + current = (await wf.client.get("/api/workflows/" + d["id"])).json() + response = await wf.client.post( + "/api/workflows/" + d["id"] + "/runs", + json={ + "draft_revision": current["revision"], + "expected_version": current["version"], + "reuse_run_id": rid, + }, + headers={"Idempotency-Key": "reuse"}, + ) + assert response.status_code == 202, response.text + shot = next(x for x in response.json()["steps"] if x["step_key"] == "shot_1") + assert shot["selected_job_id"] is None and shot["state"] == "waiting" @pytest.mark.asyncio -async def test_source_sha_participates_in_shot_semantic_hash(wf,png_bytes): +async def test_source_sha_participates_in_shot_semantic_hash(wf, png_bytes): from test_timeline_v2 import spec - upload=await wf.client.post('/api/assets',files={'file':('ref.png',png_bytes,'image/png')});aid=upload.json()['id'] - body=spec();body['shots'][0]['image_asset_id']=aid - d=(await wf.client.post('/api/workflows',json={'spec':body})).json() - first=await run(wf,d) - await wf.client.post('/api/workflow-runs/'+first['run']['id']+'/cancel',json={},headers={'Idempotency-Key':'cancel'});await tick(wf) + + upload = await wf.client.post( + "/api/assets", files={"file": ("ref.png", png_bytes, "image/png")} + ) + aid = upload.json()["id"] + body = spec() + body["shots"][0]["image_asset_id"] = aid + d = (await wf.client.post("/api/workflows", json={"spec": body})).json() + first = await run(wf, d) + await wf.client.post( + "/api/workflow-runs/" + first["run"]["id"] + "/cancel", + json={}, + headers={"Idempotency-Key": "cancel"}, + ) + await tick(wf) async with wf.app.state.db.session() as s: - a=await s.get(Asset,aid);a.sha256='b'*64;await s.commit() - d=(await wf.client.get('/api/workflows/'+d['id'])).json();second=await run(wf,d,'second') - hashes=lambda snap:{x['step_key']:x['semantic_input_hash'] for x in snap['steps']} - assert hashes(first)['shot_1']!=hashes(second)['shot_1'] - assert hashes(first)['shot_2']==hashes(second)['shot_2'] + a = await s.get(Asset, aid) + a.sha256 = "b" * 64 + await s.commit() + d = (await wf.client.get("/api/workflows/" + d["id"])).json() + second = await run(wf, d, "second") + hashes = lambda snap: {x["step_key"]: x["semantic_input_hash"] for x in snap["steps"]} + assert hashes(first)["shot_1"] != hashes(second)["shot_1"] + assert hashes(first)["shot_2"] == hashes(second)["shot_2"] @pytest.mark.asyncio async def test_compose_hash_changes_when_selected_output_bytes_change(wf): - batch=await workflow_batch(wf);rid=batch['items'][0]['target_id'] + batch = await workflow_batch(wf) + rid = batch["items"][0]["target_id"] for _ in range(3): await tick(wf) async with wf.app.state.db.session() as s: - jid=await s.scalar(select(Job.id).where(Job.run_id==rid,Job.state!='succeeded')) - await publish_video(wf,jid) + jid = await s.scalar(select(Job.id).where(Job.run_id == rid, Job.state != "succeeded")) + await publish_video(wf, jid) await tick(wf) async with wf.app.state.db.session() as s: - compose=await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id==rid,WorkflowStep.step_key=='compose')) - first=compose.semantic_input_hash;jid=compose.selected_job_id - job=await s.get(Job,jid);job.state='failed' - a=await s.scalar(select(Asset).where(Asset.source_job_id.in_(select(Job.id).where(Job.run_id==rid,Job.step_key=='shot_2'))));a.sha256='b'*64 + compose = await s.scalar( + select(WorkflowStep).where( + WorkflowStep.run_id == rid, WorkflowStep.step_key == "compose" + ) + ) + first = compose.semantic_input_hash + jid = compose.selected_job_id + job = await s.get(Job, jid) + job.state = "failed" + a = await s.scalar( + select(Asset).where( + Asset.source_job_id.in_( + select(Job.id).where(Job.run_id == rid, Job.step_key == "shot_2") + ) + ) + ) + a.sha256 = "b" * 64 await s.commit() - await tick(wf);snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - result=await wf.client.post(f'/api/workflow-runs/{rid}/steps/compose/retry',json={ - 'expected_run_version':snap['run']['version'],'target_job_id':jid},headers={'Idempotency-Key':'retry'}) - assert result.status_code==202,result.text - assert first!=next(x['semantic_input_hash'] for x in result.json()['steps'] if x['step_key']=='compose') + await tick(wf) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + result = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/compose/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": jid}, + headers={"Idempotency-Key": "retry"}, + ) + assert result.status_code == 202, result.text + assert first != next( + x["semantic_input_hash"] for x in result.json()["steps"] if x["step_key"] == "compose" + ) diff --git a/backend/tests/test_workflows_v2.py b/backend/tests/test_workflows_v2.py index fe344da..300cb51 100644 --- a/backend/tests/test_workflows_v2.py +++ b/backend/tests/test_workflows_v2.py @@ -2,270 +2,554 @@ import copy import pytest from sqlalchemy import select from app.models import Job, Asset -from app.v2_models import WorkflowRun, WorkflowStep +from app.models import WorkflowRun, WorkflowStep from test_timeline_v2 import spec + @pytest.fixture async def wf(system): - from app.workflows import router, runs_router - from app.batches import router as batches - system.app.include_router(router,prefix='/api'); system.app.include_router(runs_router,prefix='/api'); system.app.include_router(batches,prefix='/api') + from app.api.routes.workflows import router, runs_router + from app.api.routes.batches import router as batches + + system.app.include_router(router, prefix="/api") + system.app.include_router(runs_router, prefix="/api") + system.app.include_router(batches, prefix="/api") return system + async def draft(wf): - r = await wf.client.post('/api/workflows',json={'name':'test','spec':spec()}) - assert r.status_code == 201,r.text + r = await wf.client.post("/api/workflows", json={"name": "test", "spec": spec()}) + assert r.status_code == 201, r.text return r.json() -async def run(wf,d,key='start'): - r = await wf.client.post(f"/api/workflows/{d['id']}/runs",json={'draft_revision':d['revision'],'expected_version':d['version']},headers={'Idempotency-Key':key}) - assert r.status_code == 202,r.text + +async def run(wf, d, key="start"): + r = await wf.client.post( + f"/api/workflows/{d['id']}/runs", + json={"draft_revision": d["revision"], "expected_version": d["version"]}, + headers={"Idempotency-Key": key}, + ) + assert r.status_code == 202, r.text return r.json() + @pytest.mark.asyncio -async def test_snapshot_version_idempotency_owner(wf,other_client): - d = await draft(wf); a = await run(wf,d); b = await run(wf,d) - assert a['run']['id'] == b['run']['id'] - r = await other_client.get('/api/workflow-runs/'+a['run']['id']); assert r.status_code == 404 - r = await wf.client.patch('/api/workflows/'+d['id'],json={'name':'new'},headers={'If-Match':str(d['version'])}); assert r.status_code == 409 - current = (await wf.client.get('/api/workflows/'+d['id'])).json() - changed = spec(); changed['shots'][0]['prompt'] = 'new prompt' - r = await wf.client.patch('/api/workflows/'+d['id'],json={'spec':changed},headers={'If-Match':str(current['version'])}); assert r.status_code == 200 +async def test_snapshot_version_idempotency_owner(wf, other_client): + d = await draft(wf) + a = await run(wf, d) + b = await run(wf, d) + assert a["run"]["id"] == b["run"]["id"] + r = await other_client.get("/api/workflow-runs/" + a["run"]["id"]) + assert r.status_code == 404 + r = await wf.client.patch( + "/api/workflows/" + d["id"], json={"name": "new"}, headers={"If-Match": str(d["version"])} + ) + assert r.status_code == 409 + current = (await wf.client.get("/api/workflows/" + d["id"])).json() + changed = spec() + changed["shots"][0]["prompt"] = "new prompt" + r = await wf.client.patch( + "/api/workflows/" + d["id"], + json={"spec": changed}, + headers={"If-Match": str(current["version"])}, + ) + assert r.status_code == 200 async with wf.app.state.db.session() as s: - row = await s.get(WorkflowRun,a['run']['id']); assert row.spec_snapshot['shots'][0]['prompt'] != 'new prompt' + row = await s.get(WorkflowRun, a["run"]["id"]) + assert row.spec_snapshot["shots"][0]["prompt"] != "new prompt" + @pytest.mark.asyncio async def test_engine_durable_parallel_cancel_and_no_new_job(wf): - from app.workflow_engine import advance_workflows - d = await draft(wf); snap = await run(wf,d) - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap = (await wf.client.get('/api/workflow-runs/'+snap['run']['id'])).json() - assert len(snap['jobs']) == 3 and snap['jobs'][0]['step_key'] == 'shot_1' - r = await wf.client.post('/api/workflow-runs/'+snap['run']['id']+'/cancel',json={},headers={'Idempotency-Key':'cancel'}) - assert r.status_code == 200,r.text - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap = (await wf.client.get('/api/workflow-runs/'+snap['run']['id'])).json() - assert snap['run']['state'] == 'cancelled' and len(snap['jobs']) == 3 + from app.services.orchestration.workflow_engine import advance_workflows + + d = await draft(wf) + snap = await run(wf, d) + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + snap["run"]["id"])).json() + assert len(snap["jobs"]) == 3 and snap["jobs"][0]["step_key"] == "shot_1" + r = await wf.client.post( + "/api/workflow-runs/" + snap["run"]["id"] + "/cancel", + json={}, + headers={"Idempotency-Key": "cancel"}, + ) + assert r.status_code == 200, r.text + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + snap["run"]["id"])).json() + assert snap["run"]["state"] == "cancelled" and len(snap["jobs"]) == 3 assert wf.provider.submitted_payloads == [] + @pytest.mark.asyncio async def test_failed_step_explicit_retry_only_and_old_target_rejected(wf): - from app.workflow_engine import advance_workflows - snap = await run(wf,await draft(wf)); rid=snap['run']['id'] - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + from app.services.orchestration.workflow_engine import advance_workflows + + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as s: - old = await s.scalar(select(Job).where(Job.run_id==rid)); old.state='failed'; old.phase='failed'; oid=old.id; await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - assert snap['run']['state']=='blocked' and len(snap['jobs'])==3 - body={'expected_run_version':snap['run']['version'],'target_job_id':oid} - r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json=body,headers={'Idempotency-Key':'redo'}) - assert r.status_code==202,r.text - again=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json=body,headers={'Idempotency-Key':'redo'}) - assert again.status_code==202 and len(again.json()['jobs'])==4 - r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={**body,'expected_run_version':again.json()['run']['version']},headers={'Idempotency-Key':'stale'}) - assert r.status_code==409 + old = await s.scalar(select(Job).where(Job.run_id == rid)) + old.state = "failed" + old.phase = "failed" + oid = old.id + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snap["run"]["state"] == "blocked" and len(snap["jobs"]) == 3 + body = {"expected_run_version": snap["run"]["version"], "target_job_id": oid} + r = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json=body, + headers={"Idempotency-Key": "redo"}, + ) + assert r.status_code == 202, r.text + again = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json=body, + headers={"Idempotency-Key": "redo"}, + ) + assert again.status_code == 202 and len(again.json()["jobs"]) == 4 + r = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={**body, "expected_run_version": again.json()["run"]["version"]}, + headers={"Idempotency-Key": "stale"}, + ) + assert r.status_code == 409 + @pytest.mark.asyncio async def test_batch_mixed_persistent_one_active_member(wf): - d=await draft(wf) - body={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':'one'},'parameters':{}},{'kind':'workflow','draft_id':d['id'],'draft_revision':d['revision'],'expected_version':d['version']}]} - r=await wf.client.post('/api/batches',json=body,headers={'Idempotency-Key':'batch'}) - assert r.status_code==202,r.text - snap=r.json(); assert len(snap['items'])==2 + d = await draft(wf) + body = { + "items": [ + { + "kind": "job", + "task_type": "image.generate", + "input": {"prompt": "one"}, + "parameters": {}, + }, + { + "kind": "workflow", + "draft_id": d["id"], + "draft_revision": d["revision"], + "expected_version": d["version"], + }, + ] + } + r = await wf.client.post("/api/batches", json=body, headers={"Idempotency-Key": "batch"}) + assert r.status_code == 202, r.text + snap = r.json() + assert len(snap["items"]) == 2 async with wf.app.state.db.session() as s: - jobs=(await s.scalars(select(Job))).all(); assert all(j.execution_mode=='batch' for j in jobs) - same=await wf.client.post('/api/batches',json=body,headers={'Idempotency-Key':'batch'}) - assert same.json()['batch']['id']==snap['batch']['id'] + jobs = (await s.scalars(select(Job))).all() + assert all(j.execution_mode == "batch" for j in jobs) + same = await wf.client.post("/api/batches", json=body, headers={"Idempotency-Key": "batch"}) + assert same.json()["batch"]["id"] == snap["batch"]["id"] + @pytest.mark.asyncio async def test_old_result_after_retry_cannot_advance_selected_step(wf): - from app.workflow_engine import advance_workflows - snap=await run(wf,await draft(wf));rid=snap['run']['id'] - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + from app.services.orchestration.workflow_engine import advance_workflows + + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as s: - old=await s.scalar(select(Job).where(Job.run_id==rid));old.state='failed';old.phase='failed';oid=old.id;await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={'expected_run_version':snap['run']['version'],'target_job_id':oid},headers={'Idempotency-Key':'retry'}) - assert r.status_code==202 + old = await s.scalar(select(Job).where(Job.run_id == rid)) + old.state = "failed" + old.phase = "failed" + oid = old.id + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + r = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": oid}, + headers={"Idempotency-Key": "retry"}, + ) + assert r.status_code == 202 async with wf.app.state.db.session() as s: - old=await s.get(Job,oid);old.state='succeeded';await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - assert len(snap['jobs'])==4 - shot=next(s for s in snap['steps'] if s['step_key']=='shot_1') - assert shot['state']!='succeeded' and shot['selected_job_id']!=oid + old = await s.get(Job, oid) + old.state = "succeeded" + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert len(snap["jobs"]) == 4 + shot = next(s for s in snap["steps"] if s["step_key"] == "shot_1") + assert shot["state"] != "succeeded" and shot["selected_job_id"] != oid + @pytest.mark.asyncio async def test_batch_pause_resume_preserves_member_manual_pause(wf): - from app.workflow_engine import advance_workflows - d=await draft(wf) - r=await wf.client.post('/api/batches',json={'items':[{'kind':'workflow','draft_id':d['id'],'draft_revision':d['revision'],'expected_version':d['version']}]},headers={'Idempotency-Key':'b'}) - bid=r.json()['batch']['id'];rid=r.json()['items'][0]['target_id'] - r=await wf.client.post(f'/api/workflow-runs/{rid}/pause',json={},headers={'Idempotency-Key':'manual'}) - assert r.status_code==200 - for intent in ('pause','run'): - r=await wf.client.post(f'/api/batches/{bid}/control',json={'desired_state':intent},headers={'Idempotency-Key':intent}) - assert r.status_code==200,r.text - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - assert snap['run']['desired_state']=='pause' and snap['jobs']==[] + from app.services.orchestration.workflow_engine import advance_workflows + + d = await draft(wf) + r = await wf.client.post( + "/api/batches", + json={ + "items": [ + { + "kind": "workflow", + "draft_id": d["id"], + "draft_revision": d["revision"], + "expected_version": d["version"], + } + ] + }, + headers={"Idempotency-Key": "b"}, + ) + bid = r.json()["batch"]["id"] + rid = r.json()["items"][0]["target_id"] + r = await wf.client.post( + f"/api/workflow-runs/{rid}/pause", json={}, headers={"Idempotency-Key": "manual"} + ) + assert r.status_code == 200 + for intent in ("pause", "run"): + r = await wf.client.post( + f"/api/batches/{bid}/control", + json={"desired_state": intent}, + headers={"Idempotency-Key": intent}, + ) + assert r.status_code == 200, r.text + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snap["run"]["desired_state"] == "pause" and snap["jobs"] == [] + @pytest.mark.asyncio async def test_batch_qwen_uses_finish_current_admission(wf): - r=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':'math.solve','input':{'prompt':'2+2'}}]},headers={'Idempotency-Key':'unsafe'}) - assert r.status_code==202,r.text + r = await wf.client.post( + "/api/batches", + json={"items": [{"kind": "job", "task_type": "math.solve", "input": {"prompt": "2+2"}}]}, + headers={"Idempotency-Key": "unsafe"}, + ) + assert r.status_code == 202, r.text + @pytest.mark.asyncio async def test_retry_with_active_execution_refuses_even_failed_job(wf): - from app.workflow_engine import advance_workflows - from app.v2_models import Execution - snap=await run(wf,await draft(wf));rid=snap['run']['id'] - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + from app.services.orchestration.workflow_engine import advance_workflows + from app.models import Execution + + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as s: - old=await s.scalar(select(Job).where(Job.run_id==rid));old.state='failed';old.phase='failed';oid=old.id - s.add(Execution(job_id=oid,ordinal=1,phase_key='execute',resource_pool='new_gpu',fence_token='f',state='unknown'));await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={'expected_run_version':snap['run']['version'],'target_job_id':oid},headers={'Idempotency-Key':'retry'}) - assert r.status_code==409 and r.json()['detail']['code']=='cleanup_pending' + old = await s.scalar(select(Job).where(Job.run_id == rid)) + old.state = "failed" + old.phase = "failed" + oid = old.id + s.add( + Execution( + job_id=oid, + ordinal=1, + phase_key="execute", + resource_pool="new_gpu", + fence_token="f", + state="unknown", + ) + ) + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + r = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/shot_1/retry", + json={"expected_run_version": snap["run"]["version"], "target_job_id": oid}, + headers={"Idempotency-Key": "retry"}, + ) + assert r.status_code == 409 and r.json()["detail"]["code"] == "cleanup_pending" + @pytest.mark.asyncio -async def test_draft_deletion_reference_and_snapshot_guards(wf,png_bytes): - upload=await wf.client.post('/api/assets',files={'file':('reference.png',png_bytes,'image/png')}) - assert upload.status_code==201,upload.text - aid=upload.json()['id'] - body=spec();body['shots'][0]['image_asset_id']=aid - r=await wf.client.post('/api/workflows',json={'spec':body});assert r.status_code==201 - r=await wf.client.delete('/api/assets/'+aid) - assert r.status_code==409,r.text +async def test_draft_deletion_reference_and_snapshot_guards(wf, png_bytes): + upload = await wf.client.post( + "/api/assets", files={"file": ("reference.png", png_bytes, "image/png")} + ) + assert upload.status_code == 201, upload.text + aid = upload.json()["id"] + body = spec() + body["shots"][0]["image_asset_id"] = aid + r = await wf.client.post("/api/workflows", json={"spec": body}) + assert r.status_code == 201 + r = await wf.client.delete("/api/assets/" + aid) + assert r.status_code == 409, r.text + @pytest.mark.asyncio async def test_duplicate_workflow_batch_items_freeze_same_revision(wf): - d=await draft(wf);item={'kind':'workflow','draft_id':d['id'],'draft_revision':d['revision'],'expected_version':d['version']} - r=await wf.client.post('/api/batches',json={'items':[item,item]},headers={'Idempotency-Key':'tworuns'}) - assert r.status_code==202,r.text - assert len({i['target_id'] for i in r.json()['items']})==2 + d = await draft(wf) + item = { + "kind": "workflow", + "draft_id": d["id"], + "draft_revision": d["revision"], + "expected_version": d["version"], + } + r = await wf.client.post( + "/api/batches", json={"items": [item, item]}, headers={"Idempotency-Key": "tworuns"} + ) + assert r.status_code == 202, r.text + assert len({i["target_id"] for i in r.json()["items"]}) == 2 -async def publish_video(wf,jid,*,compose=False): + +async def publish_video(wf, jid, *, compose=False): import hashlib from app.models import utcnow + async with wf.app.state.db.session() as s: - j=await s.get(Job,jid);j.state='succeeded';j.phase='completed';j.finished_at=utcnow() - data=b'v';storage_key='test-'+jid+'.mp4' - (wf.settings.asset_root/storage_key).write_bytes(data) - a=Asset(owner_id=j.owner_id,name='video.mp4',storage_key=storage_key,kind='video',mime_type='video/mp4',size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(),width=1920,height=1080 if compose else 1056,duration_seconds=15 if compose else 121/24,ready=True,origin='generated',source_job_id=j.id,source_output_index=0) - s.add(a);await s.flush();aid=a.id;await s.commit();return aid + j = await s.get(Job, jid) + j.state = "succeeded" + j.phase = "completed" + j.finished_at = utcnow() + data = b"v" + storage_key = "test-" + jid + ".mp4" + (wf.settings.asset_root / storage_key).write_bytes(data) + a = Asset( + owner_id=j.owner_id, + name="video.mp4", + storage_key=storage_key, + kind="video", + mime_type="video/mp4", + size_bytes=len(data), + sha256=hashlib.sha256(data).hexdigest(), + width=1920, + height=1080 if compose else 1056, + duration_seconds=15 if compose else 121 / 24, + ready=True, + origin="generated", + source_job_id=j.id, + source_output_index=0, + ) + s.add(a) + await s.flush() + aid = a.id + await s.commit() + return aid + @pytest.mark.asyncio async def test_compose_retry_reuses_all_shots_and_old_run_cannot_overwrite(wf): - from app.workflow_engine import advance_workflows - d=await draft(wf);snap=await run(wf,d);rid=snap['run']['id'] - for key in ('shot_1','shot_2','shot_3'): - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - selected=next(s for s in snap['steps'] if s['step_key']==key)['selected_job_id'] - await publish_video(wf,selected) - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();compose=next(s for s in snap['steps'] if s['step_key']=='compose') + from app.services.orchestration.workflow_engine import advance_workflows + + d = await draft(wf) + snap = await run(wf, d) + rid = snap["run"]["id"] + for key in ("shot_1", "shot_2", "shot_3"): + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + selected = next(s for s in snap["steps"] if s["step_key"] == key)["selected_job_id"] + await publish_video(wf, selected) + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + compose = next(s for s in snap["steps"] if s["step_key"] == "compose") async with wf.app.state.db.session() as s: - j=await s.get(Job,compose['selected_job_id']);j.state='failed';j.phase='failed';await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/compose/retry',json={'expected_run_version':snap['run']['version'],'target_job_id':compose['selected_job_id']},headers={'Idempotency-Key':'compose-retry'}) - assert r.status_code==202,r.text - assert sum(j['task_type']=='video.generate' for j in r.json()['jobs'])==3 - await publish_video(wf,next(s for s in r.json()['steps'] if s['step_key']=='compose')['selected_job_id'],compose=True) - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();assert snap['run']['state']=='succeeded' - current=(await wf.client.get('/api/workflows/'+d['id'])).json() - body=spec();body['shots'][1]['prompt']='new shot2' - changed=await wf.client.patch('/api/workflows/'+d['id'],json={'spec':body},headers={'If-Match':str(current['version'])});current=changed.json() - r=await wf.client.post('/api/workflows/'+d['id']+'/runs',json={'draft_revision':current['revision'],'expected_version':current['version'],'reuse_run_id':rid},headers={'Idempotency-Key':'new-run'}) - assert r.status_code==202,r.text - new=r.json();assert sum(s['state']=='succeeded' for s in new['steps'])==2 - assert len(new['jobs'])==2 - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - current=(await wf.client.get('/api/workflows/'+d['id'])).json();assert current['current_run_id']==new['run']['id'] + j = await s.get(Job, compose["selected_job_id"]) + j.state = "failed" + j.phase = "failed" + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + r = await wf.client.post( + f"/api/workflow-runs/{rid}/steps/compose/retry", + json={ + "expected_run_version": snap["run"]["version"], + "target_job_id": compose["selected_job_id"], + }, + headers={"Idempotency-Key": "compose-retry"}, + ) + assert r.status_code == 202, r.text + assert sum(j["task_type"] == "video.generate" for j in r.json()["jobs"]) == 3 + await publish_video( + wf, + next(s for s in r.json()["steps"] if s["step_key"] == "compose")["selected_job_id"], + compose=True, + ) + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snap["run"]["state"] == "succeeded" + current = (await wf.client.get("/api/workflows/" + d["id"])).json() + body = spec() + body["shots"][1]["prompt"] = "new shot2" + changed = await wf.client.patch( + "/api/workflows/" + d["id"], + json={"spec": body}, + headers={"If-Match": str(current["version"])}, + ) + current = changed.json() + r = await wf.client.post( + "/api/workflows/" + d["id"] + "/runs", + json={ + "draft_revision": current["revision"], + "expected_version": current["version"], + "reuse_run_id": rid, + }, + headers={"Idempotency-Key": "new-run"}, + ) + assert r.status_code == 202, r.text + new = r.json() + assert sum(s["state"] == "succeeded" for s in new["steps"]) == 2 + assert len(new["jobs"]) == 2 + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + current = (await wf.client.get("/api/workflows/" + d["id"])).json() + assert current["current_run_id"] == new["run"]["id"] + @pytest.mark.asyncio async def test_cancel_with_inflight_child_waits_and_success_late_does_not_publish(wf): - from app.workflow_engine import advance_workflows - snap=await run(wf,await draft(wf));rid=snap['run']['id'] - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + from app.services.orchestration.workflow_engine import advance_workflows + + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as s: - j=await s.scalar(select(Job).where(Job.run_id==rid));j.state='running';j.phase='inference';j.upstream_id='remote';jid=j.id;await s.commit() - r=await wf.client.post('/api/workflow-runs/'+rid+'/cancel',json={},headers={'Idempotency-Key':'cancel'}) - assert r.json()['run']['state']=='cancelling' - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();assert snap['run']['state']=='cancelling' - await publish_video(wf,jid) - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();assert snap['run']['state']=='cancelled' and snap['run']['result_assets']==[] and len(snap['jobs'])==3 + j = await s.scalar(select(Job).where(Job.run_id == rid)) + j.state = "running" + j.phase = "inference" + j.upstream_id = "remote" + jid = j.id + await s.commit() + r = await wf.client.post( + "/api/workflow-runs/" + rid + "/cancel", json={}, headers={"Idempotency-Key": "cancel"} + ) + assert r.json()["run"]["state"] == "cancelling" + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snap["run"]["state"] == "cancelling" + await publish_video(wf, jid) + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert ( + snap["run"]["state"] == "cancelled" + and snap["run"]["result_assets"] == [] + and len(snap["jobs"]) == 3 + ) + @pytest.mark.asyncio async def test_parallel_run_and_patch_versions_accept_one(wf): import asyncio - d=await draft(wf) - async def patch(name):return await wf.client.patch('/api/workflows/'+d['id'],json={'name':name},headers={'If-Match':str(d['version'])}) - responses=await asyncio.gather(patch('a'),patch('b')) - assert sorted(r.status_code for r in responses)==[200,409] - d=(await wf.client.get('/api/workflows/'+d['id'])).json() - async def start(key):return await wf.client.post('/api/workflows/'+d['id']+'/runs',json={'draft_revision':d['revision'],'expected_version':d['version']},headers={'Idempotency-Key':key}) - responses=await asyncio.gather(start('a'),start('b')) - assert sorted(r.status_code for r in responses)==[202,409] + + d = await draft(wf) + + async def patch(name): + return await wf.client.patch( + "/api/workflows/" + d["id"], + json={"name": name}, + headers={"If-Match": str(d["version"])}, + ) + + responses = await asyncio.gather(patch("a"), patch("b")) + assert sorted(r.status_code for r in responses) == [200, 409] + d = (await wf.client.get("/api/workflows/" + d["id"])).json() + + async def start(key): + return await wf.client.post( + "/api/workflows/" + d["id"] + "/runs", + json={"draft_revision": d["revision"], "expected_version": d["version"]}, + headers={"Idempotency-Key": key}, + ) + + responses = await asyncio.gather(start("a"), start("b")) + assert sorted(r.status_code for r in responses) == [202, 409] + @pytest.mark.asyncio async def test_batch_retains_unknown_cleanup_while_other_member_progresses(wf): - from app.workflow_engine import advance_workflows - from app.v2_models import Execution - r=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':p}} for p in ('one','two')]},headers={'Idempotency-Key':'batch'}) - items=r.json()['items'];bid=r.json()['batch']['id'] + from app.services.orchestration.workflow_engine import advance_workflows + from app.models import Execution + + r = await wf.client.post( + "/api/batches", + json={ + "items": [ + {"kind": "job", "task_type": "image.generate", "input": {"prompt": p}} + for p in ("one", "two") + ] + }, + headers={"Idempotency-Key": "batch"}, + ) + items = r.json()["items"] + bid = r.json()["batch"]["id"] async with wf.app.state.db.session() as s: - j=await s.get(Job,items[0]['target_id']);j.state='failed';j.phase='failed' - s.add(Execution(job_id=j.id,ordinal=1,phase_key='execute',resource_pool='new_gpu',fence_token='f',state='unknown'));await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + j = await s.get(Job, items[0]["target_id"]) + j.state = "failed" + j.phase = "failed" + s.add( + Execution( + job_id=j.id, + ordinal=1, + phase_key="execute", + resource_pool="new_gpu", + fence_token="f", + state="unknown", + ) + ) + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as s: - j=await s.get(Job,items[1]['target_id']);assert 'batch_wait' not in j.hold_reasons - snap=(await wf.client.get('/api/batches/'+bid)).json();assert snap['items'][0]['state']=='cleanup_pending' + j = await s.get(Job, items[1]["target_id"]) + assert "batch_wait" not in j.hold_reasons + snap = (await wf.client.get("/api/batches/" + bid)).json() + assert snap["items"][0]["state"] == "cleanup_pending" + @pytest.mark.asyncio async def test_missing_selected_output_blocks_only_affected_run(wf): - from app.workflow_engine import advance_workflows - snap=await run(wf,await draft(wf));rid=snap['run']['id'] - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) + from app.services.orchestration.workflow_engine import advance_workflows + + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) async with wf.app.state.db.session() as s: - j=await s.scalar(select(Job).where(Job.run_id==rid));j.state='succeeded';await s.commit() - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - assert snap['run']['state']=='blocked' and len(snap['jobs'])==3 + j = await s.scalar(select(Job).where(Job.run_id == rid)) + j.state = "succeeded" + await s.commit() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snap["run"]["state"] == "blocked" and len(snap["jobs"]) == 3 + @pytest.mark.asyncio async def test_maintenance_keeps_existing_run_queued_without_creating_children(wf): - from app.workflow_engine import advance_workflows - snap=await run(wf,await draft(wf));rid=snap['run']['id'] - marker=wf.settings.state_root/'maintenance';marker.write_text('on') + from app.services.orchestration.workflow_engine import advance_workflows + + snap = await run(wf, await draft(wf)) + rid = snap["run"]["id"] + marker = wf.settings.state_root / "maintenance" + marker.write_text("on") try: - await advance_workflows(wf.app.state.db,wf.settings,wf.provider) - snap=(await wf.client.get('/api/workflow-runs/'+rid)).json() - assert snap['jobs']==[] and snap['run']['state']!='failed' - finally:marker.unlink() + await advance_workflows(wf.app.state.db, wf.settings, wf.provider) + snap = (await wf.client.get("/api/workflow-runs/" + rid)).json() + assert snap["jobs"] == [] and snap["run"]["state"] != "failed" + finally: + marker.unlink() + @pytest.mark.asyncio -async def test_batch_capability_downgrade_rejected_before_acceptance(wf,monkeypatch): - async def caps():return {'protocol_version':1,'admission_policy':False} - monkeypatch.setattr(wf.provider,'upstream_capabilities',caps,raising=False) - r=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':'one'}}]},headers={'Idempotency-Key':'old-upstream'}) - assert r.status_code==503 and r.json()['detail']['code']=='upstream_protocol_incompatible' +async def test_batch_capability_downgrade_rejected_before_acceptance(wf, monkeypatch): + async def caps(): + return {"protocol_version": 1, "admission_policy": False} + + monkeypatch.setattr(wf.provider, "upstream_capabilities", caps, raising=False) + r = await wf.client.post( + "/api/batches", + json={ + "items": [{"kind": "job", "task_type": "image.generate", "input": {"prompt": "one"}}] + }, + headers={"Idempotency-Key": "old-upstream"}, + ) + assert r.status_code == 503 and r.json()["detail"]["code"] == "upstream_protocol_incompatible" + @pytest.mark.asyncio -async def test_accepted_batch_replays_even_when_capability_goes_offline(wf,monkeypatch): - body={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':'one'}}]} - first=await wf.client.post('/api/batches',json=body,headers={'Idempotency-Key':'accepted'}) - assert first.status_code==202 - async def unavailable():raise RuntimeError('offline') - monkeypatch.setattr(wf.provider,'upstream_capabilities',unavailable,raising=False) - again=await wf.client.post('/api/batches',json=body,headers={'Idempotency-Key':'accepted'}) - assert again.status_code==202 and again.json()['batch']['id']==first.json()['batch']['id'] +async def test_accepted_batch_replays_even_when_capability_goes_offline(wf, monkeypatch): + body = {"items": [{"kind": "job", "task_type": "image.generate", "input": {"prompt": "one"}}]} + first = await wf.client.post("/api/batches", json=body, headers={"Idempotency-Key": "accepted"}) + assert first.status_code == 202 + + async def unavailable(): + raise RuntimeError("offline") + + monkeypatch.setattr(wf.provider, "upstream_capabilities", unavailable, raising=False) + again = await wf.client.post("/api/batches", json=body, headers={"Idempotency-Key": "accepted"}) + assert again.status_code == 202 and again.json()["batch"]["id"] == first.json()["batch"]["id"] diff --git a/deploy/model-gateway/README.md b/deploy/model-gateway/README.md new file mode 100644 index 0000000..97783c3 --- /dev/null +++ b/deploy/model-gateway/README.md @@ -0,0 +1,65 @@ +# 开发机直连模型 HTTP + +项目的 Vue 前端、FastAPI 业务后端继续在 Windows 本机运行,正式生产接入方式以后单独确定。模型端口18190保留开发机来源白名单;配音端口18192已取消来源IP限制,允许所有网络可达的客户端携带配音API Key调用。 + +- 模型 API:`http://192.168.28.10:18190` +- 配音 API:`http://192.168.28.10:18192/v1` +- 配音生成:`POST http://192.168.28.10:18192/v1/audio/speech`,返回WAV音频;健康检查为带鉴权的`GET /health`。 +- 原有 API Key 验证、文件上传下载与GPU调度规则继续适用。 +- Gateway 容器只转发模型请求,不运行网站、数据库或模型权重,使用 `unless-stopped` 自动重启。 + +服务器运维配置目录为 `/etc/cmvr-model-gateway`。将本目录的 `compose.yaml` 与根据模板生成的 `nginx.conf` 放入该目录。模板中的 `__DEVELOPMENT_CLIENT_IP__` 仅用于模型端口18190,必须替换为服务器实际看到的开发机来源IPv4地址;本次经实际连接确认是 `192.168.28.12`,本机网卡地址为 `192.168.0.199`,两者经过网络地址转换,不能直接互换。配音端口18192使用`allow all`;所有请求仍由TTS服务验证`Authorization: Bearer <TTS_API_KEY>`。 + +配音使用Kokoro-82M,接口模型名称为`kokoro-82m`,在CPU上串行执行;支持`zf_xiaobei`、`zm_yunxi`两个音色。`input`每次最多2000字符,`speed`范围0.5–2,`response_format`为`wav`。本接口同步返回音频,调用方应保持连接直至返回,并设置足够的等待超时。配音密钥由管理员通过私有配置分发,不写入仓库或浏览器前端。 + +Python标准库调用示例(调用机环境变量`TTS_API_KEY`须设置为真实配音密钥): + +```python +import json +import os +from pathlib import Path +from urllib.request import Request, urlopen + +request = Request( + "http://192.168.28.10:18192/v1/audio/speech", + data=json.dumps({ + "model": "kokoro-82m", + "input": "你好,这是一段内网调用生成的中文配音。", + "voice": "zf_xiaobei", + "speed": 1.0, + "response_format": "wav", + }, ensure_ascii=False).encode("utf-8"), + headers={ + "Authorization": "Bearer " + os.environ["TTS_API_KEY"], + "Content-Type": "application/json", + }, +) +with urlopen(request, timeout=330) as response: + Path("speech.wav").write_bytes(response.read()) +``` + +2026-11-13已在服务端备份配置、校验候选配置并平滑重载,仅调整18192的来源规则。使用原本被拒绝的来源`192.168.32.4`验证:放行前403,放行后正确密钥200,无密钥或错误密钥401;该来源访问18190仍为403。网关与配音容器未重启。 + +同一来源实际提交短中文文本后,返回200及有效WAV:24kHz、单声道、16bit、3.45秒。验证音频只在内存中检查,没有保存测试文件;服务端请求临时目录由现有响应清理逻辑回收。 + +首次启用前以相同镜像、网络和非root用户运行 `nginx -t` 校验配置,再在上述运维目录执行: + +```bash +docker compose config --quiet +docker compose up -d gateway +docker compose ps +``` + +已有配置先备份,不能覆盖其他服务的Nginx配置或重建模型工作区容器。本入口复用独立的 `cmvr-visual-net` 网络;上游使用Docker DNS解析,避免依赖固定容器IP。 + +Windows 私有 `.env.local` 配置: + +```dotenv +INFERENCE_BASE_URL=http://192.168.28.10:18190 +TTS_BASE_URL=http://192.168.28.10:18192/v1 +INFERENCE_REMOTE_FILES=true +``` + +本地推理密钥文件、配音密钥和其他配置维持原值,均不写入前端变量。停用旧模型隧道后,确认本机 `18190/18192` 无监听,而本地 `/api/ready` 与鉴权 `/api/system/status` 仍正常,即可验证业务已完全使用HTTP直连。 + +来源IP变化时,先核实服务器看到的新地址,再调整allow并执行 `docker compose exec gateway nginx -t` 和 `docker compose exec gateway nginx -s reload`。替换宿主机绑定配置文件后宜重建此独立gateway容器,让只读挂载读取新文件;无需重启模型容器。 diff --git a/deploy/model-gateway/compose.yaml b/deploy/model-gateway/compose.yaml new file mode 100644 index 0000000..1251c52 --- /dev/null +++ b/deploy/model-gateway/compose.yaml @@ -0,0 +1,40 @@ +name: cmvr-model-access + +services: + gateway: + image: ${MODEL_GATEWAY_IMAGE:-nginx:1.30.6-alpine} + container_name: cmvr-model-api-gateway + restart: unless-stopped + user: "101:101" + entrypoint: ["nginx"] + command: ["-g", "daemon off;"] + read_only: true + cap_drop: ["ALL"] + security_opt: ["no-new-privileges:true"] + tmpfs: + - /tmp:size=16m,mode=1777 + mem_limit: 128m + cpus: 0.5 + pids_limit: 64 + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf:ro + ports: + - "${MODEL_GATEWAY_BIND_IP:-192.168.28.10}:18190:18190" + - "${MODEL_GATEWAY_BIND_IP:-192.168.28.10}:18192:18192" + networks: [models] + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:18089/live"] + interval: 30s + timeout: 3s + retries: 3 + start_period: 3s + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + +networks: + models: + external: true + name: cmvr-visual-net diff --git a/deploy/model-gateway/nginx.conf.template b/deploy/model-gateway/nginx.conf.template new file mode 100644 index 0000000..db61f0a --- /dev/null +++ b/deploy/model-gateway/nginx.conf.template @@ -0,0 +1,70 @@ +# 模型端口限制开发机来源;配音端口允许所有来源,上游继续校验配音API Key。 +worker_processes 1; +pid /tmp/nginx.pid; +error_log stderr warn; + +events { + worker_connections 256; +} + +http { + log_format model_access '$remote_addr $request_method $uri $status $body_bytes_sent $request_time'; + access_log /dev/stdout model_access; + server_tokens off; + client_max_body_size 512m; + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + fastcgi_temp_path /tmp/fastcgi; + uwsgi_temp_path /tmp/uwsgi; + scgi_temp_path /tmp/scgi; + resolver 127.0.0.11 valid=5s ipv6=off; + + # 不缓存上传或产物,不代替业务层重试POST,避免改变幂等与取消语义。 + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $http_host; + proxy_set_header Authorization $http_authorization; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto http; + proxy_request_buffering off; + proxy_buffering off; + proxy_max_temp_file_size 0; + proxy_next_upstream off; + proxy_connect_timeout 5s; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + send_timeout 300s; + + server { + listen 18190; + allow __DEVELOPMENT_CLIENT_IP__; + deny all; + location / { + # 通过Docker DNS刷新上游地址,模型容器换IP后无需重建入口。 + set $model_api llmuser-workspace:18190; + proxy_pass http://$model_api; + } + } + + server { + listen 18192; + allow all; + location / { + set $speech_api cmvr-visual-tts:8001; + proxy_pass http://$speech_api; + } + } + + # 仅容器内部健康检查使用,此端口不发布到宿主机。 + server { + listen 127.0.0.1:18089; + access_log off; + location = /live { + return 200 "ok\n"; + } + location / { + return 404; + } + } +} diff --git a/deploy/release-checklist.md b/deploy/release-checklist.md index ff0f088..10c1aab 100644 --- a/deploy/release-checklist.md +++ b/deploy/release-checklist.md @@ -1,14 +1,15 @@ -# V2私有发布记录 +# 生产发布检查清单 -- [x] 原六表基线匹配后迁移到003,未覆盖管理员密码。 -- [x] 上游协议2、持久公平队列、窗口准入及增强产物标识。 -- [x] 前后端与模型服务独立审查,最终Linux与前端回归。 -- [x] API挂载缩窄;Nginx容器IP变化恢复实测。 -- [x] 默认三镜头真实生成、360帧完整解码、网页播放与seek。 -- [x] Qwen、配音、Whisper、Token/SSE/归属/改密真实调用。 -- [x] 升级前、升级后联合备份及隔离恢复核验。 -- [x] 共享Qwen、工作区及监管容器身份与启动时间保持不变。 -- [x] 仅清理本次带标签的验证容器/匿名卷及临时客户端文件。 -- [ ] 公网域名/HTTPS、Secure Cookie、管理员改密与专用数据库业务账号:当前保持私有入口,待公开发布时配置。 +开发阶段前端和业务后端在本地运行,通过内网 HTTP 访问模型 API。此清单用于后续正式上线准备,执行上线仍需用户明确要求。 -操作顺序为维护闭准入→确认本应用执行结束→联合备份→兼容上游/迁移→API/前端→真实验收→开放本项目准入。不得停止其它用户服务或以清队列代替恢复。镜像、备份哈希及检查结果见 `qa/v2-deployment.json`;实际边界见 `docs/V2开发与验收记录_20261110.md`。 +- 确认业务回归、接口合同、数据库结构检查和前端构建通过;验证完成后删除临时脚本、截图、媒体、隔离测试数据库、日志和打包文件,保留可复用测试及必要夹具。 +- 配置正式域名、HTTPS、`COOKIE_SECURE=true` 和 `PUBLIC_ACCESS=true`,更换初始管理员密码,使用专用数据库业务账号。私有配置及推理密钥不得进入前端、镜像、日志或版本库。 +- 关闭本应用新准入,等待本应用在途任务和进程组完成清理。保留已排队任务;不得停止其他用户服务,也不得通过清空队列替代恢复。 +- 联合备份数据库、工作空间、配置和当前部署版本,在隔离环境验证恢复及 Alembic 迁移。保留历史迁移,不用当前模型重写旧迁移。 +- 可编辑自动成片需要007:排空本项目运行后,从006执行`alembic upgrade 007`,新版API只接受007。007只追加列、旧Run默认为legacy;不执行破坏性downgrade。回退先排空auto运行,恢复已验证联合检查点,不能直接用旧API解释新编辑状态。迁移后再一致切换前端/API,不能仅更新页面。 +- 配音检查独立`SPEECH_TIMEOUT_SECONDS=330`、整体`SPEECH_TOTAL_TIMEOUT_SECONDS=360`与TTS队列/合成时限;轻量health不加载模型,部署须另验真实短句与取消清理。不得为普通回归启动真实模型。 +- 一致更新业务 API、前端和需要升级的模型协议组件。业务 API 不加载 GPU 模型;GPU FIFO、外部用户优先、主存预算和 Qwen 按需预约规则继续生效。 +- 验证健康与就绪、登录、权限隔离、素材上传和删除、共享引用副本、任务与 SSE、视频播放及下载;需要真实模型验证时明确范围,不能用模拟结果代替。 +- 确认检查通过后恢复本应用准入。发生异常时先封住新准入并排空活动执行,再按已核验的备份与兼容版本回退,避免重复执行任务或丢失业务结果。 + +当前操作见[项目 README](../README.md)、[主操作手册](../docs/操作手册_20261111.md)及[Qwen 按需运行说明](../docs/Qwen按需运行_20261112.md)。 diff --git a/docs/API-examples.md b/docs/API-examples.md index bbe65b6..7b560d6 100644 --- a/docs/API-examples.md +++ b/docs/API-examples.md @@ -1,10 +1,12 @@ # HTTP + SSE 调用示例 +2026-11-13导航调整只移除独立工作流、批量和成片页面;本文所述共享后端API、历史数据、幂等与权限合同继续保留。当前网页创作从“故事”进入,在故事内“03 成片”处理时间线,在“任务”查看进度。 + 以下针对网站业务 API,**不是**直接调用 GPU 上游。示例使用同一登录用户;素材 ID、任务 ID 均由服务器返回,不接受客户端提供的服务器路径。完整字段见 [共享契约](api-contract.md)。 ## 登录与会话 -Python/httpx 示例通过交互输入取得密码,不写在源码、命令行参数或日志里。使用 SSH 隧道的本地 HTTP 地址;正式 HTTPS 部署改成自己的同源地址。 +Python/httpx 示例通过交互输入取得密码,不写在源码、命令行参数或日志里。当前业务API在本机通过HTTP直接访问,不需要SSH隧道;正式HTTPS部署时改成自己的同源地址。 ```python import getpass @@ -12,7 +14,7 @@ import uuid from pathlib import Path import httpx -client = httpx.Client(base_url="http://127.0.0.1:18193/api", timeout=30) +client = httpx.Client(base_url="http://127.0.0.1:8000/api", timeout=30, trust_env=False) response = client.post("/auth/login", json={ "username": input("账号:"), "password": getpass.getpass("密码:"), @@ -22,7 +24,7 @@ client.headers["X-CSRF-Token"] = response.json()["csrf_token"] # client 自动携带 HttpOnly 会话 Cookie;不要打印 response 或 Cookie。 ``` -管理员创建普通用户使用 `POST /auth/users`,字段为 `username/display_name/password`,密码至少12字符;无公开注册。当前默认管理员配置在本机私有 `.env.server` 中获取,不复制进本示例。初始管理员支持本次指定的六位密码,不改变普通用户12位要求。 +管理员创建普通用户使用 `POST /auth/users`,字段为 `username/display_name/password`,初始密码至少6字符(允许6位数字);无公开注册。当前本地默认管理员配置保存在私有 `.env.local`,不复制进本示例;已有账号密码不会被重启重置。用户主动修改密码仍须至少12个字符。 ## 素材上传、编辑和读取 @@ -56,7 +58,7 @@ response.raise_for_status() Path("reference-copy.png").write_bytes(response.content) ``` -不存在、已删除或非本人素材均不可读取。删除使用 `DELETE /assets/{id}`;如果输入仍被任务引用,只从素材库移除,不立即物理删除。生成素材改名、收藏、标签或删除时,来源任务会产生新 version 和 `job.updated` 事件。 +不存在、已删除或非本人素材均不可读取。删除使用 `DELETE /assets/{id}`;仍被任务、草稿或冻结运行引用时返回409,需要先处理相关引用。删除成功会移除对应文件及数据库文件记录。生成素材改名、收藏、标签或删除时,来源任务会产生新 version 和 `job.updated` 事件。 ## 提交约定 @@ -83,7 +85,7 @@ jobs, request_key = submit(payload) job_id = jobs[0]["id"] ``` -批量仅适用于 `image.generate`、`defect.generate`,最多 4 项,各项独立排队。此例两个实际种子分别为 42、43。普通 Qwen-Image 不支持参考图编辑。 +这里的`count`是单次任务命令的数量:`image.generate`、`defect.generate`等支持最多4项,各项独立排队;不同任务类型的限制以能力接口为准。通用生产批次另外使用`POST /batches`,最多100个清单项,不是把这里的`count`改成100。此例两个实际种子分别为42、43。参考图编辑使用独立的`image.reference.generate`任务类型。 ### 2. 文生或图生视频 @@ -98,7 +100,7 @@ payload = { # 删除 image_asset_id 即为文生视频;保留时必须是本人上传/生成的图片。 ``` -最多约 5 秒,帧数须为 `4n+1` 且不超过 121,帧率固定 24。当前不是 15 秒任务,结果默认无声。 +单镜头默认121帧、约5秒,现支持最多361帧、约15秒;帧数须为`4n+1`,帧率固定24。例如10秒/15秒生成源分别使用241/361帧,成片再裁到选用的精确帧数。模型生成结果默认无声。 ### 3. Canny 条件样本 @@ -240,3 +242,44 @@ client.close() ``` 常见错误:401 登录无效;403 CSRF/权限拒绝;404 非本人或已删资源;409 幂等键冲突或任务状态不允许;400/422 参数不支持;413 上传过大。错误为 `detail.code/message`,验证错误可能附字段位置。不要向用户显示服务器绝对路径或上游认证内容。 + +## 故事工作室 v3 + +以下沿用前文已登录且设置CSRF的 `client`(base_url以 `/api` 结尾)。先读取 `/stories/capabilities`;模型不可用时接口明确拒绝参考生成,不会替换为文字生成。`reference_mode="text"` 是调用者显式选择,参考图仅作人工比对。 + +```python +import uuid + +shot_id = uuid.uuid4().hex +story = client.post("/stories", json={ + "name": "我的故事", + "spec": {"schema_version": 3, "shots": [{ + "id": shot_id, "name": "镜头一", "visual_prompt": "海边站台的清晨", + "motion_prompt": "镜头缓慢推进,海风吹动衣角", + "video_parameters": {"source_seconds": 15}, + "edit": {"start_frame": 0, "duration_frames": 360} + }], "render": {"fps": 24, "total_frames": 360}} +}).json() +path = "/stories/" + story["id"] +preview = client.get(path + "/preview").json() + +# 此镜头没有绑定参考图,因此明确使用文字生成。 +command = {"expected_version": story["version"], "shot_id": shot_id, + "kind": "frame", "source_kind": "generated", "count": 1, + "reference_mode": "text", "execution_mode": "interactive"} +key = uuid.uuid4().hex # 发请求前保存key与精确body;超时只原样重放。 +created = client.post(path + "/candidates", json=command, + headers={"Idempotency-Key": key}).json() +candidate_id = created["candidates"][0]["id"] +# 轮询 /candidates?shot_id=...&kind=frame 或接收owner SSE;ready后人工预览。 +story = client.get(path).json() +approved = client.post(path + "/selections", json={ + "expected_version": story["version"], "shot_id": shot_id, + "kind": "frame", "candidate_id": candidate_id +}, headers={"Idempotency-Key": uuid.uuid4().hex}) +approved.raise_for_status() +``` + +批准首帧后,以 `kind="video"`、`source_kind="generated"` 创建视频候选,预览后再用相同选择接口确认选片。人工首帧或视频以 `source_kind="manual",asset_id="本人素材ID"` 导入;人工视频不要求无用的首帧或提示词。调用 `/readiness` 为ready后,POST `/renders`,body为 `{expected_version,execution_mode}`,同样保存幂等键;返回原有RunSnapshot,后续通过 `/workflow-runs/{id}` 查询。冻结后的 `run.frozen_spec` 和 `run.render_inputs` 用于历史复查。 + +PATCH故事使用 `If-Match: 当前version`;普通JSON不能写入批准信息。清除批准POST `/selections/clear`;删除故事/候选使用 `If-Match`,被当前选择或历史运行引用的素材受引用保护。机器令牌继续使用 `workflows` 权限。新增owner事件为 `story.updated`、`candidate.updated`、`selection.updated`;断流/reset应重新读取快照,不能重复创建候选。 diff --git a/docs/Qwen按需运行_20261112.md b/docs/Qwen按需运行_20261112.md new file mode 100644 index 0000000..56018c7 --- /dev/null +++ b/docs/Qwen按需运行_20261112.md @@ -0,0 +1,77 @@ +# Qwen 运行方式与切换记录 + +## 当前方式:常驻 GPU0(2026-11-13) + +按用户要求,`Qwen/Qwen3.8-27B-FP8` 恢复为常驻服务:原容器 `cmvr-qwen38-fast` 长期使用 GPU0,调用结束后继续保留模型;Docker 重启策略为 `unless-stopped`。共享调用地址仍为 `http://192.168.28.10:14081/v1`。 + +自动卸载网关 `cmvr-qwen-gateway.service` 已停止并取消开机启动;`cmvr-qwen38-on-demand` 保持停止,重启策略仍为 `no`。原程序和配置保留用于受控切换,不应同时启动两个模型容器。 + +GPU0 的预约保持 `hold=true`、`queue_seq_cutoff=0`,防止媒体调度器在模型加载或重启期间领取该卡。项目图像、视频等任务继续使用符合准入条件的 GPU1–3,保留 FIFO、外部用户优先及主存检查。工作容器的384 GiB配额未改变。 + +常驻模式恢复后,调用方无需为每次请求重新等待模型加载。模型进程或服务器重启后仍需完成一次加载。此前机器人 Demo 的普通请求超时为120秒,视觉预热另有30秒上限;按需冷启动约140秒会触发这些超时,不能把健康检查成功等同于冷启动请求能在30秒内结束。 + +当前只读检查: + +```bash +docker inspect --format '{{.State.Running}} {{.HostConfig.RestartPolicy.Name}}' cmvr-qwen38-fast +systemctl is-active cmvr-qwen-gateway.service +curl --max-time 10 http://192.168.28.10:14081/health +curl --max-time 10 http://192.168.28.10:14081/v1/models +nvidia-smi --query-gpu=index,memory.used,memory.free --format=csv +``` + +预期常驻容器为 `true unless-stopped`,自动卸载网关为 `inactive`。切换前的配置和容器身份备份保存在服务器 `/root/cmvr-qwen-resident-20261113-173248/`,目录权限0700、文件0600;备份可能包含认证配置,不复制到网页或日志。 + +切换时发现管理员以 root 打开队列 SQLite 后可能创建 root 归属的 WAL/SHM 文件,阻止项目用户继续写入。已将这两个文件的归属恢复为数据库所属的1013:1014,并以项目用户恢复推理服务。后续队列诊断应使用数据库所属用户;不要通过删除 WAL/SHM、数据库或锁文件处理权限错误。 + +若后续需要释放 GPU0,应先受控排空 Qwen 请求、停止常驻模型并核验 GPU 进程退出,再调整预约及调用方式。当前长期占卡的要求不能由一次请求结束自动撤销。 + +## 2026-11-12 按需模式(历史记录,当前停用) + +项目使用的 `Qwen/Qwen3.8-27B-FP8` 已改为真实请求到达时加载到 GPU0,最后一个请求结束后停止模型容器。常驻的 HTTP 网关只使用 CPU,不加载 CUDA 或模型权重。 + +### 使用方式 + +原调用地址保持为 `http://192.168.28.10:14081/v1`。项目中的数学推理、图片理解、视频抽帧理解继续按原操作使用,不需要手动启动或关闭模型。`GET /health`、`GET /v1/models` 和基础输入校验不会加载模型。 + +冷调用需要等待模型加载。并发调用共用一次加载;其中一个调用结束不会中断其他调用。最后一个上游响应处理完成后立即停止容器,没有额外的空闲驻留时间。客户端断开时,网关继续排空该次上游响应,再释放引用。 + +2026-11-12 实测:后续冷调用约 148–155 秒(包含加载和停止),首次新容器的算子、CUDA 图预热更久。请等待任务完成;空闲显存释放的代价是下次需要重新加载。 + +视频抽帧理解目前逐帧调用 Qwen,彼此不重叠的请求会分别冷加载。这是“每次调用后释放”的结果;未来若需要整项视频理解共用一次加载,应增加明确的批次生命周期,而非偷偷延长模型驻留。 + +业务后端的 `QWEN_TIMEOUT_SECONDS` 默认 1800 秒,包含等卡和加载;普通推理控制接口仍使用原 `REQUEST_TIMEOUT_SECONDS`。同步 `QwenClient` 默认也等待 1800 秒。外部调用方需要设置足够长的 HTTP 等待时间。 + +### GPU 交接 + +网关先在 root 管理的预约文件中写入本轮唯一 token 和当前媒体队列序号上界。worker 让先到且当前可运行的媒体任务按原 FIFO 派发,等待 GPU0 上已领取或正在运行的任务自然完成;GPU1–3 继续调度。 + +worker 首次确认 GPU0 排空后,网关将同 token 的 `queue_seq_cutoff` 原子改为 0,持久封锁所有新 GPU0 领取。网关必须取得封锁后第二次新鲜确认和可信 GPU 采样,才会加载 Qwen。这个封锁在 worker 重启后仍有效,不依赖进程内记忆。 + +停止模型后,网关等待新的 GPU 采样证明计算进程消失、显存恢复,再解除预约。媒体调度继续遵守原来的 15 秒空闲门槛。损坏预约、陈旧确认、遥测错误或无法确认停止时,只封锁 GPU0 的新准入,不通过抢占现有任务取得这张卡。 + +### 运维位置 + +- 网关服务:`cmvr-qwen-gateway.service`,由 systemd 以 root 运行;执行文件 `/usr/local/libexec/cmvr-qwen-gateway.py`,使用系统 Python 的隔离模式 `-I`。 +- 配置:`/etc/cmvr-qwen-gateway.json`,root 0600;HTTP 不提供修改配置或任意 Docker 操作的接口。 +- 按需模型容器:`cmvr-qwen38-on-demand`,原镜像、GPU0、缓存与启动参数;内部端口仅绑定 `127.0.0.1:14083`,`restart=no`。 +- 原 FP8 容器:`cmvr-qwen38-fast`,停止并保留用于回退;准确版 `cmvr-qwen38-accurate` 保持原状态。 +- 预约:`/var/lib/llmuser-gpu-policy/qwen-reservation.json`。项目容器通过原只读策略目录读取,不获得 Docker 权限。 +- 备份和部署验收:`/root/cmvr-qwen-on-demand-20261112/`,root 0700;其中容器和设置备份可能含认证信息,不能复制到网页或日志。 + +只读检查: + +```bash +systemctl status cmvr-qwen-gateway.service +curl http://192.168.28.10:14081/health +docker inspect --format '{{.State.Running}}' cmvr-qwen38-on-demand +nvidia-smi --query-gpu=index,memory.used,memory.free --format=csv +``` + +### 恢复与回退 + +网关异常重启时先停止遗留的固定模型容器;存在未完成预约时,仍需新的 GPU 释放采样才能解除。不要手工删除预约或伪造 `hold=false` 绕过错误。 + +若需恢复常驻模式,先封住调用入口并排空 Qwen 请求,停止网关,证明按需容器已停止。让项目暂停新准入并排空 GPU0,再恢复原 FP8 容器的备份配置和启动状态。确认原服务正常后再恢复准入。不能在 GPU0 上仍有项目任务时直接启动原容器。 + +本次只切换推理服务;网站前端、业务后端继续在本地运行,历史素材、视频和数据库没有迁移或删除。 diff --git a/docs/V2开发与验收记录_20261110.md b/docs/V2开发与验收记录_20261110.md deleted file mode 100644 index 9f45a6f..0000000 --- a/docs/V2开发与验收记录_20261110.md +++ /dev/null @@ -1,76 +0,0 @@ -# CMVR Visual V2 开发与验收记录 - -2026-11-10,Asia/Shanghai。代码位于 `E:\workspace\hybrid\cmvr-visual`,已部署至192.168.28.10的私有入口。 - -## 已交付的行为 - -- Vue3、Element Plus、Pinia前端与FastAPI/MySQL后端分离,使用同源HTTP命令与查询、SSE状态通知。长计算由持久协调器执行,浏览器和HTTP连接关闭后继续运行。 -- 保留图像生成、视频生成、条件样本、转写、数学推演、素材理解、编排、中文配音八项入口;增加三分镜工作流、混合批量、账号维护、机器令牌、持久草稿和原键提交恢复。 -- 三分镜冻结输入与参数,每镜头121帧源视频取120帧,最终360帧、24fps、15秒;支持横竖版、留边/裁切、显式音轨选段与整片帧字幕。成功镜头可校验后复用,失败步骤单独重试。 -- Draft/Run/Step/Job/Execution分离;版本冲突返回409。旧运行与旧执行结果不能覆盖当前选择。CPU结果manifest、GPU实际attempt与fence、素材校验及恢复均已接入。 -- 新GPU模型全局只执行一个作业,保留四卡空闲选择及外部用户优先让卡策略。共享Qwen只通过HTTP调用,CPU媒体与Qwen请求各有独立单槽,不操作共享服务PID。 - -## 08:00与取消规则 - -窗口为北京时间 `[21:00,次日08:00)`。全天接受并持久排队;08:00以后停止启动新batch镜头/处理阶段,已经开始的阶段自然完成,后续阶段等待下一窗口。集成的Wan生成及Real-ESRGAN增强属于同一镜头。交互创作全天等待空闲资源。 - -手工暂停同样只关闭后续准入。外部用户占卡时,既有GPU让卡策略仍优先,清理自己的执行后用同一上游ID重排。显式取消Qwen/Kokoro时,等待当前HTTP响应结束再丢弃结果;完成状态未知则隔离本应用对应资源池,等待运维确认。窗口关闭和网页断开均不发送共享服务停止命令。 - -08:00边界通过注入时钟和真实Linux子进程测试:启动前越界被拦截、已经启动的执行跨界成功、下一项排队、回拨不能重开已关闭窗口。没有修改服务器时钟,也没有等待真实08:00做破坏性测试。 - -## 实际验证 - -| 范围 | 结果 | -| --- | --- | -| 冻结后端,Linux完整回归 | 159 passed,20 subtests passed,无媒体跳过 | -| 前端 | 65 passed;vue-tsc与Vite生产构建通过 | -| 模型服务,Linux完整回归 | 139 passed,120 subtests passed | -| MySQL8.0.36接口回归 | 8 passed,使用隔离实例 | -| 真实FFmpeg专项 | 5 passed:横/竖版各contain/cover,119帧拒绝,完整解码 | -| 迁移 | 空库、旧六表保留、部分002 DDL提交后的恢复、重复升级至003通过 | -| 浏览器 | 草稿保存/刷新、父任务、账号页、桌面及390×844手机滚动、视频播放与10.5秒seek通过;无页面异常 | - -Windows完整后端回归曾通过150项、跳过3项Linux媒体测试;最后的改动另有针对性回归,并以最终Linux159项作为生产发布依据。各测试集合分别覆盖不同范围,不相加宣称独立用例总数。 - -审查发现并修复了批次取消卡住、重试遗漏父级hold、一个额度错误回滚其它Run、增强片选择错误、Token权限绕过、未知HTTP等待者越过隔离、停用用户仍派发、素材实际额度、跨会话迟到响应以及上传解析前容量限制等问题。 - -最终回归还覆盖了资源池之间的等待隔离:Qwen与CPU媒体分别最多保留25个待执行协程,未准入任务继续保存在数据库,各池实际执行仍为单槽。50个被隔离的Qwen请求不会阻塞独立配音任务;服务退出前尚未开始执行的等待者保持排队,不被误记为失败。 - -## 真实模型成片 - -Run:`5e9108a5d1bc4f989e11ffe7bd7e7707`。 - -三镜头均使用冻结默认参数:1280×704、121帧、24fps、50步,经Real-ESRGAN增强到1920×1056,再按1920×1080画布合成。首次网页提交后关闭浏览器,后端继续完成。 - -- 提交:2026-11-10 22:51:17;完成:23:10:29,约19分12秒,包含Whisper插队与归档。 -- 最终文件:H.264,1920×1080,360帧,24fps,15.000秒,5,369,663字节;完整解码无错误。 -- 三段画面与中文字幕已人工查看,浏览器实际播放和seek通过。该次耗时是实测记录,不能直接当作并发产能承诺。 -- 验收视频保留在网站素材库,本机副本为 `qa/generated/v2-three-shot-15s.mp4`(不提交Git)。 - -同时真实完成了Qwen批量推演,结果为5和12;关闭调用端HTTP后任务继续,重复提交同键返回原批次。Kokoro通过CPU输出3.85秒、24kHz中文配音,Whisper转写为“欢迎使用智能创作平台。”。Whisper与视频共用既有GPU队列,未新建第二个GPU worker。 - -图像、SDXL/ControlNet和视觉理解沿用前轮真实验收,本轮没有重复执行全部大模型默认规格。对应功能边界仍见主README及前轮验收报告。 - -## 数据与发布 - -正式库仍为 `192.168.28.10:3306/cmvr-visual`。原六表校验后登记001,再升级至003;当前17张业务表加Alembic版本表。生产启动只校验schema,不自动改表或切换SQLite,原管理员密码哈希未重置。 - -已创建升级前与升级后的联合恢复点,位于服务器受保护目录 `/root/cmvr-visual-v2-20261110`,包含数据库、业务文件、上游SQLite及必要输出,清单记录SHA256和镜像ID。 - -升级后隔离恢复核验:1302个文件条目、12个素材原件大小与哈希、20条上游任务身份/状态、4条业务上游关联一致,SQLite完整性为ok,schema为003,管理员哈希与升级前相同。临时验证数据库容器及其匿名卷已清理,原有预览数据库保留。 - -API容器实际更换IP后,原Nginx容器无需重启即恢复访问,实测约1.54秒。共享Qwen两个容器、llmuser工作区容器和GPU监管容器的ID及启动时间均与升级前一致。当前API、前端、TTS运行正常,readiness四项检查通过。 - -## 使用入口和保留边界 - -当前服务器仅监听 `127.0.0.1:18193`,现有SSH隧道入口为 `http://127.0.0.1:8000`。网站管理员仍为用户指定的admin及初始化密码;账号页可修改。当前按要求保持私有模式与MySQL root配置。 - -公开发布前还需域名/HTTPS或受信隧道、管理员改密及本库专用数据库账号。`PUBLIC_ACCESS=true`时服务端拒绝不安全Cookie、初始化管理员密码或MySQL root配置;当前没有开放互联网入口。 - -本次保留以下明确边界: - -- GC默认dry-run,只处理经过宽限与引用校验的已知软删除素材;未启用自动清理历史工作目录与GPU原始副本。业务2TiB预算统计assets/jobs/tmp,独立GPU副本和模型权重需另做保留管理。 -- 跨阶段预处理尚未实现完整持久缓存。进程中断而结果不明确时进入待确认,不能自动重放Qwen/Kokoro或仅凭数据库改状态宣称远端已停止。 -- LoRA训练、缺陷真值mask、专业数学正确率、镜头切分、热度预测和音乐生成仍属于原方案约定的独立质量专项。 - -详细证据见仓库 `qa/v2-*.json`、浏览器脚本和截图;接口见 `docs/api-contract.md`,部署及恢复操作见主README。 diff --git a/docs/api-contract.md b/docs/api-contract.md index 6c439b3..f97a3ab 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -9,7 +9,7 @@ Private resources are owner-scoped for both regular users and `admin`: private a - POST `/auth/login` `{username,password}` → `{user:{id,username,display_name,role},csrf_token}` plus session cookie. - GET `/auth/me` → same shape; 401 when signed out. - POST `/auth/logout` → 204; close SSE on frontend. -- Admin POST `/auth/users` `{username,display_name,password}` → user. +- Admin POST `/auth/users` `{username,display_name,password}` → user. Initial passwords allow 6–256 characters, including six digits. ## Capabilities and resources @@ -17,7 +17,7 @@ Private resources are owner-scoped for both regular users and `admin`: private a - GET `/system/status` → `{inference_online:boolean,scheduler:Scheduler,models:Capability[]}`. - Capability: `{task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}`. - Scheduler: `{available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}`. No PID or user identity. -- Types: `image.generate`, `video.generate`, `defect.generate`, `audio.transcribe`, `math.solve`, `media.structure`, `video.compose`, optional `audio.speech` (only available when a real provider is configured). +- Types: `image.generate`, `image.reference.generate`, `video.generate`, `video.people.analyze`, `video.replace`, `defect.generate`, `audio.transcribe`, `math.solve`, `media.structure`, `video.compose`, optional `audio.speech` (only available when a real provider is configured). Video editing availability requires both business/inference enablement and the pinned operator validation receipt; constraints are the smaller local/remote budgets. ## Assets @@ -30,6 +30,20 @@ Private resources are owner-scoped for both regular users and `admin`: private a - GET `/assets/{id}/thumbnail` authenticated image preview (fallback image content when no separate thumbnail). - Asset: `{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated'|'shared',tags:string[],favorite:boolean,created_at:string}`. A retained generated asset may keep `source_job_id` after its source job is archived; that identifier does not guarantee an accessible job. +## Logical folders (schema 006) + +- GET `/folders` → `{items:Folder[]}`. Folder: `{id,name,parent_id:null|string,created_at,updated_at}`; private to the current owner. +- POST `/folders` `{name,parent_id?}` → 201 Folder. PATCH `/folders/{id}` `{name?,parent_id?}` → Folder. Same-parent duplicate names and parent cycles are rejected. +- DELETE `/folders/{id}` → 204. Removes this category and descendants; preserves all assets, jobs, drafts, runs and physical files. Remaining memberships in other folders survive. +- POST `/folders/assign` `{kind:'assets'|'jobs'|'drafts'|'runs',ids:string[],folder_id:null|string,mode?:'move'|'add'}` → `{updated,kind,folder_id}`. At most 200 requested IDs; all owner checks are atomic. `add` applies only to assets; `move` replaces memberships/classification. Moving a job does not change its frozen output target. +- Asset DTO adds `folder_ids:string[]`. Asset PATCH accepts `folder_ids`; upload multipart accepts `folder_id`; shared import optionally accepts `{folder_id}` while no-body calls remain valid. +- Jobs add `folder_id` and `output_folder_id`; drafts/stories add `folder_id`; runs add both. Asset/job/story/workflow/run list endpoints accept `folder_id`: omitted/empty means all, `unclassified` means no category, otherwise an owned folder ID. +- Submit accepts `folder_id` and `output_folder_id`; omitted output inherits classification, explicit null selects unclassified. Candidate/batch-candidate, story render and workflow RunCreate accept `output_folder_id`, defaulting to the draft's folder when omitted. Batch items carry the corresponding metadata on each item. +- StoryCreate optionally accepts `folder_id` and `create_folder` (default true). Omitted folder creates a unique same-name folder; explicit null or `create_folder:false` opts out. Draft/Story PATCH accepts `folder_id`. +- Output targets are persisted at submission; later draft moves do not alter queued destinations. Folder deletion falls back to unclassified during collection. Folder metadata never enters upstream model parameters or generation hashes. Legacy requests without the new fields preserve their idempotency fingerprints. +- New directory events are `folder.created`, `folder.updated`, `folder.deleted`, `folder.contents_changed`; affected assets/jobs/stories/runs also use their existing update events. Machine directory access uses `folders:read` / `folders:write`, separate from asset reads and task execution privileges. +- Bulk publish/delete in the UI uses the existing per-asset endpoints, bounded to three concurrent calls, and reports individual failures. It does not bypass reference protection or change publication-copy behavior. + ## Shared assets Shared publications are independent file and metadata snapshots, separate from private Asset DTOs. All logged-in users may read active publications, including their content and thumbnails. Shared content is read-only; import it before using it as a private job/workflow input. Bearer-token reads require `assets:read`; publish/import/withdraw require `assets:write`, and ownership still applies. @@ -64,7 +78,7 @@ Archival removes resources from ordinary list/detail/control APIs while retainin - `409 resource_in_use`: another live run still selects a job in the proposed deletion tree for reuse. Delete the dependent run first. Private asset deletion uses the separate `asset_in_use` error above. - `GET /submissions/{key}?operation=...` and replay of an archived record's original command return `410 resource_purged`. An old idempotency key cannot resurrect deleted records; intentionally creating new work requires a new submission. -Asset soft deletion and shared withdrawal do not promise immediate disk/quota recovery. GC defaults to dry-run (`dry_run=True`) with a14-day grace period; elapsed time alone does not trigger purge. Physical deletion requires explicit maintenance mode and an operator-invoked purge, rechecks job/snapshot/active-publication references, and skips protected files. Unknown/untracked files are never automatically removed. Archival audit rows are retained. +Asset DELETE and shared withdrawal now remove the owned original/thumbnail files and hard-delete their Asset rows; withdrawal also removes the publication row. Independent published/imported copies survive. Missing files are accepted for retries, unsafe paths return `409 unsafe_asset_path`, and filesystem failures return `503 asset_delete_failed` without a false success; remaining DB rows allow retry. Active producers/consumers and unresolved executions return `409 asset_in_use`. Legacy soft-deleted files retain the conservative dry-run-first maintenance GC path. Model caches and historical task audit records remain independently managed. ## Jobs @@ -80,6 +94,18 @@ Asset soft deletion and shared withdrawal do not promise immediate disk/quota re - Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly `num_inference_steps`. Video accepts5–361 integer frames with `num_frames % 4 == 1`, fixed24fps. The web duration input supports1–15 whole seconds and submits `24 * seconds + 1` frames; default5 seconds remains121 frames. A15-second native source contains361 frames (15.041667 seconds), not interpolated or slowed-down footage. No fake generation percentage. - ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result `subjects,scene,ocr,tags,frames?`, timestamps reflect actual sampled frames. Math result `{text}`; ASR result `{text,segments}`; composition produces video asset. +### Creation image and multi-person video editing + +These use the existing `POST /jobs`, owner-scoped assets, idempotency keys and durable SSE events. No new business tables or public media paths. Generated Asset DTOs additionally expose `source_output_index:number|null`; map analysis previews by this index, never by current array position, since a preview may have been deleted independently. + +- `image.reference.generate`: input `{prompt,negative_prompt?,reference_asset_ids:string[]}` with 1–3 ordered, distinct private images. Parameters use `profile:'qwen-image-edit-2511-v1'`, sizes1024×1024/1280×704/704×1280, defaults `num_inference_steps:40,guidance_scale:1,true_cfg_scale:4,max_sequence_length:1024,seed:42`. `count:1..4` creates independent jobs with all reference images preserved. Profile/model mismatch or unavailable capability fails rather than falling back to text-only generation. +- `video.people.analyze`: input `{video_asset_id}`; parameters `{profile:'wan-animate-replace-v1',max_pixels:399360,fps:24}`. `count` must be1. Result `{profile,analysis_token,source_sha256,video:{width,height,fps,frames,duration_seconds},poster_output_index,people:[{id,label,thumbnail_output_index,first_frame,last_frame,confidence,samples:[{frame,bbox:[x1,y1,x2,y2]}]}],warnings:[]}`. Bbox coordinates are normalized0..1 against the display-oriented, square-pixel output; frame indexes start at0. Detection IDs are per-video tracks, not real identities. +- `video.replace`: input `{video_asset_id,analysis_job_id,prompt,negative_prompt?,replacements:[{person_id,reference_asset_id,prompt?:string}]}`. Global `prompt` must contain non-whitespace text; each selected person must be distinct and belong to that successful analysis. Parameters `{profile:'wan-animate-replace-v1',max_pixels:399360,fps:24,num_inference_steps:20,guidance_scale:1,seed:42,preserve_audio:true,mask_expand_pixels:8,mask_feather_pixels:4}`; both mask controls are integers0..64. `count` must be1. Public Job.result includes `{profile,person_ids,source_frames,output_frames,fps,width,height,warnings,final_output_indices}` plus the private video asset. The frozen source hash, actor/reference mapping and upstream execution proof remain in internal persistence; the lower-level inference result additionally contains `actor_mapping`, source SHA and duration/audio parameters. + +Analysis must be successful, active and owned by the caller, reference the identical source asset/hash and use matching profile/fps/max_pixels. The server resolves its trusted upstream analysis ID/token; clients cannot supply mask files, arbitrary paths or another owner's analysis. Every selected identity image is held as a job input reference. Video-stream timeline, not a longer container audio tail, determines duration admission and binding. Original audio duration is frozen independently and optionally remuxed; no voice/face identity guarantee or new audio synthesis is implied. + +Default configurable video budgets are120seconds/12people/399360pixels;720p budget921600 is accepted only if both sides explicitly support it. Replacing multiple people runs temporal model passes sequentially within one job and combines their visible masks into one output while protecting other actors/background. Ambiguous tracking fails closed. Close/disconnect has no cancellation semantics; use the existing explicit cancel command and wait for process cleanup. + ## Events - GET `/events?after=0` authenticated EventSource. `Last-Event-ID` header overrides query on reconnect. @@ -118,6 +144,9 @@ HTTP remains the command/query channel, SSE the owner-scoped notification channe - GET `/live` process liveness; GET `/ready` 200/503 with database, coordinator, upstream_protocol and accepting checks. GPU capacity does not affect readiness. - User DTO adds `disabled,must_change_password`; GET/PATCH `/auth/users[/{id}]` administer users, POST `/auth/password` `{current_password,new_password}` revokes sessions and requires relogin. +- Session POST `/auth/username` `{username,current_password}` → current User DTO. The normalized login username must be unique and match 3–64 lowercase letters/digits/`_.-`; a correct current password is required. User ID, role, resources and existing sessions remain unchanged. Renaming the bootstrap administrator does not recreate the old administrator on restart. +- User management requires a current administrator session and CSRF on writes. Disabling revokes browser sessions and suspends admission without deleting resources; re-enabling clears only `admin_suspend` and preserves manual holds. Bearer access is denied while disabled. +- Admin DELETE `/auth/users/{id}` removes the account and its owned records, assets, thumbnails, publications and local job files, preserving independent copies imported by other users. It returns 204 only after cleanup. Active execution, upload or file writes first cause durable disable/cancel and 409 `cleanup_pending`; retry after confirmed cleanup. Self-deletion is rejected. Unsafe paths return 409 `unsafe_user_path`, foreign resource consumers return 409 `resource_in_use`, and file failures return 503 `user_delete_failed` while retaining the disabled account for retry. - GET/POST `/auth/tokens`, DELETE `/auth/tokens/{id}`. POST `{name,scopes,expires_at?}` returns `{token,record}` once. Use `Authorization: Bearer ...` for machine calls; tokens never grant admin authority. Interactive use additionally requires `interactive:write`. - POST `/jobs` adds `execution_mode:'interactive'|'batch'`; new UI always persists and supplies an Idempotency-Key. GET list adds `root_only=true` to exclude workflow children. Job DTO adds `run_id,step_key,batch_id,batch_item_index,execution_mode,explicit_attempt,desired_state,hold_reasons,current_execution_id`. States additionally include `paused,pausing,needs_attention`. - POST `/jobs/{id}/retry` honors Idempotency-Key; legacy callers omitting it explicitly create a fresh attempt without replay guarantees. Parent-owned children require their parent retry/control APIs. @@ -132,6 +161,18 @@ HTTP remains the command/query channel, SSE the owner-scoped notification channe Legacy workflow spec schema1 remains exactly ordered `shot_1,shot_2,shot_3`, each `{key,prompt,image_asset_id:null|string,parameters:{seed}}`, with360 frames at24fps. Its serialization and generation hashes remain compatible. +## Story studio v3 additions + +Stories use independent `/stories` endpoints and `WorkflowDraft.kind=story_v3`; legacy `/workflows` excludes these records. The full field/endpoint contract is [Story studio specification](design/2026-11-11-story-studio.md); executable usage is in [API examples](API-examples.md). MySQL revision005 adds `visual_shot_candidates` and append-only `visual_shot_selections` without changing historical001–004. + +- The v3 spec contains story context, scenes, entities with forms/appearances, stable shot IDs and cast references, frame/video parameters, per-shot trim, and the existing audio/subtitle render settings. Plain JSON contains intent, never trusted approvals. PATCH uses `If-Match`; commands freeze `expected_version` and an Idempotency-Key. +- Reference inputs are the first-occurrence ordered unique private asset IDs. The compiled prompt binds Picture numbers and unique subject aliases to the same ordered files; forms/appearances name their owning subject. `image.reference.generate` requires the enabled identical profile at both API and upstream, accepts at most3 pictures by default, and never silently falls back. Explicit text mode removes the attached-picture instructions and actually sends no images. +- Candidate DTO `input_summary` exposes `reference_mode`, `actual_reference_asset_ids`, `model_profile`, `seed`, `prompt` and optional `first_frame_asset_id`; it does not expose filesystem paths or credentials. Readiness and selection reject stale/missing/deleted/inaccessible results. Completion never selects a candidate automatically. +- Generated video requires an approved current first frame; its requested source length is1–15seconds and must cover trim before dispatch. Manual video needs neither a frame nor a generation prompt, and checks its actual source independently of unused generation parameters. Start frame is nonnegative, each selected clip is24–360frames, final source bounds are verified against real decoded media. +- V3 Runs freeze the story and ordered selected asset/SHA/trim/audio/subtitle inputs and contain only a compose step. Historical Runs do not recompile current draft intent. Deleting a shot appends empty current selections while retaining prior approval audit; reintroducing its ID cannot resurrect old approvals. +- New owner events: `story.updated`, `candidate.updated`, `selection.updated`. Reset/reconnect refetches complete loaded scopes with version/session/tombstone guards; it never resubmits generation. Machine-token scopes map stories and `story.*` submission recovery to `workflows`. +- Pending candidate plans have separate owner/global budgets4000/16000; internal bounded admission uses existing active Job quotas. Creation/retry/render commands share the existing per-minute budget and immutable replay rules. No per-user8-video limit is introduced. + Schema2 accepts1–1000 sequentially ordered `shot_N` entries with additional `duration_frames` (strict integer24–360, default120). New submissions are additionally bounded by the operator's configured shot limit. `profile=landscape_1080_v1|portrait_1080_v1`; `render={fps:24,total_frames?:integer,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}`. Omitted total_frames is derived from shots; a supplied unequal value fails validation. Each shot generates `max(121, 4 * ceil(duration_frames / 4) + 1)` source frames and composition trims to the requested frame count. A5/10/15-second workflow requests121/241/361-frame sources and produces720 final frames (30 seconds). Schema1 retains its original3×5-second contract. Audio must fit the entire dynamic timeline explicitly and subtitles use whole-film half-open frame intervals. Run total_steps is shot count+1, and steps/compose inputs follow snapshot order, including shot_10. New draft kind is multi_shot; three_shot remains accepted. Capabilities and system/status include `workflow_limits={max_shots,source_frames:121,default_source_frames:121,max_source_frames:361,default_clip_frames:120,max_clip_frames:360,fps:24}` and `execution_policy.batch_window_enabled`, `configuration_error`, nullable `next_batch_at`. `source_frames` remains a legacy default; it is not the maximum. New snapshots freeze `compiled.shot_generation_parameters` keyed by shot; legacy snapshots without that map use their original frozen shared parameters. Long-source frame counts participate in reuse/retry semantic hashes, so a short source cannot satisfy a longer shot. Both API and GPU worker hot-read the operator-owned RUNTIME_POLICY_FILE (default `/workspace/projects/llm-services/config/runtime-policy.json`): `{schema_version:1,batch_window_enabled:boolean,workflow_max_shots:integer1..1000}`. Missing means production defaults; malformed policy blocks new batch compute. False bypasses only the clock/window, preserves durable clock evidence and all manual/maintenance/owner/GPU priority controls. Client payloads cannot override this switch. Already admitted work finishes when the switch is re-enabled. @@ -139,3 +180,23 @@ Capabilities and system/status include `workflow_limits={max_shots,source_frames Manual video.compose no longer has a24-clip or1800-second final-duration cap. New commands respect the same configured clip-count limit; source cuts stay within decoded media and a86400-second source bound. Output/intermediate size, storage, process and overall execution time budgets still apply. Private inference protocol2 carries server-generated `scheduling={execution_mode,principal_id,batch_id?,run_id?,step_key?,policy_version:'night-v1'}`. Its `/capabilities` reports admission_pause/control_versions/final_output_indices. GPU result metadata identifies final enhanced output indices; workflows never choose the native intermediate by list order. Internal phase callbacks acquire separate `new_gpu`, `cpu_media`, `qwen_http` slots. No endpoint accepts arbitrary PIDs, Docker IDs, FFmpeg scripts or server filesystem paths from web users. + +## Editable production (007) + +`GET /editors/{draft_id}` returns `{draft_id,name,version,revision,manifest,issues,assets}` for the current owner. A legacy draft is converted without writing. New editor writes require a live session, CSRF, transactional session recheck, and draft version CAS. Existing story spec writes/runs return409 `editor_required` while automatic mode is active; an explicit switch to manual permits the synchronized manual interfaces. + +- `POST /editors/{id}/save` `{expected_version,manifest,name?}` + Idempotency-Key; server resolves private asset identities and SHA, reconstructs all draft references, and saves structurally valid authoring conflicts as issues. Optional name is trimmed, nonblank and at most255 characters; omitted/null keeps the existing name. Name and manifest commit atomically with one version increment. `capabilities.name_edit=true` declares support; old clients and old no-name idempotency receipts remain compatible. Historical Run inputs do not change when a draft is renamed. +- `POST /editors/{id}/from-run` `{expected_version,run_id}` + key restores an owned same-draft frozen configuration and resolved assets; it is an explicit whole-version restore. +- `POST /editors/{id}/plan` `{expected_version,output_goal:media|film,targets:[],force:[],execution_mode,output_folder_id?}` returns `{plan_hash,source_version,steps,issues}`; no model executes. +- `POST /editors/{id}/runs` adds `expected_plan_hash` and an idempotency key;202 returns RunSnapshot. The server recompiles the plan under the acceptance transaction. Binding targets use `frame:<stable_id>`, `video:<stable_id>`, `audio:<segment_id>`, plus `script/captions`. Fresh seeds are accepted once; retries preserve frozen inputs. +- `POST /editors/{id}/apply` `{expected_version,run_id}` + key only accepts a succeeded Run whose source draft version still matches. A stale result is preserved and returns a conflict, rather than replacing later edits. + +The independent `editor_manifest.schema_version=1` contains source spec, stable shot IDs, private asset bindings, audio mode/segments and caption cues. Old workflow/story schemas remain1/2/3. Incoming manual bindings may omit SHA; persisted bindings always use server facts. Text and timing overrides are independent. Final composition alone projects relative cue anchors to existing24fps absolute subtitles and a single selected audio track. + +Auto runs use `story_auto/workflow_auto`, target-driven typed Steps and direct Jobs; they do not write manual ShotSelection/ShotCandidate. `output_goal=media` publishes target assets without changing the film pointer. `film` requires compose success. Source and step-input snapshots remain immutable, `result_manifest` records resolved editable results, and `apply_state=conflict` leaves subsequent authoring untouched. Output references belong independently to each draft/run; reuse points to asset+SHA, not an old selected Job. + +New CPU tasks: `text.script.generate` uses the shared Qwen HTTP resource pool and returns per-shot JSON; `audio.assemble` consumes owned segments at frame offsets, normalizes48kHz and writes an exact-length WAV. `audio.speech` supports an optional frozen model check and independent timeouts. Speech health only confirms configured/reachable protocol; it does not certify model quality. Unknown execution outcomes remain blocked until reconciled. + +Stories support reversible editing modes without a schema migration. `EditorManifest.editing_mode` is `auto|manual` (existing manifests default to `auto`; drafts without a manifest are manual). StoryDTO and EditorDTO expose `editing_mode` and `capabilities.mode_switch`. `POST /editors/{id}/mode` accepts `{expected_version,mode}` with session/CSRF and `Idempotency-Key` (`editor.mode`), and returns EditorDTO plus the complete authoritative `story`. Only story_v3 is supported. The command checks owner, CAS and unresolved work, advances the draft version, and retains the manifest and run history. Auto bindings become unapproved manual candidates with provenance; no approval is fabricated. Manual PATCH/confirm/clear synchronize the manifest and references. Auto-only writes reject manual mode; callers cannot change modes by posting a manifest field. Legacy first editor.save remains compatible but checks idle work before conversion. + +New automatic story composition inputs freeze decoded source width, height, fps and source frame count, plus the selected audio SHA. Historical inputs missing video dimensions are executed by verifying the frozen video SHA before deriving missing dimensions from those exact bytes; stored Job/Step inputs remain unchanged. Existing dimension, fps, duration and SHA conflicts still reject execution. diff --git a/docs/design/2026-11-11-engineering-structure.md b/docs/design/2026-11-11-engineering-structure.md new file mode 100644 index 0000000..c52379a --- /dev/null +++ b/docs/design/2026-11-11-engineering-structure.md @@ -0,0 +1,31 @@ +# 前后端工程化重构设计 + +用户已明确要求继续重构,并禁止自动提交代码。采用当前完整工作区作为基线,包括尚未提交的本地运行与素材物理删除功能。 + +## 方案与边界 + +保留单仓库下的frontend、backend两个独立工程,以及inference、tts独立服务。前端采用常规Vue目录分层,拆分HTTP、业务接口、DTO、纯规则、运行服务和样式;保留标准views/components/stores,不为每个页面制造一套重复目录。后端按api/core/models/schemas/services/domain/adapters组织;不新增通用CRUD或Repository框架。 + +完整业务feature重写会同时改变大量状态和调用关系,收益不抵当前风险;仅移动文件又无法解决大模块和循环依赖。因此本轮进行目录迁移、关键职责抽离、统一格式、关键中文注释和兼容验证,不修改业务需求。 + +## 后端目标 + +- `app/main.py`保持ASGI稳定入口,组装迁往bootstrap;HTTP路由放api/routes,请求模型放schemas。 +- core承载设置、数据库、维护与安全基础;models合并当前models/v2_models,统一Base与18张业务表注册。 +- services承载账户、素材、任务、工作流、批次及编排;domain承载时间线、状态常量和执行上下文。 +- adapters承载模型协议、远端文件、CPU媒体与受限文件访问;拆分过大的Provider,消除media与Provider的基础数据循环。 +- 路由只负责请求/认证/响应,业务函数不接收FastAPI Request;只抽实际复用的查询,不造通用仓储。 +- 更新所有真实import、测试monkeypatch目标、Alembic入口和维护脚本,不依赖永久import星号兼容壳。 + +## 前端目标 + +- api/client负责HTTP、cookie、CSRF和错误;domain endpoint文件组成同一个api facade,保持spy及调用语义。 +- types只存DTO;domain存时间线/视频参数等纯规则;services存可靠提交与删除协调;utils存格式化和请求ID。 +- 保持路由、Pinia ID、会话epoch、SSE游标、tombstone、本地存储键及幂等body不变。 +- 按现有CSS级联顺序拆分styles,使用Prettier固定格式,不改变页面视觉方案。 + +## 注释与验证 + +中文注释重点解释:数据库事务与SSE提交顺序、用户所有权、不可重放的共享HTTP调用、GPU FIFO与观察退避、冻结镜头参数、执行fence、物理文件删除与数据库非原子边界、前端跨会话迟到响应和越界草稿恢复。 + +验证比较重构前后路由/表结构清单,运行后端、前端、启动脚本测试、格式检查、类型检查及构建。使用合成素材进行页面冒烟,不启动真实模型。数据库和历史Alembic迁移不做DDL改变。所有变更保留未提交。 diff --git a/docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md b/docs/design/2026-11-11-multi-gpu-fifo-design.md similarity index 100% rename from docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md rename to docs/design/2026-11-11-multi-gpu-fifo-design.md diff --git a/docs/design/2026-11-11-story-studio.md b/docs/design/2026-11-11-story-studio.md new file mode 100644 index 0000000..ae14e63 --- /dev/null +++ b/docs/design/2026-11-11-story-studio.md @@ -0,0 +1,70 @@ +# 故事工作室与跨镜头锚定实施规格 + +用户已批准完整方案并明确要求开发。保留当前未提交的工程化、物理删除与本机运行改动,不暂存、不提交、不推送。使用当前feature/v2-workflows工作区,不复制或重置已有改动。 + +## 产品与执行边界 + +快速创作、旧v1/v2工作流与手动成片保持;新故事以WorkflowDraft(kind=story_v3)保存spec v3,使用独立/studio页面和/api/stories接口。旧/workflows列表排除story_v3,避免旧页面解析新结构。三阶段为首帧候选/确认、视频候选/选片、冻结素材后合成。候选任务用现有Jobs/Execution/Submission/Batch/Events/GPU监管;人工等待不占GPU。正式v3 Run只创建compose步骤。 + +元数据进现有MySQL,新建visual_shot_candidates和visual_shot_selections;媒体仍为受限工作区文件。所有权、CSRF、幂等、版本CAS、SSE游标/epoch/tombstones、引用保护必须保留。旧001–004迁移不改,新增005。服务启动不自动DDL。 + +## 跨子任务接口合同 + +### StorySpecV3(前后端使用相同字段) + +schema_version固定3;profile为landscape_1080_v1或portrait_1080_v1。 + +- context: {era:string, style:string, palette:string, lighting:string, negative_prompt:string},默认空串。 +- scenes: [{id:32位hex, name, description, location, time, weather, lighting, reference_asset_ids:string[]}]。 +- entities: [{id:32位hex, name, kind:person|creature|prop, description, reference_asset_ids:string[], forms:[{id,name,description,reference_asset_ids}], appearances:[{id,name,description,reference_asset_ids}]}]。 +- shots: [{id:32位hex, name:string, scene_id:string|null, cast:[{id,entity_id,form_id:null|string,appearance_id:null|string,position:string,action:string}], visual_prompt:string, motion_prompt:string, overrides:{time?:string,weather?:string,lighting?:string,palette?:string}, frame_parameters:{seed:int}, video_parameters:{seed:int,source_seconds:int(1..15),num_inference_steps:int,guidance_scale:number,upscale:boolean}, edit:{start_frame:int>=0,duration_frames:int24..360}}]。 +- render: 与旧render相同结构(fps24,total_frames,fit,audio,subtitles,template_version),total_frames按edit.duration_frames求和。v3源生成时长与选用区间独立,选用不能越过源。 +- 稳定ID与展示序号分开;重排不换ID。最少1镜头、容量沿用runtime-policy。未知字段拒绝。空overrides表示继承,有字段含空串表示显式清空,移除字段恢复继承。 +- form/appearance可为空;引用必须存在且属于同一entity。仅引用本镜头出现的实体。视觉编译含故事/选定场景/角色形态造型/位置关系/visual_prompt,运动单独编译。不调用LLM静默改写。 + +### API(新接口统一/api/stories) + +所有命令用现有会话CSRF;生成/确认/清除/重试/渲染使用Idempotency-Key,body冻结expected_version。成功确认/清除同事务增加Draft.version/revision。普通PATCH不接受可信选择字段。 + +- GET /stories/capabilities -> {enabled,reference_generation:{available,task_type,max_reference_images,model,reason},frame_text_generation:{available},max_shots}。 +- GET /stories -> Page<StoryDTO>;POST /stories {name,spec} -> StoryDTO;GET/PATCH/DELETE /stories/{id},PATCH {name?,spec?} + If-Match。 +- GET /stories/{id}/preview -> {shots:[{shot_id,context_hash,frame_prompt,motion_prompt,references:[{asset_id,sha256,role,label}],effective_settings,errors:[]}],errors:[]}。 +- GET /stories/{id}/candidates?shot_id&kind&page&page_size -> Page<CandidateDTO>。 +- POST /stories/{id}/candidates {expected_version,shot_id,kind:frame|video,count:1..4,source_kind:generated|manual,asset_id?:string,execution_mode:interactive|batch,reference_mode?:text|reference} -> {story:StoryDTO,candidates:CandidateDTO[]}。 +- POST /stories/{id}/candidate-batches {expected_version,shot_ids:string[],kind,count,execution_mode,reference_mode?} -> {story:StoryDTO,batch_id,candidates:CandidateDTO[]};用持久候选计划惰性补Jobs,不能一次建全部Job。 +- POST /stories/{id}/candidates/{candidate_id}/retry {expected_version} -> 同候选创建结果;重试新candidate,原输入不变。DELETE同路径+If-Match。 +- POST /stories/{id}/selections {expected_version,shot_id,kind,candidate_id} -> StoryDTO。 +- POST /stories/{id}/selections/clear {expected_version,shot_id,kind} -> StoryDTO。 +- GET /stories/{id}/readiness -> {ready,issues:[{shot_id?,code,message}],shots:[...]}。 +- POST /stories/{id}/renders {expected_version,execution_mode} -> 既有RunSnapshot,run增加frozen_spec/render_inputs可选字段;GET /stories/{id}/runs -> Page<RunDTO>。运行控制沿用/workflow-runs。 + +StoryDTO={id,name,kind,spec,revision,version,created_at,updated_at,selections:SelectionDTO[],readiness:{ready,issues:[]}}。 +CandidateDTO={id,draft_id,shot_id,kind,source_kind,job_id:null|string,asset:Asset|null,state:string,context_hash,generation_hash,created_revision,version,created_at,stale:boolean,error?:object}。状态从关联Job派生,未派发为queued,素材就绪ready,失败failed,手动规范化也须完成后ready。 +SelectionDTO={id,draft_id,shot_id,kind,candidate_id:null|string,asset:Asset|null,context_hash,version,created_at,stale:boolean}。采用每镜头每kind最新追加选择,清除写空选择;历史Run快照独立保留。 +事件增加story.updated、candidate.updated、selection.updated;payload各带story/candidate/selection对象,owner事件流不变。API响应错误仍detail.code/message。 + +### 后端与模型任务 + +- image.reference.generate:input={prompt,negative_prompt?,reference_asset_ids:[string]},有序真实多图,首批认证1–3;参数使用独立Edit profile,显式尺寸、seed、步数、true_cfg/guidance映射;认证前available=false,禁止默降文生图。 +- image.prepare_frame:CPU任务,input={image_asset_id},parameters={width,height,fit:contain|cover};生成实际给Wan的规范化独立图片Asset。可用于手动候选;生成候选也须确保尺寸符合规范。 +- 现有image.generate纯文生图、video.generate单首帧保持原合同。frame reference任务设置固定1280x704或704x1280。 +- 后端Provider准备GPU payload、远端上传、推理runner/store/adapter、GPU_TYPES、资源profile、返回capabilities均注册新任务;图片列表逐张验证/上传/保序,缺图显式失败。 +- 输入token预算用实际tokenizer检查,不能默截断。依赖vLLM/Omni0.32.0、Diffusers0.40.0;2026-11-11已核验服务器实际安装与Edit-2511完整权重,并完成1/2/3图、同ID让卡重排、原生5/15秒视频与真实产品闭环,现正式启用2511普通3图profile。2509与4图profile未验证、不开放。当前可用状态仍以运行时能力接口为准,使用步骤见[锚定工作室操作手册](../锚定工作室操作手册_20261111.md)。 + +## 不变量 + +context_hash表示有效视觉意图,不含候选seed、镜头顺序、字幕或运动。generation_hash再加入真实seed、模型/适配器版本与参数。视频上下文包含批准首帧SHA、motion、实际源长度;只改trim不重生视频。普通JSON导入不能伪造批准。确认校验CAS、同owner同故事同镜头、存在/终态/ready/SHA、当前context_hash;异步完成只更新候选,不写选择。 + +v3正式Run冻结当前选择版本、视频Asset/SHA、按序trim、画幅、音轨与字幕;只建compose步骤。v3专门render plan,不能送旧compile_timeline。普通候选Video也执行帧数/fps/最终增强产物验证。原片/增强片角色显式选择。旧Run展示其冻结spec而不是当前draft。 + +候选输入/输出、当前选择、Run各自登记引用。删除候选只释放自己的refs;引用中的素材不能物理删除。故事/任务删除接入候选关系,删除镜头后旧结果不得恢复镜头。共享先导入私有副本。镜头外观变化过期结果保留,用户可显式作为人工素材重新复核。 + +GPU调度保留其他用户优先、立即让卡与同ID重排;四卡按原预算派发。08:00限制开关沿用runtime-policy,关闭新阶段不打断在执行阶段;窗口外持久排队。HTTP/SSE关闭不停止共享Qwen。每tick补队上限不等于单用户8个视频限制。 + +## UI + +保留/create、/workflow、/compose;新增/studio故事列表和/studio/:id故事工作室,顶栏保存/版本/阶段状态,基准板/分镜/成片三模式,左稳定镜头卡、中候选预览与对比、右当前镜头属性、下时间线。角色/形态/造型/场景/继承来源可编辑;@和按钮两种实体插入方式,缩略图和真实用途明确。未保存切换统一保护,所有异步回调绑定storyId/shotId/版本/session,SSE重连刷新不重复生成。种子等高级折叠;手动字幕/单轨及越界保留。 + +## 验收 + +后端域/事务/权限/幂等/重启/事件/删除/旧协议回归;前端类型/完整测试/构建/格式;隔离MySQL005迁移演练;真实MySQL接入前联合备份并停止本机协调器,更新后只校验。浏览器走完整人工定帧->视频候选选择->冻结合成与下载,模型PoC不通过则诚实标为不可用并继续排查,不伪造能力。所有代码留工作区,不提交。 diff --git a/docs/design/2026-11-12-creation-editing.md b/docs/design/2026-11-12-creation-editing.md new file mode 100644 index 0000000..8c2c824 --- /dev/null +++ b/docs/design/2026-11-12-creation-editing.md @@ -0,0 +1,68 @@ +# 创作图生图与可选多人视频替换规格 + +用户明确要求直接在现项目开发;补充要求:可选择视频中需要替换的人物,支持一次提交同时替换多人。保持当前所有未提交代码,不暂存/提交/推送,不复原HEAD,不创建脱离现有工程的新项目。全部源代码位于E:/workspace/hybrid/cmvr-visual。 + +## 产品与技术决定 + +新增/create/image-edit、/create/video-edit,保留/create/image、video、defect及/studio等现有入口。图生图用已部署且认证的Qwen-Image-Edit-2511,最多3张有序不同参考图片+提示词,支持横1280x704、竖704x1280、方1024x1024,1–4份独立候选Job。无图不得暗降文生图。 + +视频用Wan2.2-Animate-14B-Diffusers替换模式,补充YOLOv10m、ViTPose wholebody、SAM2。官方单人预处理不能满足多人选择,必须实现实例检测/稳定跟踪、每人独立姿态/脸部/遮罩、逐人模型替换、遮挡与未选区域保护合成。不能用逐帧图生图、静帧视频或只换首帧冒充视频替换。V2V是一个业务Job,可按人物串行处理;“同时替换多人”表示同一成片包含全部所选人物映射,不要求模型单次前向原生多主体。 + +人物支持自动识别+点击人物卡片/视频框选择,逐人物绑定一张主参考形象图片和可选局部提示词。全局提示词共同生效;未选择人物和背景保留。分析不做人脸实名识别,仅为本视频实例分配person_id。跟踪不确定/主体缺失显式提示,不把另一人自动顶替。人物遮挡遵循原视频可见区域;输出前能预览选择/跟踪效果。 + +源视频可保留原音轨(默认true),替换仅影响画面;输出统一24fps并保持源视频时间长度和比例,VFR先按实际时间转CFR。默认480p级面积832*480,可选720p级1280*720,最终尺寸取16倍数。模型内部77帧分段不等于用户只能上传77帧。初始部署资源预算:每次视频最长120秒、最多12个替换人物,均为后端配置可调且UI如实显示,非每用户任务数量限制。硬限制不得静默截断源片/丢人。后续可提高预算而无需改协议。 + +## 任务协议(与既有/api/jobs、SSE、私有素材共用) + +新增GPU任务video.people.analyze、video.replace。image.reference.generate已存在,不另建第二协议。无新增数据库表,使用现有Jobs/Execution/JobAssets/AssetReferences/Events及result_json。输出媒体仍放独立工作空间。分析及替换均用原幂等提交/取消/重排,关闭页面不取消,更不停止共享Qwen。 + +### 图生图 + +input={prompt,negative_prompt?,reference_asset_ids:[private_image_id1,...]};parameters沿用Edit profile。普通Job可count1..4,种子按原批次规则递增。参考图顺序由页面显式编号、可移除/重排;选图先校验全部可用并保序上传,缺图/越限拒绝。保留旧本地草稿key,增加可迁移的referenceAssetIds字段并正确清理被删素材;账号切换迟到回调不得填入新账号。 + +### 人物分析 + +input={video_asset_id}; parameters={profile:'wan-animate-replace-v1',max_pixels:399360,fps:24}。 + +成功Job.result包含: + +``` +{profile,analysis_token,source_sha256, + video:{width,height,fps:24,frames,duration_seconds}, + poster_output_index:0, + people:[{id:'person_0001',label:'人物1',thumbnail_output_index:1, + first_frame,last_frame,confidence, + samples:[{frame,bbox:[x1,y1,x2,y2]}]}],warnings:[]} +``` + +bbox为归一化0..1坐标,samples是有界预览记录(不是全部mask),每人至少首现/中间/末现可见样本。poster及人物缩略图为真实输出Asset,前端用result_assets对应output_index取素材。重型跟踪/姿态/遮罩及每帧时序放服务器任务私有manifest,不将路径下发浏览器;analysis_token绑定视频SHA、模型profile及不可变manifest SHA。人数/时长/解码/无人物/明显跟踪歧义均给明确结果或错误。 + +### 替换 + +``` +input={video_asset_id,analysis_job_id,prompt,negative_prompt?, + replacements:[{person_id,reference_asset_id,prompt?:string},...]} +parameters={profile:'wan-animate-replace-v1',max_pixels:399360,fps:24, + num_inference_steps:20,guidance_scale:1.0,seed:42, + preserve_audio:true,mask_expand_pixels:8,mask_feather_pixels:4} +``` + +analysis_job_id是业务分析Job ID,必须同owner、终态成功、类型正确、源视频ID/SHA及参数同源且所选person_id均存在。重复person_id、缺参考图、非图片、越限、分析已删或失败明确拒绝。用户只能提交素材/人物编号,不接受路径/URL/原始不可信mask。所有源视频与参考图加入独立JobAssets引用保护。 + +Provider将analysis_job_id解析为该分析的已知upstream_id,向既有认证推理队列发送analysis_id、analysis_token及源视频路径、有序replacements[{person_id,image_path,prompt}];远端再验证原分析成功、同principal、SHA/token/profile一致后使用其manifest。不得仅信任浏览器传的token。prompt传给真实WanAnimatePipeline(mode='replace'),并冻结实际参数、人物映射和参考图SHA;原片不覆盖。 + +GPU队列结果:分析metadata直接包含上述安全结构;替换outputs的final_output_indices指向完成全部人物合成和可选原音轨后的MP4;metadata包含实际替换person_ids、源帧数/输出帧数/fps/尺寸、模型profile、跟踪警告及不包含私有路径的阶段数据。业务Provider导入JSON元数据和所有缩略图,按output_index保持对应关系;丢输出拒绝部分发布。 + +## 能力与配置 + +业务Settings增加video_edit_enabled=false、video_edit_profile='wan-animate-replace-v1'、video_edit_max_seconds=120、video_edit_max_people=12;对应环境变量。推理Settings同名enabled/profile/limits及poc_enabled=false。只有两端同profile、全部权重/预处理ready且通过实测才正式available;未认证保留明确reason,但不能以永久disabled完成交付。上游/capabilities.video_edit={available,profile,model,max_seconds,max_people,max_pixels,fps,reason},原reference_generation保留。 + +初始模型固定HF revision:Wan-AI/Wan2.2-Animate-14B-Diffusers@6f4df10861c758af86ac3c979aacc1bf5c03eff0,完整仓库体积82,257,099,741字节;下载只取必需配置和权重并逐文件SHA校验。预处理模型来自Wan-AI/Wan2.2-Animate-14B/process_checkpoint。下载入口为 `inference/scripts/download_video_edit_models.py`,配置样例为 `inference/config/video-edit-profile.example.json`;使用明确可复现commit/版本,不隐式换模型。独立animate venv,不改变vLLM环境。 + +保持每卡68GiB分配上限与8GiB保留、其他用户优先立即让卡、四卡合格卡派发、原ID重排和全局RAM准入;建议新任务CPU RAM预算analyze32GiB/replace160GiB,实测后只能在证据支持下收紧。所有子进程必须在同一可清理进程树,不以外部守护绕过监管。分阶段读写时防符号链接/路径越界,取消/让卡清理自己的子树。批量窗口沿用既有准入,当前任务自然完成。 + +## UI与验证 + +图生图保留文字提示、负向提示、种子/步数/CFG、画幅、候选数、模式/时段及任务历史;支持多选上传/私有素材库/共享导入副本,与现有AssetInput/Picker复用。视频编辑先选源片→“识别人物”→等待SSE结果→点击多个人物卡/画面框→逐人选主参考图/局部提示→全局提示/保留声音/规格→“生成替换视频”。选源改变要失效旧分析和人物映射,保留输入但不误用;候选显示实际模型用途,已持久任务不因断线重发。 + +必须验证跨owner/已删素材/过期分析/令牌/幂等冲突/乱序回调/人物ID重用/重复映射/多主体遮挡/只选一个和全选/未选区域保护/真实媒体帧数和音轨时长。单测不能代替模型效果;真实图生图1/3图及方图,真实双人源片选择单人/多人替换、与原图和未选人对照、SSE/刷新/手机页面、现有故事及快速创作回归均需要记录。不得自动Git提交。 diff --git a/docs/design/2026-11-12-logical-folders-design.md b/docs/design/2026-11-12-logical-folders-design.md new file mode 100644 index 0000000..00ad168 --- /dev/null +++ b/docs/design/2026-11-12-logical-folders-design.md @@ -0,0 +1,45 @@ +# 数据库逻辑文件夹 + +用户已在“按照上述需求开发”中批准上一轮可行性说明;本文件固定执行细节,不追加审批。 + +目标:按故事或自定义文件夹整理素材、任务和故事,创作前选择成果保存位置。分类完全由数据库管理,实际媒体存储地址、素材 ID 和引用保持稳定。网站前后端继续本地运行。 + +采用独立文件夹表、素材多对多归属、任务和草稿/运行单归属。仅用标签无法表达默认成果位置和任务归属;将分类塞入生成参数会影响计算与幂等,因此使用独立元数据。 + +## 固定接口 + +- `Folder`: `{id,name,parent_id,created_at,updated_at}`。所有文件夹按用户隔离;支持子文件夹、创建、改名/移动、删除,禁止循环。同级重名拒绝;允许不同父级重名。 +- `GET /api/folders` → `{items:Folder[]}`;`POST /api/folders {name,parent_id?}` → 201 Folder;`PATCH /api/folders/{id} {name?,parent_id?}` → Folder;`DELETE /api/folders/{id}` → 204,删除该分类及子分类,内容变为未分类或保留其其他文件夹归属,不删除素材/任务/故事或物理文件。 +- `POST /api/folders/assign {kind:'assets'|'jobs'|'drafts'|'runs',ids:string[],folder_id:string|null,mode?:'move'|'add'}` → `{updated,kind,folder_id}`。原子校验所有记录属于当前用户;add 仅用于素材,保留已有成员关系;move 替换素材归属或修改记录归属。上限 200 个 ID,操作不重复拷贝素材。 +- 素材 DTO 增加 `folder_ids:string[]`;任务 DTO 增加 `folder_id` 与 `output_folder_id`;草稿/故事 DTO 增加 `folder_id`;运行 DTO 增加 `folder_id` 和 `output_folder_id`。前端兼容旧 DTO 缺少这些可选字段。 +- `/assets`、`/jobs`、`/stories`、`/workflows`、`/runs` 列表增加 `folder_id`:省略/空字符串为全部,`unclassified` 为未分类,其他值必须是本人有效文件夹 ID。 +- 上传 multipart 支持可选 `folder_id`;素材 PATCH 支持 `folder_ids`;共享素材导入 body 可选 `{folder_id}`,老的无 body 调用继续有效。 +- 普通任务 Submit 增加可选 `folder_id`、`output_folder_id`。输出目录省略时继承任务目录,显式 null 表示未分类。重试继承原归属;记录分类移动不回写冻结的输出目标。 +- 故事创建增加可选 `folder_id` 与 `create_folder:boolean=true`:未提供 folder_id 且 create_folder=true 时创建同名文件夹(重名时创建唯一后缀);提供有效 folder_id 时复用;显式 folder_id=null 或 create_folder=false 可未分类。故事 PATCH 可改 folder_id,新增素材引用可加入故事文件夹(不移除原有文件夹)。普通工作流创建仅选目录,不自动创建。 +- 候选创建/批量候选、故事渲染、工作流启动支持可选 `output_folder_id`,默认草稿文件夹。提交时保存目标,草稿后来改名或换目录不能改变已排队结果的目标。旧候选 plan 没有归属时按未分类处理。 +- 文件夹删除与在途任务兼容:关联列 ON DELETE SET NULL,资产成员 ON DELETE CASCADE;成果导入时用当前有效目标再次检查,已删目标回到未分类。非本人目标必须在提交前拒绝,不向上游发送 folder 元数据。 +- 幂等:未使用新字段的旧提交 payload/hash 保持兼容;相同幂等键指定不同目标拒绝。成员添加和移动不能改变资产 ID、下载路径、源任务关系、引用或已批准的选择。 + +## 数据与安全 + +新增 `visual_folders`(id/owner_id/name/parent_id/内部 parent_key/时间)及 `visual_asset_folders`(asset_id/folder_id 主键)。parent_key 根目录为空字符串,用同级唯一约束避免 MySQL NULL 唯一键漏洞。文件夹分类记录可硬删除,业务记录和媒体不会级联删除。 + +Job 增加 folder_id/output_folder_id,WorkflowDraft 增加 folder_id,WorkflowRun 增加 folder_id/output_folder_id,均可空、带索引和 ON DELETE SET NULL 外键。素材成员关系使用 selectin 加载并在新建素材时初始化空集合,避免同步 DTO 触发异步懒加载。只使用新增迁移 006,保留历史迁移。 + +前端使用统一 FolderSelect 与文件夹管理组件。素材库可创建/改名/删除文件夹、按目录浏览、批量移动/加入;素材选择器可按文件夹筛选;任务页可筛选/整理;故事列表可命名后创建并选择新建同名目录或现有目录;故事工作室显示归属并设置本次成果位置;普通创作、工具、成片和工作流具有成果保存选择。 + +未分类是动态视图,不创建特殊数据库记录。删除文件夹的确认文案明确“保留内容”;实体删除继续使用现有引用保护和文件清理机制。所有新状态跟随登录 session 清空,异步旧会话结果不得回填。 + +## 验证 + +用真实测试数据库、HTTP、文件和事件验证 CRUD、树循环/重名、用户隔离、素材多目录、删除不触文件、异步成果归档、重试/幂等、冻结运行及候选、旧数据未分类。外部模型使用 FakeProvider,不运行 GPU。 + +新增迁移须验证旧 005 数据升级后数据/路径不变及 metadata preflight;本地实际 MySQL 升级前保存私有备份。统一跑后端、前端测试与生产构建,真实浏览器验证桌面/窄屏及本地页面。没有 Git 暂存/提交/推送,不部署网站到服务器,不改变模型或 GPU 策略。 + +## 用户追加的 UI 调整 + +文件夹管理改成先选当前目录,再执行“新增子文件夹 / 编辑文件夹 / 删除文件夹”;创建和编辑字段放弹窗,不把所有操作的输入框摊在页面上。浏览选择与管理使用同一当前目录。未选实际目录时允许根级新建。 + +保留素材多选,并接入批量删除、批量发布到共享库;复用现有单项接口和引用保护,有界执行、总数确认、结果汇总、失败项保留选择。异步会话切换后不能继续替新用户发写请求或回填旧结果。 + +缩小素材卡片、预览高度和勾选控件,提高桌面列数与每页数量;窄屏不出现水平溢出。新增可选每页24/48/96,默认48;在实际浏览器确认密度增加且操作仍可用。 diff --git a/docs/design/2026-11-12-production-workflow-design.md b/docs/design/2026-11-12-production-workflow-design.md new file mode 100644 index 0000000..49fbfdf --- /dev/null +++ b/docs/design/2026-11-12-production-workflow-design.md @@ -0,0 +1,147 @@ +# 六项能力与生产流程完善方案 + +状态:2026-11-12编写的待实施方案,保留当时的代码与风险分析。2026-11-13已移除独立工作流、批量和成片页面;下文涉及旧页面的落点是历史背景,后续若实施应接入故事或任务中心,不能按旧页面名寻找入口。现有功能的操作步骤以[操作手册](../操作手册_20261111.md)第0、4、7节为准;本文新增的接口、字段和页面尚未实施。当前开发全天运行的策略保持不变。 + +**Goal:** 保留现有六项基础能力及单人审核闭环,补齐故事批次导航和夜间产能依据;如正式生产要求所有模型任务仅夜间执行,提供统一策略扩展;多人审批另列可选阶段。 + +**Architecture:** 沿用Vue/Pinia、FastAPI/MySQL、单业务协调器和独立模型调度器。复用草稿、运行、任务、批次、候选、选择与执行记录,不另建任务引擎,不引入Redis/Celery。版本化增加合同和必要迁移,既有任务、素材及历史成片继续可用。 + +**Tech Stack:** Vue 3、TypeScript、Pinia、FastAPI、SQLAlchemy async、Alembic、MySQL、现有HTTP/SSE与FFmpeg。 + +**Spec:** 用户提出的“图像生成、视频生成、数学推演、缺陷样本生成、素材结构化、成片合成;夜间批量生成,日间编排审核,按夜间算力产出制定生产节拍”。开发环境暂不固定21:00–08:00。以下未获明确规定的统计口径和审批形式均为本方案建议,不视为用户已经选择。 + +## 1. 已实现的范围及依据 + +| 需求 | 当前实现 | 主要代码 | +| --- | --- | --- | +| 图像、视频、缺陷样本 | 提示词/参考图、参数校验、独立任务及结果归档 | `frontend/src/views/WorkbenchView.vue`;`backend/app/adapters/provider/contracts.py`、`gpu.py`;`inference/llm_services/adapters.py` | +| 数学推演 | 共享Qwen返回步骤与答案,输出文本及JSON,未做形式化验证 | `backend/app/adapters/provider/cpu.py`、`qwen.py` | +| 素材结构化 | 图片或均匀抽帧的视频理解,输出主体/场景/OCR/标签/JSON;ASR为单独任务 | `frontend/src/views/ToolsView.vue`;`backend/app/adapters/provider/qwen.py` | +| 成片合成 | 已有片段或故事选片的排序、裁剪、画幅、单音轨及人工字幕 | `frontend/src/views/StoryStudioView.vue`及`components/EditableProduction.vue`;`backend/app/adapters/provider/composition.py`;`backend/app/services/stories/api.py:render` | +| 批量生成 | 通用混合批次及故事候选计划,持久保存、幂等、暂停/继续/取消和有界补队 | `backend/app/services/batches.py`;`services/stories/candidates.py`;`services/orchestration/workflow_engine.py` | +| 编排审核 | 角色/场景基准、分镜顺序、候选比较、确认首帧/选片、确认失效和冻结合成 | `frontend/src/views/StoryStudioView.vue`;`components/studio/StoryCandidates.vue`;`backend/app/models/stories.py` | +| 时段控制 | API和worker读取策略;批量在21:00–次日08:00准入,已准入执行单元继续完成 | `backend/app/services/orchestration/resource_policy.py`;`inference/llm_services/scheduling.py` | + +当前运行接口的批量时段开关为关闭,六项基础能力已开放,故事能力已启用。能力“可用”说明接口和配置具备,不等于所有题材的生成质量、数学正确率或工业标注准确率都已验收。 + +“审核”已有可追溯的本人选择记录:`visual_shot_selections`追加保存操作者、版本、上下文和素材校验信息;普通草稿不能伪造批准。它没有另外一名审核人、驳回意见或成片终审单。 + +“本地部署”目前为本机网站和业务API、局域网服务器模型与MySQL,不依赖公有云模型;不表示模型也装在当前Windows开发机。六项能力产出可供教学课件和视频使用,但没有一键生成/导出PPTX教学课件。 + +## 2. 哪些是缺口,哪些是可选扩展 + +| 编号 | 结论 | 实施范围 | +| --- | --- | --- | +| A | 原批量页的历史衔接问题 | 旧批量总表曾将非`run`成员统一链接到Job详情;独立页面已移除。后续若在任务中心呈现候选批次,仍须正确定位原故事,不能把候选编号当Job编号 | +| B | 严格解读原文时的策略缺口 | 当前交互队列全天,不能仅打开现有开关就声称“所有生成仅夜间”;增加策略作用范围。若正式生产仍保留日间交互,可继续用现有策略 | +| C | 生产节拍的管理缺口 | 已有执行与选片记录,但没有逐夜产量、合格选片、积压和产能估算页面;增加有依据的统计 | +| D | 可选组织流程 | 若“审核”指编导送给其他人审批,再补多人送审和终审;它不是现有本人选片的别名,也不是六项基础能力必须先重建的前提 | + +优先采用“在现有架构上补A与C,B按正式生产策略启用,D按组织需要选做”。重建通用工作流平台会重复现有持久任务和人工关卡;当前数据规模也不需要先引入新的消息队列或集群调度。 + +## 3. 全局约束 + +- 只在本地修改和验证;本次不部署网站、不切换真实时段、不重启共享模型。 +- 四卡按就绪FIFO派发,每卡一个本项目任务;其他用户优先、内存预算、取消清理和幂等恢复保持原规则。 +- 21:00–次日08:00按Asia/Shanghai解释,边界为21:00包含、08:00不包含;窗口关闭不终止已准入执行单元。单个GPU runner内的生成与可选增强是一个单元,允许整条pipeline结束,不承诺在内部神经网络阶段之间跨夜暂停恢复。 +- 私有内容按账号隔离。新增统计、候选详情或审核授权不能把管理员变为所有用户私有内容的默认读者。 +- 历史迁移001–006保留;新增迁移顺序按实施时仓库最新版本确定,不覆盖后来新增的版本。 +- 已冻结运行不受草稿后改影响;新版本不能继承旧版本的审核结论;未知远端结果不能自动重新生成。 +- 不自动暂存、提交或推送。验证优先使用自动清理的隔离临时目录;通过后清理临时脚本、截图、媒体、数据库和打包文件,保留复用测试与最小夹具。 + +## 4. 重点验收风险 + +1. 候选尚未派发,没有Job编号,或者不在第一页时,批量成员仍应准确打开所属故事候选。 +2. 交互/批量两条入口、后台恢复和远端worker必须执行相同的夜间策略;任务JSON不能自行改成另一模式绕过严格窗口。 +3. 新故事的首帧审核是人工关卡。视频批量不能在缺少有效首帧时偷偷越过审核,重连和重试也不能自动选片。 +4. 重排、失败重试和多阶段处理不能重复计算产量;未选候选不能直接当作“未审核”,开发数据不能冒充稳定生产产能。 +5. 审核人只能读取被明确授权的冻结包;调换ID、旧版本提交、重复决定和修改草稿均不能扩大读取范围或复用旧批准。 + +## 5. A:补齐批次导航和操作入口 + +**代码落点:** `backend/app/services/snapshots.py`、`services/stories/api.py`、`api/routes/stories.py`;`frontend/src/types/workflows.ts`、`api/stories.ts`、`views/TasksView.vue`、`views/StoryStudioView.vue`(原批量页已移除)、`components/studio/StoryCandidates.vue`。 + +**合同:** 保留现有Batch字段,在候选成员追加可空`story_context`:`story_id`、`shot_id`、`candidate_kind`(frame/video)、`candidate_id`、`job_id`、`asset_id`。在同一账号范围内读取候选归属,不能信任客户端提交的上下文。非候选成员返回空上下文,旧客户端继续读取原字段。 + +新增`GET /stories/{story_id}/candidates/{candidate_id}`,返回已有CandidateDTO;同时校验故事、候选和当前账号的归属,已删除或跨账号返回404。该接口用于直接定位较早的候选,避免为了打开第25个以后的结果连续翻页扫全库。 + +- [ ] 先补回归:`run`仍打开运行详情,`job`仍打开任务详情,`candidate`打开故事;未派发、已失败、已删除、跨账号、候选超过第一页分别检查。 +- [ ] 实现快照上下文和候选详情接口,不迁移数据库,不改变任务派发。 +- [ ] 后续若在任务中心或故事运行历史展示批次,按`target_kind`分别跳转:候选使用`/studio/{story_id}?shot={shot_id}&stage={candidate_kind}&candidate={candidate_id}`。不支持的类型显示可解释状态,不能退化成错误Job链接。 +- [ ] 故事页校验查询参数、定位镜头和阶段并加载目标候选;这些参数只定位,不生成、不确认、不重试。 +- [ ] 在“03 成片”增加明确的合成执行方式选择,复用现有`executionMode`和`RenderCreate.execution_mode`,便于日间直接选择交互CPU合成。 +- [ ] 通过后同步手册,删掉当前“回原故事查看”的导航限制说明。 + +## 6. B:让正式生产支持严格夜间模型任务 + +**代码落点:** `backend/app/core/runtime_policy.py`、`domain/tasks.py`、`services/orchestration/resource_policy.py`、`admission_clock.py`、`coordinator.py`、`adapters/provider/runtime.py`;`inference/llm_services/scheduling.py`、`store.py`、`worker.py`、`remote_bridge.py`、`api.py`;前端能力类型、服务状态和批量策略提示。 + +**配置建议:** 支持运行策略schema v2,新增`model_window_scope`,只接受`batch_only`和`all_model_tasks`。继续接受v1,并解释为当前`batch_only`;`batch_window_enabled=false`时两个范围都全天可执行。当前开发配置不变,正式严格模式是v2加`true`和`all_model_tasks`。 + +在API与worker分别实现纯规则`window_applies(task_type: str, execution_mode: str, phase: str, policy: dict) -> bool`,用同一组合同测试向量检查结果。模型阶段覆盖图像、参考图、视频、缺陷、语音生成、Whisper及Qwen推演/理解;上传、Pillow首帧规范化、FFmpeg抽音/裁剪/拼接、浏览/确认等日间编辑和审核操作继续开放。对其他项目调用共享Qwen不施加本项目策略。 + +本方案明确选择“执行单元准入”的边界:GPU worker一次启动的runner(包含该视频的生成与Real-ESRGAN增强)整体为一个单元;业务API已有独立资源阶段的租约也分别为单元。07:59准入的视频可在08:00后继续生成、增强和清理,但不能再开始另一镜头/新的runner。一次已准入的Qwen素材理解阶段可完成本阶段的抽帧理解调用。当前不引入内部阶段检查点,不以重排来假装续跑,否则会重生成已经完成的视频。`all_model_tasks`范围只约束模型执行单元,关联批次的纯CPU后期也允许日间处理;v1/`batch_only`保持原有批量阶段限制。 + +- [ ] 补20:59:59、21:00、07:59:59、08:00边界及跨日、时钟回退、暂停、取消、服务恢复测试。分别覆盖两个模式、窗口范围和资源阶段。 +- [ ] 双端读取、远端运行状态传输及本地镜像都保留新增范围;不能只改一处JSON白名单。后台恢复与旧已排队任务也按当前生效策略重新判断新阶段准入。 +- [ ] 双端先支持并通告策略版本及范围,再允许管理员激活严格模式。版本不匹配或严格模式配置不可核实时关闭新模型准入并说明原因,不允许回退为日间交互执行;CPU后期保持可用。 +- [ ] 后端在申请新的Qwen/配音等模型执行租约之前校验,GPU worker在领取及实际spawn前再次校验,保持真正执行的二次保护。测试07:59启动的视频在08:00后完成增强、不重生成,而新的视频单元等到下一窗口;新的独立HTTP模型阶段也须重新判断。 +- [ ] 页面从服务端展示“开发全天 / 仅批量夜间 / 全部模型夜间”,并区别排队等待与故障。客户端任务体没有策略覆盖字段。 +- [ ] 隔离测试通过后提供管理员切换和回退步骤;实际启用属于后续正式生产操作,本次不改运行配置。 + +## 7. C:用实际夜间产出支持生产排期 + +**代码落点:** 新建`backend/app/services/production.py`、`models/production.py`、`api/routes/production.py`、`schemas/production.py`和`frontend/src/views/ProductionView.vue`;扩展`inference/llm_services/store.py`、`worker.py`、`api.py`、`backend/app/adapters/provider/gpu.py`和`services/orchestration/executions.py`。复用现有素材、选择校验及SSE,业务模型表实名为`visual_job_executions`。 + +**必要的上游历史:** 现有业务Execution开始/结束是本地观察时间,上游`jobs.started_at`是领取时间且重排会清空,`runner_start`只是进程身份值。它们都不能代表完整的真实执行历史。先在上游SQLite增加持久`job_attempts`表,按现有`execution_id=job_id:attempt_count`唯一保存`claimed_at`、`admitted_at`、`runner_started_at`、`finished_at`、`outcome`及`admission_policy_snapshot`。所有时间为上游UTC事实:准入时间与当次最后准入检查使用的快照一起持久化;runner开始只代表Popen成功,结束代表清理确认,不称GPU核函数运行时间。未启动延期、让卡、失败、取消、超时和未知结果均保留相应尝试,不能只保留最后一次。 + +在`claim_next/admission/set_runner/defer_unlaunched/requeue_preempted/finish`等生命周期写入历史,保持attempt/fence校验。新增受原鉴权保护的`GET /jobs/{job_id}/executions?after_attempt=0&limit=100`,并在能力接口声明`execution_history_version=1`。终态历史不可变并按attempt分页;未终态尝试单列为`current`、每次重取,避免分页游标漏掉运行到完成的变化。返回持久的`store_instance_id`、完整性及可用历史范围;旧版本无历史时明确标记unknown。 + +**业务镜像与本地阶段:** 新迁移增加`visual_upstream_attempts`,以`(store_instance_id, upstream_execution_id)`唯一镜像,关联本地Job与owner,并保留原始时间和策略。补录API离线期间的尝试只更新统计镜像,禁止用旧attempt调用当前Job的状态推进或替换fence。为`visual_job_executions`增加可空`admission_policy_snapshot`,记录本地Qwen/配音等执行租约的真实准入策略;既有`started_at/finished_at`继续作为本地观察字段,不改写其含义。历史空值为`policy_unknown`;Qwen HTTP耗时、runner存活/清理区间和网页观察耗时分别展示,不将任一项冒充精确GPU利用率。 + +**观测覆盖:** 在同一新增迁移中增加`visual_production_observations`,由现有协调器至多每分钟采一条`owner_id/observed_at/policy_snapshot/service_online/eligible_gpu_count/backlog_by_profile`。这是排期样本的覆盖证据,不是新调度器。首版建议有效夜次需要至少95%的分钟样本、连续缺口不超过2分钟、同规格至少90%的有效采样有待处理需求,且真实策略已知并启用窗口;阈值为方案建议,API中公开口径。空闲无需求、离线、开发全天、旧无历史等夜次仍展示事实,但不进入产能参考。没有覆盖证据不能把缺失夜次补成零或把少数繁忙夜当稳定产能。 + +**读取合同:** `GET /production/summary?night=YYYY-MM-DD&days=7`,仅当前账号,最多31夜。`night`代表当日21:00开始的一夜,返回时区、截止时间、指标、分组、覆盖缺口、有效样本夜数与估算依据;参数异常返回422。用受限SQL聚合执行和产物事实,再对涉及的故事有界复用`preview/selections/selection_dto/readiness`检查上下文、首帧依赖、素材及裁剪;不能仅凭非空`candidate_id`计合格。大量故事时分页返回确认统计和校验进度,未校验完的统计标为不完整,不能拿部分结果预测。沿用业务数据库,不增加独立统计数据库。 + +统计口径固定如下: + +- 产物按Job/候选唯一编号计算,执行尝试单独统计;让卡重排、增强阶段和重试不算新产物。 +- 按模型类型、profile、分辨率、源长度和主要生成参数分组,不把5秒视频与15秒视频混为相同产能。 +- 按最终成功尝试的真实准入夜次归属;08:00后完成的同一在途pipeline仍计入原夜次,单列延后完成时间。白天提交但夜间执行的任务不归到提交日白天;缺少上游时间或策略时显示归属未知。 +- 展示成功候选数量、源视频秒数、截至查询时当前确认的有效视频数量、无有效选片但已有可复核候选的镜头数、失败/取消/让卡尝试和等待时间。未选候选可能已被人工淘汰,不能全部标成待审。 +- “可用于成片秒数”依据有效选择的裁剪区间计算;生成的约15.04秒源片段不等于影片使用15.04秒。 +- 首版以最近最多7个同规格、策略已记录且窗口启用的有效夜次给出实际合格产出P25至中位数的参考区间;少于3夜显示“样本不足”。每夜人力确认速度、外部占卡和可用卡数会影响结果,不把区间写成承诺。 + +- [ ] 先写跨午夜、08:00延后完成、API离线跨夜重排、分页中的运行尝试完成、重试去重、无历史、不同规格、空数据和账号隔离测试。 +- [ ] 增加上游逐attempt持久事实和版本化历史读取,再做业务镜像、本地策略快照与分钟观测迁移;冻结迁移不导入会变化的当前模型。同步重取或历史缺失不能改变当前任务/fence,不能触发重生成。 +- [ ] 实现执行事实聚合及有界有效选择校验,明示统计截止、完整性、样本不足;只读汇总不修改任务、候选或审核状态。 +- [ ] 新增“生产概览”入口,展示夜间产出、需选片镜头和排期参考;链接到已有任务/故事,不另造创作表单。 +- [ ] 用隔离数据验证口径;真实产能观察在正常业务运行中累计,不为填报表额外提交GPU测试任务。 + +## 8. D:有多人审批需要时再增加正式送审 + +该阶段是扩展选项。若当前本人编排、确认已满足审核需求,无须先实施D。 + +**代码落点:** 新建`models/reviews.py`、`schemas/reviews.py`、`services/reviews.py`、`api/routes/reviews.py`及前端审核列表/详情;在后续新迁移中创建`visual_review_requests`和`visual_review_decisions`,不改`ShotSelection`的已有含义。 + +送审单至少包括`owner_id`、`reviewer_id`、`run_id`、`frozen_spec_hash`、冻结素材清单、`state`和`version`。决定追加记录`actor_id/decision/comment/expected_version/created_at`。状态为`pending -> approved/rejected`,作者可撤回pending单;重送或换成片创建新单并关联前单,不覆盖审计。 + +接口为`POST /review-requests`、`GET /review-requests`、`GET /review-requests/{id}`、`POST /review-requests/{id}/decisions`和`POST /review-requests/{id}/withdraw`。写命令延用CSRF、幂等和CAS;决定只允许指定且仍启用的审核人,作者不可冒充审核人或借此批准另一个Run。 + +通过`GET /review-requests/{id}/assets/{asset_id}/content`提供冻结包内素材的受限预览/Range读取,复用现有安全媒体响应。审核人不能使用这次授权查询作者的其他素材或修改故事;撤回/替换送审单后收回该包访问,素材引用仍按审计与历史运行规则保护。管理权限不自动授予审核权限。 + +- [ ] 写两个普通账号与第三个无关账号的权限测试,并覆盖停用账号、替换asset ID、重复决定、版本冲突和撤回后的读取。 +- [ ] 实现冻结送审包、受限读取和追加决定,保留本人原有私有下载/预览。 +- [ ] 增加“待我审核 / 我发起的”列表,给出通过、驳回意见与版本;明确显示审批针对哪份冻结成片。 +- [ ] “终审通过”只应用于该成片版本。若未来增加正式发布通道,在该通道校验批准;不能将已有共享库任意素材一概标成终审成片。 +- [ ] 更新双人操作手册,验证全部产物引用、撤销授权和历史批准可追溯后再启用。 + +## 9. 实施顺序、验收与回退 + +先做A,让现有业务入口连贯;再做C,积累真实夜间数据。正式生产确定严格夜间时实施并启用B;若选用多人审批,再做D。每阶段独立验证、交付,A不依赖新业务表,C与D各用新增迁移。 + +验收至少包括:通用混合批次和故事候选均可定位;多空闲GPU按FIFO接任务;首帧未经确认不能生成对应视频;候选过期不能直接确认;视频未选齐不能冻结;历史Run不被后续编辑改写;窗口关闭不误杀在途;CPU后期仍能日间执行;产量不重复且私有数据不串号。 + +实施时执行相关后端pytest、前端Vitest/类型检查及迁移检查。真实模型质量和产能观察独立报告,不把模拟Provider的回归当作新增模型实测。临时验证目录自动清理,不长期保存验收媒体或代理报告。 + +回退采用关闭新增入口/开关、保留新增数据和历史运行的方式。涉及真正线上组件升级时,先暂停本项目新准入并排空本项目执行,验证数据库与媒体联合备份,再按兼容版本回退;不清空队列,不停止其他用户服务,也不删除真实业务数据。 diff --git a/docs/design/2026-11-13-editable-automation.md b/docs/design/2026-11-13-editable-automation.md new file mode 100644 index 0000000..4c67169 --- /dev/null +++ b/docs/design/2026-11-13-editable-automation.md @@ -0,0 +1,107 @@ +# 可编辑自动成片实施合同 + +用户已批准本方案并要求实施。仅修改当前 feature/v2-workflows 工作区,保留已有修改,不暂存/提交/推送,不调用真实模型、不改真实数据库或重启共享服务。本文也是实施进度记录;接口调整须先更新本文并通知协作者。 + +## 目标和边界 + +故事与工作流自动出片;之后恢复实际成果、编辑镜头/旁白/字幕,只重生成失效部分并产生新成片。保留 legacy 人工流程。auto 直接创建 Run/Step/Job,不写 ShotCandidate/人工 ShotSelection。只新增迁移007,不改001–006。新模式以 editor_manifest 为编辑真源,旧 spec 是兼容投影。 + +## 固定数据合同(JSON字段均使用下划线命名) + +EditorManifest: {schema_version:1, base_run_id?:string|null, source_kind:'story'|'workflow', spec:object, shot_ids:string[], bindings:Record<string,Binding>, audio:EditorAudio, captions:EditorCaptions}。 + +- spec 为已有故事v3或工作流v1/v2视觉配置;editor编译校验时先取 render.audio=null/subtitles=[]、按镜头求 total_frames。输入中的旧音轨/字幕仅在首次导入时迁入 audio/captions,之后 spec.render 中这两项保持空,避免双真源。 +- shot_ids 与 spec.shots 顺序对应:story 使用 shot.id,workflow 导入时创建稳定32hex ID,重排时一并移动。新增/删除不能凭数组下标继承旧绑定。 +- Binding={asset_id,sha256?:string|null,kind:'image'|'video'|'audio'|'text'|'json',input_hash?:string,context_hash?:string,source:'generated'|'manual'|'reused',locked?:boolean,source_run_id?:string,source_job_id?:string,generation_parameters?:object,duration_seconds?:number,duration_frames?:int,sample_count?:int}。键为 frame:<shot_id>、video:<shot_id>、audio:<segment_id>;输入新人工素材可省SHA,保存后的绑定必须是真实SHA。不信任客户端SHA/输入hash声明。 +- audio={mode:'silent'|'manual_track'|'generated_narration',voice:string,speed:number,track:旧Audio|null,segments:AudioSegment[]}。AudioSegment={id:32hex,shot_id:32hex,text:string,voice?:string,speed?:number}。初始每镜头一个段;编辑可分段,id不随改字改变。voice/speed省略继承全局。最多1000段,单段最多2000字。 +- captions={mode:'none'|'manual'|'script'|'ai_script',cues:Cue[]}。Cue={id:32hex,anchor:'absolute'|'shot'|'audio_segment',shot_id?:string,segment_id?:string,start_frame:int,end_frame:int,text:string,text_override:boolean,timing_override:boolean}。锚点互斥;局部时间相对选段后起点。旧字幕导入为absolute且两项override=true。none仅关闭显示,不删除已保存文案。AI只填充缺少的文案,不自动抹掉人工文字。 +- 编辑结构/资源所有权严格验证;越界、孤立锚点等存为issues,允许草稿保存与重新读取;执行film前严格验证。继承legacy profile、24fps、镜头/字幕数量及源长上限。 + +模型追加:WorkflowDraft.editor_manifest:nullable JSON;WorkflowRun.run_kind(default legacy),output_goal(default film),base_run_id:nullable string32,source_draft_version:nullable int,plan_snapshot:nullable JSON,result_manifest:nullable JSON,apply_state:nullable string16;WorkflowStep.recipe_json/resolved_input_json/result_json:nullable JSON。不更改Job表,实际所有auto Job必须绑定run_id/step_key。 + +## HTTP接口(所有新写操作仅当前会话+CSRF,事务内复核 require_session_user) + +统一 /api/editors/{draft_id},同时支持故事/普通工作流;旧接口不变。 + +- GET -> EditorDTO={draft_id,name,version,revision,manifest,issues,assets:AssetDTO[]};legacy无manifest时返回转换预览,不写库。 +- POST /save {expected_version,manifest} + Idempotency-Key -> EditorDTO。保存增加现有draft version/revision;统一重建spec+manifest全部draft引用,不能丢失绑定引用。legacy PATCH/run遇到已有editor_manifest时返回409 editor_required。 +- POST /from-run {expected_version,run_id} + key -> EditorDTO,恢复该run冻结源与实际成果,不合并当前草稿,校验同owner/同draft;使用current draft version CAS,不覆盖晚编辑。legacy run从spec_snapshot/实际outputs恢复;独立draft refs。 +- POST /plan {expected_version,output_goal:'media'|'film',targets:string[]=[],force:string[]=[],execution_mode:'interactive'|'batch',output_folder_id?:string|null} -> PlanDTO={plan_hash,output_goal,steps:[{key,kind,unit_id,status:'reuse'|'generate'|'pending_dependency'}],issues:[],source_version}。targets/force沿用binding键,另支持 script/captions。 +- POST /runs 同plan body + {expected_plan_hash} + key ->既有RunSnapshot;plan hash接纳时锁草稿重算;新seed仅首次接受后生成,重放不变。run_kind为story_auto/workflow_auto,source snapshot/spec_hash不回写。engine模块提供 plan_editor(session,draft,manifest,body,settings) 和 start_editor_run(session,draft,manifest,body,settings);API负责鉴权/幂等/提交事务/唤醒。 +- POST /apply {expected_version,run_id} + key ->EditorDTO;仅应用该Run已校验结果,CAS;成功增加version。自动应用同样以source_draft_version CAS,冲突只标apply_state=conflict,不令素材生成失败。 +- 新写操作 operation 固定 editor.save/editor.from_run/editor.run/editor.apply;submissions.resource_json只存draft_id/run_id等本命令资源回执,不嵌入来源Run导致旧记录归档误purge。 + +## 服务接口与实现分工 + +编辑后端模块 app/services/editors.py 提供: +get_editor(runtime,actor,draft_id)、save_editor(runtime,actor,draft_id,body,key)、from_run(runtime,actor,draft_id,body,key)、plan_editor_request/runtime、start_editor_request/runtime、apply_editor(runtime,actor,draft_id,body,key);内部 helpers validate_manifest(manifest)->dict、manifest_from_draft(draft)->dict、editor_issues(manifest)->list、collect_manifest_asset_ids(manifest)->set、sync_editor_refs(session,draft,manifest)、apply_run_result(session,run,settings)->bool。上述接口可在实现时细化,但必须通知引擎实现者。 + +自动引擎 app/services/orchestration/editor_engine.py 提供 plan_editor/start_editor_run(上文签名)以及 advance_editor_run(session,run,settings)。旧advance_run在加载run后第一时间分派auto分支。snapshot_run对auto先分支,返回run.output_goal/run_kind/apply_state、冻结源spec、editor_manifest与steps结果。typed output按step类型收集,不调用只返回video的legacy selected_output。复用asset+SHA,不复制旧selected_job_id。 + +## 编排、复用和完成 + +步骤recipe接纳时冻结;真实依赖完成后冻结resolved_input_json一次。step_key用frame_0001/video_0001/speech_0001等短键,稳定id放recipe。media编译仅目标祖先闭包,目标完成即成功,不建compose;film必须compose成功。原始源长与trim分开,复用真实足够长的源不改其生成参数。 + +首版每镜头1首帧/1视频,通过字节SHA/尺寸/fps/帧数校验系统选用;完整input_hash包含实际seed/参数/profile/ref SHA。人工或复用输入可无Job。force只对指定项换一版;失败retry沿原输入,blocked非终态,取消后新建Run。暂停/取消阻断未派发步骤,等待Execution清理,不盲重发unknown远端结果。 + +结果Run.result_manifest保存可恢复的manifest;开始spec_snapshot/plan_snapshot不变,最终合成输入存compose.resolved_input_json。自动应用只在草稿version与source_draft_version相同、owner仍启用、desired非cancel时原子完成。手动选用与系统选用分别追溯。旧Run/当前播放成片不被media或失败Run替换。 + +## 文案/音频provider合同(root负责) + +- 新 text.script.generate:input={shots:[{shot_id,name,visual_prompt,motion_prompt,duration_frames}],context?:object};parameters={}。输出JSON asset {segments:[{shot_id,text}]},每镜头一个短旁白,稳定ID由编排器确定。走qwen_http资源池,严格JSON/镜头ID/安全文本校验,不能借用math.solve。 +- 新 audio.assemble:input={segments:[{asset_id,offset_frame}],total_frames:int};parameters={fps:24}。检查owner由JobAssets完成,CPU重采样48k/按帧装配,非重叠,空隙补静音,总长严格total_frames*2000采样,输出WAV和JSON。段超界报invalid_timeline,不截有声区。 +- audio.speech增加独立超时及服务轻量健康检查;实际voice/model不能在接受后被新的全局默认偷偷替换。旧调用仍兼容。没有真实TTS能力时预检不可用,不默降音轨。 +- 字幕编译逻辑共享模块,script按已有文案,ai_script缺少文案时新增script依赖;有TTS按实际段时长,无TTS按镜头分配;人工文字/时间分别保护。镜头固定时长,超长报可定位冲突,不自动改写人工文案/拆镜。 + +## 任务与验证 + +1. 编辑后端/迁移/生命周期:先隔离测试恢复、CAS、越界草稿、refs、权限、legacy guards,后实现。 +2. 自动编排:先测试typed DAG、media成功、8镜头局部video复用、trim源复用、force幂等、重启取消,再实现。新任务按既有配额有界补队。 +3. provider音频/字幕:先真实小媒体/Mock HTTP边界测试再实现,绝不启动真实模型。匹配CPU资源池和取消清理。 +4. 前端:共享EditableProduction组件嵌入StoryStudio/Workflow页,GET导入后可保存/自动执行/局部强制/恢复版本/编辑配音字幕,dirty/会话epoch/outbox完整;legacy界面继续可用,03唯一时间线。新RunCard按goal区分素材与成片。 +5. root整合全量前端测试/类型/构建、适当后端回归/迁移、Mock浏览器QA、独立审查。真实服务迁移/重载前另行确认当前schema与活动执行;不会让新ORM直接连接未迁移生产库。 + +## 实施记录(续接依据) + +- 当前并行协作者:implement_editor_backend(模型/007/编辑API/refs/legacy story guards/architecture tests);implement_editor_engine(typed DAG/legacy workflow guards/snapshot);implement_editor_frontend(整个frontend接入与mock QA);root(provider/音频字幕公共编译/TTS超时与queue/整合)。 +- root已实现 services/editor_media.py 的 shot_ranges/audio_segment_ranges/materialize_cues/compile_captions;provider/editor_media.py 的 text.script.generate 和 audio.assemble;任务注册、Job嵌套音频asset解析、独立speech read330/total360超时、frozen model参数、speech_health;TTS服务queue_timeout30且排队超时不启动模型。 +- 已观察测试红基线并修复:root editor_media 9 passed(含真实FFmpeg小WAV、Mock HTTP,不调用真实模型);provider+runtime组合40 passed/20 subtests;TTS tests13 passed。后续改动需要相关复验。 +- 测试FFmpeg位于 E:/workspace/hybrid/cmvr-visual/.local/tools/ffmpeg/ffmpeg-9.0.2-essentials_build/bin,将该路径仅加到测试命令PATH,不修改用户全局PATH。 +- 变更裁定:force生成的实际seed存在binding.generation_parameters/步骤冻结输入;spec seed继续表示用户原始编辑意图,避免下一次仅compose把新变体误判失效。恢复时同时保留这两层,UI显示实际seed。 +- 输入新人工Binding允许省略SHA,服务端解析真实值;持久保存的binding必须有权威SHA,不能使用前端0占位。 +- editor.apply仅接受succeeded且源编辑版本仍匹配的结果,不借此覆写后来编辑;from-run才是显式整版恢复。 +- 运行中的真实API数据库仍为006;不要用新增ORM连接旧真实库、不要自动重载API或迁移。先完成隔离007及全套验证,真实环境启用作为有明确边界的部署步骤处理。 +- 尚待root:独立审查完整film/audio/caption流程、frontend全量测试/构建、backend全量或充分回归与007升级/降级隔离演练、fresh reviewer、mock浏览器结果检查、manual/API/release文档同步及临时文件清理。 + +2026-11-13收口记录: +- frontend首轮full suite49文件283 tests通过且build通过;之后独立review发现7个P2,由frontend实现者红绿修复中,完成后需再跑完整frontend。 +- backend首次4隔离进程全量:151+151+147+113=562通过、20 subtests,通过组之外有2个旧测试在后台prepare未提交时假设remote存在。已把测试改为显式等待准备任务;对应两个模块28项复验通过,没有改生产调度来迎合时序假设。 +- 独立review后端3项:auto短片/native产物被旧120帧/增强尺寸校验挡住、film force script被闭包裁掉、空TTS音色在不相干frame目标触发IndexError。engine实现者均已修,真实FFmpeg25帧auto导入/幂等重放和legacy仍拒绝短片共3例执行,相关30项green。 +- 两种源(story/workflow)×25/120帧完整script/TTS/frame/video/字幕/装配/compose与第二次只改字幕的复用链路已隔离通过。自动Run成果只含资产事实,reuse不再引用旧Job指针。 +- root修正nullable sample_count导致字幕编译int(None),新增回归9媒体测试green;_speech结果提供按48k归一化的sample_count,engine优先用整数样本计算ceil帧,避免5.02秒被round成120帧。 +- backend实现者追加base_run_id谱系收口;frontend实现者追加v1编辑升级、dirty重载/恢复/版本单调、RunCard刷新、模式按钮与语速继承、历史分页。收口后需要有针对性复验。 +- manual/API/README/.env样例与release清单已更新并render_manuals。真实服务仍不迁移/不重启;007降级明确拒绝破坏性downgrade,恢复联合检查点是回退策略。 +- agent与root均须清理本轮确认归属pytest tmp_path目录(pytest默认保留,不等同立即删除);全量launcher和root专项采用TemporaryDirectory --basetemp已自动清理。 + +所有工作留工作区,无暂存/提交;测试临时目录自动清理,保留可复用测试。 + +## 最终验证与交付边界 + +- 前端最终全量:53文件299 tests通过,vue-tsc与Vite build通过。独立复核原7项P2全部关闭;最新mock浏览器两页×无标记/兼容schema/已有编辑状态×1440/390验证通过,同ID重载、语速继承、历史第101条及RunCard回传实际交互通过。 +- 后端最终编辑/typed编排/媒体/007迁移/架构/真实视频导入/就绪能力专项60 passed;引擎包含锁定素材冲突、force范围、两种源×25/120帧及二次字幕成片复用。TTS服务13 passed。Ruff与diff空白检查通过。 +- 后端第二次全量4隔离组:136+141+163+136=576 passed,20 subtests;唯一失败为旧FIFO测试未等待首个后台prepare实际到达远端。补齐明确准备阶段后两个相关模块28 passed,生产调度未为测试改时序。独立审查发现的3项后端阻断均经真实媒体/纯函数回归关闭。 +- 锁定素材不兼容/失效时返回locked_dependency_changed,显式force仅授权该项更新;只在目标依赖闭包报告冲突,不阻挡无关素材目标。 +- 新API在capabilities显式声明editable_production.schema_version=1,旧API缺标记或未知版本时不显示新入口。007迁移前真实站点继续旧人工流程,避免前端先更新访问不存在端点。 +- base_run_id保留谱系并验证同owner/draft;新人工绑定时长/采样事实只接受服务端Asset数据,同资产旧可信绑定保留准确sample_count。 +- 确认清理本轮pytest-522/523/524,保留历史146/167/245;单Python逐项清理不跟随符号链接/reparse。最终全量/专项均TemporaryDirectory包装,mock测试服务5188已停止,一次性脚本与截图无残留。 +- 上述代码交付阶段未执行真实库迁移、业务API重启、真实模型调用或Git暂存/提交/推送;实际环境随后按下方授权记录启用,真实模型质量和产能验收仍单独进行。 + +## 实际环境启用记录(2026-11-13) + +- 用户明确授权“暂不提交git,帮我完成数据库迁移和重启服务”。本次仅迁移当前配置的实际业务库,重启本项目本机API和Vite;共享推理、Qwen和TTS服务未重启,未调用真实生成任务。 +- 迁移前为006,23张表共6749条记录;确认没有活动任务、运行、批次、候选或未清理执行后,启用维护准入并停止本项目API/前端。 +- 联合检查点保存在 `E:\workspace\hybrid\cmvr-visual\.local\backups\editable-007-20261113-110323-66f245`,仅本机Administrator和SYSTEM可访问。含SQL数据备份及可重放语句、约1.09GB工作空间、私有配置和迁移前源码,文件散列及逐表数据记录见 `migration-state.json`。备份属于恢复资料,须保留且不得提交Git。 +- 先将数据库备份完整恢复到临时隔离库,逐表比对原有字段定义、记录数和内容散列,再在隔离库升级007并复核。演练通过后,对实际业务库执行007;新增11个可空/有兼容默认值字段,旧记录和旧字段逐表比对一致。临时隔离库已删除。 +- 本项目API和前端已重新启动,数据库、协调器、任务准入和上游协议就绪检查均通过,维护标记已移除。访问地址仍为 `http://127.0.0.1:5173`,API为 `http://127.0.0.1:8000`。 +- 经正常登录会话,通过前端代理读取 `/api/capabilities`,确认 `editable_production.schema_version=1`;读取已有项目的新编辑接口及当前会话通过。验证会话随后退出,未改动项目或生成素材;再次比对23张表的原有6749条记录及原有字段内容一致(仅Alembic版本由006变为007)。未登录访问新编辑接口返回401。 +- Git索引散列与迁移前一致,没有暂存、提交或推送;一次性迁移脚本与其Python缓存已清理。保留业务运行日志、服务进程记录和联合备份。恢复必须使用联合检查点,007不提供破坏性降级。 diff --git a/docs/design/2026-11-13-form-layout-consistency.md b/docs/design/2026-11-13-form-layout-consistency.md new file mode 100644 index 0000000..5c9fe0a --- /dev/null +++ b/docs/design/2026-11-13-form-layout-consistency.md @@ -0,0 +1,33 @@ +# 表单尺寸与间距统一(Web优先) + +目标:常规表单字段对齐、有间距;需要完整宽度的正文/素材字段可整行;结合所在页面调整按钮和窄栏,避免机械统一尺寸降低内容密度。仅修改前端展示,不提交Git,不改变任务、权限或数据。 + +## 规范 + +- 常规单行输入、下拉与数值控件以220×36px为基准,容器窄时自然收缩;横间距12px、行间距16px、标签间距8px。 +- `forms.css` 最后导入,集中维护tokens、Element与原生控件基准;页面通过 `ui-form-grid` / `ui-form-row` / `ui-actions` 声明布局,通过 `ui-field--full` 声明正文、素材、弹窗单列等整行例外。 +- 字段网格采用flex wrap:常规字段定宽,整行字段可填满容器,避免固定CSS网格轨道把400px面板中的完整正文缩到220px。 +- 按钮统一常规高度,但宽度按文案和布局决定;只有明确的标准操作组/弹窗footer采用96px最小宽。图标与参考排序按钮为36px方形,文字链接和复选框保持自身尺寸。 +- 用户补充要求:镜头左栏新增/上移/下移/删除不能各占一整行。此处使用两列紧凑按钮组,按钮随列等宽;候选卡片、表格和其他窄栏同样按实际空间处理。 +- 用户再次补充:对齐方式按内容决定。普通无标签工具条保持自然居中,带标签的字段与按钮按控件底边对齐;故事目录区明确采用底部对齐,避免按钮比选择框高11px。 +- 自动模式的故事名称也应可编辑。使用已有editor.save原子保存可选name与manifest,并由name_edit能力门兼容旧API;保存中继续输入以及规划期间改名均不丢弃,不能通过旧PATCH绕过编辑真源。 +- 素材选择弹窗按视口高度限制外框,表体及列表承担滚动;目录、搜索和操作在桌面横排,不无谓拆成三个整行。 +- 保持已有容器滚动、鼠标悬停滚动条、自动/人工切换和03唯一时间线;不恢复已移除的三个独立页面。 + +## 范围与验收 + +- [x] 全局tokens与公共排版,以及响应式旧尺寸覆盖清理。 +- [x] 故事、自动编辑、人工候选与时间线字段/操作组。 +- [x] 创作、图生图/人物替换、声音、推演、理解参数表单。 +- [x] 素材、任务、账户、目录、登录与共享对话框。 +- [x] 桌面1440/1920各主要页面及对话框的实际控件尺寸、间距和截图复核;390只做溢出与可操作性抽查。 +- [x] 前端全量测试、类型检查、构建、独立审查和临时文件清理。 + +## 最终验证 + +- 前端52文件321项测试通过,vue-tsc、Vite生产构建及修改文件的格式检查通过;后台名称/编辑/模式/人工故事/架构45项回归通过,Ruff通过。 +- 最终浏览器64场景通过(1440×900和1920×1080各30,390×844抽查4),补充图生图/人物替换能力夹具后的4场景也通过;涵盖标准与整行字段、紧凑文字操作例外、按钮间距、镜头操作两列、目录底线、弹窗边界、卡片完整文字及模拟改名保存。没有真实API写入、未知API或浏览器错误。保留可复用 `frontend/tests/browser/form-layout.cjs`。 +- 实际目视复核故事、创作参数、用户弹窗和修正后的共享素材选择器。素材列表行设max-content避免受弹窗高度约束后卡片文字被压掉;分页与关闭按钮保留在弹窗范围。 +- 名称原子保存的失败/并发保护追加真实父子事件链:网络/409/422保存失败保留输入,保存中继续输入或回退旧名不被SSE/后台刷新覆盖;空闲跨标签同步安全更新子编辑器版本且保留镜头位置。独立复核两项P2与外部版本同步问题均关闭。 +- 确认无活动Job、未清理Execution或候选批次后,仅重载本项目API。通过真实登录的只读GET确认StoryDTO与EditorDTO的name_edit能力,未对真实故事执行改名;验证会话已退出。数据库仍007,无迁移,前端与API就绪。 +- Git索引保持迁移前原散列,未暂存或提交。一次性脚本、临时服务、截图均已清理;初次被拒的递归截图清理改为核对六个确切文件后的非递归逐文件清理完成。 diff --git a/docs/design/2026-11-13-production-mode-recovery.md b/docs/design/2026-11-13-production-mode-recovery.md new file mode 100644 index 0000000..602fa2c --- /dev/null +++ b/docs/design/2026-11-13-production-mode-recovery.md @@ -0,0 +1,35 @@ +# 自动成片与人工确认双向切换、合成缺尺寸修复 + +用户反馈启用可编辑自动成片后无法返回人工逐步确认,并报告成片任务processing_failed。本次修复同一故事内的安全双向切换和真实合成错误,继续保留本地改动,不提交Git。 + +## 已确认原因 + +- 前端将editor_manifest存在等同于启用自动模式,只提供进入按钮;服务端同时拒绝带manifest故事的旧人工写入。因此仅隐藏新版组件会展示陈旧spec且产生409。 +- 两个实际失败的compose任务在API日志中均出现media.py的KeyError:'width'。自动编排冻结clips时漏传源素材宽高,最终真实FFmpeg合成前读取尺寸失败,被通用错误处理转成processing_failed。 + +## 采用方案 + +- manifest增加editing_mode:auto/manual,缺省auto,无数据库迁移。保留同一故事、manifest、资产引用和所有历史运行,使用显式幂等模式切换API与完整StoryDTO。 +- 模式切换要求当前会话、CSRF、expected_version CAS,成功升版本;活动运行、候选批次或尚未清理执行阻止切换。旧运行不能跨越模式切换版本晚到应用。 +- auto模式继续保护旧人工写接口;manual模式的人工编辑与选片同步manifest,防止两份草稿分叉。自动素材可作为待确认候选,不能自动伪造人工批准;人工确认/清除反映至当前绑定。 +- 前端沿用01/02/03步骤,提供双向模式切换;未保存或提交在途时禁用切换并提示先保存。成功后采用服务端完整DTO,失败保留原模式和本地编辑。 +- 新编排冻结真实源素材尺寸等事实;旧失败步骤的冻结输入也须可安全重试:仅在SHA校验通过后,从同一视频实际解码事实补足旧快照缺失尺寸,不用默认尺寸掩盖错误,不跳过帧率、时长或已有尺寸校验。 + +## 验证与执行 + +- [x] 模式API、人工修改/选片同步、CAS/权限/活动运行与素材引用隔离测试先红后绿。 +- [x] 双向切换UI、脏数据/提交在途、失败保护及旧API兼容测试。 +- [x] 真实小视频通过完整自动合成路径复现并修复尺寸错误,旧冻结输入与SHA篡改回归。 +- [x] 相关前后端回归、前端完整测试与构建、独立复核和浏览器双向切换验证。 +- [x] 文档同步,确认无活动执行后重载本项目业务API并验证(不重启共享模型、不自动重试用户生成任务)。 + +## 交付验证 + +- 前端完整52文件304项通过,类型、格式与生产构建通过;双向切换Mock浏览器1440/390验证与原5场景滚动回归通过,写请求、未知API和页面错误均为0(切换交互测试使用独立的模拟POST)。 +- 后端完整回归592项及20项subtests通过;最终模式/架构/007迁移专项13项通过,包含新增软删候选清理边界。真实合成与引擎相关46项通过,Ruff和diff空白检查通过。 +- 新自动编排使用两种不同源尺寸和WAV真实输出48帧1080p;旧缺尺寸冻结Step重试可真实合成且不改原参数。视频/音轨SHA、已有尺寸、fps及源长冲突仍拒绝。 +- 使用截图对应失败任务的原始冻结请求、现存源素材,在隔离临时工作目录只执行CPU合成,输出120帧、24fps、1920×1080;未写数据库或调用模型,原请求参数未改,临时输出已清理。 +- 独立复核唯一P2是软删未派发候选误判为活动,已先红后绿修复:仅活动候选统计排除软删,关联Job/Execution检查继续覆盖软删对象,全部P1/P2关闭。 +- 确认没有非终态Job、未清理Execution、活动候选或批次后,按进程身份仅重载本项目API;保留原blocked运行,不自动恢复或重试。数据库仍为007,无迁移,前端保持运行,维护标记已解除,数据库/协调器/任务准入/上游协议就绪。 +- 登录后的只读GET确认真实故事与编辑DTO返回auto模式及mode_switch能力;未认证mode请求返回401;验证会话已退出。原blocked运行及failed合成任务保持原状态,切换人工前需先结束该运行。 +- 手册和API合同已同步,五套公开帮助已重新渲染。Git索引保持原散列,无暂存或提交;保留业务运行日志,测试目录与一次性输出自动清理。 diff --git a/docs/design/2026-11-13-story-scroll-navigation.md b/docs/design/2026-11-13-story-scroll-navigation.md new file mode 100644 index 0000000..46bd059 --- /dev/null +++ b/docs/design/2026-11-13-story-scroll-navigation.md @@ -0,0 +1,31 @@ +# 故事分镜滚动与页面精简 + +用户要求自动成片02分镜完整可达,溢出时容器内滚动;删除独立工作流、批量和成片页面。沿用当前工作区,不提交Git,不修改数据库或模型服务。 + +## 设计与边界 + +- 分镜页面外层保留固定工作区,故事标题与步骤导航占用自身高度;新版编辑面板使用剩余高度、允许内部滚动。旧人工分镜三列已有滚动规则,继续保留。 +- 当前故障是 `.story-studio.is-shots` 设置flex布局与overflow:hidden,但其新直系子元素 `.editable-production` 没有flex:1/min-height:0/overflow:auto,导致内容被裁切。移动端原先把分镜外层切回block滚动,须对新版编辑态保持一致的高度链。 +- 滚动轨道预留宽度,滚动条在悬停或键盘操作时显示;触屏可直接滑动。新编辑面板内的镜头表单取消额外视口高度上限,避免同一段内容产生不必要的嵌套滚动。 +- 移除三个独立页面组件、导航和页面专属入口;旧URL按运行/任务线索转至任务中心,否则转至故事。故事内03成片及唯一时间线保留。 +- 任务中心承接历史批次摘要与控制,使旧关联链接仍可查看及处理父记录。保留故事编排依赖的API、stores、任务类型、配额、执行模式、数据库记录与兼容键。 +- 当前帮助说明同步到存活入口,旧技术记录明确为历史资料,不清理用户资源。 + +## 执行与验证 + +- [x] 浏览器先复现旧布局无法滚动的失败,修正高度链和悬停滚动条。 +- [x] 路由行为先验证删除入口与旧地址重定向,再移除页面并处理关联记录链接。 +- [x] 跨功能测试继续覆盖文件夹冻结、字幕顺序和历史批次访问,清理仅属于已删页面的UI测试。 +- [x] 桌面1920×957、1366×768、移动390×844验证底部可达、文档不滚动、03时间线仍可用。 +- [x] 前端测试、类型检查与构建通过,当前帮助重新渲染,清理一次性验收文件。 + +## 复核记录 + +- 浏览器红基线:1920×957时编辑面板底部1119.97px,overflow:visible,滚轮后scrollTop仍0,视频和历史区域被裁切。 +- 第一轮修复后5场景通过:1920×957、1366×768、1024×768、390×844鼠标及触摸;视频、末段旁白、末镜头与展开历史可达,End滚动到底、03唯一时间线、侧栏不含三个旧页面链接。 +- 追加移动布局回归先观察到StoryShotEditor被侧栏aside规则误设display:flex,随后将选择器收窄至直系导航aside,5场景均恢复display:grid。 +- 保留可复用浏览器测试 `frontend/tests/browser/story-editor-scroll.cjs`,根目录运行 `node frontend/tests/browser/story-editor-scroll.cjs`。全部API由测试拦截,写请求失败关闭;测试截图只存自动清理的系统临时目录。 +- 独立复核要求保留历史批次删除入口,并显式区分run/job/candidate成员,避免候选编号误传任务详情;在历史摘要内复用原有删除权限与版本校验。 +- 两项复核问题均已修复并复核关闭:批次删除按钮在终态控制外复用现有组件,候选有来源时回原故事、缺来源时回故事列表并说明,未知成员不生成错误任务链接。真实模板新增两项测试先红后绿,摘要7项独立复核通过。 +- 最终前端全量52文件298项测试通过,vue-tsc与Vite生产构建通过;五套帮助已渲染并进入最终构建。修改的源码格式及diff空白检查通过。 +- root最终再次运行浏览器回归5场景0失败,写请求、未知API、浏览器错误均为0;测试临时目录无残留。业务API与前端仍就绪,未迁移数据库、未调用模型、未暂存或提交Git。 diff --git a/docs/design/2026-11-13-task-inline-results.md b/docs/design/2026-11-13-task-inline-results.md new file mode 100644 index 0000000..bc299e7 --- /dev/null +++ b/docs/design/2026-11-13-task-inline-results.md @@ -0,0 +1,16 @@ +# 任务项内预览与删除提示横排 + +用户要求将运行底部汇总成果预览移入各自阶段任务项,每项只显示一个预览入口;删除记录按钮与说明左右排列。仅调整前端,不改任务执行、删除规则或现有数据,不提交Git。 + +- 阶段按result.asset_id或当前selected_job_id的成果映射,使用素材ID区分同名文件;复用阶段没有Job时仍能预览。 +- 单成果直接使用现有AssetPreview,多成果保留单一按钮通过菜单选择;未完成/无成果不显示错误或旧尝试成果。移除底部逐资产按钮列表。 +- 删除组件保持原权限、确认与版本检查,展示改为横排,说明在右侧可换行而不压缩按钮。 +- 验证覆盖重复文件名、复用、多成果、显式重试及更新后的Job;浏览器以17阶段任务的桌面布局为主,抽查窄屏不横向溢出。 + +验证完成: + +- 全量53文件326项前端测试通过,类型检查、格式与生产构建通过;最后菜单文案和长标题样式调整后,4个RunCard测试文件17项及类型/构建再次通过。 +- 浏览器1440×900、1920×1080、390×844均通过。17阶段中16个成功阶段各一个入口、等待合成阶段无入口;34次逐项预览的src与下载ID全部正确,覆盖无Job复用、反序成果列表和同名多成果选择。 +- 删除说明在按钮右侧,水平间距12px、垂直中心一致;窄屏说明在右侧内部换行,页面不横向溢出。 +- 兼容超长step_key压力场景中标题在卡片内换行,避免串到邻卡;默认测试使用真实短键frame_0001/video_0001。保留可复用 `frontend/tests/browser/task-results.cjs`。 +- 独立复核未发现P1/P2;本轮不改后端、真实任务、素材或数据库。API与前端仍就绪,临时截图已清理,Git索引不变,无暂存或提交。 diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md deleted file mode 100644 index 4b6c96f..0000000 --- a/docs/implementation-plan.md +++ /dev/null @@ -1,25 +0,0 @@ -# CMVR Visual Implementation Plan - -**Goal:** Deliver the requested Vue3/Element Plus/Pinia and FastAPI/MySQL creative studio connected to the server's real inference queue. - -**Architecture:** Same-origin HTTP plus durable authenticated SSE; business data in MySQL; original upstream worker remains the only GPU executor. Production web CPU containers share the isolated workspace and a private Docker network with the inference container. Local test databases require explicit mode. - -**Spec:** `docs/design.md`, shared interfaces `docs/api-contract.md`. - -## Constraints and review focus - -- Preserve existing GPU priority, serial execution, services and confinement. No database-wide deletion, driver changes, global Docker/systemd restart or public publication. -- Credentials absent from source and browser; session/owner/CSRF checks protect every mutation/content stream. -- Persist immutable upstream request/key before dispatch. No duplicate inference after timeout/restart; no job replay after known upstream ID. -- Preserve running→queued preemption, cancellation races, idempotent output import and event ordering. -- Only genuine capabilities and samples; five-second video limit, no defect mask claim, no synthetic GPU percentages. -- Detached SSE must not hold transactions or cancel inference. Reconnection uses event cursor and HTTP reconciliation. - -## Implementation - -- [ ] Backend core: write failing auth/ownership/jobs/event recovery tests; implement MySQL/explicit SQLite config, schema, auth, asset storage, job coordinator and SSE. Prove negative access and upstream lifecycle transitions. -- [ ] Providers: test actual parameter/path validation, HTTP boundary, safe subprocess and output handling; implement existing GPU API adapter, Qwen math/vision, CPU FFmpeg analysis/composition, bounded file probing and optional speech provider. -- [ ] Frontend: implement shared DTOs and HTTP client, cookie/CSRF flow, Pinia versioned job/SSE store, creation forms, real asset previews/library, task center and composition. Test requeue/version handling; build/typecheck. -- [ ] Integration: install isolated dependencies, verify OpenAPI/schema contract, run tests and MySQL connectivity if credentials arrive, package private-network deployment and environment examples. Do not auto-switch DB on failure. -- [ ] Visual and live verification: run browser, inspect desktop/mobile layouts and actual actions; perform real image/ASR or CPU generation against the model host without interrupting existing users. Record any capability or credential blocker honestly. -- [ ] Deliver source, setup guide, communication recommendation, verified URLs and acceptance report. diff --git a/docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md b/docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md deleted file mode 100644 index a687fb0..0000000 --- a/docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md +++ /dev/null @@ -1,184 +0,0 @@ -# CMVR Visual V2 Implementation Plan - -> **执行修订:**用户已授权开发。08:00只关闭新批量准入,已运行镜头/处理阶段自然完成;不因时间或断开HTTP停止共享Qwen。所有旧硬截止/abort门槛条目由本修订覆盖。 - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Checkboxes track implementation, not this planning review. - -**Goal:** 在现有正式库与模型服务上交付可靠提交、三分镜15秒工作流及交互/夜间批量调度。 - -**Architecture:** 保留单FastAPI业务协调器、MySQL任务/事件与既有独立GPUworker。先升级受版本约束的上游调度/停止协议,再开放工作流;资源池new_gpu/cpu_media/qwen_http分别最多1个执行。MySQL只由业务进程产生有序领域事件,不直接扩成多API实例。 - -**Tech Stack:** Vue3、Element Plus、Pinia、TypeScript;Python/FastAPI、SQLAlchemy async、MySQL8、Alembic;既有vLLM-Omni/Diffusers/Whisper、共享Qwen HTTP、CPU FFmpeg/Kokoro。 - -**Spec:** [实施方案V2](../../实施方案V2_20261110.md)。接口、状态与配额冲突时以Spec为准;旧R1–R12继续纳入下述任务。 - -## Global Constraints - -- 主工程根目录 `E:\workspace\hybrid\cmvr-visual`,下文无前缀的路径均相对此根。 -- `GPU/`为规划时前缀;实现源码已纳入本仓库 `inference/`,仍部署到既有 `/workspace/projects/llm-services`,不创建另一套GPU worker。原源码保留作基线。 -- 正式MySQL及admin已存在,不重复初始化、不覆盖密码、不迁移旧验收样例。 -- 三段各120个成片帧,最终360帧、24fps;保持多镜头定义。 -- Asia/Shanghai `[21:00,次日08:00)`;外部用户优先、新GPU任务全局1个。 -- 现有Qwen按新请求准入排队,当前调用自然完成;不发送abort、不杀共享服务PID。 -- 不读写其他项目数据库,不全局重启Docker/驱动,不修改宿主时钟;秘密不进入源码、命令行参数或测试输出。 -- 每任务先写有意义的失败测试,再最小实现、回归、独立审查并提交;只有对应验收通过才勾选。生产操作只在任务12执行。 - -## Review Focus - -1. 响应丢失与进程/DB故障不产生未经明确意图的新计算——任务3/4。 -2. 08点与claim、崩溃、时钟回拨竞争,不越界派发且不假称释放——任务5/6。 -3. 旧Run/旧Execution晚到,不能覆盖新成片或停止新进程——任务4/8。 -4. 部分镜头失败、短源、跨镜头字幕和超长旁白仍能得到确定结果——任务7/8。 -5. 已有正式数据升级、恢复及跨账号访问保持一致——任务1/9/10/12。 - ---- - -## Task 1:基线核验、迁移机制与恢复点 - -**Files:** 新建 `backend/alembic.ini`、`backend/alembic/env.py`、`backend/alembic/versions/001_legacy_baseline.py`、`scripts/schema_preflight.py`、`scripts/backup_checkpoint.py`、`backend/tests/test_schema_migrations.py`;修改 `backend/app/database.py`、`backend/requirements.txt`。 - -**Interfaces:** `schema_preflight(connection) -> SchemaDiff`;`check_schema_revision(connection, supported: set[str]) -> None`;备份清单包含checkpoint_id、应用/上游/schema版本、文件哈希、上游job IDs、执行状态和时间。 - -- [ ] 在隔离MySQL8.0.36复制当前六表基线,测试 `test_baseline_matches_existing_schema` 与 `test_drift_refuses_stamp`:准确基线可stamp001,少唯一约束或DATETIME精度不对必须拒绝,用户和任务行不变。 -- [ ] 实现显式迁移入口和只检查的生产启动;空库upgrade,已有库先核验再stamp;include_object只管理本应用表。 -- [ ] 写 `test_checkpoint_rejects_live_execution`、`test_restore_preserves_upstream_identity`:无停止ACK不能宣称静态恢复点;恢复不得把旧ID误接到独立前进的队列。 -- [ ] 隔离库实跑upgrade、失败中断修复、镜像兼容回退与备份恢复;输出schema diff、行数与校验结果。未演练前不做正式DDL。 - -## Task 2:冻结V2 DTO、表和媒体规范 - -**Files:** 新建 `backend/app/contracts_v2.py`、`backend/alembic/versions/002_workflow_execution.py`、`backend/tests/test_contracts_v2.py`;修改 `backend/app/models.py`、`frontend/src/types.ts`。以现有六表为起点新增Spec第3节表;素材标签使用 `visual_asset_tags` 关联表。 - -**Interfaces:** `WorkflowSpec`、`DraftDTO`、`RunDTO`、`StepDTO`、`ExecutionDTO`、`BatchDTO`、`BatchItemDTO`、`SchedulingEnvelope`;新输入 `extra=forbid`,输出完整标识/模式/版本/等待原因。关键spec固定为: - -```json -{ - "schema_version": 1, - "shots": [ - {"key":"shot_1","prompt":"...","image_asset_id":null,"parameters":{"seed":42}}, - {"key":"shot_2","prompt":"...","image_asset_id":null,"parameters":{"seed":43}}, - {"key":"shot_3","prompt":"...","image_asset_id":null,"parameters":{"seed":44}} - ], - "profile":"landscape_1080_v1", - "render":{"fps":24,"total_frames":360,"fit":"contain","audio":null,"subtitles":[],"template_version":"plain-v1"} -} -``` - -profile由服务器编译成冻结的模型默认参数/版本,横版1280×704→1920×1056内容→1920×1080画布;竖版对应704×1280→1056×1920→1080×1920。字幕字段start_frame/end_frame/text;audio字段以Spec为准。客户端不提交路径、父Job关系或宿主信息。 - -- [ ] `test_rejects_unknown_scheduling_and_timeline_fields`、`test_requires_exact_three_shot_keys`、`test_preset_compilation_is_frozen`:多/少镜头、重复key、非法帧区间和未知参数失败;已接受快照不随后续默认值变化。 -- [ ] 实现002的新增/回填,保留旧hash算法及旧attempt计数;所有旧Job回填interactive,历史Execution明细保持“未知/未提供”。 -- [ ] 在MySQL与SQLite测试执行同一DTO/唯一约束规则;生产schema指纹与新版本检查通过。 - -## Task 3:端到端提交幂等和额度原子性 - -**Files:** 新建 `backend/app/submissions.py`、`backend/tests/test_submissions.py`、`frontend/src/stores/submissions.ts`、`frontend/src/stores/submissions.test.ts`;修改 `backend/app/jobs.py`、`frontend/src/api.ts`、提交入口。 - -**Interfaces:** `accept_submission(session, owner_id, operation, key, payload_schema, body) -> Submission`;`GET /api/submissions/{key}?operation=...`;前端 `submitOrRecover(operation, immutableBody) -> resource`,使用按用户隔离的本地持久存储。 - -- [ ] 测试服务器commit后丢响应,客户端刷新/重试仍返回同批Job、同资源引用;同key改body返回409,复用不重复扣配额;GET404后原POST迟到也不重复。 -- [ ] 实现版本化canonical body哈希及旧v1幂等记录回填;原Job键继续能恢复。显式retry/Run创建也要求幂等键,不能仅保护第一层POST/jobs。 -- [ ] 前端持久化发送前意图,提供“确认提交状态”与“明确新建”两种行为;离线编辑不触发自动生成,退出用户清除敏感缓存。 -- [ ] 后端对应pytest、前端submissions.test通过;注入延迟/重复HTTP的集成断言只有一组实际子任务。 - -## Task 4:Execution、结果manifest与安全取消 - -**Files:** 新建 `backend/app/executions.py`、`backend/app/artifacts.py`、`backend/tests/test_execution_recovery.py`、`backend/tests/test_artifact_reconcile.py`;修改 `coordinator.py`、`assets.py`、`media.py`、`providers.py`、`events.py`。 - -**Interfaces:** `begin_execution(session, job_id) -> Execution`;`accept_manifest(session, execution_id, fence_token, manifest) -> bool`;`request_control(session, job_id, desired_state, expected_execution_id) -> ControlResult`;`reconcile_artifacts(...) -> ReconcileReport`。 - -- [ ] 先固定R2/R3故障:provider执行后写DB失败、manifest写前后崩溃、commit已成功但客户端收到异常,断言不自动重新provider调用、不误删已提交文件。 -- [ ] 明确Job可领取状态集合,paused/needs_attention不执行、collecting只导入;当前Execution与fence不匹配的回调拒绝;CPU可信manifest仅恢复归档。 -- [ ] 固定R5:重复cancel只发一次停止并等待清理;当前media/TTS shield规则保留。控制先提交但已经领取的任务允许在途停止,不再领取后续步骤。 -- [ ] 所有状态变化与领域事件同事务;SSE drain/20秒Uvicorn graceful与45秒Docker宽限配套测试。保持长连接重启时必须在强杀前完成清理。 - -## Task 5:GPU上游V2协议与队列资格 - -**Files:** 新建 `GPU/llm_services/scheduling.py`、`GPU/tests/test_scheduling_v2.py`;修改 `GPU/llm_services/api.py`、`store.py`、`worker.py`、网站`providers.py`与协议契约。 - -**Interfaces:** `GET /capabilities`;v2 `Submission.scheduling: SchedulingEnvelope`;`PUT /jobs/{id}/control`请求/ACK含command_id、control_version、expected_execution_id;`claim_eligible(now_utc, policy) -> Lease|None`;`evaluate_window(now_utc, mode, closed_windows) -> Eligibility`。 - -- [ ] 旧上游不支持v2时batch明确不可用;同key更改mode409;旧key仍返回原ID;所有未知新字段不能静默忽略。 -- [x] 测试窗口 `[21:00,08:00)`、07:59领取08点spawn被挡、已spawn跨08自然完成、关闭窗口回拨不重新开放;不改宿主时钟,注入Clock。按用户要求不另设提前30秒硬截止。 -- [ ] 原子claim跳过不合格队首,交互/批次/用户按Spec公平规则;子任务与重试mode继承,HTTP伪造父ID或通过retry降级拒绝。 -- [ ] 以desired_state+hold而非外部直接改running实现控制;cancel高于pause、终态不可逆,旧command不影响新Execution。原124项基线范围及新增协议测试回归。 - -## Task 6:阶段资源、自然完成和共享Qwen隔离 - -**Files:** `backend/app/resource_policy.py`、`coordinator.py`、`providers.py`、`media.py`及相应资源/断连回归;既有 `inference/admin/gpu_guard.py`只保留外部优先的原有安全职责。 - -**Interfaces:** `resource_plan(task_type,input_kind)`;在NEW阶段准入检查window/hold,已开始的provider调用独立于HTTP请求继续执行。 - -- [ ] 固定时钟07:59:59开始、08:00后完成的任务成功归档;第二镜头/下一阶段等待21点,interactive可运行。 -- [ ] 视频ASR抽音→GPU、视频理解抽帧→Qwen分阶段持久结果,阶段间释放资源并重新准入;资源池不互相持有等待。 -- [ ] 网页/SSE断开不停止后台Job,不对共享Qwen发送abort或操作PID。当前请求超时/结果不明进入needs_attention而不是偷偷再调用。 -- [ ] 外部GPU抢占仍停止自己的GPU任务并重排,08点后的重排batch不立即重启;新旧控制命令幂等并保护执行代次。 - -## Task 7:15秒媒体规范化 - -**Files:** 新建 `backend/app/timeline.py`、`backend/tests/test_timeline_v2.py`;修改 `media.py`、`providers.py`、`GPU/llm_services/adapters.py`的工作流增强配置与相应测试。 - -**Interfaces:** `compile_timeline(spec, owned_assets) -> TimelinePlan`;`compose_workflow(plan, work_dir, control) -> CpuResult`;`inspect_video_track(path) -> {frames,fps,width,height,duration}`。保留现有普通video.compose兼容接口,V2走独立白名单。 - -- [ ] 真实FFmpeg夹具:三个121帧24fps源各取120帧;结果视频流精确360帧、24fps、15秒,容器尾差≤0.10秒,横/竖版分别验证。 -- [ ] 119帧短源拒绝,不能借音轨时长或冻结补帧通过;超长音轨默认拒绝,显式3–18秒裁切通过;10秒音轨offset120通过/121拒绝,15秒音轨任何正偏移拒绝;短音轨补静音。 -- [ ] 字幕跨120/240帧边界、end=360通过,负数/越界/非法控制语法拒绝;片头在360帧内叠加。文件解码/规格为硬门槛,疑似黑帧或静帧作为可人工复核的质量提示。 -- [ ] 明确增强不先烧黑边,contain/cover各测试真实内容与输出画幅。全过程固定FFmpeg argv,不接收滤镜脚本、外部URL或字体路径。 - -## Task 8:Draft/Run/Step服务和父子SSE - -**Files:** 新建 `backend/app/workflows.py`、`backend/app/workflow_engine.py`、`backend/app/batches.py`、`backend/tests/test_workflows_v2.py`、`backend/tests/test_workflow_races.py`;修改 `main.py`、`events.py`、`dto.py`和`jobs.py`。 - -**Interfaces:** Spec第5.3节接口;`create_run(session, owner_id, draft_id, expected_version, revision, mode) -> RunSnapshot`;`advance_run(session, run_id) -> None`;`snapshot_run(session, owner_id, run_id) -> {run,steps,jobs,cursor}`;所有service沿用调用方事务,不嵌套申请当前进程的DB单元锁。 - -- [ ] 两标签页Draft冲突409,旧revision不能提交;运行期间草稿变更不变更Run快照。 -- [ ] 第二镜头失败仅它新增Job,抢占两次仍为同Job新Execution;compose失败不再生成三镜头;模式和政策继承。needs_attention未确认无残留执行不能重试,safe_to_retry后才允许显式新尝试。 -- [ ] 修改成功镜头产生新Run并复用其它已验证素材;旧合成晚到不改current_run_id/output;输入hash和引用检查覆盖裁切、音轨、字幕、模板变更。 -- [ ] 父取消与claim/完成/导入竞争;已领取者停止ACK后终态,未领取者不启动;pause/resume只处理手工hold,不解除夜间或维护限制。新增workflow.updated/draft.updated完整version快照,乱序与重连不倒退。 -- [ ] Batch有独立DTO、成员表、查询/control及batch.updated;Run和独立Job均能归属,刷新恢复混合成员且每批最多1个活动成员;安全清理完成后的失败项不堵其它项,全部终态混合结果为completed_with_errors,批次取消不删除成功产物。 - -## Task 9:账号、机器调用与额度/回收 - -**Files:** 新建 `backend/app/tokens.py`、`quotas.py`、`retention.py`、`maintenance.py`、`backend/tests/test_tokens_quotas.py`、`backend/tests/test_retention.py`;修改 `auth.py`、`assets.py`、`models.py`和对应增量迁移。 - -**Interfaces:** 本人改密、admin用户列表/停用/撤销会话、owner机器Token创建/撤销;`reserve_budget(session, owner_id, operation) -> Reservation`;`collect_garbage(dry_run=True) -> GCReport`;维护状态阻止新写入与claim而保留查询。 - -- [ ] 默认admin在私有验收仍能用初始密码登录且不被重启重置;公网preflight要求先在私有入口改密,未完成不能先暴露登录入口。停用/改密撤销会话,停用给任务加admin_suspend并停止,重新启用不自动重跑;不能停用最后一个有效管理员。Token仅哈希、到期/撤销生效并关闭其事件流,scope不授管理权限。 -- [ ] 配额事务内预留、复用幂等键不重复扣;batch mode权限、跨owner资产、每池并发及入口限流覆盖直接HTTP绕过测试。 -- [ ] 上传在multipart解析前限制流量并预留空间;输出/临时空间纳入预算,达到水位停止接新任务。实际超预留需原子追加预算,失败仅保留可恢复结果,不重生成。 -- [ ] SQL分页和标签关联索引;删除与引用互斥,非终态/commit不明文件不GC;事件过期cursor返回reset。先dry-run和隔离数据测试,禁止首次上线直接删除历史文件。 - -## Task 10:Vue工作流与持久草稿 - -**Files:** 新建 `frontend/src/stores/workflows.ts`、`draftPersistence.ts`及对应测试、`frontend/src/views/WorkflowView.vue`、`BatchView.vue`、`AccountView.vue`;修改router、api、types、Workbench/Compose/Tools/Tasks/Assets与capabilities。 - -**Interfaces:** 消费任务2/8/9 DTO;Pinia提供 `saveDraft(expectedVersion)`、`startRun(revision,mode)`、`recoverSubmission(key)`、`applyRunSnapshot(version)`,步骤Job事件必须匹配当前selected_job。 - -- [ ] 测试保存中/已保存/提交待确认/已接受区别,跨页配音回填和刷新不丢草稿;版本冲突保留本地内容,离线不自动提交。 -- [ ] 父任务按镜头完成数和合成阶段显示,展开Job/Execution记录;旧Run迟到不盖新版,window/manual/resource/cleanup理由可读。 -- [ ] batch在协议/Qwen能力不足时禁用对应项;前端受限参数与后端错误field一致,标签确认合并,历史分页和收藏/来源筛选。 -- [ ] 账号/改密/Token入口使用既有Element Plus规范;桌面1440×1000和手机390×844测试表单、抽屉、播放与seek;不新增外部CDN依赖。 - -## Task 11:完整故障和兼容性回归 - -**Files:** 新建 `backend/tests/test_acceptance_v2.py`、`GPU/tests/test_upgrade_compatibility.py`、`qa/browser-v2.cjs`;更新原服务/网站契约、README和验收矩阵。 - -- [ ] 在隔离MySQL8.0.36而非仅SQLite跑任务1–10;对比现有52后端基线、TTS/前端测试及原GPU服务测试,无跳过地报告媒体和迁移覆盖。 -- [ ] 使用可控Clock、假上游和自有Linux子进程遍历Spec控制竞争表;不得改宿主时间、伪造生产guard状态或让他人作业承担压力测试。 -- [ ] 兼容矩阵覆盖新网站/旧上游拒绝batch、旧幂等恢复、老前端字段/未知字段处理、旧镜像schema支持范围;覆盖保留期reset。 -- [ ] 浏览器断网/刷新、多标签、两用户、父子SSE乱序和媒体边界;保留无密码、Cookie、Token的报告。 - -## Task 12:受控发布与真实验收 - -**Files:** 修改 `compose.yaml`、`backend/Dockerfile`、`deploy/nginx.conf`;新建 `deploy/release-checklist.md`,输出版本、迁移、恢复和真实模型记录。 - -- [ ] 先确认维护开关、恢复点、独立监管健康;冻结镜像/依赖/模型revision。按Spec顺序做兼容上游、迁移、API、前端,未通过gate保持维护。 -- [ ] 缩窄API挂载并验证原子替换状态文件仍更新;Uvicorn20秒退出/容器45秒;重建执行容器后监管allowlist匹配真实ID/UID/镜像再开admission,新API IP的Nginx解析可恢复;不全局重启其它服务。 -- [ ] 先真实小规格三镜头验证控制链,再选空闲资源执行一次冻结默认规格360帧交付;记录排队/冷加载/推理/增强/归档而非承诺原GPU·秒。夜间与抢占测试使用自己的受控作业,单独记录观察到的停止ACK延迟。 -- [ ] 配置用户提供的HTTPS域名或受信隧道后验证Secure Cookie、SSE、Range、机器Token和限流;用户决定的独立DB账号按后续授权创建,不能擅改共享root密码。 -- [ ] 完成至少一次库+文件+上游checkpoint恢复演练。发布只在各门槛实际通过后记为完成,代码合并/测试数量不能替代上线验收。 - -## Commands and completion records - -开发环境:在`backend/`执行 `.venv/Scripts/python.exe -m pytest tests -q`;在`frontend/`执行 `pnpm test`、`pnpm build`。Linux媒体/迁移/监管与GPU仓库测试在各自隔离环境执行。只运行本任务对应检查,新的失败或依赖变更才扩大回归。 - -原清单保留为设计验收目标,不凭代码存在全部勾选。V2已开发并部署到私有入口,逐项实施证据、真实模型结果及保留边界见 [V2开发与验收记录](../../V2开发与验收记录_20261110.md)。文件命名与规划原稿有少量调整,以实际仓库及该记录为准。 diff --git a/docs/superpowers/plans/2026-11-11-configurable-window-multishot.md b/docs/superpowers/plans/2026-11-11-configurable-window-multishot.md deleted file mode 100644 index 74a9ba3..0000000 --- a/docs/superpowers/plans/2026-11-11-configurable-window-multishot.md +++ /dev/null @@ -1,63 +0,0 @@ -# 可配置时段与多镜头长视频实施计划 - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. Each owner writes a failing regression, implements the change, verifies it, and freezes for root review. - -**Goal:** 开发环境全天测试批量任务,生产环境配置恢复夜间准入;可变镜头和选用帧数替代固定15秒,并交付中文手册与鲲鹏示例。 - -**Architecture:** API和既有GPU worker读取同一权威文件。工作流schema2用有序镜头,成片长度为选用帧数之和;旧schema1保持兼容。沿用Vue3/Pinia/Element Plus、FastAPI/MySQL、HTTP+SSE和现有GPU监管。 - -**Spec:** 用户2026-11-11三项修改及下列接口。用户授权直接处理;沿用现有项目与分支。 - -## 全局约束 - -- 配置:`/workspace/projects/llm-services/config/runtime-policy.json`,schema_version=1,batch_window_enabled严格布尔,workflow_max_shots严格整数1..1000(默认120)。缺失按生产限制;坏配置关闭新batch准入。 -- 开发部署batch_window_enabled=false。开启仍为北京时间21:00–08:00,当前镜头/阶段完成,后续排队;HTTP断开不影响共享Qwen。 -- 文件热读取;关闭限制绕过窗口和时钟水位门禁,但不删除水位。手动暂停、维护、用户停用和让卡始终有效。 -- schema2镜头1..1000,连续有序shot_N;duration_frames为24..120,默认120,24fps。模型仍生成121帧,合成裁剪,不把文本上下文当成视频时长。 -- 动态总帧数与字幕音轨范围;资源上限默认120镜头,可配置提高。已接受运行不受后续降低上限影响。 -- 保留schema1、历史Run、幂等键、fence及增强片选择;无数据库迁移,不操作共享Qwen进程。 - -## 审查重点 - -1. API全天而GPU仍等夜间的配置不一致。 -2. shot_10字符串排序到shot_2前面。 -3. 音轨字幕残留360帧边界或默默截断长旁白。 -4. 热开启终止当前执行、清水位,或客户端能关闭限制。 -5. 手册夸大自动拆镜、字幕对齐、身份一致和单次长生成。 - -## 任务1:共享配置 - -Owner:schedule_config_audit。Files:backend/runtime_policy、config/resource_policy/coordinator/main;inference/store/scheduling/api/worker及新回归。 - -- [x] RED:正午关闭可准入CPU/Qwen/GPU;热切换、坏配置、旧水位和手动限制。 -- [x] 严格只读解析,全路径准入和状态输出,workflow_limits输出上限。 -- [x] GREEN:针对性回归,无客户端旁路字段。 - -## 任务2:多镜头与媒体 - -Owner:long_video_backend_audit。Files:timeline/workflows/workflow_engine/providers/media/jobs及新回归。 - -- [x] RED:12镜头数值顺序、动态步骤、长音轨字幕、旧草稿、上限降低后的旧Run。 -- [x] schema2、动态依赖和合成、帧裁剪,生成语义参与复用哈希。 -- [x] GREEN:原V2回归,真实Linux FFmpeg4镜头[24,120,120,120]→384帧/16秒。 - -## 任务3:前端与说明 - -Owner:long_video_ui_manual_audit(frontend/src);root(public示例/文档)。 - -- [x] RED:增删/排序/时长、旧草稿、20镜头、动态边界、策略文案。 -- [x] 编辑器、JSON导入导出、鲲鹏示例;TTS对齐2000字上限。 -- [x] GREEN:完整前端测试/typecheck/build,桌面/手机实际编辑与保存。 -- [x] 手册覆盖现有入口/队列/账号/恢复/配置;20镜头100秒鲲鹏示例与详细步骤。 - -## 任务4:发布 - -Root负责,只在自管执行结束后更新已有服务,保留旧镜像/配置;不重启共享Qwen、工作区或监管容器。 - -- [x] 后端/GPU/前端完整测试与审查后发布。 -- [x] 注入正午时钟的批量准入、实机策略热读取、旧片保留、超过15秒合成完整解码和配置切换一致;实机当前为夜间,不改宿主时间。 -- [x] 文档注明验证范围;保持私有入口,交付代码与手册。 - -## 完成记录 - -最终后端Linux188项/20子测试,前端79项,推理149项/120子测试,真实FFmpeg6项通过。完整验证见[开发与验收记录](../../开发与验收记录_20261111.md)。实机热切换后保持开发全天;两份鲲鹏草稿未运行,完整旁白已生成。 diff --git a/docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md b/docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md deleted file mode 100644 index f2f5ad2..0000000 --- a/docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md +++ /dev/null @@ -1,79 +0,0 @@ -# Multi GPU FIFO Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans. Complete each task's RED/GREEN checks and record evidence. - -**Goal:** Dispatch ready jobs FIFO across idle GPUs and run the workspace with 384 GiB RAM. - -**Architecture:** One scheduler owns FIFO claims and persistent per-GPU leases, while independent execution monitors own task process groups. Business orchestration feeds independent ready leaves into that queue within quotas. Aggregated resource state drives the web UI. - -**Tech Stack:** Python/SQLite/Linux processes, FastAPI/SQLAlchemy, Vue/Pinia, Docker. - -**Spec:** `docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md` (approved; 384 GiB supplement). - -## Global Constraints - -- One job per GPU UUID, max_gpu_jobs=4; 68 GiB allocator, 8 GiB GPU reserve, 15-second idle admission. -- Global FIFO for eligible tasks; retain pauses, windows, quotas, output/attempt fencing and external-user priority. -- No replay of hard-crashed execution; preserve queue/model files and unrelated working-copy edits. -- Workspace RAM=384 GiB; total memory+swap limit=384 GiB (no swap allowance). Keep other services intact. -- Source baseline is isolated commit `18701ee`; integrate only this feature's delta into the current canonical checkout. - -## Review Focus - -- Delayed GPU telemetry must not allocate one physical GPU twice. -- Cancelling/preempting one runner must not stop or finalize another attempt. -- More than eight independent workflow leaves must make progress without quota transaction rollback. -- Old API/worker initialization must not silently restore the singleton index. -- Cgroup/SHM pressure and normal PID exit must not create OOM or preemption retry storms. - -### Task 1: Inference FIFO scheduler, per-GPU leases and memory admission - -Files: `inference/llm_services/{store,worker,gpu_policy,api}.py`, `inference/scripts/service.py`, new scheduler/resource helpers if useful, related inference tests. - -Interfaces: scheduler JSON schema_version=2; `active_jobs` entries carry `job_id`, `attempt_count`, `gpu_index`, `gpu_uuid`, `stage`, `state`, `reason`; top-level `running_count`, `queued_count`, `state`, `policy`, `updated_at`. States `running/waiting/idle/blocked`, with per-entry preempting allowed. Settings keys live in worker config/settings.json, never runtime-policy.json. `max_gpu_jobs=4`, `cpu_threads_per_job=2`, initial host-memory estimates GiB: image=88, video=64, defect=24, audio=12; global headroom=16. These conservative estimates are configurable and updated by real measurements. Admission accounts for current cgroup working memory, active reservations and SHM, without counting reclaimable inactive file cache as permanently consumed. - -- [x] Write and run failing tests: three UUIDs launch A/B/C FIFO while D waits; concurrent claims never duplicate UUID/job; mixed modes use eligible queue_seq; old-attempt writes rejected; one cancellation or external preemption leaves other runners alive; multiple markers block unsafe recovery; old schema migration preserves jobs; memory shortage queues head job. -- [x] Replace singleton index/claim guard with atomic GPU lease uniqueness; schema compatibility rejects legacy singleton re-creation. -- [x] Implement one event dispatcher with per-job monitors and markers. Claims/spawns ordered, monitor/cleanup independent, status single writer. Keep `run_once` compatibility for meaningful legacy fixtures or update callers deliberately. -- [x] Add attempt CAS to terminal and requeue writes, bounded all-runner shutdown, per-runner env/CPU threads, max slot and memory admission. -- [x] Run inference suite on Windows for portable parts, then complete Linux process/guard/service suite in isolated server scratch. Record RED/GREEN and commit scoped files after review. - -### Task 2: Application FIFO, parallel workflow/batch feeder - -Files: `backend/app/{coordinator,workflow_engine,batches,workflows,jobs}.py` as needed and corresponding backend tests. Do not edit providers.py (Task 4 owner). - -Interfaces: reuse existing upstream scheduling protocol/job IDs and attempt fences. Independent ready steps enqueue in stable step order within remaining per-owner quota (8 interactive GPU jobs). Multiple active batch members allowed; preserve existing current_item_index compatibility while providing active item list/count if needed. Separate new-submit FIFO from next_action_at retry polling. Bound background preparation/collection and continue querying existing upstream executions. - -- [x] Write RED tests for three independent shot submissions, 12/20-shot quota replenishment, two batch members in flight, compose waiting all chosen outputs, cancelling one child, stable FIFO ready submission despite polling timestamps. -- [x] Implement bounded per-leaf persistence and replenish; remove only unique-active-member gate, preserve run/user quotas, hold controls, permissions and dependencies. -- [x] Ensure long preparation/result imports do not starve ready submissions; retain CPU/Qwen pool limits and persisted outcomes. -- [x] Run full backend tests, report any baseline unrelated failures separately; scoped review/commit. - -### Task 3: GPU monitor disappearing-PID handling and diagnostics - -Files: `inference/admin/gpu_guard.py`, `inference/tests/test_gpu_guard.py` (and only narrowly related tests). - -Interfaces: preserve guard status schema v1, ownership and global failure behavior. A missing PID can be dropped only after one fresh NVIDIA sample confirms disappearance; permission/identity ambiguity stays fail-closed. Logs record failed PID, stage, error category without dumping command/env/secrets. - -- [x] RED tests: sampled PID exits before /proc read then absent on bounded resample -> no global error; still-present unknown PID/permission failure -> fail closed; new external process in refreshed sample is retained; sample retry bounded and existing watchdog identity tests pass. -- [x] Implement one bounded resample and structured diagnostics; retain root-only policy and pidfd signaling. -- [x] Run guard suite portable then Linux, review and scoped commit. Root deploys root-owned script only after full verification. - -### Task 4: Aggregated UI resources, documentation and integration - -Files: `backend/app/providers.py`, `backend/tests/test_resource_status*.py` or existing resource tests, frontend resource types/components/text/tests, help manuals, README and deployment checks. Root owns these files. - -- [x] RED tests for multiple active_jobs, single-card preemption with another card running/ready, schema-v1 compatibility, no sensitive process detail in public resource state. -- [x] Adapt provider resource summary and frontend types/counts/card information; remove current single-task wording, preserve history reports. -- [x] Run backend full suite, frontend full tests/typecheck/build, inference full Linux suite; independently review integration. Resolve important findings with focused RED/GREEN checks. - -### Task 5: 384 GiB deployment, selective source integration and real three-card validation - -Files: scoped deploy script, new QA evidence/README; remote backup and deployment records. - -- [x] Recheck host available RAM and target container identity; save old configuration; docker update memory and memory-swap to384g; verify exact cgroup limit412316860416 and unchanged container start time. -- [x] Compare canonical files to baseline manifest; integrate only this feature's delta with three-way preservation of concurrent edits, then retest combined source. Do not stage or deploy unrelated incomplete work. -- [x] Drain existing jobs before coordinated API/worker schema switch; retain queued jobs. Back up SQLite using backup API, configurations, service identities and touched source. -- [x] Deploy consistent inference/API/UI versions, root guard source and operator config; check readiness and Qwen/other container identity. -- [x] Submit four low-cost real GPU jobs across three free cards; prove FIFO starts, overlapping execution, fourth waiting then filling a released card, outputs decoded, per-card cleanup, single-card controlled external preemption, RAM/SHM peaks, no duplicate attempts or unexplained requeue. Do not consume GPU0 external service. -- [x] Restore prior test-only inputs/policy after validation; leave production concurrency enabled and384 GiB. Record final tests, changed service bindings, source commit and limitations. diff --git a/docs/superpowers/plans/2026-11-11-multi-gpu-progress.md b/docs/superpowers/plans/2026-11-11-multi-gpu-progress.md deleted file mode 100644 index 4185fd4..0000000 --- a/docs/superpowers/plans/2026-11-11-multi-gpu-progress.md +++ /dev/null @@ -1,46 +0,0 @@ -# SDD ledger — plan: docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md - -- Approved design and384 GiB supplement: latest user message. -- Isolation: native create_worktree tool did not return and was terminated; independent local clone plus current dirty source snapshot preserves canonical checkout. Baseline18701ee. -- Task5 memory step: 2026-11-11 10:16:52 hot update verified memory.max=412316860416, memory+swap384GiB, container identity/start unchanged. Backup /root/gpu-fifo-upgrade-20261111-101652/container-before.json. Host available427.03GiB, CPUs128. - -| Pre-flight | Producer/consumer | Finding | -|---|---|---| -| Task1 / Task4 | scheduler schema2 active_jobs -> provider/UI | Exact fields declared in plan; guard stays schema1. | -| Task1 / Task3 | monitor ownership -> per-runner yield | Global unavailable status remains protective; confirmed external occupancy affects one lease. | -| Task1 / Task2 | upstream FIFO -> application ready FIFO | Both preserve eligibility and attempt fences; prepare not ready yet can be skipped. | -| Task2 / Task4 | coordinator workflow changes / provider status | Separate owned files; public DTO additions backward compatible. | -| Task1 / Task5 | schema/markers -> coordinated switch | Drain before migration, consistent API/worker code, old singleton index cannot return. | -| Each task | Tests/code/files | RED/GREEN and full affected suite required; test ownership avoids simultaneous writes. | - -Ruling: execution continues under the approved design without a second plan approval, as user explicitly requested implementation. Runtime384 GiB supersedes design's undecided memory cap. - -Ruling: unrelated source changes are captured only as a private baseline; final transfer/deployment includes feature delta and current canonical source after conflict checks, not an overwrite with the snapshot. - -## Integration progress - -- Task1: Linux RED7 expected failures observed on baseline; initial Linux GREEN176 passed/123subtests. Latest portable156passed25skipped123subtests; final Linux in progress. Fresh review memory underestimate reproduced and fixed with conservative observed+active+new reservations. Per-card blocked metadata follow-up in progress. -- Task2: ready feeder/batch/FIFO/preparation changes stable. First Linux full224passed20subtests and1 obsolete single-child deletion assertion (updated to all3 children+refs). Fresh review caught >25-ready FIFO overflow and orphan-on-cancel during post-payload preparation; both RED reproduced and fixed, final regressions running. -- Task3: initial45tests GREEN; review caught lost continuous-idle credit on occupied->empty refresh; RED reproduced, fixed46/46. Final Linux verification pending latest aggregate package. -- Task4: resource summary initial3RED ->17provider pass2skip20subtests; executor-global-blocked visibility RED ->4focusedpass. Frontend103tests pass and productionbuild/typecheck pass; final build after last UI refinement pending. -- Canonical source advanced independently to5909e38 (v4 private/shared assets release), deployed by its own chat. Its non-overlapping changes copied into this private clone; current manuals merged, generatedHTML regenerated. No application source overlap with our3ownedappfiles. Original source still untouched by this feature. - -Ruling: use conservative whole-container working memory plus all active reservations when process attribution is unavailable; double-counting can reduce heavy-image concurrency, but prevents known background-growth underestimation. Three expected64GiB Wan jobs remain admissible under384GiB. - -Ruling: generated manual.html textual conflict is resolved by regenerating from the three-way-merged current Markdown manual, preserving v4 help additions and new parallel scheduling rules. - -Remote sessions: rootSSH20909, SFTP5325; scratch/root records /root/cmvr-gpu-fifo-20261111; user test source /workspace/projects/cmvr-visual-fifo-qa/green. Deployment helper .deploy/deploy_parallel_remote.py is prepared but NOT executed. Production still serial as of this entry; only RAM cap is live384GiB. - -## Completion - -- Task1 complete: Linux185passed123subtests; atomic FIFO/multiple UUID leases/attempt fencing/independent cleanup and blocked metadata proven. Extra root CPU thread propagation regression2RED->2GREEN, included in185. -- Task2 complete: Linux backend229passed20subtests; quota,27readyFIFO,cancellation/preparationrace,parallelbatch andexistingprivate/shared/deletion regressions pass. -- Task3 complete: latest guard46portablepassed, fullLinux185includesallguardchecks. ControlledexternalPID causedonlytargetedjobtorequeue; peerattemptremained1. Normalexitsgeneratedno unexplainedrequeue. -- Task4 complete: frontend103passed; typecheck/build pass; authenticated browser resourcepanel fourcards, noJSerrors. Source integration appliedthree-way onto canonical5909e38;34featurefiles matched testedclone. Featurecommit89dcec1. -- Task5 complete: memory384GiB hotupdated(no workspace restart), staged imagesbuilt; activated11:00:51 aftersafe CPU/GPUdrain/backups/workeridentity+heartbeat+authority+protocolgates. FourFIFOrealjobs passed withthreephysicalcards,onecontrolledprioritypairpassed(1intendedretry only),threemodelresourcecalibrationpassed. NineMP4outputsdecoded with exact5/25frames. Measuredcontainer currentpeak105.13GiB, workingpeak102.95GiB; noOOM/maxevents. Runtimehashes12criticalsourcefiles verified againstcanonicalcommit. GPU0Qwen preserved, GPU1precise remainsstopped, formerGPU3trainingnotrestarted. - -Final review fixed activation risks: waitwholeCPUexecutionquiescencebeforemaintenance,freezeAPIbrieflyonlyforrace-freezero-executioncheckusingindependentread-onlyDBprobe;thenmaintenance+GPUqueuepauseandnaturaldrain. Resumeonlywithverifiedworkerbirth+argv,freshschema2heartbeat,freshhealthyGPUauthority,fullappupstreamprotocolreadiness. Actualactivationallgatespassedandqueuefullyrestored. - -Ruling: preserveexisting15-secondcontinuousidleadmissionbetweenownjobs;realFIFO4thjobwaitsuntilafreedcardhasregainedidlecredit,notuntilallpeerjobsfinishasapolicyrequirement. - -Noimportantreviewfindingremains. Nodeferredminorfindings. Nothingpublishedtopublicinternet;existingprivateentryandpermissionspreserved. Detailedruntimeevidenceiscanonicalqa/gpu-fifo-*.jsonanddocs/多GPU并发与384GiB升级验收_20261111.md. diff --git a/docs/superpowers/plans/2026-11-11-private-delete-shared-assets.md b/docs/superpowers/plans/2026-11-11-private-delete-shared-assets.md deleted file mode 100644 index a11f73a..0000000 --- a/docs/superpowers/plans/2026-11-11-private-delete-shared-assets.md +++ /dev/null @@ -1,28 +0,0 @@ -# 私有内容删除、共享素材与15秒单镜头验证计划 - -> For agentic workers: use subagent-driven-development. Root integrates schema, deployment, GPU verification and records; three owners implement disjoint backend/frontend scopes with RED→GREEN tests. - -**Goal:** 回答实际存储位置,验证单次15秒生成,并交付可用的个人内容删除及共享素材库。 - -**Architecture:** 正式网站业务继续MySQL;媒体原件/模型权重在工作空间磁盘;独立GPU执行队列保留SQLite恢复隔离。用户明确选择发布独立副本、他人导入个人副本。沿用现有Vue3/Pinia/Element Plus、FastAPI、单GPU公平队列、外部用户优先及配置时段。 - -## 已定接口与语义 - -- 004迁移:Job/Draft/Run/Batch的nullable deleted_at;Asset.library_scope默认private;SharedAsset表保存发布者、隐藏独立copyasset、原件溯源、version、创建和撤回时间。 -- GET /shared-assets及详情/内容/缩略图登录可读;POST /assets/{id}/publish;POST /shared-assets/{id}/import返回个人Asset;DELETE /shared-assets/{id}仅发布者撤回。共享copy不暴露隐藏AssetId、原私有来源和任务;他人导入字节独立。 -- DELETE /jobs/{id},/workflows/{id},/workflow-runs/{id},/batches/{id}返回{deleted:{job_ids,run_ids,draft_ids,batch_ids}}。所有命令按owner过滤;重复删除幂等,可选If-Match。仅终态且Execution清理确认允许;父级任务从父级删除,仍被其他Run复用的旧Job保护。 -- 删除草稿/运行/批次级联归档相应历史,保留生成素材和审计;释放失效引用,原幂等提交返回410。SSE发送各类deleted事件和递增version;前端墓碑拦截迟到响应与跨会话数据。 -- 素材逻辑删除;引用中的素材受保护。物理GC仍需维护模式、保留期及显式启用,默认dry-run;只有真正清理后才释放占用配额。共享发布copy和导入copy各自计对应用户配额。 -- 15秒使用既有队列低成本361帧探针,再1280×704、50步原生测试;24fps。只临时白名单放宽私有runner,网页维持121帧。实验完成恢复原文件哈希,不停止共享Qwen或其他用户服务。 - -## 工作包与进度 - -- [x] Root:只读确认正式MySQL17表、SQLite仅GPU队列;004迁移RED→GREEN6项,部分DDL重复升级保护,旧用户/素材保留。 -- [x] Sharing owner:发布/浏览/导入/撤回、私有scope隔离、复制哈希、GC与配额、双用户/令牌/幂等/篡改测试。 -- [x] Deletion owner:四类删除、级联与引用、query/fence/幂等/事件,13项专项及最终31项回归。 -- [x] Frontend owner:所有删除入口、共享库/只读预览/选择器导入、会话墓碑及编译组件测试、构建冻结。 -- [x] 独立安全/前端审查并处理可复现问题。 -- [x] Linux完整后端、隔离MySQL004升级/恢复/接口、前端与双用户真实浏览器验收。 -- [x] 单镜头361帧生成、解码计数、画面检查、资源监测与恢复校验。 -- [x] 自管数据维护、备份、迁移、API/前端发布;不复制模型代码覆盖正在验证的临时runner,不重建工作区或共享Qwen。 -- [x] 更新操作手册、存储/删除/共享说明、验证记录和代码提交。 diff --git a/docs/单镜头15秒功能与验收_20261111.md b/docs/单镜头15秒功能与验收_20261111.md deleted file mode 100644 index bd57db5..0000000 --- a/docs/单镜头15秒功能与验收_20261111.md +++ /dev/null @@ -1,27 +0,0 @@ -# 单镜头15秒功能与验收 - -当前网站为本机开发运行:前端`http://127.0.0.1:5173`,API`http://127.0.0.1:8000`。业务数据仍使用服务器MySQL,推理继续调用192.168.28.10工作区中的模型服务。 - -## 如何使用 - -进入“创作”并选择视频,在视频时长控件选择5秒、10秒或15秒,也可输入1–15的整数秒;默认仍为5秒。输入提示词、可选参考图,选择步数及画质增强后提交。网页会显示本次真实提交的源帧数:5秒为121帧、10秒为241帧、15秒为361帧,固定24fps。模型源视频多一个尾帧,因此15秒源片段实际为15.041667秒。 - -进入“工作流”,逐镜头修改选用时长,支持1–15秒,页面按0.25秒调整;JSON可以指定24–360的整数帧。每个镜头按自己的长度生成,最后裁取精确选用帧数。例如5秒、10秒、15秒三个镜头请求121、241、361源帧,合成720帧、精确30秒成片。 - -旧工作流仍按冻结参数执行,旧schema1仍为三个完整5秒镜头。5秒以内的裁剪继续使用121帧源片段,保留原先的短片复用规则;长镜头所需生成长度变化会影响复用,旧5秒源不能冒充15秒镜头。镜头顺序或长度改变后,需要重新检查字幕和音轨时间。 - -## 验证证据 - -- 浏览器实际渲染了1/5/10/15秒选择,拦截提交证明分别发送25/121/241/361帧;这些浏览器表单验收不转发GPU请求。 -- 混合5/10/15秒草稿经真实MySQL保存、重载、JSON导出/导入,始终为720帧。超出当前能力的恢复值被保留并报错,不会静默改成5秒。 -- Linux真实FFmpeg使用121、241、361帧源片段完成720帧、24fps、1920×1080、30秒输出,并完整解码。用5秒短片替代15秒输入时被拒绝,没有补帧、冻结或慢放伪造时长。 -- 正常网站API提交361帧请求后,实际经过vLLM-Omni生成与Real-ESRGAN增强,两份结果均解码为361帧、24fps、15.041667秒。该次为512×288、4步的低成本链路验收,约156.8秒;不是新的1080p质量或耗时基准。完整记录为`qa/shot15-e2e.json`。 -- 前轮1280×704、50步的原生361帧生成已完整解码通过,约817秒;本轮没有重复该高规格基准。较长镜头不保证复杂动作遵循或角色一致性。 - -浏览器记录与截图在`qa/shot15-browser.json`及`qa/shot15-*.png`;原生与增强验收样片保存在admin私有素材库,名称前缀为`15秒原生镜头端到端验收`,未发布到共享库。 - -## 运行与兼容 - -服务端runner上限从121改为361,默认121和4n+1约束保留。采用同目录原子替换供新任务读取,没有重启推理API、GPU worker、工作容器、GPU guard或共享Qwen。只重启本机网站API加载新业务合同,现有模型调度、多GPU、其他用户优先和资源保护保持原状。 - -不需要数据库迁移。新Run在JSON快照中冻结每镜头生成参数;旧快照没有新字段时继续使用原参数。工作流最大总帧数与1000个镜头、每镜头360帧保持一致;运行仍受到管理员镜头数量、存储、输出大小及执行超时约束。 diff --git a/docs/单镜头超过5秒实测报告_20261111.md b/docs/单镜头超过5秒实测报告_20261111.md deleted file mode 100644 index 4e76b5f..0000000 --- a/docs/单镜头超过5秒实测报告_20261111.md +++ /dev/null @@ -1,64 +0,0 @@ -# 单镜头超过5秒:环境核验与实际生成报告 - -2026-11-11,Asia/Shanghai。结论:**当前环境已实测支持约10秒的单镜头文生视频**,包括原片和Real-ESRGAN空间增强;这不等于网页已经开放10秒,也不代表可无限延长。 - -## 当前条件 - -| 项目 | 实际配置 | -| --- | --- | -| GPU | 4张H100 80GB;本次使用空闲GPU2,另外三张有外部业务 | -| 工作区容器 | 内存上限128GiB,共享内存8GiB | -| 模型 | 本地Wan2.2-TI2V-5B,BF16;现有Real-ESRGAN | -| 软件 | vLLM/Omni0.32.0,Torch2.13.0+cu130,Diffusers0.40.0,Transformers5.19.0 | -| 执行 | 单卡TP1,module CPU offload,VAE tiling/slicing,原68GiB分配器预算与8GiB预留 | -| 调度 | 既有单GPU任务队列和守护器;其他用户优先、占卡即让行规则保持 | - -本地模型配置的VAE时间压缩比为4、空间压缩比16;Transformer patch为[1,2,2]、RoPE轴长度1024。241帧对应61个时间潜变量,位置表不会在121帧处截断。 - -官方[TI2V-5B配置](https://github.com/Wan-Video/Wan2.2/blob/main/wan/configs/wan_ti2v_5B.py)使用121帧、24fps、50步作为默认规格;[生成入口](https://github.com/Wan-Video/Wan2.2/blob/main/generate.py)允许传入4n+1帧。[Omni0.32的管线](https://github.com/vllm-project/vllm-omni/blob/v0.32.0/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2.py)按请求动态构造时间潜变量。因此121是本项目的服务保护上限和官方标准档位,不能当作架构硬上限;更长时长的质量与资源消耗仍需实测。 - -## 实验与结果 - -两项测试均通过原队列执行,batch=1、24fps、seed42、guidance5.0。同一提示词描述固定机位下的单艘红帆白船和海面,避免用多镜头叙事混淆连续时长。 - -| 测试 | 参数 | 结果 | 执行耗时 | -| --- | --- | --- | --- | -| 低成本通路 | 512×288、241帧、4步、不增强 | 成功;仅证明动态帧数通路 | 56.42秒 | -| 当前源规格 | 1280×704、241帧、50步 | 原片成功,H264、24fps、10.041667秒 | 模型阶段约458.85秒,含加载/清理 | -| 空间增强 | 上述同一原片→1920×1056 | 成功;仍为241帧、24fps、10.041667秒 | 增强阶段约288.79秒,含阶段交接 | - -标准测试总执行**748.32秒,约12分28秒**,另有13.55秒排队;attempt=1、preemptions=0。阶段耗时由结果文件完成时间估算,不是GPU·秒。1920×1056保持原纵横比,尚未填边成标准1920×1080。 - -标准测试约1秒间隔采样707次,监测到GPU使用峰值**18.17GiB**、最低空闲61.01GiB。采样可能遗漏短暂尖峰,这也不是对其他型号/24GB卡的可用性保证;本次依赖上述H100、128GiB容器内存及CPU卸载条件。低成本测试未覆盖全部显存采样,不用于峰值结论。 - -## 单镜头与质量证据 - -- 既有adapter在一次实际`Omni.generate`请求中传入241帧,并检查模型返回帧数。没有通过拼接、插帧、循环或降低播放帧率来增加时长;增强仅逐帧提高空间分辨率。 -- 原片和增强版均通过ffprobe实际解码计数与FFmpeg完整解码:各241帧、24/1fps;各有241个不同的解码帧哈希。哈希不同不等于动作质量合格。 -- 浏览器实际播放、1/5/9.5秒定位均通过,没有页面或媒体错误。 -- 每秒抽帧审查显示帆船、岸线基本保持,未见明显场景切换;但船的横向运动较弱,开头有色调变化,未充分实现提示词中的航行动作。这里只验证一个简单文生场景,未做统计质量验收。 - -![原片每秒抽帧](../qa/longshot-native-contact.jpg) - -拼版按0至10秒排列,共11个采样;末格为空白,不是成片黑帧。增强版抽帧另见`qa/longshot-enhanced-contact.jpg`。 - -## 服务保护与当前开放范围 - -测试只对私有runner临时加入精确匹配实验提示词和161/241帧的白名单校验。网页API一直保持121帧,普通请求未放宽。测试结束已逐字节还原runner,SHA256为`0e3054b0385c8308e87626c5c1138b6714aa694ad500eaa0ecd903047176fd4a`。 - -没有升级环境、下载新模型、启动第二个GPU worker或改动GPU预算。网站API/前端、TTS、工作区、GPU守护器及共享Qwen两个容器的ID和启动时间全部与实验前相同。执行发生在白天,使用现有开发全天配置;没有调整服务器时间或伪造GPU状态。 - -**底层能力已验证到约10秒;当前网页的单镜头仍是1–5秒。** 如果正式开放,需要同时调整服务端帧数校验、能力输出、编辑器时长、工作流源帧数/复用校验和执行预算。单纯把页面输入上限改为10不完整。建议先做有明确上限的10秒实验档,保留默认5秒。 - -尚未验证15/30/60秒、10秒图生视频或鲲鹏复杂变形;不能据此承诺这些场景。长剧情仍需要分镜、参考形象和人工质量检查。 - -## 样片位置 - -当前管理员的“素材”中已保存: - -- “单镜头10秒实测-720P原片.mp4”,素材`c1deafe1baa04c2db785f1d864578272`。 -- “单镜头10秒实测-1080P增强.mp4”,素材`344bfbfcdba04479814e2641488899de`。 - -可按“单镜头实测”标签查找。它们作为实验样片上传,未伪装成网站已支持的10秒生成任务。原片本机副本在`qa/generated/single-shot-10s-720p.mp4`,增强版为`qa/generated/single-shot-10s-enhanced.mp4`,视频不提交Git。 - -完整参数、帧数、文件哈希、采样与浏览器结果见`qa/longshot-validation-20261111.json`;原始监测位于服务器受保护目录`/root/cmvr-longshot-validation-20261111`。队列任务为`8b6de497a83c4acd91a1ec055a337eec`和`9b373f04c1ac463788ff54d99439963c`。 diff --git a/docs/图生图与视频人物替换操作手册_20261112.md b/docs/图生图与视频人物替换操作手册_20261112.md new file mode 100644 index 0000000..e6113d8 --- /dev/null +++ b/docs/图生图与视频人物替换操作手册_20261112.md @@ -0,0 +1,69 @@ +# 图生图与视频人物替换操作手册 + +这两个功能位于“创作”。图生图使用 Qwen-Image-Edit-2511;视频人物替换使用独立的 Wan2.2-Animate-14B,并通过检测、姿态和时序遮罩区分同一视频中的人物。已有文生图、Wan2.2-TI2V-5B 单镜头生成和故事工作室继续使用各自的入口。 + +页面根据服务器的真实能力开放操作。视频编辑权重未就绪、尚未通过模型验收或开关关闭时,会显示原因并阻止提交。任务元数据和人物绑定记录保存在既有 MySQL 任务表,媒体文件保存在用户工作空间;本次无需增加数据库表。 + +## 1. 图生图 + +1. 登录后进入“创作”,选择“图生图”,地址为 `/create/image-edit`。 +2. 上传参考图片,或从个人素材库选择。共享素材需要先导入个人库;选择器支持这个流程。 +3. 最多使用三张不同的参考图片。确认缩略图顺序,使用前移、后移或移除按钮调整。提示词中的“第一张、第二张、第三张”对应此处的顺序。 +4. 填写提示词,明确每张图提供什么,以及希望保留或修改的部分。例如:“保留第一张图片中女性的脸型和发型,穿第二张图片的绿色外套,站在第三张图片的海边车站,电影摄影,自然光;只出现一个人。” +5. 选择方图 1024×1024、横图 1280×704 或竖图 704×1280。首次使用建议保持默认高级参数:40 步、guidance 1、true CFG 4、序列长度 1024。 +6. 候选数量为 1–4。每个候选是独立任务,按顺序递增种子,并真实传递全部参考图;不会自动改成文生图。 +7. 点击生成,在当前任务区或“任务”查看排队、运行和结果。生成图片进入个人素材库,可以下载、发布共享副本,或进入故事工作室作为首帧/角色参考。 + +参考图片用于引导外观与内容,不保证逐像素保留、严格排版或人物身份完全一致。需要修正时,优先明确提示词中的对应关系,再更换清晰的参考图;一次只调整少量参数,便于比较。 + +## 2. 分析视频并选择人物 + +1. 进入“创作 → 视频人物替换”,地址为 `/create/video-edit`。 +2. 上传视频或选择个人库中的视频。默认一次处理最多 120 秒、跟踪最多 12 位人物(包括未选择替换的人);页面展示实际配置的上限。这是可调整的资源预算,不是每用户可生成视频的数量限制。 +3. 选择处理规格。默认使用约 480p 的像素预算;只有服务器明确开放相应能力后才能选择 720p。画幅按源视频显示方向处理,帧率统一为 24fps。 +4. 点击“识别人物”,等待分析任务完成。分析也使用受监管的 GPU 队列,不会在浏览器中执行模型。 +5. 在人物卡片或视频预览框中选择需要替换的人。可以只选一个,也可以同时选择多个人。人物编号仅用于当前视频中的轨迹,不是姓名或实名识别结果。 +6. 拖动视频播放进度,对照人物缩略图和检测框确认选择。多个轨迹交叉、长时间遮挡或人物消失后重新出现时,跟踪可能无法确定身份;系统会拒绝无法可靠对应的分析,而不是自行猜测谁是谁。此时应剪出更清晰的片段后重新分析。 + +更换源视频或处理规格后,原分析和人物绑定失效,需要重新识别。刷新页面可以恢复本地草稿和已持久化的任务;不要用旧分析结果绑定新视频。 + +## 3. 为一个或多个人物分别绑定参考图 + +1. 为每个已选人物单独选择一张身份参考图片。建议使用清晰、无遮挡、脸部可见且服装完整的单人图片。 +2. 在对应人物下填写可选的局部提示词,例如人物一:“短发女性,绿色外套,保留原动作”;人物二:“卷发男性,棕色夹克,保留原动作”。不同人物可以绑定不同图片。 +3. 填写必填的全局提示词,描述整个视频要保持的场景、动作和风格。例如:“将所选两人分别替换为各自参考图中的人物,保持海边车站、原始站位、镜头运动和原动作,自然呼吸和眨眼,不增加其他人物。” +4. 按需设置负面提示词、步数、CFG 和种子。默认 20 步、guidance 1、种子 42,先用默认参数比较效果。接口另支持遮罩扩展和羽化参数,范围为 0–64 像素;页面目前使用默认的 8 和 4 像素。 +5. “保留原音轨”默认开启。它保留源视频声音,不会更换配音、模仿新人物声线或自动对口型;源视频无声音时仍输出无声视频。 +6. 点击生成。服务器按人物逐个运行时序替换,再将结果合成;同一人物在处理窗口之间传递上一段的生成条件。所有已选人物都会出现在同一个最终视频中。 +7. 完成后逐段播放结果,尤其检查人物相交处、手和头发边缘,以及约每 3 秒的处理窗口连接处。检查原音轨、动作和未选人物,再下载;需要继续剪辑时,在故事“02 分镜”导入视频并确认选片,再到“03 成片”处理时间线与合成。 + +人物替换以原人物的可见区域为边界,并保护其他人物和背景。大幅改变体型、轮廓、发型或增加原遮罩之外的服饰可能被边界裁切;换脸相似度和复杂遮挡需要逐片验收。它适合保留原动作与镜头的外观替换;提示词不能把任意原动作变成完全不同的运动。 + +## 4. 排队、断线和删除 + +任务与原有创作共用持久队列。关闭网页或 HTTP/SSE 断线不会取消任务,不会停止共享 Qwen,也不会影响其他用户。返回页面后查看原任务即可。 + +其他服务器用户有更高的 GPU 优先级。外部用户开始占卡时,本应用停止自己的推理并释放显存,使用同一上游任务编号重新排队;当前推理进度会丢失,页面可能由“运行”变为“排队”。 + +所有输入、人物预览和结果只对所属用户可见。输入仍被任务引用时不能直接删除;先取消并等待执行退出,再按既有任务归档和素材删除流程处理。发布到共享库是独立副本,导入者的副本不因原件删除而消失。 + +## 5. 配置与部署 + +业务 API 配置文件使用以下键。修改后重启本应用 API;默认关闭新视频能力,避免把未验收的模型显示为可用。 + +```dotenv +REFERENCE_GENERATION_ENABLED=true +REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1 +REFERENCE_MAX_IMAGES=3 +VIDEO_EDIT_ENABLED=false +VIDEO_EDIT_PROFILE=wan-animate-replace-v1 +VIDEO_EDIT_MAX_SECONDS=120 +VIDEO_EDIT_MAX_PEOPLE=12 +VIDEO_EDIT_MAX_PIXELS=399360 +``` + +推理工作空间的 `config/settings.json` 对应 `video_edit_enabled`、`video_edit_profile`、`video_edit_max_seconds`、`video_edit_max_people`、`video_edit_max_pixels` 和 `video_edit_python`。业务与推理均启用,并且固定模型校验清单记录已通过真实验收后,页面才开放生成。两端上限不同时按较小值执行;720p 需要将两端像素上限显式配置为 921600,并完成对应资源和效果验收。 + +`video_edit_poc_enabled` 仅用于部署时经认证接口验证模型,不代表网站能力已开放。模型、预处理检查点、外部 ONNX 张量和预处理源码均需进入完整哈希清单。新增环境与已有模型环境分开安装;调度、让卡和每卡显存预算继续由既有 GPU 监管器执行。 + +批量夜间准入仍使用原 `runtime-policy.json` 配置;开发全天开关不改变其他用户优先、资源不足等待和显式暂停规则。 diff --git a/docs/多GPU并发与384GiB升级验收_20261111.md b/docs/多GPU并发与384GiB升级验收_20261111.md deleted file mode 100644 index 9baee2d..0000000 --- a/docs/多GPU并发与384GiB升级验收_20261111.md +++ /dev/null @@ -1,81 +0,0 @@ -# 多GPU并发与384 GiB升级验收 - -2026-11-11,北京时间。服务器:192.168.28.10。代码提交:`89dcec1c3bfb1ca0529c7c061b3b98d71902df4d`。 - -## 已上线行为 - -- 有多张符合条件的空闲GPU时,可以同时执行多个独立任务,每卡一个任务,配置上限4个。 -- 满足依赖、暂停和运行时段要求的任务按持久入队顺序派发,完成顺序不作限制。独立分镜和批次成员有界补队;合成等待全部所需输出。 -- 外部用户占用某张卡时,只让出对应卡并保留任务ID重排。其他卡上的任务继续;任务可以重新分配到另一张空闲卡。 -- 保留68 GiB单任务GPU预算、8 GiB显存预留、连续空闲15秒准入、权限/配额/运行时段及崩溃恢复约束。 -- 项目工作容器内存从128 GiB热更新至384 GiB,`memory.max=412316860416`。内存与swap总上限也为384 GiB,不额外允许swap。工作容器没有重启。 -- 每任务CPU线程配置为2,容器原8 CPU、8 GiB共享内存和512进程上限保留。按任务类型预留主存,并检查实际cgroup工作内存和共享内存;不足时队首等待,不能绕过FIFO启动较晚的轻任务。 -- 网页资源面板显示逐卡状态、运行数、排队数及调度暂停原因,避免一张卡让行覆盖其他卡状态。 - -## 自动化与审查 - -| 验证 | 结果 | -| --- | --- | -| Linux推理服务全量 | 185 passed,123 subtests passed | -| Linux业务后端全量 | 229 passed,20 subtests passed | -| 前端 | 103 tests passed;类型检查及生产构建通过 | -| 浏览器 | 登录和四卡资源面板通过,无JavaScript错误 | -| 源码一致性 | 12个关键运行文件与提交源码的LF规范化SHA-256一致 | - -覆盖了逐卡唯一租约、延迟GPU采样、并发领取、旧attempt写入拒绝、取消/超时/抢占隔离、多runner恢复与停机、20镜头配额补队、27就绪任务FIFO、准备期间取消、批次控制、素材隔离及删除回归。 - -独立审查发现的问题已复现并修复:退出PID的连续空闲计时、主存基线增长低估、准备阶段取消导致上游任务失联、超过25个就绪任务时的FIFO倒置、逐卡blocked状态丢失。另修复了模型子进程覆盖每任务CPU线程上限的问题。 - -发布流程先等待完整CPU执行结束,再以短暂API冻结和独立只读数据库检查建立无竞态维护入口;GPU任务自然完成后备份并切换。恢复队列前校验新worker出生身份和命令、新版调度心跳、健康GPU监控及完整应用就绪状态。上线时间11:00:51,所有就绪检查通过,原队列保留。 - -## 真实GPU验收 - -### 三卡并发与第四任务排队 - -四个低成本Wan视频任务,256×256、5帧、2步,全部输出成功且各执行一次,没有抢占重排。 - -| 任务 | 显卡 | 启动 | 完成 | -| --- | --- | --- | --- | -| A | GPU1 | 11:01:50.496 | 11:02:52.547 | -| B | GPU2 | 11:01:50.509 | 11:02:50.387 | -| C | GPU3 | 11:01:50.523 | 11:02:48.731 | -| D | GPU2 | 11:03:05.948 | 11:03:56.455 | - -监控同时观察到GPU1、GPU2、GPU3的实际模型进程。D等待释放卡重新满足连续空闲15秒规则后启动,不是按完成顺序派发新任务。 - -### 单卡外部优先 - -两个独立25帧视频任务并行期间,管理员受控探针短暂占用其中一张卡: - -- 受影响任务仅重排一次,从GPU1转到GPU2,第2次执行成功。 -- 同期GPU3任务保持第1次执行,没有重排,正常完成。 -- 探针正常退出,未残留GPU占用。原GPU0快速Qwen容器身份、启动时间未变,健康接口200。 - -### 三模型主存校准 - -另做三个256×256、5帧、1步Wan任务,同时观察到三卡实际模型进程,全部一次成功。每0.5秒读取实际工作容器cgroup及共享内存: - -- 容器已计费内存采样峰值:105.13 GiB。 -- 扣除可回收inactive file cache后的工作内存采样峰值:102.95 GiB。 -- 本次小规格任务共享内存采样峰值:12 KiB。 -- `memory.events`的`max`、`oom`、`oom_kill`没有增加。 - -以上是小规格通路和模型加载并发验收,不将其等同于任意参数、混合模型或四卡重负载的峰值承诺。GPU0保留其他业务,因此真实硬件验收使用三张空闲卡;配置允许最多四张合格空闲卡。 - -九个最终MP4产物均通过认证下载和完整帧数解码检查(5帧或25帧),并记录了SHA-256。测试结束后无活动runner或排队任务,GPU1/2/3各恢复约79.2 GiB可用显存。 - -## 配置、边界和证据 - -工作容器仍为`llmuser-workspace`;操作员调度配置位于`/workspace/projects/llm-services/config/settings.json`。并发上限4,主存预估GiB:图像88、视频64、缺陷24、转写12,额外预留16。为避免无法归属的容器内存增长被误认为模型预留已经兑现,准入采用保守的“当前工作内存+活动任务预留+新任务预估+额外预留”。因此显卡空闲但主存预算不足时,仍可能等待。 - -GPU0原快速Qwen服务继续运行;GPU1原精确服务及GPU3旧训练保持此前停止状态。网站仍使用原私有入口,未变更访问权限。 - -原始记录: - -- `qa/gpu-fifo-acceptance.json`:FIFO与单卡优先验收时间线、输出解码和校验值。 -- `qa/gpu-fifo-memory-calibration.json`:三模型实际内存采样及OOM计数。 -- `qa/gpu-fifo-deployment.json`、`qa/gpu-fifo-final-status.json`:部署与收尾状态。 -- `qa/gpu-fifo-source-verification.json`:运行文件与代码提交一致性。 -- `qa/gpu-fifo-browser.json`、`qa/gpu-fifo-resource-panel.png`:浏览器验收。 - -服务器备份和详细运行日志保存在root专用目录`/root/cmvr-gpu-fifo-20261111`;原容器限额备份位于`/root/gpu-fifo-upgrade-20261111-101652`。回退前必须排空活动执行,不得用旧队列快照覆盖新任务,也不得删除锁或恢复标记强行启动。 diff --git a/docs/存储隔离共享与15秒验证_20261111.md b/docs/存储隔离共享与15秒验证_20261111.md deleted file mode 100644 index 85dc335..0000000 --- a/docs/存储隔离共享与15秒验证_20261111.md +++ /dev/null @@ -1,73 +0,0 @@ -# 存储、私有内容删除、共享素材与15秒单镜头验证 - -本轮已在192.168.28.10更新网站API和前端,数据库版本为004。项目代码位于`E:\workspace\hybrid\cmvr-visual`。验收数据见`qa/v4-validation.json`和`qa/v4-browser.json`。 - -后续功能更新:单镜头15秒现已接入网页和正常接口,本文下方“网页仍约5秒”是当次容量验证结束时的历史状态。当前操作以《操作手册_20261111.md》为准,最新链路验收见《单镜头15秒功能与验收_20261111.md》。 - -## 实际数据位置 - -| 数据 | 当前存储 | 说明 | -| --- | --- | --- | -| 网站业务数据 | MySQL `192.168.28.10:3306/cmvr-visual` | 用户、会话、素材元数据、任务、工作流、批次、共享发布、审计事件与提交记录 | -| 图片、视频、音频、文本及副本 | 宿主机`/data/llmusers/llmuser/workspace/cmvr-visual/assets` | 容器内为`/workspace/cmvr-visual/assets`;MySQL记录所有者、文件位置、大小和哈希,文件在磁盘 | -| 推理执行队列 | 容器内`/workspace/projects/llm-services/state/jobs.sqlite3` | 独立GPU调度服务的恢复队列;不保存网站的用户、工作流和共享库业务 | -| 测试和预览数据库 | 自动测试临时SQLite、隔离验证MySQL | 与正式网站数据库分开;正式模式禁止SQLite | - -因此,正式网站业务已经使用MySQL,无需把它从SQLite再迁移一次。底层单机GPU队列保留SQLite,可以让推理服务独立恢复,并在网站维护时继续运行。备份网站需要同时备份MySQL和媒体文件;不能用GPU队列文件替代业务备份。 - -## 个人内容与删除 - -包括admin在内,账号只能读取和修改自己的私有素材、任务、草稿、运行和批次。猜测他人ID、直接请求媒体地址或删除接口均不能绕过所有者检查。共享内容通过单独的、要求登录的共享素材接口访问。 - -素材卡片和预览、创作任务卡片、任务列表和详情、工作流草稿/运行、批次均新增删除入口。记录删除采用软归档:从日常列表消失,保留必要审计记录。规则如下: - -- 活动任务先取消,等待执行退出和清理确认后删除;不确定执行状态会阻止删除。 -- 工作流/批次子任务通过所属父记录删除。删除运行会归档其子任务、保留草稿;删除草稿会归档其运行和子任务;删除批次会归档其运行和任务、保留草稿。 -- 删除任务、运行、草稿或批次,保留已经生成的素材;需要清理素材时再删除素材本身。 -- 被草稿、运行或活动任务引用的素材受到保护。先解除引用并保存,或按提示取消/删除所属运行或批次,再删除素材。 -- 已归档记录的原提交键恢复/重放返回410,不能通过重复提交让旧记录重新出现。SSE同步删除,前端拦截迟到响应和跨会话缓存。 - -软删除不会立即释放磁盘或额度。GC默认只盘点,默认保留14天;物理清理需要运维显式维护、启用purge并再次检查引用,真正移除文件后才释放占用。 - -## 共享素材的操作 - -1. 打开“素材”→“我的素材”,在素材卡片或预览中点击“发布到共享素材库”,阅读并确认独立副本说明。 -2. 登录用户在“共享素材”中查找、预览。需要用于创作时点击“导入我的素材”,或在创作的素材选择器切到“共享素材”,选择后自动导入再使用。 -3. 导入结果属于导入者的私有素材,可以重命名、打标签、用于任务或再次选择。其他人不能直接使用发布者的私有素材ID或共享发布ID提交模型任务。 -4. 发布者可在自己发布的条目中“撤回共享”。只有发布者有撤回权限;删除原件不会自动撤回已发布的副本。 - -发布副本和每次导入均复制真实字节及缩略图,不使用硬链接。删除原件、撤回共享,都不会影响别人已经导入的素材和作品。发布副本计入作者额度,导入副本计入导入者额度;重复导入可能产生额外副本。内容发布后,作者无法收回别人已经导入的副本。 - -本轮只向共享库发布了合成验收素材,测试后均已撤回、清理;没有自动共享用户的既有作品。 - -## 单镜头15秒的实测结果 - -服务器有四张NVIDIA H100,单卡总显存81559 MiB。本次通过现有全局串行GPU队列执行,在GPU2运行,未并行启动第二个自管GPU任务,保留其他用户优先及抢占规则。 - -| 项目 | 低成本通路验证 | 完整规格验证 | -| --- | --- | --- | -| 模型 | Wan2.2-TI2V-5B | Wan2.2-TI2V-5B | -| 分辨率 | 512×288 | 1280×704 | -| 推理步数 | 4 | 50 | -| 原生输出 | 361帧,24fps,15.041667秒 | 361帧,24fps,15.041667秒 | -| 执行时间,不含排队 | 61.43秒 | 817.08秒,约13分37秒 | -| 完整解码/帧数检查 | 通过,361帧 | 通过,361帧 | - -完整规格样片来自一次连续生成。另提供移除最后一帧后的360帧、精确15.000秒版本,未改变帧率或播放速度。完整视频已逐帧解码,361个解码帧哈希均不同。抽帧检查显示帆船和海面持续存在、镜头连续,但帆船横移幅度较小;这证明当前环境能完成该规格的15秒生成,不代表复杂动作、人物一致性或鲲鹏变形效果已经达标,也不能外推为无限长镜头保证。 - -完整规格运行期间NVML采样最高21697 MiB,约21.19 GiB。该值是采样到的整卡使用量,不是分配器精确峰值。工作区容器采样最高约47.76 GiB,包含工作区其他进程。此次没有追加Real-ESRGAN增强测试;15秒高分辨率增强的总耗时与资源占用不能直接套用本结果。 - -实验完成后已恢复原runner文件哈希,并重新验证普通请求:121帧允许、241/361帧拒绝。网页当前仍为约5秒单镜头,尚未把15秒单镜头接入普通提交入口;长视频仍通过多镜头工作流制作。关闭网页或HTTP连接不会停止共享Qwen服务。 - -精确15秒样片已导入admin的**私有素材库**,名称为`单镜头15秒实测_1280x704_20261111.mp4`,未发布到共享库。本机文件位于`qa/generated/single-shot-15s-1280x704.mp4`,原始361帧版本位于`qa/generated/single-shot-15s-native-361.mp4`。 - -## 验收与更新保护 - -- 后端Linux完整测试213项、20个子测试;前端103项、类型检查和构建通过;Linux媒体处理6项通过。 -- 真实MySQL接口测试23项通过;升级矩阵覆盖unicode_ci、0900_ai_ci、bin及不同父列排序规则,包含部分DDL中断恢复和重复升级,共7个场景。 -- 真实网站双用户验收110/110通过,包含管理员不能读取他人私有内容、共享与独立导入、删除级联、引用保护、提交恢复410。临时账号已停用、会话已失效,验收内容全部清理。 -- Chrome验收覆盖发布、导入、撤回、跨标签SSE删除同步、删除入口及桌面/移动布局;没有页面异常或服务端5xx,验收素材已清理。 -- 更新前备份位于服务器受保护目录`/root/cmvr-visual-v4-20261111`。数据库备份已在隔离MySQL恢复验证;实际检查点的2个原用户(含密码哈希)、23条素材、18条任务、4份草稿、2次运行均保留。 -- 本轮仅重建网站API和前端;工作区、GPU guard、TTS及共享Qwen容器的ID和启动时间均未改变。GPU推理队列没有回滚或重启。回退旧003代码需要共同恢复对应网站数据库与文件检查点,不能仅换旧镜像。 - -操作步骤见《操作手册_20261111.md》;鲲鹏长视频的分镜、旁白和合成步骤见《鲲鹏长视频制作指南_20261111.md》。 diff --git a/docs/实施方案V2_20261110.md b/docs/实施方案V2_20261110.md index 679d2ea..ab0ef31 100644 --- a/docs/实施方案V2_20261110.md +++ b/docs/实施方案V2_20261110.md @@ -1,6 +1,6 @@ # CMVR Visual 实施方案 V2 -日期:2026-11-10,Asia/Shanghai。状态:**已开发、部署并通过私有入口验收**。本文件按用户最新执行规则修订:08:00关闭新批量执行准入,当前已运行的镜头/处理阶段继续完成,后续阶段排队。实际交付与边界见 [V2开发与验收记录](V2开发与验收记录_20261110.md)。 +日期:2026-11-10,Asia/Shanghai。本文保留 V2 业务设计,运行入口和当前操作以[操作手册](操作手册_20261111.md)及项目 README 为准。网站前后端现于本地运行,模型 API 通过内网 HTTP 访问。时段策略控制新阶段准入,已经运行的阶段继续完成。 本方案承接[上一版复核](需求复核与落地方案_20261110.md),保留其中R1–R12和业务质量专项;以下规则解决上一版尚未明确的实施边界。发生冲突时以本方案为准。已完成的正式MySQL接入和默认管理员不重复执行。 @@ -186,7 +186,7 @@ MySQL DDL可能隐式提交,升级失败不能当成普通事务rollback即可 ### 6.3 建议初始配额(配置项,实施时校准) -原V2方案设定每用户最多8个未结束交互GPU子Job。2026-11-11已按用户要求取消默认8条限制,`MAX_INTERACTIVE_GPU_JOBS=0`表示关闭此限制;正数仅用于运维显式启用。每分钟6次创建命令、最多1个活动交互Run、单batch最多100项、每用户未结束叶任务最多500及全局最多2000等保护继续保留,均不限制历史累计生成数量。GPU与批次执行现已升级为多GPU并发,详见《多GPU并发与384GiB升级验收_20261111.md》。创建前事务内检查配额,复用同幂等提交不二次扣额。 +原V2方案设定每用户最多8个未结束交互GPU子Job。2026-11-11已按用户要求取消默认8条限制,`MAX_INTERACTIVE_GPU_JOBS=0`表示关闭此限制;正数仅用于运维显式启用。每分钟6次创建命令、最多1个活动交互Run、单batch最多100项、每用户未结束叶任务最多500及全局最多2000等保护继续保留,均不限制历史累计生成数量。GPU与批次执行现已升级为多GPU并发,详见[多 GPU 与 FIFO 调度设计](design/2026-11-11-multi-gpu-fifo-design.md)。创建前事务内检查配额,复用同幂等提交不二次扣额。 单文件仍512MiB;每用户保留素材100GiB,业务数据总预算2TiB。专用卷剩余低于max(50GiB,5%卷容量)或工作区预算不足时拒绝新计算/上传;为已接受任务预留预估输出与临时空间,实际超限终止自己的作业并明确失败。数字为起始配置,不是已验证产能,不允许耗尽整个服务器共享盘。 @@ -215,4 +215,4 @@ SSE事件保留30天,最小可重放cursor单独记录;早于它的客户端 | M4 | Vue草稿/任务中心/批量入口、账号/标签/分页 | 多标签冲突、断网刷新、额度拒绝、跨账号不可读、父子事件乱序 | | M5 | 公网接入与上线演练 | 真实MySQL及小规格模型端到端、真实默认规格三镜头、恢复演练、配额和外部Token;HTTPS入口SSE/Range通过 | -实施文件、接口签名和分任务回归见[执行计划](superpowers/plans/2026-11-10-cmvr-visual-v2.md)。当前已完成上游协议升级、正式库003迁移和私有网站部署;公网域名/HTTPS及专用数据库账号仍留在公开发布门槛内,实际验收记录与原设计目标分别列明。 +当前接口见[API 合同](api-contract.md),运行与升级约束见[发布检查清单](../deploy/release-checklist.md)。公网域名、HTTPS 及专用数据库账号仍属于正式生产发布前的配置事项;本文的设计目标不等同于当前环境的实测结果。 diff --git a/docs/工程结构与开发约定.md b/docs/工程结构与开发约定.md new file mode 100644 index 0000000..9d08efe --- /dev/null +++ b/docs/工程结构与开发约定.md @@ -0,0 +1,124 @@ +# 工程结构与开发约定 + +本项目保留前后端分离的单仓库结构。浏览器只调用业务 API;业务 API 管理账号、数据库、任务及文件;模型推理、共享 Qwen 和 CPU 配音是独立服务。目录调整不改变数据库表、接口、任务队列及现有数据。根目录的 `.editorconfig`、`.gitattributes` 统一源码编码和换行,避免 Windows 与 Linux 的格式反复变化。 + +## 目录和职责 + +```text +cmvr-visual/ +├─ frontend/ Vue 3 独立工程 +│ └─ src/ +│ ├─ api/ HTTP 客户端、各业务接口、统一 api 对象 +│ ├─ types/ 接口 DTO 和共享类型,不执行业务操作 +│ ├─ domain/ 时间线、视频参数等纯业务规则 +│ ├─ services/ 可靠提交、删除及浏览器端协调 +│ ├─ stores/ Pinia 状态、SSE 应用及会话隔离 +│ ├─ views/ 路由页面 +│ ├─ components/ 可复用界面组件 +│ ├─ utils/ 请求 ID、显示格式等通用小函数 +│ ├─ styles/ 按原级联顺序组织的样式 +│ ├─ App.vue 应用壳及会话生命周期 +│ ├─ main.ts Vue 启动入口 +│ └─ router.ts 页面路由 +├─ backend/ +│ ├─ app/ +│ │ ├─ main.py 稳定 ASGI 入口:app.main:app +│ │ ├─ bootstrap.py 应用组装、中间件和启动/关闭生命周期 +│ │ ├─ api/ 路由、认证依赖和 HTTP 中间件 +│ │ ├─ schemas/ 请求模型与字段校验 +│ │ ├─ core/ 配置、数据库连接、安全及维护基础 +│ │ ├─ models/ SQLAlchemy 表模型、统一 Base 注册 +│ │ ├─ domain/ 纯规则、任务状态和阶段执行上下文 +│ │ ├─ services/ 账号、素材、任务等业务用例 +│ │ │ └─ orchestration/ 持久协调器、工作流编排及资源准入 +│ │ └─ adapters/ +│ │ ├─ provider/ 模型服务协议和分工明确的适配器 +│ │ ├─ media.py FFmpeg、媒体探测和处理 +│ │ └─ storage.py 受限文件路径访问 +│ ├─ tests/ 业务及接口回归、结构合同基线 +│ └─ alembic/ 数据库迁移,历史版本保留 +├─ inference/ 独立 GPU 推理队列与守护服务 +├─ tts/ 独立 CPU 配音服务 +├─ scripts/ 启动、预检、验证和文档工具 +├─ deploy/ 部署样例与运行策略样例 +├─ docs/ 业务方案、操作手册与开发约定 +├─ outputs/ 用户业务成片、配音、配乐和字幕(不提交 Git) +└─ AGENTS.md 工作区协作规则,禁止自动提交 +``` + +前端测试继续与被测代码就近放置,名称为 `*.test.ts`。不为每个页面额外建立一套重复的目录;确有跨页面复用时才抽取组件或服务。 + +后端统一从 `app.models` 导入表模型。`Base.metadata` 一次注册全部业务表,Alembic、运行时和测试共用同一注册入口。历史迁移不得改为引用会持续变化的当前模型。 + +故事工作室另有 `domain/stories.py`(v3结构、确定性提示词/参考图片语义绑定与哈希),`services/stories/`(API服务、引用、候选、批准、冻结合成),以及候选/选择表模型。前端对应 `types/stories.ts`、`api/stories.ts`、`domain/stories/`、`stores/stories.ts` 和 `components/studio/`;`StoryStudioView.vue` 组合这三种模式。旧workflows模块保留v1/v2合同,不能把v3直接送入旧timeline编译器。 + +## 依赖和新增代码的落点 + +后端 HTTP 路由负责解析请求、取得用户、调用业务服务并组织响应;服务负责权限、事务和业务状态;适配器负责外部 HTTP、文件、媒体及模型协议。纯规则放 `domain`,不得依赖 FastAPI、SQLAlchemy、外部 HTTP 客户端或适配器。`bootstrap` 负责组合这些对象,避免业务代码反向导入应用入口。 + +模型调用通过 `app.adapters.provider.client.Provider` 进入。其子模块分别管理能力约束、传输、运行策略、远端文件、GPU、Qwen、语音及成片。共享的执行结果、阶段回调和媒体错误放在纯规则层,避免媒体工具和 Provider 相互导入。业务 API 本身不加载 GPU 模型。 + +前端页面调用统一 `api` 对象,HTTP 细节只在 `api/client.ts` 维护。纯 DTO 不导入 store 或发请求。可靠提交服务保留同一幂等键及精确序列化请求体;请求 ID 工具不反向依赖提交服务。Pinia 管理页面状态,用户切换时必须隔离旧会话的迟到响应。 + +新增一个功能时,通常依次补请求类型/校验、业务服务、接口和页面。不要把数据库查询塞回路由或把请求操作塞进纯类型文件,也不必为简单查询引入通用仓储框架。 + +## 关键约束及注释 + +注释优先解释“为什么”,重点保留以下约束: + +- 用户归属必须在列表、详情、下载、删除和共享导入中验证;管理员也不自动读取他人私有创作。 +- 任务状态和事件在事务内一同持久化,提交后才能通过 SSE 对外可见;断开浏览器连接不能取消持久任务。 +- 上游提交重试必须沿用同一幂等键和请求体。共享 Qwen 请求结果未知时不能直接重新发起或停止共享服务。 +- 物理文件删除与数据库提交不是同一原子操作;必须保留路径限制、引用检查及失败恢复顺序。 +- 镜头运行使用已冻结的参数和执行代次,不能根据后来的草稿修改重新解释运行中的任务。 +- 前端通过会话 epoch、单调版本/SSE 游标和删除标记,拒绝旧响应覆盖新状态或使删除记录复活。 +- 恢复已有草稿时,控件不得静默截断越界值;验证应明确提示。样式拆分必须保留级联顺序。 + +## 开发和验证 + +首次安装后端开发依赖: + +```powershell +Set-Location E:\workspace\hybrid\cmvr-visual +& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements-dev.txt +pnpm --dir frontend install --frozen-lockfile +``` + +后端业务检查在 `backend` 中运行。格式化只面向应用、测试和迁移加载入口,不重写冻结的历史迁移: + +```powershell +Set-Location E:\workspace\hybrid\cmvr-visual\backend +& ./.venv/Scripts/python.exe -m ruff check app tests alembic/env.py +& ./.venv/Scripts/python.exe -m ruff format --check app tests alembic/env.py +& ./.venv/Scripts/python.exe -m pytest -q +``` + +前端检查: + +```powershell +Set-Location E:\workspace\hybrid\cmvr-visual\frontend +pnpm test +pnpm build +pnpm format:check +# 需要统一格式时执行 pnpm format。 +``` + +在项目根目录运行本地启动器回归,它使用模拟进程和独立临时库,不连接正式模型: + +```powershell +& ./backend/.venv/Scripts/python.exe -m unittest discover -s scripts/tests -v +``` + +`test_architecture_contract.py` 对照合同快照检查 HTTP 路由及 MySQL 表定义,避免整理目录时意外改变合同。快照是必要测试夹具,不能在测试失败时直接覆盖为新结果。单元测试通过不能代替真实推理验证;一次性验证数据在测试通过后清理,不长期保存截图、日志、临时媒体及代理执行记录。 + +本机服务继续通过 `scripts/local_dev.py start|status|stop` 管理,正式部署继续使用 `app.main:app`。私有配置、模型密钥、运行数据及构建产物不属于源码。重构不迁移数据、不调整 GPU 优先策略、不重启共享模型。 + +## 版本控制 + +仅在用户明确要求时创建提交或推送。日常开发先保留工作区改动并报告验证结果,供用户检查。本轮重构不会创建提交、移动已有提交或配置远端仓库。 + +## 临时文件与业务数据 + +开发验证优先使用自动清理的临时目录和隔离数据。测试通过后清理本次临时脚本、截图、日志、媒体、数据库及打包文件;只保留复用的自动化测试代码和最小夹具。长期业务设计放在 `docs/design/`,过程计划和代理报告不作为交付内容。 + +`.local/workspace` 的素材与任务文件、`.local/config` 私有配置、`.local/backups` 数据库备份和媒体工具是运行数据与依赖,不能按测试文件删除。用户要求的业务成片及源音频字幕放在 `outputs/`。 diff --git a/docs/开发与验收记录_20261111.md b/docs/开发与验收记录_20261111.md deleted file mode 100644 index 47e1c94..0000000 --- a/docs/开发与验收记录_20261111.md +++ /dev/null @@ -1,46 +0,0 @@ -# 可配置时段与多镜头版本开发、部署及验收 - -2026-11-11,Asia/Shanghai。本轮在原项目、原数据库和原模型服务上增量更新,schema仍为003;没有新建第二个GPU worker。私有入口为 http://127.0.0.1:8000 ,项目代码位于`E:\workspace\hybrid\cmvr-visual`。 - -## 已完成 - -- 新增共享权威文件`/workspace/projects/llm-services/config/runtime-policy.json`。API和既有GPU worker热读取;当前`batch_window_enabled=false`,开发阶段批量全天可用。改为true恢复21:00–08:00后续阶段准入,当前阶段自然完成。文件缺失用生产默认,坏配置阻止新批量计算;工作流和编排新提交也需有效资源上限。原暂停、维护、停用、额度和外部用户优先仍生效。 -- schema2支持有序可变镜头、每镜头选用24–120帧、24fps,总帧数动态求和;默认资源上限120镜头,可配置1–1000。旧schema1三镜头、历史Run和生成哈希保持兼容。单次Wan仍生成121源帧,缩短选用时长是剪辑,不保证同比节省推理。 -- 镜头增删/排序/时长、动态音轨字幕范围、JSON导入导出、示例载入、超过shot_9后的数值顺序均已接通。新运行快照、依赖和合成输入依照分镜顺序。仅剪辑时长改变时可复用相同生成结果。 -- 普通成片编排移除24段/30分钟固定门槛,新提交受同一资源上限约束。已有工作流子任务可在上限降低后完成;新批次成员不能借内部标记绕过上限。输出大小、磁盘、源文件范围与执行超时继续保护服务器。 -- 选择旁白默认保留完整音频。超出成片范围会显示警告并阻止保存,直到用户增加镜头或明确裁剪。配音输入与后端2000字限制对齐。 -- 工作流页提供操作手册、鲲鹏步骤、20镜头100秒模板。另提供45秒紧凑版下载。HTML手册可在浏览器阅读/打印,Markdown可下载;生成脚本为`scripts/render_manuals.py`。 - -## 验证结果 - -| 范围 | 最终结果 | -| --- | --- | -| Linux后端完整回归 | 188 passed,20 subtests passed | -| 前端完整回归 | 79 passed,typecheck/Vite构建通过 | -| Linux推理服务完整回归 | 149 passed,120 subtests passed;1条Starlette弃用提示 | -| 真实FFmpeg专项 | 6 passed;包括横竖版/适配、短源拒绝及4镜头16秒完整解码 | -| 实机网页 | 20镜头载入、增删排序、时长、保存/刷新、桌面和390×844手机滚动通过,无页面异常 | -| 旁白交互 | 44.425秒音频选进15秒草稿仍保留44425ms,保存前阻止;选入45秒草稿可完整容纳 | -| 实际16秒影片 | 1920×1080、H264、384帧、24fps、5,699,705字节;完整解码与浏览器15.5秒seek通过 | -| 配置热切换 | API与GPU实际同时读到true/false,最终恢复false,无重启共享服务 | -| 关闭HTTP | Qwen批次在原调用端关闭后完成,答案15;CPU合成与配音持久执行 | - -正午准入、08:00边界、坏配置、旧水位、启动前重新检查和启动后自然完成使用注入时钟/隔离Linux子进程验证。实机部署发生在夜间;没有修改宿主时间、伪造生产GPU状态或声称经历了真实白天/08:00边界。推理首次选错缺NumPy的轻量测试环境,已改用具备验证依赖的环境完整重跑通过,未修改模型运行环境。 - -独立审查发现的批次绕过上限问题已经RED→GREEN修复,并验证混合批次失败原子回滚、原键重放和已接受工作流继续执行。测试集合分别报告,不相加当作独立用例总数。 - -## 已准备的鲲鹏素材 - -- 草稿“鲲鹏·20镜头100秒示例(未运行)”:`265761009d2346598065033c377258b0`。 -- 草稿“鲲鹏·45秒旁白版(未运行)”:`cecafd1041a6465eb3982a0449717208`,已关联当前管理员的完整旁白。 -- 旁白“鲲鹏完整旁白(开发验收).wav”:203字,zm_yunxi、速度0.85,实际44.425秒,24kHz。素材编号`34e1c004c3214f298d201d3cc22d18a9`。 - -这两份草稿都没有启动全片生成。100秒是更舒缓叙事的视觉模板,不能把44秒旁白与100秒字幕直接当作已同步成片。45秒版更适合先测试完整故事;两版字幕都需试听校准,参考图片还需选择。未进行20个鲲鹏镜头的整片质量验收。 - -## 发布与数据保护 - -发布前确认本应用无运行/排队模型任务、无未知执行,保存SQL、上游SQLite和业务文件/旧源码联合恢复点,位于受保护目录`/root/cmvr-visual-v3-20261111`。清单记录字节数与SHA256,SQLite完整性为ok。旧API/前端镜像保留为`pre-v3-20261111`;本轮未重复上轮已完成的全量隔离恢复演练。 - -仅更新本应用API/前端容器,并在空闲期停止/重启既有模型服务的API/worker子进程以加载调度代码。共享Qwen两个容器、llmuser工作区容器、GPU监管和TTS容器ID及启动时间均未变化。未重建工作区、未调整其他用户GPU任务、未变更数据库密码或对互联网开放端口。 - -证据:`qa/v3-deployment.json`、`qa/v3-policy-hot.json`、`qa/v3-live.json`、`qa/v3-browser*.json`及相应截图。实际16秒影片副本在`qa/generated/v3-long-video-16s.mp4`(不提交Git)。配置更改与鲲鹏完整步骤见[操作手册](操作手册_20261111.md)和[制作指南](鲲鹏长视频制作指南_20261111.md)。 diff --git a/docs/操作手册_20261111.md b/docs/操作手册_20261111.md index 0502890..9deec1b 100644 --- a/docs/操作手册_20261111.md +++ b/docs/操作手册_20261111.md @@ -1,12 +1,39 @@ # CMVR Visual 操作手册 -适用版本:2026-11-11的可配置时段、多镜头、私有内容删除与共享素材版本。模型在192.168.28.10运行,项目在`E:\workspace\hybrid\cmvr-visual`。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。 +“创作”新增多图参考的图生图和可选择多个人物的视频替换入口,操作步骤、模型区别及配置见[图生图与视频人物替换操作手册](图生图与视频人物替换操作手册_20261112.md)。 + +新增“故事”入口的基准板、跨镜头角色/形态引用、首帧与视频人工确认流程,见[锚定故事工作室操作手册](锚定工作室操作手册_20261111.md)。首次使用可从该手册第 0 节开始,按“两个 5 秒镜头 → 10 秒成片”逐步完成新建、保存、角色绑定、首帧确认、视频选片、字幕音轨和合成下载;故事编辑页顶部“使用手册”可直接打开网页版本。候选数是 1–4 的数值框,只影响下一次模型生成,人工导入每次为 1 个。希望一次自动生成并在之后局部修改时,在故事中启用“可编辑自动成片”,操作见第12节。独立“工作流”“批量”“成片”页面已移除;旧链接会转至故事或任务,既有数据与共享API保留。 + +适用版本:2026-11-13,含故事可编辑自动成片、容器内滚动、逻辑文件夹、批量整理、可配置时段、私有内容删除与共享素材。模型在192.168.28.10运行,项目在`E:\workspace\hybrid\cmvr-visual`。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。 + +## 0. 六项业务能力与生产流程对应关系 + +六项能力的基础功能、批量生成、人工编排与选片确认均已实现。这里的“审核”是创作者在自己的故事中查看候选、确认首帧、确认视频和检查成片;当前没有单独的“审核中心”、指定另一账号审批或成片终审发布状态。 + +| 功能需求 | 在哪里操作 | 当前实现与边界 | +| --- | --- | --- | +| 图像生成 | 左侧“创作”→“图片”;路径 `/create/image` | 输入提示词生成图片;多图参考编辑另见“图生图”。没有风格 LoRA 管理平台 | +| 视频生成 | “创作”→“视频”;路径 `/create/video` | 文生或首帧图生单镜头,最长约15秒;长故事使用“故事”。生成片段默认无声 | +| 数学推演 | 左侧“推演”;路径 `/math` | 输入问题,输出解题文字和文本/JSON素材;由模型作答,没有符号计算验证或形式化证明 | +| 缺陷样本生成 | “创作”→“缺陷样本”;路径 `/create/defect` | 参考图加缺陷描述,生成合成图与Canny控制图;控制图不是缺陷真值掩膜,不能当作完整标注数据集 | +| 素材结构化 | 左侧“理解”;路径 `/analyze`;声音转写在 `/audio` | 图片或视频抽帧输出主体、场景、OCR、标签和结构化JSON;语音转写是另一个任务。没有完整镜头切分或自动标签回写 | +| 成片合成 | “故事”→目标故事→“03 成片” | 视频排序、裁切、画幅适配、单音轨和人工字幕,输出MP4;不含多轨混音、自动配乐、转场编辑和PPTX课件导出 | + +| 要完成的工作 | 应使用的入口 | +| --- | --- | +| 角色/场景基准、首帧审核、视频候选比较、逐镜选片后合成 | “故事”→打开故事→“01 基准板 / 02 分镜 / 03 成片” | +| 填好一组镜头后自动生成并合成,完成后再审片 | “故事”→“启用可编辑自动成片”→“自动生成初稿并成片” | +| 故事自动生成按批量策略排队 | 可编辑自动成片中选择“批量队列”,再提交素材或成片生成 | +| 新故事的所有镜头批量生成首帧或视频候选 | 故事内“02 分镜”→“全故事候选计划” | +| 使用已有视频做后期 | 故事“02 分镜”导入视频并确认选片→“03 成片”调整时间线并合成 | + +当前开发环境关闭批量时段限制,可以全天提交并等待空闲资源。正式启用夜间开关后,现有规则只约束“批量队列”,交互队列仍全天可用;不能把现有开关理解为“所有模型调用只能夜间运行”。日间审核和后期本身不需要改这个开关。生产节拍统计、严格夜间模式及多人审批的完善方案见文末第11节。 ## 1. 登录与基本流程 -现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。 +当前网页入口为 http://127.0.0.1:5173 ,业务接口在本机 http://127.0.0.1:8000 运行。模型和配音分别通过内网 HTTP 入口 `192.168.28.10:18190`、`192.168.28.10:18192` 连接,使用本机项目无需建立 SSH 隧道。网页地址用于当前开发机本地访问;网页打不开时先检查本地前端和后端是否已启动,模型连接问题可在“创作服务状态”查看。 -使用分配的账号登录。默认管理员名为`admin`,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。 +使用分配的账号登录。默认管理员名为`admin`(可在头像菜单修改用户名),初始密码以私有部署配置为准;点击左下角头像,在“退出登录”上方选择“修改密码”。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。 一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。 @@ -18,14 +45,12 @@ | --- | --- | --- | | 创作:图片 | Qwen-Image文生图 | 提示词、尺寸、种子等 → 图片 | | 创作:视频 | Wan单镜头文生/图生视频 | 提示词、可选参考首帧 → 自选1–15秒无声片段,默认5秒,可选增强 | -| 创作:条件样本 | SDXL+Canny ControlNet | 参考图片、提示词、控制强度 → 合成图及Canny控制图 | -| 工作流 | 多镜头故事自动逐镜生成并合成 | 每镜头提示词/参考图/选用时长 → 一部多镜头影片 | +| 创作:缺陷样本 | SDXL+Canny ControlNet | 参考图片、提示词、控制强度 → 合成图及Canny控制图 | +| 故事 | 可编辑自动成片,或候选生成与人工审核 | 自动生成后局部修改,或基准板 → 首帧确认 → 视频选片;统一在“03 成片”处理时间线 | | 声音 | 中文配音、Whisper转写 | 文本 → WAV;音频/有声视频 → 转写结果 | | 推演 | 复用共享Qwen做文本推演 | 问题 → 文本解答 | | 理解 | 图片理解、视频抽帧分析 | 素材 → 场景、主体、OCR、标签等 | -| 成片 | 编辑已有视频素材 | 排序、裁切、单音轨、人工字幕 → MP4 | -| 批量 | 混合提交任务或已保存工作流 | 任务清单 → 持久批次,运行时段服从配置 | -| 素材 / 任务 / 账户 | 管理结果、进度、用户和令牌 | 见下文 | +| 素材 / 任务 / 账户 | 管理结果和进度;管理员在账户页管理用户 | 见下文 | ## 3. 图片、短视频和条件样本 @@ -34,77 +59,94 @@ 1. 进入“创作”,切换到图片。 2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。 3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。 -4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。 +4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为故事的参考图片使用。 ### 单镜头视频 1. 切换视频模式,写一个镜头中的主体动作与镜头运动。 2. 可选择参考图片作为首帧;文生视频可不选图。 3. 在视频时长中选择5秒、10秒、15秒,或输入1–15的整数秒,默认5秒。再按需要调整参数和1080p画质增强开关。当前单次接口最多361帧、24fps;增加提示词长度不会自动延长单镜头。 -4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。 +4. 需要更长故事时进入“故事”增加镜头;已有视频可在故事“02 分镜”导入并确认选片,再去“03 成片”拼接。 -2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过。网页现已接入最长15秒单镜头。原生源片段采用`4n+1`帧,选择15秒时输出361帧,实际约15.04秒;工作流合成会裁到选用的精确帧数。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。较长镜头通常需要更多时间和资源,增强另有耗时。 +2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过。网页现已接入最长15秒单镜头。原生源片段采用`4n+1`帧,选择15秒时输出361帧,实际约15.04秒;故事合成按设定裁到选用的精确帧数。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。较长镜头通常需要更多时间和资源,增强另有耗时。 ### 条件样本 选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。 -## 4. 多镜头工作流 +## 4. 故事中的多镜头创作 -### 新建、编辑和保存 +### 可编辑自动成片 -1. 打开“工作流”,点击“新建”,填写故事名称。 -2. 每个镜头填写提示词,选择种子和可选参考图片。 -3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。 -4. 每镜头选择1–15秒的选用时长,页面可按0.25秒调整;JSON接受24–360的整数帧。5秒以内继续生成121帧源片段再裁取,以兼容既有草稿和复用规则;超过5秒时按该镜头需要生成更长的原生片段,10秒/15秒分别生成241/361帧。不同镜头各用自己的生成长度,不会统一生成最长镜头。改变长镜头长度可能使原生成结果不再符合复用条件,需要重新生成。 -5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。 -6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。 +1. 打开左侧“故事”,新建或打开故事,填写名称、基准板和镜头并保存。 +2. 点击“启用可编辑自动成片”。在“02 分镜”编辑画面、运动、选用区间和旁白;在“03 成片”配置音轨与字幕,时间线只在这里显示。 +3. 在自动成片工具条选择“交互队列”或“批量队列”,点击“自动生成初稿并成片”。正常流程会生成所需素材再合成,不等待逐镜人工确认。 +4. 检查完成成片;需要修改时编辑对应镜头、旁白或字幕,点击“生成修改部分并成片”。运行进度与成果可在历史中的“查看运行进度与成果”或“任务”查看。 -总时长由镜头选用时长相加,24fps下`总秒数=总帧数÷24`。例如5秒、10秒、15秒三个镜头合计30秒、720帧;20个5秒镜头合计100秒。音轨和字幕需要匹配调整后的总时长。 +完整的局部重生成、字幕保护和版本恢复规则见第12节。自动与人工候选是两条创作路径,不要把自动生成按钮和人工“确认首帧 / 确认选片”步骤混用。 -默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。 +### 分镜滚动与时间范围 -### 音轨和字幕 +“02 分镜”内容超过工作区时,只在对应编辑容器内滚动,故事标题和步骤导航保持可见。鼠标移入容器时显示滚动条,移出后隐藏;键盘聚焦时也可显示,触屏直接滑动。鼠标放在需要查看的镜头列表、编辑区或候选区内再滚动;声音和字幕时间线在“03 成片”,不必寻找页面底部的独立成片入口。 -工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。 +总时长由镜头选用帧数相加,24fps下`总秒数=总帧数÷24`。例如5秒、10秒、15秒三个镜头合计30秒、720帧。音轨、旁白和字幕须匹配总时长;镜头数、磁盘、任务额度和超时仍受环境配置保护。 -- 源入点/出点单位是**毫秒**,表示取音频的哪一段。 -- 偏移单位是**帧**,表示从成片的哪一帧开始播放。24帧=1秒。 -- 选段长度加偏移必须放得进成片,源出点不能超过音频真实时长。过长不会被悄悄截断;应增加镜头、缩短旁白或重新配音。 -- 旁白比成片短时,尾部补静音。当前不提供多音轨混音、自动配乐或自动对齐旁白。 +### 编排审核在哪里,怎么操作 -人工字幕的开始/结束是整片帧号,区间为`[开始帧,结束帧)`。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。 +需要生成后由人把关再进入下一步时,使用故事的人工候选流程;本小节对应尚未启用可编辑自动成片的故事。推荐按下面顺序完成一部片子: -### 运行、复用与恢复 +1. 打开“故事”列表,新建故事或打开已有故事,设置故事归属文件夹和“成果保存到”。 +2. 在“01 基准板”填写故事共同设定,建立场景、角色和形态并选择参考图片,点“保存故事”。 +3. 在“02 分镜”添加镜头,填写画面与动作,设置镜头顺序、生成源长度和选用区间;调整后再次保存。这里的顺序和裁剪就是编排。 +4. 选择“1 首帧生成 / 导入 → 确认首帧”,生成或导入候选。任务完成显示“可复核”后,点缩略图预览,必要时点“对比”,在满意候选卡片上点“确认首帧”。仅预览不算确认。 +5. 选择“2 视频生成 / 导入 → 确认选片”,生成或导入视频候选。检查人物、动作、教学内容、实际源长度和选段后,点“确认选片”。已有人工视频可以直接导入复核,不必先生成首帧。 +6. 每个镜头都须确认有效视频。对不满意的结果,可重新生成当前镜头或导入替代视频;失败候选可点“重试为新候选”。需要撤销决定时点“清除确认”。生成成功不会自动确认,也不会替换之前的选择。 +7. 在“03 成片”设置画幅、裁剪适配、单音轨和人工字幕,展开“查看镜头选片检查”,确认没有“需要有效选片”,然后保存故事并点“冻结素材并合成”。合成沿用“02 分镜”选择的队列;正式夜间限制开启而日间要做CPU合成时,先在“02 分镜”切回“交互队列”,再进入“03 成片”提交。缺少有效选片时服务端会拒绝合成。 +8. 成功后在“成片预览”点“播放成片”“新窗口播放”或“下载成片”。再次编辑不会改变已冻结的历史成片;修改了会使选片过期的设定时,须重新复核。 -点击“保存并运行”。服务器冻结本次参数和修订,独立镜头按就绪顺序分配到空闲GPU并行生成,全部完成后再按镜头顺序合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。 +首帧/视频的确认、清除和替换会记录版本及操作者。现有权限仍按账号隔离:管理员不能直接审核另一账号的私有故事。当前也没有成片“送审、驳回、终审通过、发布”的独立流程。逐字段操作与失效规则见[锚定故事工作室操作手册](锚定工作室操作手册_20261111.md)。 -- “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。 -- “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。 -- “重试此阶段”:仅用于允许安全重试的失败步骤;其他成功镜头保留。 -- 修改草稿后再次运行,可在复用下拉框选择旧Run。只有生成输入一致、产物仍存在且校验通过的成功镜头可复用。提示词、参考图、种子、画幅变更会使对应镜头重新生成;单纯选用时长变更可复用原始生成片段再剪辑。 -- “同步”重新读取后台状态。结果未知/需人工确认表示远端执行结果未确认,不应靠反复提交规避。 +### 旧工作流兼容说明 -JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。 +原独立工作流页的草稿、冻结运行、镜头复用和JSON合同继续保留在后端;删除页面不会删除历史数据。旧三镜头和可变多镜头数据仍按原合同读取,详情见[API示例](API-examples.md)和[共享契约](api-contract.md)。旧工作流JSON不是当前故事页可直接导入的模板;新项目按上面的故事流程建立,旧运行进度与成果到“任务”查看。 ## 5. 声音、推演与理解 “声音”选择“配音生成”,输入不超过2000字,选择`zf_xiaobei`或`zm_yunxi`,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。 -转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。 +转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成故事分镜的功能,也不保证专业数学结论正确。 -“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。 +“推演”的具体步骤:进入左侧“推演”→填写问题和所需输出长度→点“开始推演”→在当前结果或“任务”查看解题内容→复核后下载文本/JSON,或将需要的文字用于文案、字幕和配音。当前没有把数学答案自动转换成分镜或PPTX的按钮。 + +“理解”的具体步骤:进入左侧“理解”→上传或选择本人的图片/视频→视频可设置1–12张采样帧→点“解析素材”→到当前结果或“任务”查看主体、场景、OCR、标签及采样时间→在“素材”查看或下载结构化JSON和抽帧结果。它只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。需要声音内容时,另外在“声音”选择转写。 + +理解结果中的标签不会自动回写源素材的检索标签;复核后,在源素材预览中编辑标签并保存,再用素材库的标签筛选。生成结果仍须人工检查,特别是教学数学结论和工业缺陷标注。 ## 6. 成片、素材与任务管理 -“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。 +已有视频片段时,进入故事“02 分镜”,导入视频候选并确认选片,调整顺序和选用范围,再到“03 成片”处理音轨、字幕并合成;无需独立成片页面。可编辑自动成片的素材绑定和时间线操作见第12节。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件;裁剪范围必须在真实媒体范围内。 ### 我的素材与共享素材库 -普通账号和`admin`在“我的素材”、任务、工作流和批量记录中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。 +普通账号和`admin`在“我的素材”、故事、任务及历史运行中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。 “我的素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找,也可修改名称和标签。“共享库导入”来源用于查找从共享库取得的个人副本。 +### 文件夹与批量整理 + +文件夹用于项目内分类。移动分类、改名不会移动磁盘文件,也不会改变素材编号和故事引用。旧素材、任务和故事先显示在“未分类”。 + +1. 在素材库顶部“浏览目录”选择文件夹。选择“全部文件夹”或“未分类”时,点击“新建文件夹”创建根目录;选择一个已有文件夹后,会出现“新增子文件夹”“编辑文件夹”“删除文件夹”三个操作。名称、父目录等字段在操作弹窗中填写。 +2. 进入一个文件夹后上传,素材自动归入该文件夹。整理已有素材时勾选卡片左上角;选中后才会显示“整理到”及批量按钮。“移动分类”替换原有文件夹归属,“加入文件夹”保留原归属,允许同一素材同时用于故事 A 和故事 B,无须复制原文件。 +3. 可逐项勾选,也可“选择本页”。点击“发布到共享库”或“批量删除素材”后,确认本次总数;完成后显示成功和失败数量。仍被任务或故事引用的素材不会被强行删除,失败项保持勾选,可展开“查看失败原因”。成功发布的是独立共享副本。 +4. 新建故事时填写故事名称,默认自动新建同名文件夹;取消“自动新建同名文件夹”后可选择已有目录或未分类。故事工作室顶部可修改“故事归属”,修改后保存故事。 +5. 创作、声音、推演、理解和故事生成均可选择“成果保存到”。故事默认使用自己的文件夹;候选、批量候选和成片也可另选目录。提交后目标已固定,之后再移动故事不会改变已排队任务的成果位置。 +6. 任务中心可以按目录筛选并整理任务;移动任务分类不会改写已冻结的成果目标。素材选择器也可按目录找图、找视频或音轨。共享素材导入时可选择放入哪个个人文件夹。 + +“删除文件夹”只删除分类及其子分类,保留素材、任务、故事和实际文件;仅归属该目录的内容回到未分类,同时属于其他目录的素材保留其他归属。删除实际素材仍使用素材删除操作和原有引用检查。 + +素材库默认每页 48 项,可以切换 24 / 48 / 96 项;素材卡片已缩小,窄屏自动换行并保留两列预览。没有选中素材时,批量工具会收起以留出更多浏览空间。 + 1. 分享时,在自己的素材卡片或预览中点击“发布到共享库”,阅读并确认发布范围。系统复制原件和当前名称、标签等信息,生成一份独立的共享副本;所有已登录用户均可查看、下载和导入。 2. 在“共享素材库”预览的内容是只读共享副本。点击“导入我的素材库”后,会创建属于当前账号的独立私有副本,可再编辑、删除或用于创作。创作中的素材选择器也可切到“共享素材”,选择后先导入,再将个人副本用于当前输入。 3. 发布者可通过“我发布的”筛选并打开预览,点击“撤回共享”。撤回后其他用户无法继续查看或导入该发布,已经导入的个人副本仍然保留。删除私有原件也不会删除已发布的共享副本或他人的导入副本;要停止共享,需要单独撤回。 @@ -113,15 +155,15 @@ JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本 ### 删除素材和记录 -自己的素材卡片/预览、任务卡片/详情、工作流草稿、运行卡片和批量记录均提供删除入口。删除记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复。 +自己的素材卡片/预览、任务卡片/详情及可管理的运行记录提供删除入口;历史工作流草稿和批次的删除合同仍保留在API。任务、工作流和批量记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复;素材删除则同步移除文件和数据库文件记录。 - 删除独立Job只删除任务记录,已经生成的素材继续保留在“我的素材”。要清理这些素材,需要再逐项删除素材。 -- 删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。 -- 工作流子任务或批量成员不能单独删除,按页面提示到父运行或批次管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。 +- 历史数据的API归档规则保持不变:删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。 +- 工作流子任务或批量成员不能单独删除,按提示通过父运行或批次的受支持接口管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。 - 活跃记录须先取消,等待执行退出及资源清理确认后再删。点过“取消”不表示已完成清理,仍显示排队、执行中或取消中时不能直接删除。 - 删除素材若返回409引用冲突,先从草稿解除引用并保存;冻结运行中的引用需要删除相关运行或父批次。活动任务使用中的素材应先取消任务、等待退出,再按依赖关系处理。不要直接去磁盘删除文件。 -素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做`dry-run`盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。 +素材删除成功后,会同步移除该素材的原文件、缩略图及数据库文件记录,释放对应素材占用。撤回共享时删除共享库中的独立快照;已经引用到个人素材库的副本继续保留,由引用者独立管理。文件被占用或暂时无法删除时会提示失败,可稍后重试。旧版本遗留的软删除文件仍由运维清理流程处理。 “任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。 @@ -133,7 +175,44 @@ JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本 ## 7. 批量与开发/生产配置 -“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。 +### 7.1 可编辑自动成片怎样使用批量队列 + +1. 打开“故事”并启用可编辑自动成片,完成需要生成的镜头、声音与字幕设定。 +2. 在自动成片工具条的执行方式中选择“批量队列”。选择队列本身不会提交任务。 +3. 按目标点击“自动生成初稿并成片”“生成修改部分并成片”或“仅生成素材”。实际生成前会保存并校验,后端继续按原资源和时段策略持久排队。 +4. 在版本与运行历史点击“查看运行进度与成果”,或进入“任务”跟踪;编辑与最终成片仍回原故事处理。 + +独立“批量”页面已移除,“批量队列”执行模式继续保留。关闭网页不会取消已经接受的任务;交互队列仍适用于全天等待空闲资源的提交。 + +### 7.2 旧通用批次与工作流API + +原提示词JSON清单、多个旧工作流混合批次及其历史数据仍由共享后端API保留,独立页面移除不改变接口合同。当前网页不再提供“快速整理”“加入已保存工作流”或“类型化清单JSON”表单;新手请使用故事流程,不要寻找这些旧按钮。 + +已有API集成继续使用原幂等键、版本校验及归属检查,通用批次仍为1–100个清单项,部分生图类型的单项`count`另有1–4限制。草稿、冻结运行和批次的控制/归档仍遵守父子引用规则;技术用法见[API示例](API-examples.md)和[共享契约](api-contract.md)。故事编号不能直接充当旧工作流编号。 + +### 7.3 怎样批量生成一个故事的所有镜头 + +1. 在故事的人工候选流程中打开“02 分镜”,完成所有镜头的设定并点“保存故事”;启用自动成片的故事使用7.1节。 +2. 在首帧阶段选择生成方式、候选数(1–4)和“批量队列”,点“全故事候选计划”。例如20个镜头、候选数2,会安排40个当前阶段的候选。 +3. 等首帧候选可复核后,逐镜预览并点“确认首帧”。不满意的镜头单独点“生成当前镜头”,避免为所有镜头重复付出生成时间。 +4. 各镜头首帧有效后,切到视频阶段,检查各镜头生成源长度覆盖选段;选择候选数和队列,再点“全故事候选计划”。 +5. 视频生成完成后逐镜“确认选片”,进入“03 成片”补音轨、字幕并冻结合成。 + +“全故事候选计划”一次只安排当前首帧或视频阶段,不自动确认,不自动接着生成下一阶段,也不自动跳过已经有候选的镜头。“全故事”指范围,“批量队列”指调度方式,两者必须分别选择;默认的交互队列不会因为点了“全故事”就变成夜间批量。 + +故事候选计划的上限由镜头数、候选数和账号容量共同决定,不套用通用JSON清单的100项上限。故事候选的查看与审核以原故事“02 分镜”为准;独立批量页已移除,不要把候选编号当普通任务编号使用。 + +### 7.4 暂停、继续、取消与日夜生产节拍 + +- 历史通用批次的暂停、继续和取消仍通过原批次控制API处理;独立“批量记录”页面已移除。暂停只阻止后续准入,当前已运行阶段自然完成;继续不自动重做失败成员。已取消的批次不能靠继续恢复。 +- 故事候选可在“任务”查看生成状态,回原故事复核;旧工作流运行还可在失败的可重试阶段使用“重试此阶段”。不明远端结果或清理未完成时,先查明状态,不能反复创建替代任务。 +- 时段限制关闭时,以上批量流程都可在开发日间运行。启用后,新批量任务/阶段只在21:00–次日08:00准入;08:00时已运行阶段继续完成,后续阶段等待下一窗口。 +- 这里的GPU执行单元包括同一个视频任务的生成与可选画质增强,08:00后可继续完成整条处理流程;不在生成与增强之间强制停下,下一镜头等新的执行单元才重新判断窗口。 +- 生产排期中,单人审核可以在日间完成,FFmpeg剪辑合成可采用交互方式。需要首帧人工把关的新故事通常是“第1天编排 → 第1夜首帧候选 → 第2天确认首帧 → 第2夜视频候选 → 第3天审片、字幕与合成”,不是同一夜自动越过人工确认。 +- 若已有批准首帧,可直接从视频批量阶段开始;若接受生成后再统一审片,可以在故事中使用可编辑自动成片和“批量队列”,次日再检查成片。 +- 当前没有按夜统计合格镜头产量、审核积压和次夜产能预测的生产看板。排期先依据任务实际耗时、合格选片数及其他用户占卡情况安排,不能把四张GPU当作每晚固定满额可用。 + +### 7.5 管理员怎样切换开发与生产时段 权威配置位于容器内: @@ -179,13 +258,19 @@ bye 切回开发模式时把上传源文件改为`runtime-policy.development.json`,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。 -## 8. 账号、令牌和未确认提交 +## 8. 用户管理与修改密码 -在“账户”修改密码;管理员可创建、停用用户。停用用户不代表去停止共享模型服务。包括`admin`在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。 +“账户”页面仅管理员可见,普通用户不能进入该页面或调用用户管理接口。页面只提供新增、禁用/启用和删除用户;不能禁用或删除当前登录的管理员账号。新增用户的初始密码允许6–256个字符,包括`123456`这样的6位数字。 -机器令牌用于外部系统调用,创建时按用途选择权限,令牌仅显示一次,立即安全保存;撤销后失效。不要把令牌放进截图、公共仓库或浏览器地址。 +禁用用户后,该账号不能登录,已有登录会话立即失效,相关任务暂停准入;素材、故事、工作流与任务记录仍保留。重新启用后,用户重新登录即可继续使用原资源;用户自己设置的暂停不会被自动解除。停用用户不会停止共享模型服务。 -“未确认提交”表示客户端没有确认服务器是否已接受。先查询原提交键,确认后再恢复;不要换一个键重复创建。接口细节见`docs/api-contract.md`和FastAPI接口文档。 +删除用户将永久清理该账号、自有素材(含共享发布)、故事、工作流、批量和任务记录及对应本地文件,无法恢复。其他用户已经独立导入的副本保留。若任务或上传尚未结束,会先停用账号并请求取消,提示等待清理;确认执行停止后点击“重试删除”,清理成功才会显示删除成功。 + +所有登录用户都可点击左下角头像,选择“修改密码”,输入当前密码、新密码和确认新密码后点击“确定”。新密码须为12–256个字符,修改成功后重新登录。账户页不再显示改密、API令牌或未确认提交管理区。 + +头像菜单还提供“修改用户名”:填写新的登录用户名和当前密码,确认后使用新用户名登录。用户名为3–64位小写字母、数字、点、下划线或横线,不能与已有账号重复;显示名保持独立。修改后当前登录会话、账号ID、角色及已有资源均保留。管理员修改用户名后,重启不会重新创建旧用户名的初始管理员。 + +包括`admin`在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。 记录删除后,原幂等提交的恢复或重放会返回`410 resource_purged`,表示原结果已归档,不能通过重放把已删除记录恢复。只有确实要创建一项新工作时,才发起新的提交。 @@ -194,10 +279,12 @@ bye | 数据 | 实际位置与用途 | | --- | --- | | 网站业务数据 | MySQL `192.168.28.10:3306/cmvr-visual`,保存用户、素材元数据、任务、工作流、批次、共享发布和审计等网站业务记录 | -| 媒体文件 | 服务器宿主机`/data/llmusers/llmuser/workspace/cmvr-visual/assets`,保存上传、生成、共享发布和导入副本的媒体原件/缩略图;容器内对应`/workspace/cmvr-visual/assets` | +| 当前本地媒体与任务工作文件 | `E:\workspace\hybrid\cmvr-visual\.local\workspace\cmvr-visual\assets` 和同级 `jobs`,保存网页上传、归档结果、共享发布及导入副本;访问通过受认证的业务API | +| 服务器推理工作文件 | 模型API管理自己的输入、尝试目录和输出,本地业务API通过HTTP上传/归档;它与本地素材目录是两份独立存储 | +| 业务交付副本 | `E:\workspace\hybrid\cmvr-visual\outputs`,例如保留的鲲鹏成片、音频与字幕;这里的副本不是网页素材库的数据库来源 | | GPU调度恢复 | 推理服务自己的SQLite,仅负责独立GPU执行队列与恢复,不是网站业务数据库,也不保存网站的用户、工作流和共享素材业务 | -网页所见的素材列表来自MySQL元数据,视频、图片、音频文件在上述媒体目录。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。 +网页所见的素材列表来自MySQL元数据,当前业务媒体存放在本机上述目录。后续正式部署的路径由当时配置决定,不能把旧服务器部署路径当作当前素材库位置。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。 ## 10. 常见问题 @@ -211,10 +298,56 @@ bye | 转写没有声音 | 检查源视频是否有音轨;模型生成片段默认无声 | | 结果未知/需要人工确认 | 运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止 | | 删除返回409 | 检查活动执行、父级控制和引用依赖,先取消并等待退出,或解除引用/删除相关父记录后重试 | -| 删除后磁盘没有立即下降 | 软删除保留文件;GC默认dry-run,默认14天保留期后仍需运维维护清理 | +| 素材删除失败或仍占空间 | 先解除任务和工作流引用;文件被占用时稍后重试。旧版本遗留文件由运维清理;模型临时缓存和共享副本独立管理 | | 找不到其他账号的旁白或参考图 | 请原作者发布到共享素材库,再导入自己的私有副本;管理员也不能直接读取他人的私有素材 | | 输出过大或空间不足 | 减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列 | -完整案例见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。模板在`frontend/public/examples/kunpeng-storyboard.json`,原文旁白在同目录的`kunpeng-narration.txt`。 +历史分镜、JSON格式与旁白实测参考见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。旧模板在`frontend/public/examples/kunpeng-storyboard.json`,当前故事页不提供直接导入;原文旁白在同目录的`kunpeng-narration.txt`。 另提供`kunpeng-storyboard-45s.json`,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。 + +## 11. 尚未覆盖的生产管理需求与完善方案 + +基础六项能力和“批量生成→人工编排审核→合成”的流程已经具备。以下是需要区分的完善项: + +| 尚未覆盖或需完善的部分 | 当前可用方式 | 落地方向 | +| --- | --- | --- | +| 后续若在任务中心展示候选批次的详情跳转 | 当前回故事“02 分镜”查看与审核,独立批量页已移除 | 保留候选所属故事、镜头和阶段信息,按成员类型跳转,候选尚未派发时也能查看计划 | +| 所有模型调用严格限于夜间 | 目前仅批量受夜间开关约束,交互全天 | 增加明确的时段作用范围,API与推理worker一致判断;日间编排、审核和CPU后期保留可用 | +| 以实测夜间产量安排生产节拍 | 人工查看任务、选片和资源状态 | 汇总逐夜成功镜头、合格选片、执行耗时和审核积压,以有效历史样本给出区间估算 | +| 编导提交给另一个审核人、驳回意见、成片终审 | 本人预览和确认,按账号隔离 | 作为可选扩展增加版本化送审单与明确授权;不开放管理员对全部私有内容的默认访问 | + +完整的代码落点、接口、数据保护、实施顺序及验收条件见[生产流程完善方案](design/2026-11-12-production-workflow-design.md)。这些是待实施设计,当前页面没有的按钮不能按方案描述操作。教学数学验证、缺陷真值标注、多轨混音等也未实现,但它们是对应基础能力的后续专项,不把现有模型输出冒充这些成果。 + +## 12. 可编辑自动成片(代码版本007) + +本节适用于已完成007迁移并启动新版API的环境。真实数据库和运行服务不会由代码更新自动迁移;先按发布清单完成联合备份、升级和业务API切换。自动流程继续使用现有队列及资源策略。 + +### 首次生成 + +1. 从“故事”新建或打开故事,配置画面、场景、角色、镜头与时长,点“保存故事”,再点击“启用可编辑自动成片”。 +2. 在“02 分镜”编辑镜头,按需输入旁白。内容超出时在分镜编辑容器内滚动,移入显示滚动条、移出隐藏;故事只在“03 成片”显示音轨与字幕时间线。 +3. 声音选择静音、人工单音轨或生成旁白;字幕选择关闭、人工、旁白文案或AI补齐文案。配音需真实TTS服务通过部署验收,轻量健康检查不代替声音质量验收。 +4. 选择“交互队列”或“批量队列”,点击“自动生成初稿并成片”。系统保存版本、检查计划,再生成和校验素材、字幕及音轨,最后合成。正常阶段不等待逐镜头确认,关闭网页不取消后台运行。 + +### 局部修改与新版本 + +故事名称可在页面顶部修改,人工流程点击“保存故事”,自动模式点击“保存编辑”。自动模式的名称和分镜等编辑会一起保存;尚未保存或保存失败的名称仍保留在输入框中。 + +需要恢复逐步骤确认时,保存当前修改,再点击故事导航栏“返回逐步骤人工确认”。故事、镜头、素材和历史运行保留,自动素材作为待确认候选显示,仍需你确认首帧与视频。人工编辑和确认也会带回自动模式;点击“启用可编辑自动成片”即可再切换。存在未结束的运行、候选任务或未清理执行时会提示先处理,切换失败不会丢弃当前编辑。 + +修改镜头画面/运动、裁剪或选用私有素材,可“仅生成素材”,也可“生成修改部分并成片”。指定重新生成会创建新变体,实际种子显示在绑定详情,网络重试不重复创建。 + +- 改运动重生成对应视频;改画面或参考图影响依赖首帧和视频;共享角色/场景可能影响多个镜头。 +- 重排或选用区间仍在实际源长内时复用源视频;源不够长时需重新生成。 +- 修改旁白段只重生成该段,再装配单音轨;修改字幕只改显示文字,明确同步到旁白才重新配音。 +- 字幕分别保护人工文字、人工时间,锚点可选全片、镜头、旁白段。冲突可保存,成片前须处理,不默默截配音或改写人工文字。 +- 编辑版本仍匹配时自动采用新结果;用户已经继续编辑时保留为运行成果并提示冲突,不能覆盖后来的输入。 + +### 恢复与失败 + +历史区分素材/成片。“从此版本恢复编辑”明确恢复整版冻结配置和实际成果,先处理当前未保存修改。“应用此运行成果”只接受源编辑版本仍匹配的成功Run;不匹配时使用明确的整版恢复。 + +素材运行和失败运行不会替换最近完成成片。原版本保留,新合成输出新文件;只重跑失效模型任务不代表最终MP4原地局部修改,CPU合成仍可能处理整片。 + +可暂停、继续、取消和安全重试;远端结果未知或清理未确认时不盲重发。旧Run归档仅释放自身引用,其他工程/版本仍引用的素材继续保护。账号禁用与删除规则保持不变。 diff --git a/docs/锚定工作室操作手册_20261111.md b/docs/锚定工作室操作手册_20261111.md new file mode 100644 index 0000000..d9ef653 --- /dev/null +++ b/docs/锚定工作室操作手册_20261111.md @@ -0,0 +1,422 @@ +# 锚定故事工作室操作手册 + +适用版本:2026-11-13 的“故事”工作室。入口为登录后的侧栏“故事”,页面路径 `/studio`;单个故事在 `/studio/故事编号` 编辑。多镜头自动生成、人工选片和“03 成片”统一在故事内进行;独立“工作流”“批量”“成片”页面已移除,既有数据和共享后端API保留。旧链接会转至故事或任务。 + +希望一次生成初稿并在之后局部修改时,先保存故事,再点击“启用可编辑自动成片”;具体步骤见[主操作手册](操作手册_20261111.md)第12节。希望逐镜人工确认时,按本手册第0节先做完一个 **2 镜头、10 秒**的小故事,再增加镜头。实际操作顺序是:**新建并命名 → 建基准板 → 写分镜并保存 → 逐镜确认首帧 → 逐镜确认视频 → 调整时间线 → 保存并合成 → 下载成片**。只有已有视频、只需剪辑时,才可直接从视频导入开始。 + +**验证状态:**本次已通过 **1、2、3 张参考图真实生成**、**1280×704 的5秒和15秒视频及增强**,以及网站“三图首帧→确认→视频→页面选片→冻结合成”的真实闭环。当前开发环境已开放参考生成,验收故事名为“锚定模型全链路验收(真实生成)”。按钮是否开放仍以当前环境返回的能力状态为准;通过样例不代表每种题材、身份一致性、复杂变形或长镜头质量都已验收。 + +## 0. 人工候选流程:两个镜头完成第一个故事 + +本节适用于人工候选流程;自动生成路径使用主手册第12节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;已有自动素材会作为待确认候选保留,由你逐步确认,故事和历史运行不变。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。 + +### 第 1 步:进入故事并命名 + +1. 登录网站,在左侧点击“故事”。这里会列出你自己的故事;继续旧作品时,点击对应故事卡片即可。 +2. 点击右上角“新建故事”。进入后,默认显示“02 分镜”,左侧已有一个“新镜头”,不需要再加第一个镜头。 +3. 点击顶部名称输入框,把“未命名故事”改成“青衣旅人走向山门”,再点“保存故事”。 + +**应看到:**顶部显示新名称和“版本 … · 已保存”;模式栏显示“1 镜头 · 5.00s”。以后修改故事内容,顶部会变成“未保存”,生成和确认会暂时不可用。 + +### 第 2 步:先定横竖屏,再填共同设定 + +1. 本例使用默认横屏。若你要竖屏,先切到“03 成片”,把“画幅”改成“竖屏 1080 × 1920”,点“保存故事”,再开始首帧。生成后改变画幅可能使相关候选过期。 +2. 点击“01 基准板”。填写“时代”为“古代东方”,“视觉风格”为“写实电影,自然材质,完整主体”,“色彩”为“青绿山色,红围巾点缀”,“全局光线”为“柔和晨光,薄雾”,“负向提示词”为“多余肢体,重复人物,文字,水印”。 +3. 在“角色与道具”旁点击“添加角色 / 道具”。名称填“青衣旅人”,类型选“人物”,描述填“成年旅人,体型修长,黑色长发,青色长袍,红色围巾;两个镜头保持同一外观”。 +4. 如果需要管理多种身体形态或衣服,可在这名角色下面点“添加形态”和“添加造型”。本例可添加“人形”和“青衣红围巾”,分别填写身体特征与服装特征。只有一种外观时,也可以只写角色描述,不必为了生成强行增加形态。 +5. 在“场景”旁点击“添加场景”。名称填“山门晨雾”,环境描述填“石阶通向古朴山门,远处青山,低处薄雾”;地点填“山间石阶”,时间填“清晨”,天气填“晴,薄雾”,光线填“柔和晨光”。 + +**应看到:**基准板里有一张“青衣旅人”角色卡和一张“山门晨雾”场景卡。后续镜头引用这两张卡,不用每个镜头重新建同名角色或场景。 + +### 第 3 步:有参考图就挂图,没有图也能继续 + +1. 如果已有旅人参考图,在角色卡点“添加参考图片”。弹窗“选择你的素材”中,点“我的素材”里的一张图片;本机图片则点“上传素材”,选文件并等上传完成。场景参考图同样添加到“山门晨雾”场景卡。 +2. 使用“共享素材”时,选择后会导入你的私有副本。选择器只显示当前入口可使用的素材类型;参考图入口选图片,不能选视频。 +3. 本例最多先放“角色 1 张 + 场景 1 张”。如果角色、形态、造型和场景都放了图,要按本镜头实际引用的不同图片合计,当前参考生成通道最多 3 张,以页面实际能力为准。 +4. 没有参考图时,跳过上传,后面使用“文字生成(不读取参考图)”。如果有图但参考生成能力未开放,也可人工导入首帧;不要把“已在基准板挂图”误认为文字生成已经读取了图片。 +5. 点击顶部“保存故事”。 + +**应看到:**已选参考图显示在对应卡片上;顶部恢复“已保存”。给基准板挂图还不等于镜头已绑定角色,下一步仍需选择场景并“加入镜头”。 + +### 第 4 步:编辑第一个镜头,真正加入角色 + +1. 点击“02 分镜”,选中左侧第一个镜头。在右侧“当前镜头”把名称改为“山门远景”,在“场景”下拉框选择“山门晨雾”。 +2. “画面描述”填:“远景,青衣旅人背对镜头站在石阶下方,红围巾清晰可见,山门位于画面上方,青山和薄雾形成纵深,人物完整入画。” +3. 将光标放到这段文字**最后**,键入一个 `@`,点击弹出列表中的“青衣旅人”。也可以在下面“选择角色 / 道具”下拉框选“青衣旅人”,再点“加入镜头”。选中后,右侧会出现角色卡;`@` 不需要保留在正文里。 +4. 如果第 2 步建了形态、造型,在角色卡里分别选择“人形”“青衣红围巾”;“位置关系”填“画面下方中央,石阶前”,“动作 / 姿态”填“背对镜头站立”。 +5. “运动描述”填:“旅人缓慢迈上一级石阶,围巾轻轻摆动,镜头缓慢向前推进,保持人物外观和山门结构。” +6. 右侧保留“生成源长度(秒,1–15)”为 `5`、“源起始帧(24fps)”为 `0`、“选用帧数(24–360)”为 `120`。点“保存故事”。 + +**应看到:**左侧镜头名变为“山门远景”,时长仍为 5.00s;右侧有一张“青衣旅人”角色卡。如果只有正文里的“@青衣旅人”文字、没有角色卡,还没有完成绑定。 + +### 第 5 步:增加第二个镜头 + +1. 点击左侧“镜头”标题旁的“+”。新镜头会被选中;这次新建不会自动复制前一个镜头的角色、场景或提示词。 +2. 名称改为“旅人近景”,“场景”仍选“山门晨雾”。从下拉框选同一个“青衣旅人”,点“加入镜头”,并选择相同形态、造型。 +3. “画面描述”填:“中近景,从侧后方看青衣旅人,黑色长发和红围巾清晰,前方山门虚化,柔和晨光,同一人物、同一服装。” +4. “位置关系”填“画面右侧,石阶中段”,“动作 / 姿态”填“停步,面向山门”;“运动描述”填:“旅人停下后轻轻抬头,围巾轻微摆动,镜头缓慢侧移,不改变服装和人物比例。” +5. 同样保留生成长度 `5`、源起始 `0`、选用 `120`。点“保存故事”。如果顺序不对,选中镜头后用“上移”“下移”调整,再保存。 + +**应看到:**左侧有“1 · 山门远景”和“2 · 旅人近景”;模式栏显示“2 镜头 · 10.00s”,底部“时间线”显示“240 帧 / 10.00 秒”。 + +### 第 6 步:生成第一镜头首帧并确认 + +1. 点击左侧“山门远景”,中间点“1 首帧生成 / 导入 → 确认首帧”。有参考图时检查生成方式是“参考图生成”;没有图时选“文字生成(不读取参考图)”。 +2. 在“候选数”用 `+ / −` 或直接输入 `1`。当前模型生成可填 `1–4` 个整数;初次先用 `1`。选“交互队列”,点一次“生成当前镜头”。 +3. 等候候选卡从“排队中”“生成中”变为“可复核”。暂未更新时点“刷新”,也可去侧栏“任务”查看队列原因;不要因等待而重复生成。 +4. 点击候选**缩略图**,在弹窗检查人物、红围巾、构图和山门。关闭弹窗后,在这张卡上点“确认首帧”。如果不满意,可调整设定、保存后再生成;有两张候选时,分别点“对比”查看并排缩略图,需要放大时点击对应缩略图。 + +**应看到:**首帧候选区域显示“已有确认”,所选卡按钮显示“已确认”,左侧该镜头显示“已有首帧”。点缩略图只打开预览弹窗,不会完成确认。 + +如果想直接用自己的图片,在这一步改点“导入图片并规范化首帧”,选择或上传图片,等规范化产物成为“可复核”后再“确认首帧”。每次人工导入只新增 1 个候选,不受上面的“候选数”影响。 + +### 第 7 步:为第二镜头也确认首帧 + +1. 点击左侧“旅人近景”,保持在首帧阶段。检查它自己的角色和场景都已绑定。 +2. 按上一小节选择生成方式、候选数、队列并点“生成当前镜头”;或导入自己的近景首帧。 +3. 检查它是否与第一镜头保持同一旅人、衣服和环境,再点“确认首帧”。 + +**应看到:**两个镜头各有自己的首帧确认。第一镜头确认过,不会自动替第二镜头确认。熟悉后可以用“全故事候选计划”一次安排当前阶段的候选;计划不会帮你逐镜选图,也不会接着自动生成视频。 + +### 第 8 步:逐镜生成视频并确认选片 + +1. 选中“山门远景”,点“2 视频生成 / 导入 → 确认选片”。确保右侧“运动描述”已填、顶部是“已保存”、生成长度 `5` 秒能覆盖 `0 + 120` 帧的选段。 +2. 初次保留“高级生成参数”默认值。按需设“候选数”为 `1`,点“生成当前镜头”。视频生成只用该镜头**已确认首帧**作为图像起点;不会把基准板所有图再次作为多图输入。 +3. 等视频候选变为“可复核”。点缩略图,在弹窗中点击播放,完整看一遍动作、稳定性和片尾;关闭弹窗会停止播放。若启用“使用增强片作为候选产物”,需要等增强产物完成并校验。 +4. 满意后点此视频卡的“确认选片”。再选“旅人近景”,重复生成、播放和“确认选片”。 + +**应看到:**两个镜头左侧都显示“已有选片”;视频候选卡显示“已确认”。视频已经生成、能播放或已下载,都不等于已经选入成片。 + +如果已有两条合适视频,可分别给两个镜头点“上传 / 导入视频候选”,选入后预览并“确认选片”。这条路径不需要先生成或确认首帧,仍要符合素材权限、24fps 和实际视频长度要求。 + +### 第 9 步:检查选段,按需加声音和字幕 + +1. 本例两个镜头都保留“源起始帧”`0`、“选用帧数”`120`,按时间线顺序拼为 10 秒。若想从视频第 1 秒开始选 4 秒,填起始 `24`、选用 `96`,同时确认实际源片足够长。 +2. 不需要声音或字幕可以直接下一步。需要配音时,在底部“声音与字幕”点“添加音轨”,选一条已有音频。本例 10 秒音轨可填“音频源开始 ms”`0`、“音频源结束 ms”`10000`、“成片偏移帧”`0`;源音频本身必须至少 10 秒。音频更长就手动缩短选段,短音轨尾部会补静音。 +3. 点“添加字幕”,填开始 `0`、结束 `120`、文字“晨雾中,他来到山门前。”;再添加一条,开始 `120`、结束 `240`、文字“抬头望去,新的旅程即将开始。”这两个时间都是**整部成片**的帧数。 +4. 点“保存故事”。如果改了镜头顺序或长度,重新调整字幕和音轨;它们不会自动跟着镜头移动。 + +**应看到:**时间线总长仍为 240 帧 / 10 秒;字幕列出两个时间段;顶部为“已保存”。如果有“超出范围”提示,先改选段或音轨、字幕时间,提示未解决前不要继续合成。 + +### 第 10 步:冻结合成并下载 + +1. 点击“03 成片”,顶部是“成片预览”。展开下方“查看镜头选片检查”,确认两个镜头逐项显示“选片已确认”。确认“画幅”为“横屏 1920 × 1080”;“适配”选“完整显示(留边)”可保留整个画面,选“填充画幅(裁边)”会裁去边缘以铺满画布。 +2. 如有修改,先点“保存故事”,再点“冻结素材并合成”。系统会再次检查实际素材与选段;弹出“素材已冻结,合成任务已提交”后,等候成片历史更新。这个按钮只合成已确认视频,不会替你补生成缺少的镜头。 +3. 点顶部“刷新成片”同步结果。合成成功后,最新成片以缩略图显示在顶部,无需先翻过镜头清单。点击缩略图或“播放成片”,在弹窗中检查镜头顺序、转接处、字幕和声音;可拖动播放器进度条、调整音量或全屏查看。 +4. 想单独查看时点“新窗口播放”;保存最终文件时点“下载成片”。要查看旧版本或运行进度,展开下方“合成历史”,其中仍可播放、下载历史视频及查看冻结设定。 + +**应看到:**顶部“成片预览”显示最新完成的视频缩略图,点击后弹窗播放;“合成历史”有本次记录、冻结版本和处理阶段,历史视频也通过缩略图打开。之后再改故事,不会改变这次成片;需要新版时,保存新修改并再次合成。候选区的“下载此素材”下载的是单个首帧或源视频,最终成片使用这里的“下载成片”。 + +## 1. 先选择创作路径 + +| 你已有的素材 | 操作路径 | 是否需要首帧确认 | +| ---------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------- | +| 只有故事设定,希望模型生成视频 | 建基准板 → 引用场景与角色 → 生成或导入首帧 → 确认首帧 → 生成视频 → 确认选片 → 合成 | 需要,生成视频使用已批准的单张首帧 | +| 已有满意图片,希望让画面动起来 | 导入图片并规范化首帧 → 确认首帧 → 生成视频 → 确认选片 → 合成 | 需要;图片导入不等于已经确认 | +| 已有视频,只需要选段、拼接、加音轨与字幕 | 直接导入视频候选 → 确认选片 → 调整裁剪 → 合成 | 不需要;也不要求填写文生图提示词 | + +上表是人工候选流程:工作室将“生成结果”和“本次决定使用的结果”分开,任务完成只会增加或更新候选,不会自动确认或合成。可编辑自动成片则按保存版本自动生成素材并合成,之后在故事中局部修改;它不等待上述逐镜人工确认。 + +## 2. 新建故事与界面位置 + +1. 点击侧栏“故事”,再点“新建故事”。如果按钮不可用,查看页面的能力或连接说明。 +2. 在工作室顶部修改故事名称,点“保存故事”。顶部显示服务器版本和“已保存 / 未保存”。 +3. 按需要切换三个模式: + +| 模式 | 主要操作 | +| ----------- | ------------------------------------------------ | +| `01 基准板` | 设置时代、风格、角色、形态、造型、场景及参考图 | +| `02 分镜` | 自动路径编辑镜头与旁白;人工路径选镜头、看候选与对比、编辑当前镜头 | +| `03 成片` | 统一查看音轨与字幕时间线、成片预览和历史;人工路径检查选片并冻结合成 | + +“保存故事”保存你填写的设定与剪辑;“确认首帧”“确认选片”会直接把这次选择记录到服务器,成功后不必再为同一个确认重复保存。后续又修改设定、提示词或时间值时,仍需先保存。单纯切换预览、模式或当前镜头不会替你保存。 + +分镜和成片模式下,左栏“+”增加镜头;选中卡片后用“上移”“下移”重排,用“删除当前镜头”移除。至少保留一个镜头。镜头数量上限由当前环境配置,默认通常为 120;页面达到上限后不再允许添加。 + +镜头名称和展示序号不是身份:重排不会把另一镜头的角色、候选或确认结果移到当前镜头。下方时间线中的镜头块也可点击,用于选中镜头;裁剪通过右侧数值输入完成。 + +## 3. 建立故事基准板 + +### 故事共同设定 + +在“基准板”填写“时代”“视觉风格”“色彩”“全局光线”“负向提示词”。例如: + +| 字段 | 鲲鹏示例 | +| ---------- | ------------------------------------------ | +| 时代 | 上古神话世界 | +| 视觉风格 | 史诗电影、写实 CG、自然材质、完整主体 | +| 色彩 | 青黑与冷蓝为主,淡金色细节 | +| 全局光线 | 晨光、柔和逆光、体积雾 | +| 负向提示词 | 多余肢体、主体重复、文字水印、明显现代建筑 | + +这些文字会和镜头实际引用的场景、角色设定一起组织为首帧输入。系统不会自动把一段长故事改编成全部分镜,也不会通过隐藏的语言模型改写替代你的决定。 + +### 场景 + +点“添加场景”,填写场景名称、环境描述,以及“地点”“时间”“天气”“光线”。再点“添加参考图片”,选择私有素材或上传图片。 + +同一场景可以供多个镜头使用。每个镜头右侧的“场景”下拉框决定该镜头引用哪个场景;仅在基准板添加场景、没有在镜头中选中,不会让它自动进入该镜头的输入。 + +### 角色、形态与造型 + +1. 点“添加角色 / 道具”,选择“人物”“生物”或“道具”,填写名称和共同特征。 +2. 用“添加形态”区分同一实体的身体形态,例如鲲形、鹏形、人形、原形。 +3. 用“添加造型”区分服装、装备或外观状态,例如常服、战甲、雨湿羽毛。造型不等同于另一个角色。 +4. 在实体、形态、造型各自的“添加参考图片”中,放入对应范围的参考图。 + +对“鲲变鹏”,建议只建一个生物实体“鲲鹏”,共同描述金色眼睛、青黑主色和淡金云纹;在它下面建“鲲形”和“鹏形”。鱼鳍、鱼腹写入鲲形,羽翼、羽缘写入鹏形,避免把互相矛盾的身体特征都写进共同描述。 + +修改名称不会让已有引用变成另一个角色。删除角色会同时清除当前草稿中对它的镜头引用;删除某个形态或造型,也会清除对应的镜头选择。删除前先检查相关镜头,历史成片仍按自己的冻结设定保存。 + +## 4. 在镜头中使用角色与覆盖设定 + +### `@` 与“加入镜头”是两条等价入口 + +在“分镜”右侧: + +1. 在“画面描述”末尾键入 `@`,从出现的列表选择实体;或使用“选择角色 / 道具”下拉框,再点“加入镜头”。 +2. 角色会出现在该镜头的角色卡片中。当前界面通过这张卡片保存稳定引用,不要求你在文字里手写素材编号;仅输入“@鲲鹏”几个字不等于完成绑定。 +3. 在卡片里选择“形态”“造型”,再填写“位置关系”和“动作 / 姿态”。同一角色不会因重复点击而被重复加入。 +4. 不需要该实体时,点角色卡片上的“移除”。 + +每个镜头只组织自己已加入的实体及选定的形态、造型。没有加入镜头的角色、其他镜头的参考图,不会因它们同属一个故事而自动送入模型。 + +“画面描述”适合写构图、景别、主体关系和静态画面;“运动描述”单独写动作、摄像机运动和节奏,供视频生成使用。先把一张首帧说明白,再设计它如何运动。 + +### 镜头覆盖与继承 + +展开“镜头覆盖与继承”,可单独调整“时间”“天气”“光线”“色彩”: + +| 项目 | 没有镜头覆盖时的来源 | +| ---------- | ------------------------------------ | +| 时间、天气 | 当前场景 | +| 光线 | 场景光线;场景未填时继承故事全局光线 | +| 色彩 | 故事共同色彩 | + +在输入框修改后,会变成“镜头覆盖”。**把覆盖内容删为空白,表示这个镜头显式清空该值;要重新继承,必须点“恢复继承”。**例如同一北海场景中,一个镜头可以覆盖为暴风雨,后面的镜头再恢复场景默认天气。 + +## 5. 参考图的数量与真实用途 + +当前参考图生成通道最多接收 **3 张不同图片**,不是“场景 3 张、角色再 3 张”。本镜头选定场景、已加入实体、选定形态与造型的参考图会合并计算;同一图片承担多个角色时按首次出现顺序只传一次。若当前环境返回的上限更低,以实际能力状态为准。 + +建议先用“当前形态 1 张 + 场景 1 张”,确有必要时再加入第三张造型图。鲲形镜头不要同时挂入完整鹏形参考,除非你明确需要它们共同约束一张画面。 + +| 操作 | 图片实际用途 | +| ------------------------------------ | ------------------------------------------------------------------------ | +| 首帧方式选“参考图生成” | 本镜头汇入的参考图片作为真实图像输入,和文字一起生成新的首帧候选 | +| 首帧方式选“文字生成(不读取参考图)” | 只使用文字;基准板图片仅供人工比对,没有传给文生图模型 | +| 点“导入图片并规范化首帧” | 上传或选中的图片经过尺寸适配,生成独立的首帧素材,供确认后的视频生成使用 | +| 使用已确认首帧生成视频 | 视频模型使用这张批准后的首帧;不是再把全部场景、角色参考图作为多图输入 | +| 点“上传 / 导入视频候选” | 使用已有视频做候选和后续合成,不会因此运行参考图生成 | + +本镜头有参考图时,默认采用“参考图生成”。如果能力不可用,系统不会静默改为文生图。你可以选择人工导入首帧;也可以**主动**改选“文字生成(不读取参考图)”,接受“参考图仅人工比对,未传模型”的含义。 + +判断一个已有候选实际用了什么,先点它的缩略图,关闭预览弹窗后展开“此候选的冻结输入与图片真实用途”。这里显示该次请求的实际参考图片数量、图片编号,以及可用的实际首帧、种子、模型配置、文字输入。下方“查看当前草稿编译预览(非历史候选输入)”表示现在的草稿,不可据此倒推旧候选当时用了哪些图。 + +参考图约束和稳定角色引用能帮助保持一致,但**不保证模型在所有镜头中完美保留身份、比例、脸部、服装细节或形态转换**。相同种子也不能代替参考图或人工复核。 + +## 6. 首帧候选:生成、导入与确认 + +先点“保存故事”,再在“分镜”中选择“1 首帧生成 / 导入 → 确认首帧”。 + +### “候选数”怎么用 + +1. “候选数”是数值输入框,默认 `1`。点两侧 `+ / −`,或点击中间数字后直接输入 `1`、`2`、`3`、`4`。它不是下拉菜单,当前只接受 1–4 的整数;到 1 时不能继续减,到 4 时不能继续加。 +2. 这个数字表示**下一次模型生成命令为每个镜头新建几个候选**。例如当前镜头设 `3` 再点“生成当前镜头”,会新增 3 个首帧或视频候选;2 个镜头设 `3` 再点“全故事候选计划”,会安排 6 个候选。 +3. 只改数字不会启动生成,不会删除已成功的候选、撤销确认或把现有候选变成该数量。列表可保留多次生成的结果,因此总数可能超过 4。只想多比较已有作品时,直接点缩略图或“对比”,无需重新生成。 +4. 候选数、首帧生成方式和队列是本次提交选项;只改它们不需要保存故事。角色、提示词、种子、时长、裁剪等故事内容改动则需要先保存。即使生成按钮因为未保存或缺少首帧而不可用,仍可先调整候选数。 +5. 人工图片、视频每次导入只增加 **1 个**候选;“重试为新候选”也针对失败的那一个候选。把候选数改成 `4`,不会把一张上传图片自动复制成四个版本。 + +### 模型生成 + +1. 选择“参考图生成”或“文字生成(不读取参考图)”。文生图仍需要有效画面描述;参考图生成还要满足图片权限、数量和能力要求。 +2. 按上面的方式将“候选数”设为 1–4。初次检查建议先生成 1 张。 +3. 选择“交互队列”或“批量队列”,点“生成当前镜头”。队列是否立即执行取决于空闲资源及当前时段策略。 +4. “全故事候选计划”会为故事中的所有镜头安排**当前首帧或视频阶段**的候选,已有满意结果的镜头也在内;它不自动跳过已完成镜头,不自动确认,也不接着进入下一阶段。未明确选用文字方式时,各镜头按自己的参考图决定默认模式;显式选用文字方式时,要确认你愿意让整批只用文字。只补一个不满意的镜头时,用“生成当前镜头”。 + +### 人工图片导入 + +1. 点“导入图片并规范化首帧”。 +2. 在素材选择器中使用“我的素材”,或点“上传素材”;也可以从“共享素材”先导入自己的私有副本。 +3. 导入后可能先显示“排队中”,此时还没有可确认的规范化产物。等状态成为“可复核”,再检查画面。 + +规范化首帧按故事画幅使用横屏 1280 × 704 或竖屏 704 × 1280。最终成片画布另有 1920 × 1080 / 1080 × 1920 设置;“导入首帧”不是直接把原图当作未经处理的模型输入,也不是已经生成视频。 + +### 人工复核 + +- 点缩略图,在弹窗中检查主体、形态、服装、空间和构图;页面只保留紧凑缩略图,横竖画幅均完整显示。 +- 对两个候选分别点“对比”,在“并排对比(最多两个)”中查看缩略图;点“移出对比”取消。点击任一对比缩略图可弹窗查看或播放,不提供同步双路播放。 +- 选择满意、未过期且状态为“可复核”的候选,点“确认首帧”。 +- “清除确认”撤销当前决定,不等同于删除候选或素材。 +- 失败候选可点“重试为新候选”;旧候选的输入不被这次重试改写。 + +## 7. 视频候选:模型生成或直接导入 + +### 使用已批准首帧生成 + +1. 先确认当前镜头有效首帧,再切到“2 视频生成 / 导入 → 确认选片”。 +2. 在右侧填写“运动描述”。展开“高级生成参数”,按需调整视频种子、步数、引导系数,以及“使用增强片作为候选产物”。 +3. 设置“生成源长度(秒,1–15)”,默认 5 秒,只接受整数秒。 +4. 检查当前裁剪区间能放入将生成的源片:`源起始帧 + 选用帧数 ≤ 生成秒数 × 24`。不满足时只会阻止这次生成,不会自动截断你填写的裁剪值。 +5. 点“生成当前镜头”;需要批量时再使用“全故事候选计划”。等待候选“可复核”,检查运动、外观与实际时长,点“确认选片”。 + +选择增强产物时,候选还要等待对应的最终产物校验。候选预览会显示实际源时长和尺寸;不要把“任务处理完成”当成已经选定可合成的视频。 + +### 种子和高级参数的操作顺序 + +1. 在右侧展开“高级生成参数”。“首帧种子”只影响下一次首帧生成,“视频种子”只影响下一次视频生成;两项默认均为 `42`,范围为 `0–4294967295` 的整数。 +2. 网页新建镜头的“视频步数”为 `20`、“引导系数”为 `5`,默认勾选“使用增强片作为候选产物”。步数可设 1–100,引导系数采用 1–20;首次使用可保留默认值。更多步数或增强通常需要更多处理时间,不保证每次更满意。 +3. 修改这些镜头参数后,点“保存故事”,再生成。候选数为 3、该类种子为 42 时,同次新建候选依次使用 42、43、44;每张候选可展开“此候选的冻结输入与图片真实用途”查看自己的实际种子。 +4. 下一次提交不会因为上一批生成过就自动随机换种子。想尝试新变化,可改种子并保存后再生成;仅想重新比较或确认旧结果时,不必修改种子或重生成。新增候选不会自动取代已确认的成功结果。 +5. 全故事视频计划要求各镜头已确认有效首帧,且每个镜头生成长度都能覆盖选用区间;当前镜头能生成,不代表其他镜头也已满足。先逐镜补齐,再提交全故事计划。 + +### 已有视频直接导入 + +1. 切到“2 视频生成 / 导入 → 确认选片”,点“上传 / 导入视频候选”。 +2. 选择私有视频、上传视频,或从共享库导入私有副本。 +3. 人工视频不需要先确认首帧,也不要求填写文生图提示词。仍需满足素材权限、完整性、24fps 及实际解码帧数等检查。 +4. 检查实际画面及选段,点“确认选片”。每个镜头都要明确确认自己使用哪个候选。 + +当前草稿的编译预览可能仍显示缺少画面提示词的生成诊断。这不等同于人工视频不能合成;最终看已选视频与“冻结素材并合成”前的就绪检查。其他问题,例如不存在的参考素材、无权访问的素材,仍须解决。 + +## 8. 实际源长度、裁剪与长故事 + +三个数值含义不同: + +| 字段 | 含义与范围 | +| ---------- | ------------------------------------------------------------------------ | +| 生成源长度 | 下一次模型生成视频的目标长度,1–15 秒;不代表已导入视频的长度 | +| 源起始帧 | 从已选视频的哪一帧开始取,0 起计的非负整数;长视频允许从更靠后的位置取段 | +| 选用帧数 | 当前镜头进入成片的长度,24–360 整数帧,即 1–15 秒 | + +24fps 下,24 帧为 1 秒,240 帧为 10 秒。区间按 `[源起始帧, 源起始帧 + 选用帧数)` 计算。右侧会显示已选视频实际秒数和近似帧数;最终边界以服务端解码检查为准。 + +| 素材或操作 | 参数示例 | 结果 | +| ----------------------------------------- | ---------------------- | ----------------------------------------------------------- | +| 导入实际 15 秒视频,生成参数仍为默认 5 秒 | 起始 0,选用 240 帧 | 可取 10 秒,不必把生成参数改为 10 秒 | +| 导入实际 60 秒视频 | 起始 1000,选用 240 帧 | 取约第 41.67–51.67 秒,允许从长素材后段取片 | +| 实际源只有 3 秒 | 起始 24,选用 120 帧 | 超过真实范围;保留数值并提示,须手动修正 | +| 点击生成 5 秒视频 | 起始 24,选用 120 帧 | 将生成的 120 帧覆盖不了结束帧 144;应增加生成长度或修改选段 | + +**只改裁剪会改变合成选段,不会自动重生视频。**实际视频仍要足够长;若改后的选段越界,就绪检查会阻止合成。旁白、字幕和音轨偏移也不会随镜头改动被悄悄截短或平移。 + +“长视频故事”通常指很多镜头合成后的总长,不等于模型一次生成一条长镜头:6 个 5 秒镜头共 30 秒;20 个 5 秒镜头共 100 秒。一个 60 秒已有视频也可以分别导入不同镜头,给每个镜头设置不同起点,每镜头最多选用 15 秒。上传格式、容量和总资源仍以当前环境限制为准。 + +## 9. 鲲鹏形态切换:六镜头操作实例 + +以下为**手动搭建示例**,不是点击后自动生成的模板,也不代表这六镜头已经完成真实视频验收。鲲鹏旧JSON仅作历史分镜参考,独立工作流入口已移除,不会自动变成故事基准板。 + +### 先建可复用设定 + +- 实体“鲲鹏”:类型选“生物”;共同特征写“金色眼睛、青黑主色、淡金云纹,同一神话生命,身体特征由当前形态决定”。 +- 形态“鲲形”:青黑巨鱼、银白腹部、宽阔鱼鳍;放一张满意的鲲形参考。 +- 形态“鹏形”:青黑巨鹏、淡金羽缘、完整双翼;放一张满意的鹏形参考。 +- 造型“云纹本相”:淡金云纹贯穿身体,避免新加互相冲突的肢体描述;可先只填文字。 +- 场景“北海晨雾”:冷蓝海面、低云、淡金晨光,放一张北海参考;再建“高空云海”和“南方天光”。 + +每个镜头用 `@` 或“加入镜头”引用同一个“鲲鹏”,再选择该镜头的形态,不要为每个镜头重新建立同名角色。通常“当前形态图 + 当前场景图”共两张,留意合计上限。 + +| 镜头名称 | 场景 / 形态 | 画面描述重点 | 运动描述重点 | 选用 | +| -------- | --------------- | -------------------------------------- | ---------------------------------------- | ------ | +| 北冥全景 | 北海晨雾 / 鲲形 | 巨鲲在海面下,完整鱼形,远景表现尺度 | 海浪缓慢起伏,镜头平稳前推 | 120 帧 | +| 金眼特写 | 北海晨雾 / 鲲形 | 金色眼睛、青黑鳞片和淡金云纹 | 眼睛轻微转动,镜头缓慢侧移 | 120 帧 | +| 大风水幕 | 北海晨雾 / 鲲形 | 鲲跃近水面,逆光与水幕遮挡身体 | 只做一次缓慢抬升,水雾遮住画面 | 120 帧 | +| 鹏出云层 | 北海晨雾 / 鹏形 | 水雾后露出完整鹏鸟,保留共同色彩和眼睛 | 完整双翼缓慢展开,不要求暴露连续解剖变形 | 120 帧 | +| 展翼上升 | 高空云海 / 鹏形 | 全身鸟形、淡金羽缘、云层作比例参照 | 平稳上升,镜头侧向跟随 | 120 帧 | +| 南迁远影 | 南方天光 / 鹏形 | 巨鹏面向南方,北海退到远处 | 远景缓慢离开,留出收尾空间 | 120 帧 | + +第三镜头可在“镜头覆盖与继承”里把天气改为大风、光线改为逆光;第四镜头点“恢复继承”回到场景默认。保存后逐镜定首帧,用“对比”检查鲲形与鹏形是否保留相同的关键识别特征,再开始视频候选。 + +鲲变鹏是高难度形变。采用“水幕遮挡 → 切到完整鹏形”更容易人工控制;只有视频实际表现合格时,才选用暴露身体连续变形的版本。角色身份引用相同,不等于模型已经学会稳定的鱼鸟变形。 + +六镜头总长 720 帧、30 秒。要扩展到 100 秒,可进一步拆解北海、鲲形、遮挡、鹏形、南迁等镜头,并按实际旁白长度安排节奏。不要仅把所有镜头设为 15 秒,就认为复杂动作和画面连续性会自动改善。 + +## 10. 声音、字幕与冻结合成 + +1. 在底部“声音与字幕”点“添加音轨”,选择一条已有配音或外部合成好的音频;已有音轨可点“更换音轨”或“移除音轨”。 +2. “音频源开始 ms / 音频源结束 ms”是音频内的毫秒位置;“成片偏移帧”是这段声音从整片哪一帧开始。短音轨尾部补静音;长音轨不会自动截断,需要缩短选段、增加成片长度或重新处理声音。 +3. 点“添加字幕”,填整片的“开始帧”“结束帧”和文字。字幕使用成片绝对帧:例如第 5–10 秒是 120–240,不是某个镜头内部的局部时间。当前没有自动旁白对齐功能。 +4. 更改镜头顺序、长度后,重新试听并检查音轨和字幕;系统保留原时间值,不自动平移。 +5. 切到“03 成片”,选择“横屏 1920 × 1080”或“竖屏 1080 × 1920”,以及“完整显示(留边)”或“填充画幅(裁边)”。这会影响画面适配;修改后保存并留意相关候选是否需要重新复核。 +6. 每个镜头都确认有效选片后,点“保存故事”,再点“冻结素材并合成”。服务端会复核实际素材、裁剪区间、音轨和字幕;有问题时按提示修正,不会静默截断。 + +本次合成冻结当前选片及版本、素材校验信息、镜头顺序、裁剪、画幅、音轨和字幕。它只合成已选视频,不会在后台自动补生成缺失镜头。之后再改草稿、换片或清除确认,不会改变历史运行的冻结输入。 + +进入“03 成片”后,顶部“成片预览”显示最新完成的视频缩略图。点缩略图或“播放成片”打开弹窗播放,也可用“新窗口播放”单独查看,或点“下载成片”保存文件。新任务仍在合成时,可以先预览上一次已完成的视频;点“刷新成片”同步最新结果。展开“合成历史”可点击旧版本缩略图播放、查看进度和下载入口,再展开“查看此次冻结设定”查看该次设定。运行中按可用按钮“暂停”“继续”“取消”控制本次运行;取消不能视为可随时恢复的暂停。 + +## 11. 失效、重新复核与删除 + +| 改动 | 应怎样检查 | +| -------------------------------------------------- | ---------------------------------------------------------------------- | +| 改故事风格、场景、实体、当前形态、造型或相关参考图 | 相关视觉候选可能“设定已变化”;重新生成或显式重新导入复核 | +| 改运动描述或换批准首帧 | 检查视频选择是否过期;首帧本身不因只改运动而必然失效 | +| 改生成长度 | 模型生成的视频受其输入变化影响;人工导入视频的真实长度不由这个参数决定 | +| 只改裁剪、镜头顺序、字幕 | 保留已有视频;重新检查实际范围及成片时间,不会自动重生素材 | +| 换种子生成更多候选 | 不会把其他已有候选自动选中;查看每个候选自己的冻结输入 | + +过期候选仍可预览和下载,但不能直接点确认。确实要沿用旧画面时,下载后用“导入图片并规范化首帧”或“上传 / 导入视频候选”重新作为人工素材复核;这表示你主动认可它在当前设定下的用途,不是修改旧候选历史。 + +候选卡片上的“删除”用于移除候选记录;当前确认中的候选,先点“清除确认”再操作。正在执行的候选需要先到“任务”取消,并等待终态及执行清理确认,不能用删除按钮强行打断未知的远端执行。 + +故事列表中的“删除故事”会要求确认,并由服务端处理候选、运行等关联记录。独立素材仍由素材库管理;删除候选或故事不等于立即物理删除所有图片、视频。当前选择、候选和冻结运行的引用分别保护素材;素材库提示仍被引用时,应按实际关联记录处理,不要绕过保护去删服务器文件。 + +私有故事与素材按账号隔离。共享素材选择后会先导入本账号的私有副本;发布者撤回共享不会改写已经导入的副本,也不会自动向别人复制你的故事。 + +## 12. 保存、断线恢复与移动端 + +“保存故事”保存到服务器。“未保存”内容仍在当前编辑页面,切换三个模式或当前镜头会保留,但不是已上传的备份。返回故事列表、切到其他页面、换故事、退出登录或关闭页面时会提示未保存内容;不要依赖浏览器强制关闭后自动恢复。生成、确认和冻结合成前先保存。 + +如果提示“服务器已有新版本”或版本冲突,当前输入会保留供处理。先把尚未保存的重要文字、时间值等复制留存,再返回故事列表,按提示决定是否放弃本地修改,重新打开服务器版本并合并;不要反复点击保存覆盖他处更新。故事当前不提供旧工作流JSON的直接导入、导出;旧独立页面已移除,历史JSON和API合同仍保留。 + +HTTP/SSE 断线、关闭网页或切换页面不会取消已经保存提交的任务,也不会停止共享模型。恢复连接后会重取故事及已加载候选的快照,补齐候选状态和离线期间删除的记录;不会因为重连自动再生成一次,也不会替你做确认。需要人工同步时用分镜“刷新”或成片“刷新历史”。 + +如果提交时断网、结果未知,先恢复连接并查看原候选、任务与当前确认状态。系统保留原提交意图用于幂等恢复;重复点击或重新创建一批任务不是确认执行结果的方法。 + +### 等待、时段和额度怎么看 + +1. 在网页右上角打开“创作服务状态”,刷新查看服务连接、运行策略和资源状态;再到“任务”查看具体任务的排队原因。页面上的“刷新”是同步结果,不是重新发起生成。 +2. “交互队列”全天可提交并等待空闲资源;“批量队列”按当前环境的时段策略启动。启用批量时段限制时,新阶段仅在北京时间 **21:00–次日 08:00** 启动;开发环境关闭限制时可全天等待执行。以状态面板当前生效的策略为准。 +3. “全故事候选计划”描述的是覆盖哪些镜头,“交互队列 / 批量队列”描述的是执行方式,两者独立。提交全故事计划前仍要检查当前队列选项。 +4. 排队不等于失败。空闲 GPU、系统资源和其他用户优先规则决定实际开始时间;浏览器开着不会占到更多 GPU。已开始任务在服务器执行,关闭浏览器、离开故事页、HTTP/SSE 断线都不会取消它。需要停止任务时,使用“任务”或对应运行里的明确取消入口,并等执行清理完成。 +5. 当前默认没有“累计只能生成 8 个视频”的限制。创建频率、未完成任务、故事候选计划、活动运行和素材空间仍分别受额度约束。默认创建频率为每分钟 6 次,已有其他创作提交也会共用这项额度;遇到 429 或额度提示,先看具体原因,等任务完成或按提示清理后再试。 +6. 候选数越多,新安排的候选和资源消耗越多;不代表能同时运行相同数量的 GPU。已有成功结果仍可预览和下载,未过期且满足确认条件的可继续确认;不要为了验证候选数控件是否可点,额外发起一批真实生成。 + +“02 分镜”的自动编辑面板、镜头列表、候选或属性区内容超出时,只在对应容器内滚动;故事标题和步骤导航保持可见。鼠标移入显示滚动条,移出隐藏,键盘聚焦时也可显示;触屏直接在容器内滑动。窄屏会重排镜头卡和对比区域,底部内容仍通过容器内滚动到达。声音、字幕和唯一时间线请切到“03 成片”查看;时间线较长时在该区域横向滚动。手机和电脑使用相同的版本校验、保存和人工流程确认规则;移动端不是离线剪辑模式。 + +## 13. 常见提示 + +| 提示或现象 | 处理 | +| ---------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| “新建故事”或生成按钮不可用 | 先看故事能力、连接说明;等读取完成。编辑中先保存;生成过程中等本次提交结束,具体限制看页面提示 | +| “保存故事”不可用 | 检查名称是否为空、页面是否还在读取,以及字幕、音轨、裁剪等是否触发校验错误;修正提示后再保存 | +| 想选“候选数”,找不到下拉选项 | 这是数值框,用 `+ / −` 或直接输入 1–4;只调整数量不触发生成,也不要求先确认首帧 | +| 候选数改成 3,已有作品仍只有 1 个 | 正常;数量只作用于下一次模型生成,不补齐、不重生、不复制旧结果。人工导入每次始终是 1 个 | +| “参考图生成”不可选 | 查看当前能力原因;即使模型 PoC 已通过,未开放或上游离线的环境仍会禁用。可人工导入,或明确选择文字方式 | +| 参考图数量超限 | 检查本镜头场景、实体、当前形态、造型汇入的不同图片总数,减少到当前上限内 | +| 首帧导入后看不到图片、暂不能确认 | 等待规范化任务完成并成为“可复核”;查看候选错误和任务状态 | +| 点缩略图后仍提示没有确认 | 缩略图只打开预览弹窗;关闭后在对应卡片点“确认首帧”或“确认选片”,并检查是否显示“已确认” | +| “确认首帧 / 确认选片”不可用 | 先保存;候选须有可用素材、状态为“可复核”且没有“设定已变化”。过期候选按第 11 节重新导入或生成 | +| 生成视频按钮不可用 | 先保存,确认有效首帧,再检查“生成源长度”能否覆盖选用区间;人工视频导入仍走独立路径 | +| 当前镜头可生成,“全故事候选计划”不可用 | 检查其他镜头的生成长度、选段和首帧确认;一个镜头满足条件不能代表全部镜头 | +| “冻结素材并合成”不可用或提交被拒绝 | 先保存,检查每个镜头都有有效选片,再根据就绪提示修正真实长度、音轨和字幕;缺少视频不会被自动补生成 | +| 编译预览提示缺少画面文字,但已有人工视频 | 这是生成诊断;人工视频无需文生图提示词,继续检查有效选片和合成就绪状态 | +| “选用区间超过已选视频实际范围” | 根据实际视频时长调整起始帧或选用帧数;仅修改生成长度不能把已有视频变长 | +| 修改镜头后字幕、旁白越界 | 它们使用整片时间且原值会保留,手动调整或增加成片长度 | +| 旧候选变灰或显示设定变化 | 查看它的冻结输入;重新生成,或明确导入为人工素材再复核 | +| 删除被拒绝 | 查看是否仍在执行、等待执行清理、或素材仍被候选/选择/历史运行引用;先处理对应记录 | +| 一直排队或提示等待窗口 | 看“创作服务状态”的批量策略和“任务”的等待原因;切换页面或反复生成不会消除资源、时段和额度限制 | +| 任务完成后没有最终成片下载 | 先逐镜“确认选片”,再去故事内“03 成片”冻结合成;成功后在顶部“成片预览”点“下载成片”,旧版本在“合成历史”中 | + +相关入口说明见[主操作手册](操作手册_20261111.md);旧工作流的长故事与旁白示例见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。后者的旧模板、独立模型实测结果不能替代新版锚定工作室链路的验收结论。 + +## 14. 本工作室对应的“编排审核”和“批量生成” + +需求中的日间“编排审核”,在这里对应“01 基准板”的共同设定、“02 分镜”的顺序与裁剪、候选比较,以及明确点击“确认首帧 / 确认选片”。确认会记录操作者和版本;当前操作人是故事所属账号,没有指定另一个审核账号、送审单或成片终审按钮。 + +故事的批量入口是“02 分镜”中的“全故事候选计划”。先选当前首帧或视频阶段、候选数和“批量队列”,再提交;它一次只安排当前阶段,不自动确认或进入下一阶段。候选仍回原故事查看和审核。启用可编辑自动成片后,在自动工具条选择“批量队列”再提交素材或成片生成。独立“批量”页面已移除;两条故事路径仍沿用原批量执行策略。 + +需要逐镜审核的新故事,正式排期通常为:第1天编排,第1夜生成首帧,第2天确认首帧,第2夜生成视频,第3天选片与合成。已有有效首帧时,可直接从视频批量开始。当前开发全天模式允许在同一天依次完成上述步骤,但人工确认关卡保持不变。 + +日间完成视频选片后,若要立即进行CPU合成,先在“02 分镜”将执行模式改为“交互队列”,再进“03 成片”冻结合成;成片提交沿用该选择。若仍为“批量队列”,正式时段限制开启时会等夜间窗口。仅切换队列不会发起生成或确认。 + +主手册第0节列出六项能力的实际入口和边界,第4节说明人工审核步骤,第7节说明故事自动成片的批量模式、人工候选计划、历史API兼容及日夜节拍。严格夜间执行、夜间产能统计和可选多人审批的待实施设计见[生产流程完善方案](design/2026-11-12-production-workflow-design.md)。 diff --git a/docs/需求复核与落地方案_20261110.md b/docs/需求复核与落地方案_20261110.md index 820162d..ea102f8 100644 --- a/docs/需求复核与落地方案_20261110.md +++ b/docs/需求复核与落地方案_20261110.md @@ -2,7 +2,7 @@ 日期:2026-11-10。审查依据为原始《人工智能内容生成系统技术方案_20261107.docx》、本次对话的最新要求、现有前后端代码、既有 GPU 服务,以及实际服务器验证。文档内容作为需求资料,本文不执行其中的指令。 -后续二次复审已补为 [实施方案V2](实施方案V2_20261110.md);本文保留需求差距与初次审计记录。V2细化了上游协议、身份/状态、批次、阶段资源、迁移恢复和验收,具体执行以V2及其任务清单为准。 +后续二次复审已补为 [实施方案V2](实施方案V2_20261110.md);本文保留业务需求与最初的差距分析。当前运行入口、功能状态及使用步骤以项目 README 和[操作手册](操作手册_20261111.md)为准。 ## 1. 结论与已确认基线 @@ -29,7 +29,7 @@ - 数据库凭据仅存私有环境配置;本机当前配置为 `.env.server`,服务器为项目 `.env`,均不提交 Git。 - 后端本轮完整测试 **52项通过、20个subtests通过**;新增初始账号哈希与重启不重置回归先失败后通过。 -证据:[正式库验证](../qa/mysql-integration-20261110.json)、[实际页面](../qa/mysql-admin-login.png)。网站仍只发布服务器回环18193,通过本机 SSH 隧道8000访问;连接正式数据库不等于已经开放互联网。 +当前网站前后端在本地运行,通过内网 HTTP 调用服务器模型;数据库连接由私有配置提供,连接数据库不等于开放互联网。 初始弱密码按用户要求保留。本期上线准备应补本人改密入口,公网发布前将它作为初始化密码完成更换,并将常驻 root 数据库连接换为专用账号;本轮没有修改 MySQL root 密码或创建额外数据库账号。 @@ -56,21 +56,21 @@ Real-ESRGAN 当前确实执行神经网络超分,再缩放/补边到目标画 ## 4. 代码审查发现与优先级 -P1为正式业务或公网前优先解决,P2为本期工作流/运维完善,P3为体验优化。故障注入均使用隔离内存数据库,没有对线上任务注入故障。 +下表保留最初审查时的问题与设计依据,不能当作当前待办清单。代码链接已更新为现有目录;当前合同与实现边界见[API 合同](api-contract.md)及[工程约定](工程结构与开发约定.md)。 | 编号 | 等级 | 问题、触发与证据 | 最小改动与验收 | | --- | --- | --- | --- | -| R1 | P1 | 前端每次调用submit换幂等键。POST落库但响应丢失后再次点击会新建昂贵任务。[api.ts:44](../frontend/src/api.ts#L44);后端已支持复用同键 | 持久保存一次提交的key和不可变payload;结果不明时复用。断网、刷新、恢复后仍是同批任务;明确再次生成才换key | -| R2 | P1 | CPU执行失败且失败状态写库也失败时,done task异常被忽略,仍running的记录下一轮可再次执行。隔离故障注入得到执行次数2。[coordinator.py:157](../backend/app/coordinator.py#L157)、[195](../backend/app/coordinator.py#L195) | 增加持久attempt与运行时丢失任务守卫;不明确的执行转待确认/中断,不能自动当新执行。故障注入确认未经显式重试不重复执行 | -| R3 | P1 | 资产commit结果不明时外层异常无条件删目录,存在“库中有行、文件已删”的窗口;这是源码确认的故障窗口,尚未完整注入复现。[assets.py:106](../backend/app/assets.py#L106)、[141](../backend/app/assets.py#L141) | commit开始后结果不明保留暂存文件;数据库与文件对账后清理。复用pending记录前检查文件;恢复只重导入,不重生成 | -| R4 | P1 | SSE长连接使Uvicorn更新时等待,Docker45秒后强停;本轮切库实际观察到了这段等待。[Dockerfile](../backend/Dockerfile)、[events.py](../backend/app/events.py)、[compose](../compose.yaml) | Uvicorn graceful timeout约20秒,小于Docker45秒;配合drain与协调器清理。保持SSE连接更新,验证未进入强杀且恢复任务不重复 | -| R5 | P2 | 协调器每轮再次cancel正在清理的CPU task,可打断一般provider异步清理。[coordinator.py:184](../backend/app/coordinator.py#L184) | 取消信号只发一次,等待清理确认再终态。现有media与TTS已有shield,不能据此宣称当前FFmpeg必然遗留进程 | +| R1 | P1 | 前端每次调用submit换幂等键。POST落库但响应丢失后再次点击会新建昂贵任务。[api.ts](../frontend/src/api/durable.ts);后端已支持复用同键 | 持久保存一次提交的key和不可变payload;结果不明时复用。断网、刷新、恢复后仍是同批任务;明确再次生成才换key | +| R2 | P1 | CPU执行失败且失败状态写库也失败时,done task异常被忽略,仍running的记录下一轮可再次执行。隔离故障注入得到执行次数2。[coordinator.py](../backend/app/services/orchestration/coordinator.py)、[协调器](../backend/app/services/orchestration/coordinator.py) | 增加持久attempt与运行时丢失任务守卫;不明确的执行转待确认/中断,不能自动当新执行。故障注入确认未经显式重试不重复执行 | +| R3 | P1 | 资产commit结果不明时外层异常无条件删目录,存在“库中有行、文件已删”的窗口;这是源码确认的故障窗口,尚未完整注入复现。[assets.py](../backend/app/services/assets.py)、[141](../backend/app/services/assets.py) | commit开始后结果不明保留暂存文件;数据库与文件对账后清理。复用pending记录前检查文件;恢复只重导入,不重生成 | +| R4 | P1 | SSE长连接使Uvicorn更新时等待,Docker45秒后强停;本轮切库实际观察到了这段等待。[Dockerfile](../backend/Dockerfile)、[events.py](../backend/app/api/routes/events.py)、[compose](../compose.yaml) | Uvicorn graceful timeout约20秒,小于Docker45秒;配合drain与协调器清理。保持SSE连接更新,验证未进入强杀且恢复任务不重复 | +| R5 | P2 | 协调器每轮再次cancel正在清理的CPU task,可打断一般provider异步清理。[coordinator.py](../backend/app/services/orchestration/coordinator.py) | 取消信号只发一次,等待清理确认再终态。现有media与TTS已有shield,不能据此宣称当前FFmpeg必然遗留进程 | | R6 | P2 | 成片草稿存组件ref,去声音页配音再返回就丢片段、字幕、裁切。[ComposeView.vue:18](../frontend/src/views/ComposeView.vue#L18) | Pinia管理并按用户持久保存草稿;跨页和刷新不丢,显式新建才清空 | -| R7 | P2 | 素材列表先读取全库后内存分页;标签也在Python过滤,数据库全局单元锁会放大阻塞。[assets.py:164](../backend/app/assets.py#L164)、[database.py:25](../backend/app/database.py#L25) | SQL计数/分页;标签关联表或MySQL索引;owner/状态/时间复合索引。较大素材库下查询不拖住SSE与提交 | -| R8 | P2 | 当前只有创建用户API,没有本人改密、用户停用/会话撤销及管理页;登录无节流且密码计算位于数据库全局锁内。[auth.py](../backend/app/auth.py)、[router.ts](../frontend/src/router.ts) | 补改密、建用户/列表/停用、会话撤销;密码计算移出DB锁,账号/IP登录限流;沿用admin/user与owner权限 | +| R7 | P2 | 素材列表先读取全库后内存分页;标签也在Python过滤,数据库全局单元锁会放大阻塞。[assets.py](../backend/app/services/assets.py)、[database.py](../backend/app/core/database.py) | SQL计数/分页;标签关联表或MySQL索引;owner/状态/时间复合索引。较大素材库下查询不拖住SSE与提交 | +| R8 | P2 | 当前只有创建用户API,没有本人改密、用户停用/会话撤销及管理页;登录无节流且密码计算位于数据库全局锁内。[auth.py](../backend/app/services/auth.py)、[router.ts](../frontend/src/router.ts) | 补改密、建用户/列表/停用、会话撤销;密码计算移出DB锁,账号/IP登录限流;沿用admin/user与owner权限 | | R9 | P2 | UI可输入不满足步长/Canny关系的值、超2000字配音、超24片段,依赖提交后报错。[WorkbenchView.vue](../frontend/src/views/WorkbenchView.vue)、[ToolsView.vue](../frontend/src/views/ToolsView.vue) | 共用参数schema/校验函数、字数与时长提示;错误定位到字段,后端继续保留最终校验 | | R10 | P2 | 理解标签未应用到原素材;工具历史从混合最近48条筛选,旧记录易被挤出;“已配置”可能显示为“就绪” | 增加标签确认合并、按任务类型分页、区分配置/在线/可执行;加入故障断连与旧数据测试 | -| R11 | P2 | API整个workspace可写;没有schema升级、文件回收和容量控制闭环。[compose.yaml:22](../compose.yaml#L22)、[database.py:31](../backend/app/database.py#L31) | 缩窄挂载、模型密钥/状态目录只读;Alembic迁移;用户容量/任务上限、对账回收、联合备份恢复演练 | +| R11 | P2 | API整个workspace可写;没有schema升级、文件回收和容量控制闭环。[compose.yaml:22](../compose.yaml#L22)、[database.py](../backend/app/core/database.py) | 缩窄挂载、模型密钥/状态目录只读;Alembic迁移;用户容量/任务上限、对账回收、联合备份恢复演练 | | R12 | P3 | 收藏无筛选入口,上传与生成作品混合查找 | 复用素材库增加favorite/origin服务端筛选,无须另建复杂项目管理系统 | ## 5. 架构取舍 diff --git a/docs/验收报告.md b/docs/验收报告.md deleted file mode 100644 index 941cd19..0000000 --- a/docs/验收报告.md +++ /dev/null @@ -1,51 +0,0 @@ -# CMVR Visual 验收记录 - -后续更新(2026-11-10):现已接入用户指定的正式MySQL并创建默认管理员,见 [实际接入记录](../qa/mysql-integration-20261110.json)。后端新增初始账号回归后52项通过。下面保留的是**数据库切换之前的功能验收基线**,其中“账号待提供”“独立验收库”等均为当时状态;样例数据未迁入正式库。最新差距与后续计划见 [需求复核方案](需求复核与落地方案_20261110.md)。 - -验收日期:2026-11-10。代码位于 `E:\workspace\hybrid\cmvr-visual`;服务器源码位于受限工作区 `/workspace/projects/cmvr-visual`。 - -## 交付与访问 - -- Vue 3 + Element Plus + Pinia;Python FastAPI + SQLAlchemy async + MySQL;HTTP 提交与文件传输,SSE 实时事件。 -- 已启动 API、中文配音、Nginx 前端三个独立容器。仅 Nginx 发布宿主 `127.0.0.1:18193`,当前本机 SSH 隧道访问入口为 `http://127.0.0.1:8000`。隧道断开后按 [README](../README.md) 重建;网站容器继续运行。 -- 本机私有 `.env.preview` 中的 `ADMIN_USERNAME`、`ADMIN_PASSWORD` 为临时验收登录信息,不进入源码、镜像或报告。 -- **当前使用独立 MySQL 8.0.36 验收实例。正式 `192.168.28.10:3306/cmvr-visual` 的专用账号仍未提供,未连接、未修改正式库。**页面持续显示“验收环境 · MySQL”。互联网域名、HTTPS 或穿透入口尚未配置。 - -## 真实调用 - -以下八类任务均通过网站业务 API 创建,使用真实服务执行并归档到 MySQL 与素材库,无模拟生成。 - -| 能力 | 实际验证 | -| --- | --- | -| 图像生成 | Qwen-Image,512×512、10步;成品可下载、上传和预览 | -| 首帧视频 | Wan2.2-TI2V-5B,512×288、25帧、4步,使用真实图片首帧 | -| 条件样本 | SDXL+Canny ControlNet,512×512、6步,输出生成图与控制图 | -| 中文配音 | 本地 CPU Kokoro-82M,两个普通话音色均通过 HTTP 生成有效 WAV;小贝样例8.45秒,云希样例3.4秒 | -| 语音转写 | Whisper 将上述配音转为中文,与测试文本内容相符 | -| 数学推演 | 现有 Qwen 文本服务得到 `17×23=391`;浏览器实际提交 `2+3` 得到 `5` | -| 素材理解 | 现有 Qwen 视觉服务返回图片主体、场景、标签与 OCR 结构 | -| 成片编排 | CPU FFmpeg 拼接两个真实视频片段,加入配音和中文字幕,输出640×360、24fps、约2.12秒成片 | - -以上低分辨率、低步数任务验证功能连接,不代表默认生成质量、生产吞吐或耗时承诺。当前生成视频上限为121帧/24fps,约5秒;配音不是音乐生成;Canny 控制图不是缺陷真值掩膜;数学结果没有专业正确率或形式化证明保证。 - -## 自动化与浏览器 - -- Linux 后端:**51项通过,20个 subtests 通过,无跳过**;包含实际 FFmpeg 媒体处理、幂等恢复、取消与归档竞争、队列公平、归属权限和 SSE 重放。 -- TTS:**12项通过**;包含等待取消、重复取消、进程组清理、响应发送失败清理以及子进程不继承服务密钥。测试框架有1条 Starlette TestClient 依赖弃用提示,不影响本次断言。 -- 前端:**12项通过**;TypeScript 类型检查与生产构建通过。合计75项测试,subtests 另计。 -- 真实业务脚本:21项断言通过,八类任务成功;收到81条真实事件;验证上传、修改、收藏、标签、删除、预约取消、显式重试、CSRF、跨账号不可读与视频 Range。 -- 正式 Nginx 构建浏览器验收:1440×1000、390×844,共35条页面记录与34张截图;无页面脚本错误、HTTP错误、重试或横向溢出。 -- 桌面与手机图片可解码;视频/音频四次播放和定位均成功;捕获10次 Range 206。冷缓存任务直达链接会实际读取任务详情。 -- 实际 UI 数学任务的 SSE 连续经过 submitting → running → collecting → succeeded,版本1至5;流连接1次、断连0次。 -- Nginx 配置检查通过;首次 SSE 注释约0.094秒到达本机;首页与素材库路由不缓存,静态哈希文件保留长缓存;同源 CSP 生效。 -- 实际设置 `max_tokens=1` 时返回明确 `output_truncated`,不发布不完整答案为成功产物。 - -最终页面截图见 [桌面](../qa/browser-desktop-create-image.png)、[手机](../qa/browser-mobile-create-image.png)、[手机任务详情](../qa/browser-mobile-task-detail.png);真实成片字幕帧见 [字幕帧](../qa/composition-frame.png)。 - -原始记录:[服务器测试](../qa/server-tests.json)、[业务调用](../qa/e2e.json)、[浏览器](../qa/browser.json)、[代理](../qa/proxy-check.json)、[截断处理](../qa/truncation-check.json)、[部署与文件校验](../qa/deployment.json)。 - -## 资源与后续接入 - -新 API 与配音容器均无 GPU grant。GPU 推理继续使用原 `llmuser` worker、四卡空闲选择与外部用户优先守护;网站不重部署驱动、既有模型或其他用户服务。原 `llmuser-workspace` 容器 ID 保持不变,GPU 守护仍运行。CPU 配音仅挂载自己的模型只读目录、work、cache、tmp,不挂载推理服务密钥所在项目。 - -正式接入尚需数据库专用用户名和密码。收到后按 [正式配置说明](../README.md#正式-mysql-配置) 修改私有配置、初始化本应用 `visual_*` 表并重新连接验证;不会自动搬迁或覆盖数据。公网使用须提供 HTTPS 域名/反代或用户选择的受信穿透入口,设置 Secure Cookie 并保留 SSE 与鉴权文件代理行为。 diff --git a/docs/鲲鹏长视频制作指南_20261111.md b/docs/鲲鹏长视频制作指南_20261111.md index d3385ec..a3d3218 100644 --- a/docs/鲲鹏长视频制作指南_20261111.md +++ b/docs/鲲鹏长视频制作指南_20261111.md @@ -1,6 +1,15 @@ # 鲲鹏长视频制作指南 -本例把您给出的完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可修改的故事板,不是对原生模型生成100秒连续镜头的承诺。载入模板只修改本地草稿,不会自动耗用GPU或开始出片。 +> 历史参考(2026-11-13更新):本指南保留旧工作流的20镜头分镜、JSON格式、旁白与模型实测记录。独立“工作流”“批量”“成片”页面已经移除,下面带旧按钮名的步骤只解释历史版本,不能作为当前新手操作步骤;旧JSON不提供故事页直接导入。既有数据与共享后端API继续保留。 + +## 当前网页怎么制作鲲鹏故事 + +1. 从“故事”新建项目,在“01 基准板”建立鲲/鹏形态与统一场景,参考下方20镜头表在“02 分镜”组织画面与选用时长。 +2. 要自动出初稿,保存故事并“启用可编辑自动成片”,选择交互或批量队列后生成;要逐镜审核,使用故事的首帧/视频候选与确认流程。 +3. 音轨和字幕统一在故事“03 成片”中调整;已有视频先在人工候选流程导入并确认选片,再冻结合成。 +4. 在“任务”跟踪运行与历史成果。完整步骤见[主操作手册](操作手册_20261111.md)第4、7、12节和[故事操作手册](锚定工作室操作手册_20261111.md)。02分镜内容超出时在对应容器内滚动,滚动条悬停显示、移出隐藏。 + +以下旧版示例把完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可供当前故事手工编排参考的故事板,不是对原生模型生成100秒连续镜头的承诺。历史JSON载入行为仅适用于旧编辑页。 本次已实际生成完整旁白:素材名“鲲鹏完整旁白(开发验收).wav”,`zm_yunxi`、速度0.85,时长**44.425秒**。因此另提供20镜头、每镜头2.25秒、共45秒的紧凑版模板`kunpeng-storyboard-45s.json`。建议先用45秒版验证完整故事;100秒版需要扩写旁白、加入停顿或重新设计节奏,不能直接把44秒旁白与100秒分镜字幕当作已经对齐的成片。 @@ -10,7 +19,7 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页面现在支持最长361帧、约15秒原生单镜头,再按需要做多镜头合成。模型背景见[Wan2.2模型卡](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B)。 -2026-11-11的独立帆船测试已在1280×704、50步、24fps下一次生成361帧(15.041667秒),完整解码通过;这证明当前环境可以完成该规格的15秒原生镜头,但画面移动较小,不能保证鲲鹏变形等复杂动作的效果。普通视频创作和工作流现均可选择最长15秒单镜头。工作流可混合5秒、10秒、15秒镜头,合计30秒;按动作适合的长度分配,而不是将所有镜头改为15秒。本指南现有45秒/100秒模板仍保留原先的短镜头编排。 +2026-11-11的独立帆船测试已在1280×704、50步、24fps下一次生成361帧(15.041667秒),完整解码通过;这证明当前环境可以完成该规格的15秒原生镜头,但画面移动较小,不能保证鲲鹏变形等复杂动作的效果。普通视频创作支持最长15秒单镜头;旧工作流API也保留该规格。多镜头可混合5秒、10秒、15秒,合计30秒;按动作适合的长度分配,而不是将所有镜头改为15秒。本指南现有45秒/100秒模板仍保留原先的短镜头编排。 ## 二、准备故事原文与旁白 @@ -26,9 +35,9 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 旁白原文也在`frontend/public/examples/kunpeng-narration.txt`。模板中的字幕只是按分镜分配的初稿,**并未与真实配音逐句对齐**。 -使用现有旁白时,素材所属账号可跳过重新生成配音,在“我的素材”中按“鲲鹏/旁白”标签查找上述WAV。45秒模板从“导入工作流 JSON”载入;预置的“鲲鹏·45秒旁白版(未运行)”草稿属于当前管理员,已关联该管理员的完整旁白,参考图片仍需选择。普通账号和`admin`都只能直接访问自己的私有素材、任务、草稿、运行和批次,因此其他账号不会自动看到这份私有旁白或草稿。 +使用现有旁白时,素材所属账号可跳过重新生成配音,在“我的素材”中按“鲲鹏/旁白”标签查找上述WAV。旧版曾从“导入工作流 JSON”载入45秒模板,该独立页面现已移除;预置的“鲲鹏·45秒旁白版(未运行)”草稿属于当前管理员,已关联该管理员的完整旁白,参考图片仍需选择。普通账号和`admin`都只能直接访问自己的私有素材、任务、草稿、运行和批次,因此其他账号不会自动看到这份私有旁白或草稿。 -要共用旁白或参考图片,请原作者在素材中点击“发布到共享库”并确认,再由使用者切到“共享素材库”预览并导入。共享页仅登录用户可见,共享内容只读;导入后得到自己的独立私有副本。工作流的素材选择器也可切到“共享素材”,先导入再使用,不要把发布ID或他人的私有素材ID写进模板。发布者撤回共享或删除原件,不会影响已经导入的副本;共享发布占发布者磁盘额度,每份导入占导入者额度。共享素材不会自动复制工作流草稿,故事板仍需各账号自行导入JSON。 +要共用旁白或参考图片,请原作者在素材中点击“发布到共享库”并确认,再由使用者切到“共享素材库”预览并导入。共享页仅登录用户可见,共享内容只读;导入后得到自己的独立私有副本。故事的素材选择器也可切到“共享素材”,先导入再使用,不要把发布ID或他人的私有素材ID写进模板。发布者撤回共享或删除原件,不会影响已经导入的副本;共享发布占发布者磁盘额度,每份导入占导入者额度。共享素材不会自动复制旧工作流草稿;当前故事需按分镜内容自行建立,不提供旧JSON直接导入。 45秒模板总帧数1080,每镜头54帧;字幕仍须按试听调整。 @@ -41,9 +50,11 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 3. 后面在对应镜头点击“选择参考图片”。一个镜头使用一张首帧参考,不要以为模型能自动读取其它镜头的参考图。 4. 鲲变鹏属于复杂形变。先试云雾遮挡的剪影、随后切到完整鹏鸟;如果变形不稳定,用“鲲入水雾→鹏出云层”的剪辑衔接代替长时间暴露变形过程。 -## 四、载入100秒示例 +## 四、旧版100秒JSON与分镜参考 -1. 进入“工作流”,点击“载入鲲鹏示例”;如已有未保存内容,先保存或导出JSON,再确认替换。 +以下三步仅保留旧编辑页的载入语义;当前页面请按文首“当前网页怎么制作鲲鹏故事”操作,不要寻找已移除的导入入口。 + +1. 历史操作:下载100秒JSON,在旧工作流页“导入工作流 JSON”;替换前先保存或导出未保存内容。当前下载文件仅用于查看历史格式、提示词和时间安排。 2. 填写名称,例如“鲲鹏南迁-首版”。模板已填20段提示词、种子42、每段5秒、横屏画布和分镜字幕;参考图与音轨留空,需要您选择本账号素材。 3. 逐镜检查下面的内容,修改词语、时长或镜头顺序。完整可复制提示词位于导入JSON;表格是简要分镜说明。 @@ -94,7 +105,7 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 如果某镜头失败,在运行卡中“重试此阶段”。如果内容不满意,改草稿相应提示词后新建一次运行,并选择上一Run复用成功镜头。未改生成内容的镜头可复用,避免全片重新生成;改顺序导致编号变化时,某些镜头可能需要重新匹配或生成,请看提交后的步骤状态。 -想精细调整已有片段,可到“成片”选择这些视频,调整裁剪与顺序再导出。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。 +当前要精细调整已有片段,在故事人工候选流程导入视频并确认选片,再去“03 成片”调整裁剪、顺序和时间线后合成。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。 不再需要的试片可在任务卡片/详情删除记录,生成素材仍保留在“我的素材”。运行卡片删除会级联归档其子任务;删除草稿会连同其运行和子任务归档;批量成员应从所属批次删除,批次归档会包含其运行和任务,保留工作流草稿及生成素材。软归档后记录从常规页面消失,后台审计保留,原提交恢复/重放返回`410 resource_purged`,不能用原提交键恢复已删记录。 @@ -104,7 +115,7 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 ## 八、成片验收与继续扩展 -完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果您修改了时长,以工作流显示和媒体实测为准。 +完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果修改了时长,以当前故事显示和媒体实测为准。 要扩展为几分钟影片,继续添加镜头并为每镜头写具体动作、参考和字幕,再按实际旁白长度调整总时长。默认资源上限为120镜头(5秒/镜头时10分钟),管理员可提高到1000;磁盘、任务额度和超时仍有效。不要通过给单镜头填整篇故事期待一次得到几分钟连续视频。 @@ -112,6 +123,6 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 模板JSON:`frontend/public/examples/kunpeng-storyboard.json`。它不含任何账号、令牌或服务器文件路径;导入后需要手动选择您自己的参考图和音轨。 -45秒版JSON:`frontend/public/examples/kunpeng-storyboard-45s.json`。网站帮助页提供下载链接。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。 +45秒版JSON:`frontend/public/examples/kunpeng-storyboard-45s.json`。网站帮助页提供标为“旧版”的下载链接,不表示当前故事支持直接导入。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。 本项目网站业务数据保存在MySQL `192.168.28.10:3306/cmvr-visual`;生成视频、旁白、参考图以及共享/导入副本的媒体文件位于服务器宿主机`/data/llmusers/llmuser/workspace/cmvr-visual/assets`。GPU服务的SQLite只用于独立执行队列和恢复,不保存网站业务。迁移或备份鲲鹏项目应同时保留业务数据库和媒体目录,不能只复制GPU队列数据库。 diff --git a/frontend/.prettierignore b/frontend/.prettierignore new file mode 100644 index 0000000..805ea41 --- /dev/null +++ b/frontend/.prettierignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +public/ +pnpm-lock.yaml +.env* diff --git a/frontend/.prettierrc.json b/frontend/.prettierrc.json new file mode 100644 index 0000000..a91ac58 --- /dev/null +++ b/frontend/.prettierrc.json @@ -0,0 +1,7 @@ +{ + "semi": false, + "singleQuote": true, + "printWidth": 100, + "singleAttributePerLine": true, + "endOfLine": "lf" +} diff --git a/frontend/index.html b/frontend/index.html index 14e05e1..21c9614 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -1,2 +1,26 @@ <!doctype html> -<html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="#0e1116"/><meta name="description" content="CMVR Visual,本地多模态视觉创作工作台。"/><title>CMVR Visual · 视觉创作台
+ + + + + + + CMVR Visual · 视觉创作台 + + +
+ + + diff --git a/frontend/package.json b/frontend/package.json index 715d82d..92e7ffb 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,7 +8,9 @@ "typecheck": "vue-tsc --noEmit", "build": "vue-tsc --noEmit && vite build", "test": "vitest run", - "preview": "vite preview --host 127.0.0.1" + "preview": "vite preview --host 127.0.0.1", + "format": "prettier --write src package.json tsconfig.json vite.config.ts index.html .prettierrc.json pnpm-workspace.yaml", + "format:check": "prettier --check src package.json tsconfig.json vite.config.ts index.html .prettierrc.json pnpm-workspace.yaml" }, "dependencies": { "@element-plus/icons-vue": "2.3.2", @@ -23,6 +25,7 @@ "@types/katex": "0.16.8", "@types/node": "24.10.1", "@vitejs/plugin-vue": "6.0.10", + "prettier": "3.9.10", "typescript": "5.9.3", "vite": "8.3.7", "vitest": "5.1.0", diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 60c4daf..8fa6d1c 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -39,6 +39,9 @@ importers: '@vitejs/plugin-vue': specifier: 6.0.10 version: 6.0.10(vite@8.3.7(@types/node@24.10.1))(vue@3.5.45(typescript@5.9.3)) + prettier: + specifier: 3.9.10 + version: 3.9.10 typescript: specifier: 5.9.3 version: 5.9.3 @@ -547,6 +550,11 @@ packages: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} + prettier@3.9.10: + resolution: {integrity: sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==} + engines: {node: '>=14'} + hasBin: true + rolldown@1.2.18: resolution: {integrity: sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -1119,6 +1127,8 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 + prettier@3.9.10: {} + rolldown@1.2.18: dependencies: '@oxc-project/types': 0.156.0 diff --git a/frontend/public/help/editing.html b/frontend/public/help/editing.html new file mode 100644 index 0000000..4c87b2a --- /dev/null +++ b/frontend/public/help/editing.html @@ -0,0 +1,8 @@ +图生图与视频人物替换 · CMVR Visual
CMVR Visual · 使用帮助

图生图与视频人物替换操作手册

这两个功能位于“创作”。图生图使用 Qwen-Image-Edit-2511;视频人物替换使用独立的 Wan2.2-Animate-14B,并通过检测、姿态和时序遮罩区分同一视频中的人物。已有文生图、Wan2.2-TI2V-5B 单镜头生成和故事工作室继续使用各自的入口。

页面根据服务器的真实能力开放操作。视频编辑权重未就绪、尚未通过模型验收或开关关闭时,会显示原因并阻止提交。任务元数据和人物绑定记录保存在既有 MySQL 任务表,媒体文件保存在用户工作空间;本次无需增加数据库表。

1. 图生图

  1. 登录后进入“创作”,选择“图生图”,地址为 /create/image-edit。
  2. 上传参考图片,或从个人素材库选择。共享素材需要先导入个人库;选择器支持这个流程。
  3. 最多使用三张不同的参考图片。确认缩略图顺序,使用前移、后移或移除按钮调整。提示词中的“第一张、第二张、第三张”对应此处的顺序。
  4. 填写提示词,明确每张图提供什么,以及希望保留或修改的部分。例如:“保留第一张图片中女性的脸型和发型,穿第二张图片的绿色外套,站在第三张图片的海边车站,电影摄影,自然光;只出现一个人。”
  5. 选择方图 1024×1024、横图 1280×704 或竖图 704×1280。首次使用建议保持默认高级参数:40 步、guidance 1、true CFG 4、序列长度 1024。
  6. 候选数量为 1–4。每个候选是独立任务,按顺序递增种子,并真实传递全部参考图;不会自动改成文生图。
  7. 点击生成,在当前任务区或“任务”查看排队、运行和结果。生成图片进入个人素材库,可以下载、发布共享副本,或进入故事工作室作为首帧/角色参考。

参考图片用于引导外观与内容,不保证逐像素保留、严格排版或人物身份完全一致。需要修正时,优先明确提示词中的对应关系,再更换清晰的参考图;一次只调整少量参数,便于比较。

2. 分析视频并选择人物

  1. 进入“创作 → 视频人物替换”,地址为 /create/video-edit。
  2. 上传视频或选择个人库中的视频。默认一次处理最多 120 秒、跟踪最多 12 位人物(包括未选择替换的人);页面展示实际配置的上限。这是可调整的资源预算,不是每用户可生成视频的数量限制。
  3. 选择处理规格。默认使用约 480p 的像素预算;只有服务器明确开放相应能力后才能选择 720p。画幅按源视频显示方向处理,帧率统一为 24fps。
  4. 点击“识别人物”,等待分析任务完成。分析也使用受监管的 GPU 队列,不会在浏览器中执行模型。
  5. 在人物卡片或视频预览框中选择需要替换的人。可以只选一个,也可以同时选择多个人。人物编号仅用于当前视频中的轨迹,不是姓名或实名识别结果。
  6. 拖动视频播放进度,对照人物缩略图和检测框确认选择。多个轨迹交叉、长时间遮挡或人物消失后重新出现时,跟踪可能无法确定身份;系统会拒绝无法可靠对应的分析,而不是自行猜测谁是谁。此时应剪出更清晰的片段后重新分析。

更换源视频或处理规格后,原分析和人物绑定失效,需要重新识别。刷新页面可以恢复本地草稿和已持久化的任务;不要用旧分析结果绑定新视频。

3. 为一个或多个人物分别绑定参考图

  1. 为每个已选人物单独选择一张身份参考图片。建议使用清晰、无遮挡、脸部可见且服装完整的单人图片。
  2. 在对应人物下填写可选的局部提示词,例如人物一:“短发女性,绿色外套,保留原动作”;人物二:“卷发男性,棕色夹克,保留原动作”。不同人物可以绑定不同图片。
  3. 填写必填的全局提示词,描述整个视频要保持的场景、动作和风格。例如:“将所选两人分别替换为各自参考图中的人物,保持海边车站、原始站位、镜头运动和原动作,自然呼吸和眨眼,不增加其他人物。”
  4. 按需设置负面提示词、步数、CFG 和种子。默认 20 步、guidance 1、种子 42,先用默认参数比较效果。接口另支持遮罩扩展和羽化参数,范围为 0–64 像素;页面目前使用默认的 8 和 4 像素。
  5. “保留原音轨”默认开启。它保留源视频声音,不会更换配音、模仿新人物声线或自动对口型;源视频无声音时仍输出无声视频。
  6. 点击生成。服务器按人物逐个运行时序替换,再将结果合成;同一人物在处理窗口之间传递上一段的生成条件。所有已选人物都会出现在同一个最终视频中。
  7. 完成后逐段播放结果,尤其检查人物相交处、手和头发边缘,以及约每 3 秒的处理窗口连接处。检查原音轨、动作和未选人物,再下载;需要继续剪辑时,在故事“02 分镜”导入视频并确认选片,再到“03 成片”处理时间线与合成。

人物替换以原人物的可见区域为边界,并保护其他人物和背景。大幅改变体型、轮廓、发型或增加原遮罩之外的服饰可能被边界裁切;换脸相似度和复杂遮挡需要逐片验收。它适合保留原动作与镜头的外观替换;提示词不能把任意原动作变成完全不同的运动。

4. 排队、断线和删除

任务与原有创作共用持久队列。关闭网页或 HTTP/SSE 断线不会取消任务,不会停止共享 Qwen,也不会影响其他用户。返回页面后查看原任务即可。

其他服务器用户有更高的 GPU 优先级。外部用户开始占卡时,本应用停止自己的推理并释放显存,使用同一上游任务编号重新排队;当前推理进度会丢失,页面可能由“运行”变为“排队”。

所有输入、人物预览和结果只对所属用户可见。输入仍被任务引用时不能直接删除;先取消并等待执行退出,再按既有任务归档和素材删除流程处理。发布到共享库是独立副本,导入者的副本不因原件删除而消失。

5. 配置与部署

业务 API 配置文件使用以下键。修改后重启本应用 API;默认关闭新视频能力,避免把未验收的模型显示为可用。

REFERENCE_GENERATION_ENABLED=true
+REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1
+REFERENCE_MAX_IMAGES=3
+VIDEO_EDIT_ENABLED=false
+VIDEO_EDIT_PROFILE=wan-animate-replace-v1
+VIDEO_EDIT_MAX_SECONDS=120
+VIDEO_EDIT_MAX_PEOPLE=12
+VIDEO_EDIT_MAX_PIXELS=399360

推理工作空间的 config/settings.json 对应 video_edit_enabled、video_edit_profile、video_edit_max_seconds、video_edit_max_people、video_edit_max_pixels 和 video_edit_python。业务与推理均启用,并且固定模型校验清单记录已通过真实验收后,页面才开放生成。两端上限不同时按较小值执行;720p 需要将两端像素上限显式配置为 921600,并完成对应资源和效果验收。

video_edit_poc_enabled 仅用于部署时经认证接口验证模型,不代表网站能力已开放。模型、预处理检查点、外部 ONNX 张量和预处理源码均需进入完整哈希清单。新增环境与已有模型环境分开安装;调度、让卡和每卡显存预算继续由既有 GPU 监管器执行。

批量夜间准入仍使用原 runtime-policy.json 配置;开发全天开关不改变其他用户优先、资源不足等待和显式暂停规则。

版本:2026-11-13 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file diff --git a/frontend/public/help/editing.md b/frontend/public/help/editing.md new file mode 100644 index 0000000..e6113d8 --- /dev/null +++ b/frontend/public/help/editing.md @@ -0,0 +1,69 @@ +# 图生图与视频人物替换操作手册 + +这两个功能位于“创作”。图生图使用 Qwen-Image-Edit-2511;视频人物替换使用独立的 Wan2.2-Animate-14B,并通过检测、姿态和时序遮罩区分同一视频中的人物。已有文生图、Wan2.2-TI2V-5B 单镜头生成和故事工作室继续使用各自的入口。 + +页面根据服务器的真实能力开放操作。视频编辑权重未就绪、尚未通过模型验收或开关关闭时,会显示原因并阻止提交。任务元数据和人物绑定记录保存在既有 MySQL 任务表,媒体文件保存在用户工作空间;本次无需增加数据库表。 + +## 1. 图生图 + +1. 登录后进入“创作”,选择“图生图”,地址为 `/create/image-edit`。 +2. 上传参考图片,或从个人素材库选择。共享素材需要先导入个人库;选择器支持这个流程。 +3. 最多使用三张不同的参考图片。确认缩略图顺序,使用前移、后移或移除按钮调整。提示词中的“第一张、第二张、第三张”对应此处的顺序。 +4. 填写提示词,明确每张图提供什么,以及希望保留或修改的部分。例如:“保留第一张图片中女性的脸型和发型,穿第二张图片的绿色外套,站在第三张图片的海边车站,电影摄影,自然光;只出现一个人。” +5. 选择方图 1024×1024、横图 1280×704 或竖图 704×1280。首次使用建议保持默认高级参数:40 步、guidance 1、true CFG 4、序列长度 1024。 +6. 候选数量为 1–4。每个候选是独立任务,按顺序递增种子,并真实传递全部参考图;不会自动改成文生图。 +7. 点击生成,在当前任务区或“任务”查看排队、运行和结果。生成图片进入个人素材库,可以下载、发布共享副本,或进入故事工作室作为首帧/角色参考。 + +参考图片用于引导外观与内容,不保证逐像素保留、严格排版或人物身份完全一致。需要修正时,优先明确提示词中的对应关系,再更换清晰的参考图;一次只调整少量参数,便于比较。 + +## 2. 分析视频并选择人物 + +1. 进入“创作 → 视频人物替换”,地址为 `/create/video-edit`。 +2. 上传视频或选择个人库中的视频。默认一次处理最多 120 秒、跟踪最多 12 位人物(包括未选择替换的人);页面展示实际配置的上限。这是可调整的资源预算,不是每用户可生成视频的数量限制。 +3. 选择处理规格。默认使用约 480p 的像素预算;只有服务器明确开放相应能力后才能选择 720p。画幅按源视频显示方向处理,帧率统一为 24fps。 +4. 点击“识别人物”,等待分析任务完成。分析也使用受监管的 GPU 队列,不会在浏览器中执行模型。 +5. 在人物卡片或视频预览框中选择需要替换的人。可以只选一个,也可以同时选择多个人。人物编号仅用于当前视频中的轨迹,不是姓名或实名识别结果。 +6. 拖动视频播放进度,对照人物缩略图和检测框确认选择。多个轨迹交叉、长时间遮挡或人物消失后重新出现时,跟踪可能无法确定身份;系统会拒绝无法可靠对应的分析,而不是自行猜测谁是谁。此时应剪出更清晰的片段后重新分析。 + +更换源视频或处理规格后,原分析和人物绑定失效,需要重新识别。刷新页面可以恢复本地草稿和已持久化的任务;不要用旧分析结果绑定新视频。 + +## 3. 为一个或多个人物分别绑定参考图 + +1. 为每个已选人物单独选择一张身份参考图片。建议使用清晰、无遮挡、脸部可见且服装完整的单人图片。 +2. 在对应人物下填写可选的局部提示词,例如人物一:“短发女性,绿色外套,保留原动作”;人物二:“卷发男性,棕色夹克,保留原动作”。不同人物可以绑定不同图片。 +3. 填写必填的全局提示词,描述整个视频要保持的场景、动作和风格。例如:“将所选两人分别替换为各自参考图中的人物,保持海边车站、原始站位、镜头运动和原动作,自然呼吸和眨眼,不增加其他人物。” +4. 按需设置负面提示词、步数、CFG 和种子。默认 20 步、guidance 1、种子 42,先用默认参数比较效果。接口另支持遮罩扩展和羽化参数,范围为 0–64 像素;页面目前使用默认的 8 和 4 像素。 +5. “保留原音轨”默认开启。它保留源视频声音,不会更换配音、模仿新人物声线或自动对口型;源视频无声音时仍输出无声视频。 +6. 点击生成。服务器按人物逐个运行时序替换,再将结果合成;同一人物在处理窗口之间传递上一段的生成条件。所有已选人物都会出现在同一个最终视频中。 +7. 完成后逐段播放结果,尤其检查人物相交处、手和头发边缘,以及约每 3 秒的处理窗口连接处。检查原音轨、动作和未选人物,再下载;需要继续剪辑时,在故事“02 分镜”导入视频并确认选片,再到“03 成片”处理时间线与合成。 + +人物替换以原人物的可见区域为边界,并保护其他人物和背景。大幅改变体型、轮廓、发型或增加原遮罩之外的服饰可能被边界裁切;换脸相似度和复杂遮挡需要逐片验收。它适合保留原动作与镜头的外观替换;提示词不能把任意原动作变成完全不同的运动。 + +## 4. 排队、断线和删除 + +任务与原有创作共用持久队列。关闭网页或 HTTP/SSE 断线不会取消任务,不会停止共享 Qwen,也不会影响其他用户。返回页面后查看原任务即可。 + +其他服务器用户有更高的 GPU 优先级。外部用户开始占卡时,本应用停止自己的推理并释放显存,使用同一上游任务编号重新排队;当前推理进度会丢失,页面可能由“运行”变为“排队”。 + +所有输入、人物预览和结果只对所属用户可见。输入仍被任务引用时不能直接删除;先取消并等待执行退出,再按既有任务归档和素材删除流程处理。发布到共享库是独立副本,导入者的副本不因原件删除而消失。 + +## 5. 配置与部署 + +业务 API 配置文件使用以下键。修改后重启本应用 API;默认关闭新视频能力,避免把未验收的模型显示为可用。 + +```dotenv +REFERENCE_GENERATION_ENABLED=true +REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1 +REFERENCE_MAX_IMAGES=3 +VIDEO_EDIT_ENABLED=false +VIDEO_EDIT_PROFILE=wan-animate-replace-v1 +VIDEO_EDIT_MAX_SECONDS=120 +VIDEO_EDIT_MAX_PEOPLE=12 +VIDEO_EDIT_MAX_PIXELS=399360 +``` + +推理工作空间的 `config/settings.json` 对应 `video_edit_enabled`、`video_edit_profile`、`video_edit_max_seconds`、`video_edit_max_people`、`video_edit_max_pixels` 和 `video_edit_python`。业务与推理均启用,并且固定模型校验清单记录已通过真实验收后,页面才开放生成。两端上限不同时按较小值执行;720p 需要将两端像素上限显式配置为 921600,并完成对应资源和效果验收。 + +`video_edit_poc_enabled` 仅用于部署时经认证接口验证模型,不代表网站能力已开放。模型、预处理检查点、外部 ONNX 张量和预处理源码均需进入完整哈希清单。新增环境与已有模型环境分开安装;调度、让卡和每卡显存预算继续由既有 GPU 监管器执行。 + +批量夜间准入仍使用原 `runtime-policy.json` 配置;开发全天开关不改变其他用户优先、资源不足等待和显式暂停规则。 diff --git a/frontend/public/help/kunpeng.html b/frontend/public/help/kunpeng.html index 69d72df..ea0a7f3 100644 --- a/frontend/public/help/kunpeng.html +++ b/frontend/public/help/kunpeng.html @@ -1 +1 @@ -鲲鹏长视频制作指南 · CMVR Visual
CMVR Visual · 使用帮助

鲲鹏长视频制作指南

本例把您给出的完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可修改的故事板,不是对原生模型生成100秒连续镜头的承诺。载入模板只修改本地草稿,不会自动耗用GPU或开始出片。

本次已实际生成完整旁白:素材名“鲲鹏完整旁白(开发验收).wav”,zm_yunxi、速度0.85,时长44.425秒。因此另提供20镜头、每镜头2.25秒、共45秒的紧凑版模板kunpeng-storyboard-45s.json。建议先用45秒版验证完整故事;100秒版需要扩写旁白、加入停顿或重新设计节奏,不能直接把44秒旁白与100秒分镜字幕当作已经对齐的成片。

一、先明确成片方式

当前采用“逐镜生成短片段 → 选用所需帧 → 直切拼接 → 叠加一条旁白与人工字幕”。每镜头保持一个主要动作,使用统一形象和画风。跨镜头没有自动记忆,不能仅凭相同种子保证鲲、鹏长相一致。文本上下文长度控制提示词可包含多少信息,并不直接决定视频秒数;单次视频的帧数、显存、训练分布和动作复杂度也决定效果。

TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页面现在支持最长361帧、约15秒原生单镜头,再按需要做多镜头合成。模型背景见Wan2.2模型卡。

2026-11-11的独立帆船测试已在1280×704、50步、24fps下一次生成361帧(15.041667秒),完整解码通过;这证明当前环境可以完成该规格的15秒原生镜头,但画面移动较小,不能保证鲲鹏变形等复杂动作的效果。普通视频创作和工作流现均可选择最长15秒单镜头。工作流可混合5秒、10秒、15秒镜头,合计30秒;按动作适合的长度分配,而不是将所有镜头改为15秒。本指南现有45秒/100秒模板仍保留原先的短镜头编排。

二、准备故事原文与旁白

原文:

北方的大海里有一条鱼,它的名字叫鲲。鲲的体积,不知道大到有几千里。遇见大风的时候,鲲就会从鱼变化成为鸟,鸟的名字就叫做鹏。鹏的脊背,真不知道长到有几千里;当它奋起而飞的时候,那展开的翅膀就好像天边的云,正所谓大鹏一日同风起,浮云直上九万里。这只鹏鸟,当海动风气的时候就要迁徙到南方的大海去了。鹏往南方的大海迁徙的时候,翅膀拍打水面,能激起三千里的浪涛,环绕着旋风飞上了九万里的高空,乘着六月的风离开了北海。
  1. 打开“声音”,切到“配音生成”,粘贴整段原文(本例小于2000字)。
  2. 选择希望的音色;先用速度1试听,再根据叙事节奏调整。zm_yunxi或zf_xiaobei都是当前可选音色,先听后选。
  3. 点击“生成配音”,在任务完成后试听素材,记录实际音频时长T。没有生成音频前,不应假定文字一定能在100秒读完。
  4. 如果T≤100秒,可沿用100秒故事板,留出的时间作为画面呼吸或尾部静音;如果T>100秒,增加镜头,或改写旁白/调整语速。不要硬把长音频截成15秒。
  5. 将旁白素材收藏或标记“鲲鹏-完整旁白”,方便后续选择。若用自己的配音或配乐混合音轨,先在外部音频工具完成混音,再上传一条最终音轨;当前网页没有多轨混音。

旁白原文也在frontend/public/examples/kunpeng-narration.txt。模板中的字幕只是按分镜分配的初稿,并未与真实配音逐句对齐。

使用现有旁白时,素材所属账号可跳过重新生成配音,在“我的素材”中按“鲲鹏/旁白”标签查找上述WAV。45秒模板从“导入工作流 JSON”载入;预置的“鲲鹏·45秒旁白版(未运行)”草稿属于当前管理员,已关联该管理员的完整旁白,参考图片仍需选择。普通账号和admin都只能直接访问自己的私有素材、任务、草稿、运行和批次,因此其他账号不会自动看到这份私有旁白或草稿。

要共用旁白或参考图片,请原作者在素材中点击“发布到共享库”并确认,再由使用者切到“共享素材库”预览并导入。共享页仅登录用户可见,共享内容只读;导入后得到自己的独立私有副本。工作流的素材选择器也可切到“共享素材”,先导入再使用,不要把发布ID或他人的私有素材ID写进模板。发布者撤回共享或删除原件,不会影响已经导入的副本;共享发布占发布者磁盘额度,每份导入占导入者额度。共享素材不会自动复制工作流草稿,故事板仍需各账号自行导入JSON。

45秒模板总帧数1080,每镜头54帧;字幕仍须按试听调整。

三、先确定鲲和鹏的形象

建议统一视觉设定:上古神话史诗、写实CG、冷蓝北海、淡金晨光。鲲为青黑色巨鱼、银白腹部、背部淡金云纹、金色眼睛;鹏继承青黑与淡金纹理、金色眼睛。

  1. 在“创作→图片”分别生成鲲、鹏及关键变形姿态的参考图片,人工挑选满意版本。
  2. 在“素材”给参考图添加“鲲鹏/鲲/鹏/参考”标签。
  3. 后面在对应镜头点击“选择参考图片”。一个镜头使用一张首帧参考,不要以为模型能自动读取其它镜头的参考图。
  4. 鲲变鹏属于复杂形变。先试云雾遮挡的剪影、随后切到完整鹏鸟;如果变形不稳定,用“鲲入水雾→鹏出云层”的剪辑衔接代替长时间暴露变形过程。

四、载入100秒示例

  1. 进入“工作流”,点击“载入鲲鹏示例”;如已有未保存内容,先保存或导出JSON,再确认替换。
  2. 填写名称,例如“鲲鹏南迁-首版”。模板已填20段提示词、种子42、每段5秒、横屏画布和分镜字幕;参考图与音轨留空,需要您选择本账号素材。
  3. 逐镜检查下面的内容,修改词语、时长或镜头顺序。完整可复制提示词位于导入JSON;表格是简要分镜说明。
镜头成片时间旁白初稿画面与动作
1 · 北冥海面0–5秒北方的大海里有一条鱼,北方无边的深靛蓝海面,云雾低垂,一条青黑色巨鱼的轮廓在海面下缓缓游过。高空极远景,镜头缓慢向前推进,以海浪衬托鱼体的巨大。
2 · 鲲的眼睛5–10秒它的名字叫鲲。青黑色巨鱼鲲的金色眼睛特写,银白色腹部边缘与淡金云纹若隐若现。鲲缓缓转动眼睛,细小水流掠过表面,镜头平稳侧移。
3 · 巨鲲全貌10–15秒鲲的体积,从深海侧面看到完整的青黑巨鲲,银白腹部,背部淡金云纹,宽阔鱼鳍轻缓划水,形体如海底山脉。镜头缓慢后退,展示壮阔全貌。
4 · 千里之巨15–20秒不知道大到有几千里。极高空俯瞰,巨鲲的脊背仿佛一片移动的大陆穿过北海,身旁细小浪纹作为尺度参照,云影掠过青黑鱼背。固定广角,仅鱼体缓慢前进。
5 · 大风将起20–25秒遇见大风的时候,北海远方乌云聚拢,大风推动海面形成巨大的波纹,青黑巨鲲露出一段背脊。广角平视,镜头慢慢抬起,云层成为画面主体。
6 · 化鹏一瞬25–30秒鲲就会从鱼变化成为鸟,巨鲲跃出北海的侧面剪影,被逆光云雾和水幕包围;宽大鱼鳍在水幕遮挡中逐渐展开为羽翼,青黑与淡金纹理保持一致。一个主体,一次缓慢展开动作,固定侧面中远景。
7 · 鹏鸟显形30–35秒鸟的名字就叫做鹏。水雾散去,一只青黑色巨鹏出现在北海上空,金色眼睛,羽缘带淡金云纹。鹏保持完整鸟形,缓缓展开双翼,低机位仰拍。
8 · 鹏背如山35–40秒鹏的脊背,巨鹏青黑羽毛覆盖的背脊近景,淡金纹理连成山峦般的起伏,薄云从羽毛上方掠过。镜头沿背部缓慢向前滑行。
9 · 背脊无尽40–45秒真不知道长到有几千里;镜头从巨鹏背部缓缓升高并后退,鹏的背脊延伸到远方云海,金色羽缘在晨光下微亮,用云层显示宏大尺度。
10 · 奋起而飞45–50秒当它奋起而飞的时候,完整的青黑巨鹏在云海上方振翅一次,身体随气流平稳抬升,淡金羽缘反光。正侧面全景,摄影机平稳跟随,不旋转。
11 · 翼若垂天云50–55秒那展开的翅膀就好像天边的云,从鹏下方仰看,一只巨鹏的双翼横贯天空,青黑羽毛与淡金羽缘连成天边云幕,阳光从羽翼间透下。固定超广角,羽翼缓慢舒展。
12 · 同风而起55–60秒正所谓大鹏一日同风起,巨鹏顺着强劲风流向上飞,青黑羽翼稳定展开,云带在其身后分开。宽幅远景,镜头以相同速度平稳上升。
13 · 扶摇高空60–65秒浮云直上九万里。从极远处看到一只完整巨鹏穿过明亮的云层上升,北海缩小在下方,青金色光线勾勒鸟的轮廓。镜头缓慢拉远,突出高空。
14 · 海动风气65–70秒这只鹏鸟,当海动风气的时候北海上空风云涌动,海面形成螺旋状涌浪,一只青黑巨鹏在高处顺风盘旋。高空广角,镜头缓慢横移,保持主体完整。
15 · 南冥召唤70–75秒就要迁徙到南方的大海去了。云层间露出南方温暖的金色天光,青黑巨鹏面向南方,羽缘淡金纹理清晰,北方冷蓝海面留在身后。镜头从侧后方缓慢跟随。
16 · 离海启程75–80秒鹏往南方的大海迁徙的时候,巨鹏从北海海面上方向南方平稳掠过,广阔青黑双翼保持完整,海浪被气流分开。贴近海面的远距离侧向跟拍,主体缓慢前进。
17 · 拍海三千里80–85秒翅膀拍打水面,能激起三千里的浪涛,青黑巨鹏的一次振翼掠过北海水面,强劲气流激起连绵巨浪,水花在金色逆光中飞散。极远景展示完整鸟形与波涛,镜头稳定。
18 · 扶摇九万里85–90秒环绕着旋风飞上了九万里的高空,一只青黑巨鹏沿巨大气流旋涡的边缘平稳向上飞,云带环绕,北海在下方逐渐遥远。摄影机平稳抬升,不快速翻转,展现清晰鸟形。
19 · 六月长风90–95秒乘着六月的风温暖的六月阳光穿透薄云,巨鹏的淡金羽缘泛光,它借助稳定南风展开双翼滑翔。侧后方远景,镜头平缓跟随,冷蓝逐渐过渡到暖金。
20 · 北海南迁95–100秒离开了北海。辽阔高空全景,青黑巨鹏向南方明亮的海天交界滑翔,北海冷蓝云层渐渐远去,鹏的剪影逐渐变小。摄影机缓慢拉远,形成庄严宁静的结尾。

五、添加音轨并校正字幕

  1. 在“成片设置”选择横屏和“完整画面(留边)”;若希望填满画面,可改“填满画面”,但要检查巨鹏翅膀是否被裁掉。
  2. 点击“选择音频素材”,选前面生成的完整旁白。源入点填0,源出点填音频实际毫秒数,偏移填0帧。例如旁白实测92.4秒,出点为92400;这只是单位示例,不是本例实际配音结果。
  3. 若源出点+偏移超过2400帧,应增加镜头或调整时长。字幕与旁白不能超出最终总帧数。
  4. 按实际试听改字幕时间:开始帧=开始秒数×24、结束帧=结束秒数×24,取整数帧。例:一句实际出现在31.5至36秒,填756至864。
  5. 模板的20条字幕每条初始占5秒。改变镜头顺序/时长后重新检查,系统不会自动把字幕重新对齐到配音。

六、先做小样,再生成全片

建议先“新建”一个3镜头测试草稿,复制北海、变形、鹏鸟三种代表性提示词,选相应参考图,生成并检查。不要直接在20镜头模板上随意试全部参数。

检查角色外形、翅膀数量、变形可信度、海浪尺度、色调、镜头运动、参考图是否生效、横竖版裁切。如果复杂动作失败,把一个镜头拆成两个简单镜头。单次生成的短片也可以先用较低步数在“创作→视频”测试;工作流默认仍采用经过验收的50步规格。

小样满意后,打开保存的20镜头草稿,补全全部参考图、音轨和字幕,点击“保存草稿”,再“保存并运行”。仅保存不会开始生成。首次完整运行不应盲选不相关的旧Run复用。

七、观察与修改

任务会按镜头1、2……20顺序生成,再进入成片渲染,共21个步骤。网页可以关闭,服务器仍继续;外部用户使用GPU时会优先让卡,因此总等待时间不固定。

前轮3镜头默认规格实测约19分12秒,包含冷加载、Whisper插队与归档。按相近条件估算20镜头是小时级工作,约2小时只能作为粗略资源预算,不能作为完成时间保证。排队、抢占、模型切换和失败重试都会改变耗时。

如果某镜头失败,在运行卡中“重试此阶段”。如果内容不满意,改草稿相应提示词后新建一次运行,并选择上一Run复用成功镜头。未改生成内容的镜头可复用,避免全片重新生成;改顺序导致编号变化时,某些镜头可能需要重新匹配或生成,请看提交后的步骤状态。

想精细调整已有片段,可到“成片”选择这些视频,调整裁剪与顺序再导出。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。

不再需要的试片可在任务卡片/详情删除记录,生成素材仍保留在“我的素材”。运行卡片删除会级联归档其子任务;删除草稿会连同其运行和子任务归档;批量成员应从所属批次删除,批次归档会包含其运行和任务,保留工作流草稿及生成素材。软归档后记录从常规页面消失,后台审计保留,原提交恢复/重放返回410 resource_purged,不能用原提交键恢复已删记录。

清理前先考虑后续复用:旧镜头任务仍被其他运行选用时,删除会返回409,须先删除依赖它的运行;参考图、旁白和片段仍被草稿/冻结运行引用时,先解除草稿引用并保存,或删除相关运行/父批次。活跃记录先取消,等待执行退出和清理确认再删。若要同时清理媒体,需要再删除相应私有素材;共享撤回应单独操作,已导入副本不受影响。

删除和撤回不会立即腾出磁盘。GC默认dry-run盘点,默认14天保留期后仍须运维显式开启维护并执行物理清理(purge),且仍有引用的文件会受保护;文件真正清理后才释放相应占用。

八、成片验收与继续扩展

完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果您修改了时长,以工作流显示和媒体实测为准。

要扩展为几分钟影片,继续添加镜头并为每镜头写具体动作、参考和字幕,再按实际旁白长度调整总时长。默认资源上限为120镜头(5秒/镜头时10分钟),管理员可提高到1000;磁盘、任务额度和超时仍有效。不要通过给单镜头填整篇故事期待一次得到几分钟连续视频。

开发阶段批量时段限制关闭时可全天测试;生产启用后,批量08:00停止后续镜头/阶段准入,当前阶段完成,余下镜头等21:00。详情见操作手册。

模板JSON:frontend/public/examples/kunpeng-storyboard.json。它不含任何账号、令牌或服务器文件路径;导入后需要手动选择您自己的参考图和音轨。

45秒版JSON:frontend/public/examples/kunpeng-storyboard-45s.json。网站帮助页提供下载链接。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。

本项目网站业务数据保存在MySQL 192.168.28.10:3306/cmvr-visual;生成视频、旁白、参考图以及共享/导入副本的媒体文件位于服务器宿主机/data/llmusers/llmuser/workspace/cmvr-visual/assets。GPU服务的SQLite只用于独立执行队列和恢复,不保存网站业务。迁移或备份鲲鹏项目应同时保留业务数据库和媒体目录,不能只复制GPU队列数据库。

版本:2026-11-11 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file +鲲鹏长视频制作指南 · CMVR Visual
CMVR Visual · 使用帮助

鲲鹏长视频制作指南

历史参考(2026-11-13更新):本指南保留旧工作流的20镜头分镜、JSON格式、旁白与模型实测记录。独立“工作流”“批量”“成片”页面已经移除,下面带旧按钮名的步骤只解释历史版本,不能作为当前新手操作步骤;旧JSON不提供故事页直接导入。既有数据与共享后端API继续保留。

当前网页怎么制作鲲鹏故事

  1. 从“故事”新建项目,在“01 基准板”建立鲲/鹏形态与统一场景,参考下方20镜头表在“02 分镜”组织画面与选用时长。
  2. 要自动出初稿,保存故事并“启用可编辑自动成片”,选择交互或批量队列后生成;要逐镜审核,使用故事的首帧/视频候选与确认流程。
  3. 音轨和字幕统一在故事“03 成片”中调整;已有视频先在人工候选流程导入并确认选片,再冻结合成。
  4. 在“任务”跟踪运行与历史成果。完整步骤见主操作手册第4、7、12节和故事操作手册。02分镜内容超出时在对应容器内滚动,滚动条悬停显示、移出隐藏。

以下旧版示例把完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可供当前故事手工编排参考的故事板,不是对原生模型生成100秒连续镜头的承诺。历史JSON载入行为仅适用于旧编辑页。

本次已实际生成完整旁白:素材名“鲲鹏完整旁白(开发验收).wav”,zm_yunxi、速度0.85,时长44.425秒。因此另提供20镜头、每镜头2.25秒、共45秒的紧凑版模板kunpeng-storyboard-45s.json。建议先用45秒版验证完整故事;100秒版需要扩写旁白、加入停顿或重新设计节奏,不能直接把44秒旁白与100秒分镜字幕当作已经对齐的成片。

一、先明确成片方式

当前采用“逐镜生成短片段 → 选用所需帧 → 直切拼接 → 叠加一条旁白与人工字幕”。每镜头保持一个主要动作,使用统一形象和画风。跨镜头没有自动记忆,不能仅凭相同种子保证鲲、鹏长相一致。文本上下文长度控制提示词可包含多少信息,并不直接决定视频秒数;单次视频的帧数、显存、训练分布和动作复杂度也决定效果。

TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页面现在支持最长361帧、约15秒原生单镜头,再按需要做多镜头合成。模型背景见Wan2.2模型卡。

2026-11-11的独立帆船测试已在1280×704、50步、24fps下一次生成361帧(15.041667秒),完整解码通过;这证明当前环境可以完成该规格的15秒原生镜头,但画面移动较小,不能保证鲲鹏变形等复杂动作的效果。普通视频创作支持最长15秒单镜头;旧工作流API也保留该规格。多镜头可混合5秒、10秒、15秒,合计30秒;按动作适合的长度分配,而不是将所有镜头改为15秒。本指南现有45秒/100秒模板仍保留原先的短镜头编排。

二、准备故事原文与旁白

原文:

北方的大海里有一条鱼,它的名字叫鲲。鲲的体积,不知道大到有几千里。遇见大风的时候,鲲就会从鱼变化成为鸟,鸟的名字就叫做鹏。鹏的脊背,真不知道长到有几千里;当它奋起而飞的时候,那展开的翅膀就好像天边的云,正所谓大鹏一日同风起,浮云直上九万里。这只鹏鸟,当海动风气的时候就要迁徙到南方的大海去了。鹏往南方的大海迁徙的时候,翅膀拍打水面,能激起三千里的浪涛,环绕着旋风飞上了九万里的高空,乘着六月的风离开了北海。
  1. 打开“声音”,切到“配音生成”,粘贴整段原文(本例小于2000字)。
  2. 选择希望的音色;先用速度1试听,再根据叙事节奏调整。zm_yunxi或zf_xiaobei都是当前可选音色,先听后选。
  3. 点击“生成配音”,在任务完成后试听素材,记录实际音频时长T。没有生成音频前,不应假定文字一定能在100秒读完。
  4. 如果T≤100秒,可沿用100秒故事板,留出的时间作为画面呼吸或尾部静音;如果T>100秒,增加镜头,或改写旁白/调整语速。不要硬把长音频截成15秒。
  5. 将旁白素材收藏或标记“鲲鹏-完整旁白”,方便后续选择。若用自己的配音或配乐混合音轨,先在外部音频工具完成混音,再上传一条最终音轨;当前网页没有多轨混音。

旁白原文也在frontend/public/examples/kunpeng-narration.txt。模板中的字幕只是按分镜分配的初稿,并未与真实配音逐句对齐。

使用现有旁白时,素材所属账号可跳过重新生成配音,在“我的素材”中按“鲲鹏/旁白”标签查找上述WAV。旧版曾从“导入工作流 JSON”载入45秒模板,该独立页面现已移除;预置的“鲲鹏·45秒旁白版(未运行)”草稿属于当前管理员,已关联该管理员的完整旁白,参考图片仍需选择。普通账号和admin都只能直接访问自己的私有素材、任务、草稿、运行和批次,因此其他账号不会自动看到这份私有旁白或草稿。

要共用旁白或参考图片,请原作者在素材中点击“发布到共享库”并确认,再由使用者切到“共享素材库”预览并导入。共享页仅登录用户可见,共享内容只读;导入后得到自己的独立私有副本。故事的素材选择器也可切到“共享素材”,先导入再使用,不要把发布ID或他人的私有素材ID写进模板。发布者撤回共享或删除原件,不会影响已经导入的副本;共享发布占发布者磁盘额度,每份导入占导入者额度。共享素材不会自动复制旧工作流草稿;当前故事需按分镜内容自行建立,不提供旧JSON直接导入。

45秒模板总帧数1080,每镜头54帧;字幕仍须按试听调整。

三、先确定鲲和鹏的形象

建议统一视觉设定:上古神话史诗、写实CG、冷蓝北海、淡金晨光。鲲为青黑色巨鱼、银白腹部、背部淡金云纹、金色眼睛;鹏继承青黑与淡金纹理、金色眼睛。

  1. 在“创作→图片”分别生成鲲、鹏及关键变形姿态的参考图片,人工挑选满意版本。
  2. 在“素材”给参考图添加“鲲鹏/鲲/鹏/参考”标签。
  3. 后面在对应镜头点击“选择参考图片”。一个镜头使用一张首帧参考,不要以为模型能自动读取其它镜头的参考图。
  4. 鲲变鹏属于复杂形变。先试云雾遮挡的剪影、随后切到完整鹏鸟;如果变形不稳定,用“鲲入水雾→鹏出云层”的剪辑衔接代替长时间暴露变形过程。

四、旧版100秒JSON与分镜参考

以下三步仅保留旧编辑页的载入语义;当前页面请按文首“当前网页怎么制作鲲鹏故事”操作,不要寻找已移除的导入入口。

  1. 历史操作:下载100秒JSON,在旧工作流页“导入工作流 JSON”;替换前先保存或导出未保存内容。当前下载文件仅用于查看历史格式、提示词和时间安排。
  2. 填写名称,例如“鲲鹏南迁-首版”。模板已填20段提示词、种子42、每段5秒、横屏画布和分镜字幕;参考图与音轨留空,需要您选择本账号素材。
  3. 逐镜检查下面的内容,修改词语、时长或镜头顺序。完整可复制提示词位于导入JSON;表格是简要分镜说明。
镜头成片时间旁白初稿画面与动作
1 · 北冥海面0–5秒北方的大海里有一条鱼,北方无边的深靛蓝海面,云雾低垂,一条青黑色巨鱼的轮廓在海面下缓缓游过。高空极远景,镜头缓慢向前推进,以海浪衬托鱼体的巨大。
2 · 鲲的眼睛5–10秒它的名字叫鲲。青黑色巨鱼鲲的金色眼睛特写,银白色腹部边缘与淡金云纹若隐若现。鲲缓缓转动眼睛,细小水流掠过表面,镜头平稳侧移。
3 · 巨鲲全貌10–15秒鲲的体积,从深海侧面看到完整的青黑巨鲲,银白腹部,背部淡金云纹,宽阔鱼鳍轻缓划水,形体如海底山脉。镜头缓慢后退,展示壮阔全貌。
4 · 千里之巨15–20秒不知道大到有几千里。极高空俯瞰,巨鲲的脊背仿佛一片移动的大陆穿过北海,身旁细小浪纹作为尺度参照,云影掠过青黑鱼背。固定广角,仅鱼体缓慢前进。
5 · 大风将起20–25秒遇见大风的时候,北海远方乌云聚拢,大风推动海面形成巨大的波纹,青黑巨鲲露出一段背脊。广角平视,镜头慢慢抬起,云层成为画面主体。
6 · 化鹏一瞬25–30秒鲲就会从鱼变化成为鸟,巨鲲跃出北海的侧面剪影,被逆光云雾和水幕包围;宽大鱼鳍在水幕遮挡中逐渐展开为羽翼,青黑与淡金纹理保持一致。一个主体,一次缓慢展开动作,固定侧面中远景。
7 · 鹏鸟显形30–35秒鸟的名字就叫做鹏。水雾散去,一只青黑色巨鹏出现在北海上空,金色眼睛,羽缘带淡金云纹。鹏保持完整鸟形,缓缓展开双翼,低机位仰拍。
8 · 鹏背如山35–40秒鹏的脊背,巨鹏青黑羽毛覆盖的背脊近景,淡金纹理连成山峦般的起伏,薄云从羽毛上方掠过。镜头沿背部缓慢向前滑行。
9 · 背脊无尽40–45秒真不知道长到有几千里;镜头从巨鹏背部缓缓升高并后退,鹏的背脊延伸到远方云海,金色羽缘在晨光下微亮,用云层显示宏大尺度。
10 · 奋起而飞45–50秒当它奋起而飞的时候,完整的青黑巨鹏在云海上方振翅一次,身体随气流平稳抬升,淡金羽缘反光。正侧面全景,摄影机平稳跟随,不旋转。
11 · 翼若垂天云50–55秒那展开的翅膀就好像天边的云,从鹏下方仰看,一只巨鹏的双翼横贯天空,青黑羽毛与淡金羽缘连成天边云幕,阳光从羽翼间透下。固定超广角,羽翼缓慢舒展。
12 · 同风而起55–60秒正所谓大鹏一日同风起,巨鹏顺着强劲风流向上飞,青黑羽翼稳定展开,云带在其身后分开。宽幅远景,镜头以相同速度平稳上升。
13 · 扶摇高空60–65秒浮云直上九万里。从极远处看到一只完整巨鹏穿过明亮的云层上升,北海缩小在下方,青金色光线勾勒鸟的轮廓。镜头缓慢拉远,突出高空。
14 · 海动风气65–70秒这只鹏鸟,当海动风气的时候北海上空风云涌动,海面形成螺旋状涌浪,一只青黑巨鹏在高处顺风盘旋。高空广角,镜头缓慢横移,保持主体完整。
15 · 南冥召唤70–75秒就要迁徙到南方的大海去了。云层间露出南方温暖的金色天光,青黑巨鹏面向南方,羽缘淡金纹理清晰,北方冷蓝海面留在身后。镜头从侧后方缓慢跟随。
16 · 离海启程75–80秒鹏往南方的大海迁徙的时候,巨鹏从北海海面上方向南方平稳掠过,广阔青黑双翼保持完整,海浪被气流分开。贴近海面的远距离侧向跟拍,主体缓慢前进。
17 · 拍海三千里80–85秒翅膀拍打水面,能激起三千里的浪涛,青黑巨鹏的一次振翼掠过北海水面,强劲气流激起连绵巨浪,水花在金色逆光中飞散。极远景展示完整鸟形与波涛,镜头稳定。
18 · 扶摇九万里85–90秒环绕着旋风飞上了九万里的高空,一只青黑巨鹏沿巨大气流旋涡的边缘平稳向上飞,云带环绕,北海在下方逐渐遥远。摄影机平稳抬升,不快速翻转,展现清晰鸟形。
19 · 六月长风90–95秒乘着六月的风温暖的六月阳光穿透薄云,巨鹏的淡金羽缘泛光,它借助稳定南风展开双翼滑翔。侧后方远景,镜头平缓跟随,冷蓝逐渐过渡到暖金。
20 · 北海南迁95–100秒离开了北海。辽阔高空全景,青黑巨鹏向南方明亮的海天交界滑翔,北海冷蓝云层渐渐远去,鹏的剪影逐渐变小。摄影机缓慢拉远,形成庄严宁静的结尾。

五、添加音轨并校正字幕

  1. 在“成片设置”选择横屏和“完整画面(留边)”;若希望填满画面,可改“填满画面”,但要检查巨鹏翅膀是否被裁掉。
  2. 点击“选择音频素材”,选前面生成的完整旁白。源入点填0,源出点填音频实际毫秒数,偏移填0帧。例如旁白实测92.4秒,出点为92400;这只是单位示例,不是本例实际配音结果。
  3. 若源出点+偏移超过2400帧,应增加镜头或调整时长。字幕与旁白不能超出最终总帧数。
  4. 按实际试听改字幕时间:开始帧=开始秒数×24、结束帧=结束秒数×24,取整数帧。例:一句实际出现在31.5至36秒,填756至864。
  5. 模板的20条字幕每条初始占5秒。改变镜头顺序/时长后重新检查,系统不会自动把字幕重新对齐到配音。

六、先做小样,再生成全片

建议先“新建”一个3镜头测试草稿,复制北海、变形、鹏鸟三种代表性提示词,选相应参考图,生成并检查。不要直接在20镜头模板上随意试全部参数。

检查角色外形、翅膀数量、变形可信度、海浪尺度、色调、镜头运动、参考图是否生效、横竖版裁切。如果复杂动作失败,把一个镜头拆成两个简单镜头。单次生成的短片也可以先用较低步数在“创作→视频”测试;工作流默认仍采用经过验收的50步规格。

小样满意后,打开保存的20镜头草稿,补全全部参考图、音轨和字幕,点击“保存草稿”,再“保存并运行”。仅保存不会开始生成。首次完整运行不应盲选不相关的旧Run复用。

七、观察与修改

任务会按镜头1、2……20顺序生成,再进入成片渲染,共21个步骤。网页可以关闭,服务器仍继续;外部用户使用GPU时会优先让卡,因此总等待时间不固定。

前轮3镜头默认规格实测约19分12秒,包含冷加载、Whisper插队与归档。按相近条件估算20镜头是小时级工作,约2小时只能作为粗略资源预算,不能作为完成时间保证。排队、抢占、模型切换和失败重试都会改变耗时。

如果某镜头失败,在运行卡中“重试此阶段”。如果内容不满意,改草稿相应提示词后新建一次运行,并选择上一Run复用成功镜头。未改生成内容的镜头可复用,避免全片重新生成;改顺序导致编号变化时,某些镜头可能需要重新匹配或生成,请看提交后的步骤状态。

当前要精细调整已有片段,在故事人工候选流程导入视频并确认选片,再去“03 成片”调整裁剪、顺序和时间线后合成。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。

不再需要的试片可在任务卡片/详情删除记录,生成素材仍保留在“我的素材”。运行卡片删除会级联归档其子任务;删除草稿会连同其运行和子任务归档;批量成员应从所属批次删除,批次归档会包含其运行和任务,保留工作流草稿及生成素材。软归档后记录从常规页面消失,后台审计保留,原提交恢复/重放返回410 resource_purged,不能用原提交键恢复已删记录。

清理前先考虑后续复用:旧镜头任务仍被其他运行选用时,删除会返回409,须先删除依赖它的运行;参考图、旁白和片段仍被草稿/冻结运行引用时,先解除草稿引用并保存,或删除相关运行/父批次。活跃记录先取消,等待执行退出和清理确认再删。若要同时清理媒体,需要再删除相应私有素材;共享撤回应单独操作,已导入副本不受影响。

删除和撤回不会立即腾出磁盘。GC默认dry-run盘点,默认14天保留期后仍须运维显式开启维护并执行物理清理(purge),且仍有引用的文件会受保护;文件真正清理后才释放相应占用。

八、成片验收与继续扩展

完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果修改了时长,以当前故事显示和媒体实测为准。

要扩展为几分钟影片,继续添加镜头并为每镜头写具体动作、参考和字幕,再按实际旁白长度调整总时长。默认资源上限为120镜头(5秒/镜头时10分钟),管理员可提高到1000;磁盘、任务额度和超时仍有效。不要通过给单镜头填整篇故事期待一次得到几分钟连续视频。

开发阶段批量时段限制关闭时可全天测试;生产启用后,批量08:00停止后续镜头/阶段准入,当前阶段完成,余下镜头等21:00。详情见操作手册功能与生产流程。

模板JSON:frontend/public/examples/kunpeng-storyboard.json。它不含任何账号、令牌或服务器文件路径;导入后需要手动选择您自己的参考图和音轨。

45秒版JSON:frontend/public/examples/kunpeng-storyboard-45s.json。网站帮助页提供标为“旧版”的下载链接,不表示当前故事支持直接导入。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。

本项目网站业务数据保存在MySQL 192.168.28.10:3306/cmvr-visual;生成视频、旁白、参考图以及共享/导入副本的媒体文件位于服务器宿主机/data/llmusers/llmuser/workspace/cmvr-visual/assets。GPU服务的SQLite只用于独立执行队列和恢复,不保存网站业务。迁移或备份鲲鹏项目应同时保留业务数据库和媒体目录,不能只复制GPU队列数据库。

版本:2026-11-13 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file diff --git a/frontend/public/help/kunpeng.md b/frontend/public/help/kunpeng.md index d3385ec..a3d3218 100644 --- a/frontend/public/help/kunpeng.md +++ b/frontend/public/help/kunpeng.md @@ -1,6 +1,15 @@ # 鲲鹏长视频制作指南 -本例把您给出的完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可修改的故事板,不是对原生模型生成100秒连续镜头的承诺。载入模板只修改本地草稿,不会自动耗用GPU或开始出片。 +> 历史参考(2026-11-13更新):本指南保留旧工作流的20镜头分镜、JSON格式、旁白与模型实测记录。独立“工作流”“批量”“成片”页面已经移除,下面带旧按钮名的步骤只解释历史版本,不能作为当前新手操作步骤;旧JSON不提供故事页直接导入。既有数据与共享后端API继续保留。 + +## 当前网页怎么制作鲲鹏故事 + +1. 从“故事”新建项目,在“01 基准板”建立鲲/鹏形态与统一场景,参考下方20镜头表在“02 分镜”组织画面与选用时长。 +2. 要自动出初稿,保存故事并“启用可编辑自动成片”,选择交互或批量队列后生成;要逐镜审核,使用故事的首帧/视频候选与确认流程。 +3. 音轨和字幕统一在故事“03 成片”中调整;已有视频先在人工候选流程导入并确认选片,再冻结合成。 +4. 在“任务”跟踪运行与历史成果。完整步骤见[主操作手册](操作手册_20261111.md)第4、7、12节和[故事操作手册](锚定工作室操作手册_20261111.md)。02分镜内容超出时在对应容器内滚动,滚动条悬停显示、移出隐藏。 + +以下旧版示例把完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可供当前故事手工编排参考的故事板,不是对原生模型生成100秒连续镜头的承诺。历史JSON载入行为仅适用于旧编辑页。 本次已实际生成完整旁白:素材名“鲲鹏完整旁白(开发验收).wav”,`zm_yunxi`、速度0.85,时长**44.425秒**。因此另提供20镜头、每镜头2.25秒、共45秒的紧凑版模板`kunpeng-storyboard-45s.json`。建议先用45秒版验证完整故事;100秒版需要扩写旁白、加入停顿或重新设计节奏,不能直接把44秒旁白与100秒分镜字幕当作已经对齐的成片。 @@ -10,7 +19,7 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页面现在支持最长361帧、约15秒原生单镜头,再按需要做多镜头合成。模型背景见[Wan2.2模型卡](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B)。 -2026-11-11的独立帆船测试已在1280×704、50步、24fps下一次生成361帧(15.041667秒),完整解码通过;这证明当前环境可以完成该规格的15秒原生镜头,但画面移动较小,不能保证鲲鹏变形等复杂动作的效果。普通视频创作和工作流现均可选择最长15秒单镜头。工作流可混合5秒、10秒、15秒镜头,合计30秒;按动作适合的长度分配,而不是将所有镜头改为15秒。本指南现有45秒/100秒模板仍保留原先的短镜头编排。 +2026-11-11的独立帆船测试已在1280×704、50步、24fps下一次生成361帧(15.041667秒),完整解码通过;这证明当前环境可以完成该规格的15秒原生镜头,但画面移动较小,不能保证鲲鹏变形等复杂动作的效果。普通视频创作支持最长15秒单镜头;旧工作流API也保留该规格。多镜头可混合5秒、10秒、15秒,合计30秒;按动作适合的长度分配,而不是将所有镜头改为15秒。本指南现有45秒/100秒模板仍保留原先的短镜头编排。 ## 二、准备故事原文与旁白 @@ -26,9 +35,9 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 旁白原文也在`frontend/public/examples/kunpeng-narration.txt`。模板中的字幕只是按分镜分配的初稿,**并未与真实配音逐句对齐**。 -使用现有旁白时,素材所属账号可跳过重新生成配音,在“我的素材”中按“鲲鹏/旁白”标签查找上述WAV。45秒模板从“导入工作流 JSON”载入;预置的“鲲鹏·45秒旁白版(未运行)”草稿属于当前管理员,已关联该管理员的完整旁白,参考图片仍需选择。普通账号和`admin`都只能直接访问自己的私有素材、任务、草稿、运行和批次,因此其他账号不会自动看到这份私有旁白或草稿。 +使用现有旁白时,素材所属账号可跳过重新生成配音,在“我的素材”中按“鲲鹏/旁白”标签查找上述WAV。旧版曾从“导入工作流 JSON”载入45秒模板,该独立页面现已移除;预置的“鲲鹏·45秒旁白版(未运行)”草稿属于当前管理员,已关联该管理员的完整旁白,参考图片仍需选择。普通账号和`admin`都只能直接访问自己的私有素材、任务、草稿、运行和批次,因此其他账号不会自动看到这份私有旁白或草稿。 -要共用旁白或参考图片,请原作者在素材中点击“发布到共享库”并确认,再由使用者切到“共享素材库”预览并导入。共享页仅登录用户可见,共享内容只读;导入后得到自己的独立私有副本。工作流的素材选择器也可切到“共享素材”,先导入再使用,不要把发布ID或他人的私有素材ID写进模板。发布者撤回共享或删除原件,不会影响已经导入的副本;共享发布占发布者磁盘额度,每份导入占导入者额度。共享素材不会自动复制工作流草稿,故事板仍需各账号自行导入JSON。 +要共用旁白或参考图片,请原作者在素材中点击“发布到共享库”并确认,再由使用者切到“共享素材库”预览并导入。共享页仅登录用户可见,共享内容只读;导入后得到自己的独立私有副本。故事的素材选择器也可切到“共享素材”,先导入再使用,不要把发布ID或他人的私有素材ID写进模板。发布者撤回共享或删除原件,不会影响已经导入的副本;共享发布占发布者磁盘额度,每份导入占导入者额度。共享素材不会自动复制旧工作流草稿;当前故事需按分镜内容自行建立,不提供旧JSON直接导入。 45秒模板总帧数1080,每镜头54帧;字幕仍须按试听调整。 @@ -41,9 +50,11 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 3. 后面在对应镜头点击“选择参考图片”。一个镜头使用一张首帧参考,不要以为模型能自动读取其它镜头的参考图。 4. 鲲变鹏属于复杂形变。先试云雾遮挡的剪影、随后切到完整鹏鸟;如果变形不稳定,用“鲲入水雾→鹏出云层”的剪辑衔接代替长时间暴露变形过程。 -## 四、载入100秒示例 +## 四、旧版100秒JSON与分镜参考 -1. 进入“工作流”,点击“载入鲲鹏示例”;如已有未保存内容,先保存或导出JSON,再确认替换。 +以下三步仅保留旧编辑页的载入语义;当前页面请按文首“当前网页怎么制作鲲鹏故事”操作,不要寻找已移除的导入入口。 + +1. 历史操作:下载100秒JSON,在旧工作流页“导入工作流 JSON”;替换前先保存或导出未保存内容。当前下载文件仅用于查看历史格式、提示词和时间安排。 2. 填写名称,例如“鲲鹏南迁-首版”。模板已填20段提示词、种子42、每段5秒、横屏画布和分镜字幕;参考图与音轨留空,需要您选择本账号素材。 3. 逐镜检查下面的内容,修改词语、时长或镜头顺序。完整可复制提示词位于导入JSON;表格是简要分镜说明。 @@ -94,7 +105,7 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 如果某镜头失败,在运行卡中“重试此阶段”。如果内容不满意,改草稿相应提示词后新建一次运行,并选择上一Run复用成功镜头。未改生成内容的镜头可复用,避免全片重新生成;改顺序导致编号变化时,某些镜头可能需要重新匹配或生成,请看提交后的步骤状态。 -想精细调整已有片段,可到“成片”选择这些视频,调整裁剪与顺序再导出。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。 +当前要精细调整已有片段,在故事人工候选流程导入视频并确认选片,再去“03 成片”调整裁剪、顺序和时间线后合成。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。 不再需要的试片可在任务卡片/详情删除记录,生成素材仍保留在“我的素材”。运行卡片删除会级联归档其子任务;删除草稿会连同其运行和子任务归档;批量成员应从所属批次删除,批次归档会包含其运行和任务,保留工作流草稿及生成素材。软归档后记录从常规页面消失,后台审计保留,原提交恢复/重放返回`410 resource_purged`,不能用原提交键恢复已删记录。 @@ -104,7 +115,7 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 ## 八、成片验收与继续扩展 -完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果您修改了时长,以工作流显示和媒体实测为准。 +完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果修改了时长,以当前故事显示和媒体实测为准。 要扩展为几分钟影片,继续添加镜头并为每镜头写具体动作、参考和字幕,再按实际旁白长度调整总时长。默认资源上限为120镜头(5秒/镜头时10分钟),管理员可提高到1000;磁盘、任务额度和超时仍有效。不要通过给单镜头填整篇故事期待一次得到几分钟连续视频。 @@ -112,6 +123,6 @@ TI2V-5B以24fps生成文生/图生视频;本项目默认121帧、约5秒,页 模板JSON:`frontend/public/examples/kunpeng-storyboard.json`。它不含任何账号、令牌或服务器文件路径;导入后需要手动选择您自己的参考图和音轨。 -45秒版JSON:`frontend/public/examples/kunpeng-storyboard-45s.json`。网站帮助页提供下载链接。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。 +45秒版JSON:`frontend/public/examples/kunpeng-storyboard-45s.json`。网站帮助页提供标为“旧版”的下载链接,不表示当前故事支持直接导入。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。 本项目网站业务数据保存在MySQL `192.168.28.10:3306/cmvr-visual`;生成视频、旁白、参考图以及共享/导入副本的媒体文件位于服务器宿主机`/data/llmusers/llmuser/workspace/cmvr-visual/assets`。GPU服务的SQLite只用于独立执行队列和恢复,不保存网站业务。迁移或备份鲲鹏项目应同时保留业务数据库和媒体目录,不能只复制GPU队列数据库。 diff --git a/frontend/public/help/manual.html b/frontend/public/help/manual.html index e68039a..f4bc82c 100644 --- a/frontend/public/help/manual.html +++ b/frontend/public/help/manual.html @@ -1,4 +1,4 @@ -操作手册 · CMVR Visual
CMVR Visual · 使用帮助

CMVR Visual 操作手册

适用版本:2026-11-11的可配置时段、多镜头、私有内容删除与共享素材版本。模型在192.168.28.10运行,项目在E:\workspace\hybrid\cmvr-visual。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。

1. 登录与基本流程

现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。

使用分配的账号登录。默认管理员名为admin,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。

一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。

网页负责提交和查看,服务器负责持久执行。关闭网页、切换页面、断开HTTP/SSE不会取消任务,也不会停止共享Qwen。网络异常时先同步或恢复原提交,不要反复点击生成。

2. 功能入口

入口用途输入与输出
创作:图片Qwen-Image文生图提示词、尺寸、种子等 → 图片
创作:视频Wan单镜头文生/图生视频提示词、可选参考首帧 → 自选1–15秒无声片段,默认5秒,可选增强
创作:条件样本SDXL+Canny ControlNet参考图片、提示词、控制强度 → 合成图及Canny控制图
工作流多镜头故事自动逐镜生成并合成每镜头提示词/参考图/选用时长 → 一部多镜头影片
声音中文配音、Whisper转写文本 → WAV;音频/有声视频 → 转写结果
推演复用共享Qwen做文本推演问题 → 文本解答
理解图片理解、视频抽帧分析素材 → 场景、主体、OCR、标签等
成片编辑已有视频素材排序、裁切、单音轨、人工字幕 → MP4
批量混合提交任务或已保存工作流任务清单 → 持久批次,运行时段服从配置
素材 / 任务 / 账户管理结果、进度、用户和令牌见下文

3. 图片、短视频和条件样本

图片

  1. 进入“创作”,切换到图片。
  2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。
  3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。
  4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。

单镜头视频

  1. 切换视频模式,写一个镜头中的主体动作与镜头运动。
  2. 可选择参考图片作为首帧;文生视频可不选图。
  3. 在视频时长中选择5秒、10秒、15秒,或输入1–15的整数秒,默认5秒。再按需要调整参数和1080p画质增强开关。当前单次接口最多361帧、24fps;增加提示词长度不会自动延长单镜头。
  4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。

2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过。网页现已接入最长15秒单镜头。原生源片段采用4n+1帧,选择15秒时输出361帧,实际约15.04秒;工作流合成会裁到选用的精确帧数。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。较长镜头通常需要更多时间和资源,增强另有耗时。

条件样本

选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。

4. 多镜头工作流

新建、编辑和保存

  1. 打开“工作流”,点击“新建”,填写故事名称。
  2. 每个镜头填写提示词,选择种子和可选参考图片。
  3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。
  4. 每镜头选择1–15秒的选用时长,页面可按0.25秒调整;JSON接受24–360的整数帧。5秒以内继续生成121帧源片段再裁取,以兼容既有草稿和复用规则;超过5秒时按该镜头需要生成更长的原生片段,10秒/15秒分别生成241/361帧。不同镜头各用自己的生成长度,不会统一生成最长镜头。改变长镜头长度可能使原生成结果不再符合复用条件,需要重新生成。
  5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。
  6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。

总时长由镜头选用时长相加,24fps下总秒数=总帧数÷24。例如5秒、10秒、15秒三个镜头合计30秒、720帧;20个5秒镜头合计100秒。音轨和字幕需要匹配调整后的总时长。

默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。

音轨和字幕

工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。

  • 源入点/出点单位是毫秒,表示取音频的哪一段。
  • 偏移单位是帧,表示从成片的哪一帧开始播放。24帧=1秒。
  • 选段长度加偏移必须放得进成片,源出点不能超过音频真实时长。过长不会被悄悄截断;应增加镜头、缩短旁白或重新配音。
  • 旁白比成片短时,尾部补静音。当前不提供多音轨混音、自动配乐或自动对齐旁白。

人工字幕的开始/结束是整片帧号,区间为[开始帧,结束帧)。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。

运行、复用与恢复

点击“保存并运行”。服务器冻结本次参数和修订,独立镜头按就绪顺序分配到空闲GPU并行生成,全部完成后再按镜头顺序合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。

  • “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。
  • “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。
  • “重试此阶段”:仅用于允许安全重试的失败步骤;其他成功镜头保留。
  • 修改草稿后再次运行,可在复用下拉框选择旧Run。只有生成输入一致、产物仍存在且校验通过的成功镜头可复用。提示词、参考图、种子、画幅变更会使对应镜头重新生成;单纯选用时长变更可复用原始生成片段再剪辑。
  • “同步”重新读取后台状态。结果未知/需人工确认表示远端执行结果未确认,不应靠反复提交规避。

JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。

5. 声音、推演与理解

“声音”选择“配音生成”,输入不超过2000字,选择zf_xiaobei或zm_yunxi,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。

转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。

“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。

6. 成片、素材与任务管理

“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。

我的素材与共享素材库

普通账号和admin在“我的素材”、任务、工作流和批量记录中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。

“我的素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找,也可修改名称和标签。“共享库导入”来源用于查找从共享库取得的个人副本。

  1. 分享时,在自己的素材卡片或预览中点击“发布到共享库”,阅读并确认发布范围。系统复制原件和当前名称、标签等信息,生成一份独立的共享副本;所有已登录用户均可查看、下载和导入。
  2. 在“共享素材库”预览的内容是只读共享副本。点击“导入我的素材库”后,会创建属于当前账号的独立私有副本,可再编辑、删除或用于创作。创作中的素材选择器也可切到“共享素材”,选择后先导入,再将个人副本用于当前输入。
  3. 发布者可通过“我发布的”筛选并打开预览,点击“撤回共享”。撤回后其他用户无法继续查看或导入该发布,已经导入的个人副本仍然保留。删除私有原件也不会删除已发布的共享副本或他人的导入副本;要停止共享,需要单独撤回。

共享发布需要实际复制文件,占用发布者的磁盘额度;每次导入的独立副本占用导入者的磁盘额度。发布后的共享副本不会随原件修改自动更新。

删除素材和记录

自己的素材卡片/预览、任务卡片/详情、工作流草稿、运行卡片和批量记录均提供删除入口。删除记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复。

  • 删除独立Job只删除任务记录,已经生成的素材继续保留在“我的素材”。要清理这些素材,需要再逐项删除素材。
  • 删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。
  • 工作流子任务或批量成员不能单独删除,按页面提示到父运行或批次管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。
  • 活跃记录须先取消,等待执行退出及资源清理确认后再删。点过“取消”不表示已完成清理,仍显示排队、执行中或取消中时不能直接删除。
  • 删除素材若返回409引用冲突,先从草稿解除引用并保存;冻结运行中的引用需要删除相关运行或父批次。活动任务使用中的素材应先取消任务、等待退出,再按依赖关系处理。不要直接去磁盘删除文件。

素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做dry-run盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。

“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。

生成数量与排队

当前不再默认限制每用户只能有8个未完成的视频或其他交互GPU任务,第9个及后续任务可以继续入队;没有“累计只能生成8个视频”的限制。空闲GPU、内存和其他用户优先规则决定何时实际执行。

网站后端环境文件中的MAX_INTERACTIVE_GPU_JOBS=0表示关闭该单用户队列条数限制,默认即为0;只有显式设置正整数才重新启用。它不控制GPU并发数,也不是夜间时段开关。每分钟6次创建命令、每用户最多500个未结束叶任务、全局最多2000个及磁盘预算仍有效;已完成作品不占未完成任务额度。工作流每轮有界补充镜头,后续轮次继续入队,不会因已有8个未完成镜头停止。

7. 批量与开发/生产配置

“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。

权威配置位于容器内:

/workspace/projects/llm-services/config/runtime-policy.json

服务器宿主机对应:

/data/llmusers/llmuser/workspace/projects/llm-services/config/runtime-policy.json

开发模式:

{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":120}

正式环境启用时段限制:

{"schema_version":1,"batch_window_enabled":true,"workflow_max_shots":120}

API与GPU worker热读取同一个文件,不需要重启模型或共享Qwen。建议用同目录临时文件写完后原子替换,避免编辑中的半个JSON短暂触发保护。true/false是JSON布尔,不能加引号;不要在任务JSON或网页上添加绕过字段。

  • false:批量也可全天等待空闲资源;手动暂停、维护、账号禁用、容量限额和其他用户优先仍生效。
  • true:批量的新镜头/处理阶段只在北京时间21:00–08:00启动。08:00时当前阶段自然完成,后续排队到下一窗口。交互仍全天可用。
  • 文件不存在:使用生产默认限制。文件错误:关闭新批量准入并显示配置错误;不要为解决此问题删除时钟水位文件。
  • 上限降低只限制新提交/草稿保存,不会截断已经接受的长视频运行。

在网页右上角“创作服务状态”刷新检查生效状态。开发全天与数据库运行模式、公网发布是不同配置;关闭夜间限制不会开放互联网。

若通过SFTP维护配置,可从本机执行以下操作(按提示输入llmuser密码,不把密码写进命令):

sftp llmuser@192.168.28.10
+操作手册 · CMVR Visual
CMVR Visual · 使用帮助

CMVR Visual 操作手册

“创作”新增多图参考的图生图和可选择多个人物的视频替换入口,操作步骤、模型区别及配置见图生图与视频人物替换操作手册。

新增“故事”入口的基准板、跨镜头角色/形态引用、首帧与视频人工确认流程,见锚定故事工作室操作手册。首次使用可从该手册第 0 节开始,按“两个 5 秒镜头 → 10 秒成片”逐步完成新建、保存、角色绑定、首帧确认、视频选片、字幕音轨和合成下载;故事编辑页顶部“使用手册”可直接打开网页版本。候选数是 1–4 的数值框,只影响下一次模型生成,人工导入每次为 1 个。希望一次自动生成并在之后局部修改时,在故事中启用“可编辑自动成片”,操作见第12节。独立“工作流”“批量”“成片”页面已移除;旧链接会转至故事或任务,既有数据与共享API保留。

适用版本:2026-11-13,含故事可编辑自动成片、容器内滚动、逻辑文件夹、批量整理、可配置时段、私有内容删除与共享素材。模型在192.168.28.10运行,项目在E:\workspace\hybrid\cmvr-visual。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。

0. 六项业务能力与生产流程对应关系

六项能力的基础功能、批量生成、人工编排与选片确认均已实现。这里的“审核”是创作者在自己的故事中查看候选、确认首帧、确认视频和检查成片;当前没有单独的“审核中心”、指定另一账号审批或成片终审发布状态。

功能需求在哪里操作当前实现与边界
图像生成左侧“创作”→“图片”;路径 /create/image输入提示词生成图片;多图参考编辑另见“图生图”。没有风格 LoRA 管理平台
视频生成“创作”→“视频”;路径 /create/video文生或首帧图生单镜头,最长约15秒;长故事使用“故事”。生成片段默认无声
数学推演左侧“推演”;路径 /math输入问题,输出解题文字和文本/JSON素材;由模型作答,没有符号计算验证或形式化证明
缺陷样本生成“创作”→“缺陷样本”;路径 /create/defect参考图加缺陷描述,生成合成图与Canny控制图;控制图不是缺陷真值掩膜,不能当作完整标注数据集
素材结构化左侧“理解”;路径 /analyze;声音转写在 /audio图片或视频抽帧输出主体、场景、OCR、标签和结构化JSON;语音转写是另一个任务。没有完整镜头切分或自动标签回写
成片合成“故事”→目标故事→“03 成片”视频排序、裁切、画幅适配、单音轨和人工字幕,输出MP4;不含多轨混音、自动配乐、转场编辑和PPTX课件导出
要完成的工作应使用的入口
角色/场景基准、首帧审核、视频候选比较、逐镜选片后合成“故事”→打开故事→“01 基准板 / 02 分镜 / 03 成片”
填好一组镜头后自动生成并合成,完成后再审片“故事”→“启用可编辑自动成片”→“自动生成初稿并成片”
故事自动生成按批量策略排队可编辑自动成片中选择“批量队列”,再提交素材或成片生成
新故事的所有镜头批量生成首帧或视频候选故事内“02 分镜”→“全故事候选计划”
使用已有视频做后期故事“02 分镜”导入视频并确认选片→“03 成片”调整时间线并合成

当前开发环境关闭批量时段限制,可以全天提交并等待空闲资源。正式启用夜间开关后,现有规则只约束“批量队列”,交互队列仍全天可用;不能把现有开关理解为“所有模型调用只能夜间运行”。日间审核和后期本身不需要改这个开关。生产节拍统计、严格夜间模式及多人审批的完善方案见文末第11节。

1. 登录与基本流程

当前网页入口为 http://127.0.0.1:5173 ,业务接口在本机 http://127.0.0.1:8000 运行。模型和配音分别通过内网 HTTP 入口 192.168.28.10:18190、192.168.28.10:18192 连接,使用本机项目无需建立 SSH 隧道。网页地址用于当前开发机本地访问;网页打不开时先检查本地前端和后端是否已启动,模型连接问题可在“创作服务状态”查看。

使用分配的账号登录。默认管理员名为admin(可在头像菜单修改用户名),初始密码以私有部署配置为准;点击左下角头像,在“退出登录”上方选择“修改密码”。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。

一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。

网页负责提交和查看,服务器负责持久执行。关闭网页、切换页面、断开HTTP/SSE不会取消任务,也不会停止共享Qwen。网络异常时先同步或恢复原提交,不要反复点击生成。

2. 功能入口

入口用途输入与输出
创作:图片Qwen-Image文生图提示词、尺寸、种子等 → 图片
创作:视频Wan单镜头文生/图生视频提示词、可选参考首帧 → 自选1–15秒无声片段,默认5秒,可选增强
创作:缺陷样本SDXL+Canny ControlNet参考图片、提示词、控制强度 → 合成图及Canny控制图
故事可编辑自动成片,或候选生成与人工审核自动生成后局部修改,或基准板 → 首帧确认 → 视频选片;统一在“03 成片”处理时间线
声音中文配音、Whisper转写文本 → WAV;音频/有声视频 → 转写结果
推演复用共享Qwen做文本推演问题 → 文本解答
理解图片理解、视频抽帧分析素材 → 场景、主体、OCR、标签等
素材 / 任务 / 账户管理结果和进度;管理员在账户页管理用户见下文

3. 图片、短视频和条件样本

图片

  1. 进入“创作”,切换到图片。
  2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。
  3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。
  4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为故事的参考图片使用。

单镜头视频

  1. 切换视频模式,写一个镜头中的主体动作与镜头运动。
  2. 可选择参考图片作为首帧;文生视频可不选图。
  3. 在视频时长中选择5秒、10秒、15秒,或输入1–15的整数秒,默认5秒。再按需要调整参数和1080p画质增强开关。当前单次接口最多361帧、24fps;增加提示词长度不会自动延长单镜头。
  4. 需要更长故事时进入“故事”增加镜头;已有视频可在故事“02 分镜”导入并确认选片,再去“03 成片”拼接。

2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过。网页现已接入最长15秒单镜头。原生源片段采用4n+1帧,选择15秒时输出361帧,实际约15.04秒;故事合成按设定裁到选用的精确帧数。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。较长镜头通常需要更多时间和资源,增强另有耗时。

条件样本

选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。

4. 故事中的多镜头创作

可编辑自动成片

  1. 打开左侧“故事”,新建或打开故事,填写名称、基准板和镜头并保存。
  2. 点击“启用可编辑自动成片”。在“02 分镜”编辑画面、运动、选用区间和旁白;在“03 成片”配置音轨与字幕,时间线只在这里显示。
  3. 在自动成片工具条选择“交互队列”或“批量队列”,点击“自动生成初稿并成片”。正常流程会生成所需素材再合成,不等待逐镜人工确认。
  4. 检查完成成片;需要修改时编辑对应镜头、旁白或字幕,点击“生成修改部分并成片”。运行进度与成果可在历史中的“查看运行进度与成果”或“任务”查看。

完整的局部重生成、字幕保护和版本恢复规则见第12节。自动与人工候选是两条创作路径,不要把自动生成按钮和人工“确认首帧 / 确认选片”步骤混用。

分镜滚动与时间范围

“02 分镜”内容超过工作区时,只在对应编辑容器内滚动,故事标题和步骤导航保持可见。鼠标移入容器时显示滚动条,移出后隐藏;键盘聚焦时也可显示,触屏直接滑动。鼠标放在需要查看的镜头列表、编辑区或候选区内再滚动;声音和字幕时间线在“03 成片”,不必寻找页面底部的独立成片入口。

总时长由镜头选用帧数相加,24fps下总秒数=总帧数÷24。例如5秒、10秒、15秒三个镜头合计30秒、720帧。音轨、旁白和字幕须匹配总时长;镜头数、磁盘、任务额度和超时仍受环境配置保护。

编排审核在哪里,怎么操作

需要生成后由人把关再进入下一步时,使用故事的人工候选流程;本小节对应尚未启用可编辑自动成片的故事。推荐按下面顺序完成一部片子:

  1. 打开“故事”列表,新建故事或打开已有故事,设置故事归属文件夹和“成果保存到”。
  2. 在“01 基准板”填写故事共同设定,建立场景、角色和形态并选择参考图片,点“保存故事”。
  3. 在“02 分镜”添加镜头,填写画面与动作,设置镜头顺序、生成源长度和选用区间;调整后再次保存。这里的顺序和裁剪就是编排。
  4. 选择“1 首帧生成 / 导入 → 确认首帧”,生成或导入候选。任务完成显示“可复核”后,点缩略图预览,必要时点“对比”,在满意候选卡片上点“确认首帧”。仅预览不算确认。
  5. 选择“2 视频生成 / 导入 → 确认选片”,生成或导入视频候选。检查人物、动作、教学内容、实际源长度和选段后,点“确认选片”。已有人工视频可以直接导入复核,不必先生成首帧。
  6. 每个镜头都须确认有效视频。对不满意的结果,可重新生成当前镜头或导入替代视频;失败候选可点“重试为新候选”。需要撤销决定时点“清除确认”。生成成功不会自动确认,也不会替换之前的选择。
  7. 在“03 成片”设置画幅、裁剪适配、单音轨和人工字幕,展开“查看镜头选片检查”,确认没有“需要有效选片”,然后保存故事并点“冻结素材并合成”。合成沿用“02 分镜”选择的队列;正式夜间限制开启而日间要做CPU合成时,先在“02 分镜”切回“交互队列”,再进入“03 成片”提交。缺少有效选片时服务端会拒绝合成。
  8. 成功后在“成片预览”点“播放成片”“新窗口播放”或“下载成片”。再次编辑不会改变已冻结的历史成片;修改了会使选片过期的设定时,须重新复核。

首帧/视频的确认、清除和替换会记录版本及操作者。现有权限仍按账号隔离:管理员不能直接审核另一账号的私有故事。当前也没有成片“送审、驳回、终审通过、发布”的独立流程。逐字段操作与失效规则见锚定故事工作室操作手册。

旧工作流兼容说明

原独立工作流页的草稿、冻结运行、镜头复用和JSON合同继续保留在后端;删除页面不会删除历史数据。旧三镜头和可变多镜头数据仍按原合同读取,详情见API示例和共享契约。旧工作流JSON不是当前故事页可直接导入的模板;新项目按上面的故事流程建立,旧运行进度与成果到“任务”查看。

5. 声音、推演与理解

“声音”选择“配音生成”,输入不超过2000字,选择zf_xiaobei或zm_yunxi,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。

转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成故事分镜的功能,也不保证专业数学结论正确。

“推演”的具体步骤:进入左侧“推演”→填写问题和所需输出长度→点“开始推演”→在当前结果或“任务”查看解题内容→复核后下载文本/JSON,或将需要的文字用于文案、字幕和配音。当前没有把数学答案自动转换成分镜或PPTX的按钮。

“理解”的具体步骤:进入左侧“理解”→上传或选择本人的图片/视频→视频可设置1–12张采样帧→点“解析素材”→到当前结果或“任务”查看主体、场景、OCR、标签及采样时间→在“素材”查看或下载结构化JSON和抽帧结果。它只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。需要声音内容时,另外在“声音”选择转写。

理解结果中的标签不会自动回写源素材的检索标签;复核后,在源素材预览中编辑标签并保存,再用素材库的标签筛选。生成结果仍须人工检查,特别是教学数学结论和工业缺陷标注。

6. 成片、素材与任务管理

已有视频片段时,进入故事“02 分镜”,导入视频候选并确认选片,调整顺序和选用范围,再到“03 成片”处理音轨、字幕并合成;无需独立成片页面。可编辑自动成片的素材绑定和时间线操作见第12节。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件;裁剪范围必须在真实媒体范围内。

我的素材与共享素材库

普通账号和admin在“我的素材”、故事、任务及历史运行中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。

“我的素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找,也可修改名称和标签。“共享库导入”来源用于查找从共享库取得的个人副本。

文件夹与批量整理

文件夹用于项目内分类。移动分类、改名不会移动磁盘文件,也不会改变素材编号和故事引用。旧素材、任务和故事先显示在“未分类”。

  1. 在素材库顶部“浏览目录”选择文件夹。选择“全部文件夹”或“未分类”时,点击“新建文件夹”创建根目录;选择一个已有文件夹后,会出现“新增子文件夹”“编辑文件夹”“删除文件夹”三个操作。名称、父目录等字段在操作弹窗中填写。
  2. 进入一个文件夹后上传,素材自动归入该文件夹。整理已有素材时勾选卡片左上角;选中后才会显示“整理到”及批量按钮。“移动分类”替换原有文件夹归属,“加入文件夹”保留原归属,允许同一素材同时用于故事 A 和故事 B,无须复制原文件。
  3. 可逐项勾选,也可“选择本页”。点击“发布到共享库”或“批量删除素材”后,确认本次总数;完成后显示成功和失败数量。仍被任务或故事引用的素材不会被强行删除,失败项保持勾选,可展开“查看失败原因”。成功发布的是独立共享副本。
  4. 新建故事时填写故事名称,默认自动新建同名文件夹;取消“自动新建同名文件夹”后可选择已有目录或未分类。故事工作室顶部可修改“故事归属”,修改后保存故事。
  5. 创作、声音、推演、理解和故事生成均可选择“成果保存到”。故事默认使用自己的文件夹;候选、批量候选和成片也可另选目录。提交后目标已固定,之后再移动故事不会改变已排队任务的成果位置。
  6. 任务中心可以按目录筛选并整理任务;移动任务分类不会改写已冻结的成果目标。素材选择器也可按目录找图、找视频或音轨。共享素材导入时可选择放入哪个个人文件夹。

“删除文件夹”只删除分类及其子分类,保留素材、任务、故事和实际文件;仅归属该目录的内容回到未分类,同时属于其他目录的素材保留其他归属。删除实际素材仍使用素材删除操作和原有引用检查。

素材库默认每页 48 项,可以切换 24 / 48 / 96 项;素材卡片已缩小,窄屏自动换行并保留两列预览。没有选中素材时,批量工具会收起以留出更多浏览空间。

  1. 分享时,在自己的素材卡片或预览中点击“发布到共享库”,阅读并确认发布范围。系统复制原件和当前名称、标签等信息,生成一份独立的共享副本;所有已登录用户均可查看、下载和导入。
  2. 在“共享素材库”预览的内容是只读共享副本。点击“导入我的素材库”后,会创建属于当前账号的独立私有副本,可再编辑、删除或用于创作。创作中的素材选择器也可切到“共享素材”,选择后先导入,再将个人副本用于当前输入。
  3. 发布者可通过“我发布的”筛选并打开预览,点击“撤回共享”。撤回后其他用户无法继续查看或导入该发布,已经导入的个人副本仍然保留。删除私有原件也不会删除已发布的共享副本或他人的导入副本;要停止共享,需要单独撤回。

共享发布需要实际复制文件,占用发布者的磁盘额度;每次导入的独立副本占用导入者的磁盘额度。发布后的共享副本不会随原件修改自动更新。

删除素材和记录

自己的素材卡片/预览、任务卡片/详情及可管理的运行记录提供删除入口;历史工作流草稿和批次的删除合同仍保留在API。任务、工作流和批量记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复;素材删除则同步移除文件和数据库文件记录。

  • 删除独立Job只删除任务记录,已经生成的素材继续保留在“我的素材”。要清理这些素材,需要再逐项删除素材。
  • 历史数据的API归档规则保持不变:删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。
  • 工作流子任务或批量成员不能单独删除,按提示通过父运行或批次的受支持接口管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。
  • 活跃记录须先取消,等待执行退出及资源清理确认后再删。点过“取消”不表示已完成清理,仍显示排队、执行中或取消中时不能直接删除。
  • 删除素材若返回409引用冲突,先从草稿解除引用并保存;冻结运行中的引用需要删除相关运行或父批次。活动任务使用中的素材应先取消任务、等待退出,再按依赖关系处理。不要直接去磁盘删除文件。

素材删除成功后,会同步移除该素材的原文件、缩略图及数据库文件记录,释放对应素材占用。撤回共享时删除共享库中的独立快照;已经引用到个人素材库的副本继续保留,由引用者独立管理。文件被占用或暂时无法删除时会提示失败,可稍后重试。旧版本遗留的软删除文件仍由运维清理流程处理。

“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。

生成数量与排队

当前不再默认限制每用户只能有8个未完成的视频或其他交互GPU任务,第9个及后续任务可以继续入队;没有“累计只能生成8个视频”的限制。空闲GPU、内存和其他用户优先规则决定何时实际执行。

网站后端环境文件中的MAX_INTERACTIVE_GPU_JOBS=0表示关闭该单用户队列条数限制,默认即为0;只有显式设置正整数才重新启用。它不控制GPU并发数,也不是夜间时段开关。每分钟6次创建命令、每用户最多500个未结束叶任务、全局最多2000个及磁盘预算仍有效;已完成作品不占未完成任务额度。工作流每轮有界补充镜头,后续轮次继续入队,不会因已有8个未完成镜头停止。

7. 批量与开发/生产配置

7.1 可编辑自动成片怎样使用批量队列

  1. 打开“故事”并启用可编辑自动成片,完成需要生成的镜头、声音与字幕设定。
  2. 在自动成片工具条的执行方式中选择“批量队列”。选择队列本身不会提交任务。
  3. 按目标点击“自动生成初稿并成片”“生成修改部分并成片”或“仅生成素材”。实际生成前会保存并校验,后端继续按原资源和时段策略持久排队。
  4. 在版本与运行历史点击“查看运行进度与成果”,或进入“任务”跟踪;编辑与最终成片仍回原故事处理。

独立“批量”页面已移除,“批量队列”执行模式继续保留。关闭网页不会取消已经接受的任务;交互队列仍适用于全天等待空闲资源的提交。

7.2 旧通用批次与工作流API

原提示词JSON清单、多个旧工作流混合批次及其历史数据仍由共享后端API保留,独立页面移除不改变接口合同。当前网页不再提供“快速整理”“加入已保存工作流”或“类型化清单JSON”表单;新手请使用故事流程,不要寻找这些旧按钮。

已有API集成继续使用原幂等键、版本校验及归属检查,通用批次仍为1–100个清单项,部分生图类型的单项count另有1–4限制。草稿、冻结运行和批次的控制/归档仍遵守父子引用规则;技术用法见API示例和共享契约。故事编号不能直接充当旧工作流编号。

7.3 怎样批量生成一个故事的所有镜头

  1. 在故事的人工候选流程中打开“02 分镜”,完成所有镜头的设定并点“保存故事”;启用自动成片的故事使用7.1节。
  2. 在首帧阶段选择生成方式、候选数(1–4)和“批量队列”,点“全故事候选计划”。例如20个镜头、候选数2,会安排40个当前阶段的候选。
  3. 等首帧候选可复核后,逐镜预览并点“确认首帧”。不满意的镜头单独点“生成当前镜头”,避免为所有镜头重复付出生成时间。
  4. 各镜头首帧有效后,切到视频阶段,检查各镜头生成源长度覆盖选段;选择候选数和队列,再点“全故事候选计划”。
  5. 视频生成完成后逐镜“确认选片”,进入“03 成片”补音轨、字幕并冻结合成。

“全故事候选计划”一次只安排当前首帧或视频阶段,不自动确认,不自动接着生成下一阶段,也不自动跳过已经有候选的镜头。“全故事”指范围,“批量队列”指调度方式,两者必须分别选择;默认的交互队列不会因为点了“全故事”就变成夜间批量。

故事候选计划的上限由镜头数、候选数和账号容量共同决定,不套用通用JSON清单的100项上限。故事候选的查看与审核以原故事“02 分镜”为准;独立批量页已移除,不要把候选编号当普通任务编号使用。

7.4 暂停、继续、取消与日夜生产节拍

  • 历史通用批次的暂停、继续和取消仍通过原批次控制API处理;独立“批量记录”页面已移除。暂停只阻止后续准入,当前已运行阶段自然完成;继续不自动重做失败成员。已取消的批次不能靠继续恢复。
  • 故事候选可在“任务”查看生成状态,回原故事复核;旧工作流运行还可在失败的可重试阶段使用“重试此阶段”。不明远端结果或清理未完成时,先查明状态,不能反复创建替代任务。
  • 时段限制关闭时,以上批量流程都可在开发日间运行。启用后,新批量任务/阶段只在21:00–次日08:00准入;08:00时已运行阶段继续完成,后续阶段等待下一窗口。
  • 这里的GPU执行单元包括同一个视频任务的生成与可选画质增强,08:00后可继续完成整条处理流程;不在生成与增强之间强制停下,下一镜头等新的执行单元才重新判断窗口。
  • 生产排期中,单人审核可以在日间完成,FFmpeg剪辑合成可采用交互方式。需要首帧人工把关的新故事通常是“第1天编排 → 第1夜首帧候选 → 第2天确认首帧 → 第2夜视频候选 → 第3天审片、字幕与合成”,不是同一夜自动越过人工确认。
  • 若已有批准首帧,可直接从视频批量阶段开始;若接受生成后再统一审片,可以在故事中使用可编辑自动成片和“批量队列”,次日再检查成片。
  • 当前没有按夜统计合格镜头产量、审核积压和次夜产能预测的生产看板。排期先依据任务实际耗时、合格选片数及其他用户占卡情况安排,不能把四张GPU当作每晚固定满额可用。

7.5 管理员怎样切换开发与生产时段

权威配置位于容器内:

/workspace/projects/llm-services/config/runtime-policy.json

服务器宿主机对应:

/data/llmusers/llmuser/workspace/projects/llm-services/config/runtime-policy.json

开发模式:

{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":120}

正式环境启用时段限制:

{"schema_version":1,"batch_window_enabled":true,"workflow_max_shots":120}

API与GPU worker热读取同一个文件,不需要重启模型或共享Qwen。建议用同目录临时文件写完后原子替换,避免编辑中的半个JSON短暂触发保护。true/false是JSON布尔,不能加引号;不要在任务JSON或网页上添加绕过字段。

  • false:批量也可全天等待空闲资源;手动暂停、维护、账号禁用、容量限额和其他用户优先仍生效。
  • true:批量的新镜头/处理阶段只在北京时间21:00–08:00启动。08:00时当前阶段自然完成,后续排队到下一窗口。交互仍全天可用。
  • 文件不存在:使用生产默认限制。文件错误:关闭新批量准入并显示配置错误;不要为解决此问题删除时钟水位文件。
  • 上限降低只限制新提交/草稿保存,不会截断已经接受的长视频运行。

在网页右上角“创作服务状态”刷新检查生效状态。开发全天与数据库运行模式、公网发布是不同配置;关闭夜间限制不会开放互联网。

若通过SFTP维护配置,可从本机执行以下操作(按提示输入llmuser密码,不把密码写进命令):

sftp llmuser@192.168.28.10
 put E:/workspace/hybrid/cmvr-visual/deploy/runtime-policy.production.json /workspace/projects/llm-services/config/runtime-policy.next.json
 rename /workspace/projects/llm-services/config/runtime-policy.next.json /workspace/projects/llm-services/config/runtime-policy.json
-bye

切回开发模式时把上传源文件改为runtime-policy.development.json,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。

8. 账号、令牌和未确认提交

在“账户”修改密码;管理员可创建、停用用户。停用用户不代表去停止共享模型服务。包括admin在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。

机器令牌用于外部系统调用,创建时按用途选择权限,令牌仅显示一次,立即安全保存;撤销后失效。不要把令牌放进截图、公共仓库或浏览器地址。

“未确认提交”表示客户端没有确认服务器是否已接受。先查询原提交键,确认后再恢复;不要换一个键重复创建。接口细节见docs/api-contract.md和FastAPI接口文档。

记录删除后,原幂等提交的恢复或重放会返回410 resource_purged,表示原结果已归档,不能通过重放把已删除记录恢复。只有确实要创建一项新工作时,才发起新的提交。

9. 数据存放在哪里

数据实际位置与用途
网站业务数据MySQL 192.168.28.10:3306/cmvr-visual,保存用户、素材元数据、任务、工作流、批次、共享发布和审计等网站业务记录
媒体文件服务器宿主机/data/llmusers/llmuser/workspace/cmvr-visual/assets,保存上传、生成、共享发布和导入副本的媒体原件/缩略图;容器内对应/workspace/cmvr-visual/assets
GPU调度恢复推理服务自己的SQLite,仅负责独立GPU执行队列与恢复,不是网站业务数据库,也不保存网站的用户、工作流和共享素材业务

网页所见的素材列表来自MySQL元数据,视频、图片、音频文件在上述媒体目录。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。

10. 常见问题

现象处理
一直等待窗口在状态面板检查开关;开发模式需要API和GPU实际使用同一配置文件
等待GPU/外部用户使用等待空闲资源,不要停止他人的任务
音轨放不进影片先测实际音频长度,增加镜头或缩短旁白;检查毫秒与帧单位
草稿版本冲突保留本地内容,重新载入服务器版本后再决定合并,不反复覆盖
角色变形、鲲鹏不一致统一形象描述、使用参考首帧,分镜小步验证,人工挑选重做
转写没有声音检查源视频是否有音轨;模型生成片段默认无声
结果未知/需要人工确认运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止
删除返回409检查活动执行、父级控制和引用依赖,先取消并等待退出,或解除引用/删除相关父记录后重试
删除后磁盘没有立即下降软删除保留文件;GC默认dry-run,默认14天保留期后仍需运维维护清理
找不到其他账号的旁白或参考图请原作者发布到共享素材库,再导入自己的私有副本;管理员也不能直接读取他人的私有素材
输出过大或空间不足减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列

完整案例见鲲鹏长视频制作指南。模板在frontend/public/examples/kunpeng-storyboard.json,原文旁白在同目录的kunpeng-narration.txt。

另提供kunpeng-storyboard-45s.json,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。

版本:2026-11-11 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file +bye

切回开发模式时把上传源文件改为runtime-policy.development.json,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。

8. 用户管理与修改密码

“账户”页面仅管理员可见,普通用户不能进入该页面或调用用户管理接口。页面只提供新增、禁用/启用和删除用户;不能禁用或删除当前登录的管理员账号。新增用户的初始密码允许6–256个字符,包括123456这样的6位数字。

禁用用户后,该账号不能登录,已有登录会话立即失效,相关任务暂停准入;素材、故事、工作流与任务记录仍保留。重新启用后,用户重新登录即可继续使用原资源;用户自己设置的暂停不会被自动解除。停用用户不会停止共享模型服务。

删除用户将永久清理该账号、自有素材(含共享发布)、故事、工作流、批量和任务记录及对应本地文件,无法恢复。其他用户已经独立导入的副本保留。若任务或上传尚未结束,会先停用账号并请求取消,提示等待清理;确认执行停止后点击“重试删除”,清理成功才会显示删除成功。

所有登录用户都可点击左下角头像,选择“修改密码”,输入当前密码、新密码和确认新密码后点击“确定”。新密码须为12–256个字符,修改成功后重新登录。账户页不再显示改密、API令牌或未确认提交管理区。

头像菜单还提供“修改用户名”:填写新的登录用户名和当前密码,确认后使用新用户名登录。用户名为3–64位小写字母、数字、点、下划线或横线,不能与已有账号重复;显示名保持独立。修改后当前登录会话、账号ID、角色及已有资源均保留。管理员修改用户名后,重启不会重新创建旧用户名的初始管理员。

包括admin在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。

记录删除后,原幂等提交的恢复或重放会返回410 resource_purged,表示原结果已归档,不能通过重放把已删除记录恢复。只有确实要创建一项新工作时,才发起新的提交。

9. 数据存放在哪里

数据实际位置与用途
网站业务数据MySQL 192.168.28.10:3306/cmvr-visual,保存用户、素材元数据、任务、工作流、批次、共享发布和审计等网站业务记录
当前本地媒体与任务工作文件E:\workspace\hybrid\cmvr-visual\.local\workspace\cmvr-visual\assets 和同级 jobs,保存网页上传、归档结果、共享发布及导入副本;访问通过受认证的业务API
服务器推理工作文件模型API管理自己的输入、尝试目录和输出,本地业务API通过HTTP上传/归档;它与本地素材目录是两份独立存储
业务交付副本E:\workspace\hybrid\cmvr-visual\outputs,例如保留的鲲鹏成片、音频与字幕;这里的副本不是网页素材库的数据库来源
GPU调度恢复推理服务自己的SQLite,仅负责独立GPU执行队列与恢复,不是网站业务数据库,也不保存网站的用户、工作流和共享素材业务

网页所见的素材列表来自MySQL元数据,当前业务媒体存放在本机上述目录。后续正式部署的路径由当时配置决定,不能把旧服务器部署路径当作当前素材库位置。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。

10. 常见问题

现象处理
一直等待窗口在状态面板检查开关;开发模式需要API和GPU实际使用同一配置文件
等待GPU/外部用户使用等待空闲资源,不要停止他人的任务
音轨放不进影片先测实际音频长度,增加镜头或缩短旁白;检查毫秒与帧单位
草稿版本冲突保留本地内容,重新载入服务器版本后再决定合并,不反复覆盖
角色变形、鲲鹏不一致统一形象描述、使用参考首帧,分镜小步验证,人工挑选重做
转写没有声音检查源视频是否有音轨;模型生成片段默认无声
结果未知/需要人工确认运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止
删除返回409检查活动执行、父级控制和引用依赖,先取消并等待退出,或解除引用/删除相关父记录后重试
素材删除失败或仍占空间先解除任务和工作流引用;文件被占用时稍后重试。旧版本遗留文件由运维清理;模型临时缓存和共享副本独立管理
找不到其他账号的旁白或参考图请原作者发布到共享素材库,再导入自己的私有副本;管理员也不能直接读取他人的私有素材
输出过大或空间不足减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列

历史分镜、JSON格式与旁白实测参考见鲲鹏长视频制作指南。旧模板在frontend/public/examples/kunpeng-storyboard.json,当前故事页不提供直接导入;原文旁白在同目录的kunpeng-narration.txt。

另提供kunpeng-storyboard-45s.json,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。

11. 尚未覆盖的生产管理需求与完善方案

基础六项能力和“批量生成→人工编排审核→合成”的流程已经具备。以下是需要区分的完善项:

尚未覆盖或需完善的部分当前可用方式落地方向
后续若在任务中心展示候选批次的详情跳转当前回故事“02 分镜”查看与审核,独立批量页已移除保留候选所属故事、镜头和阶段信息,按成员类型跳转,候选尚未派发时也能查看计划
所有模型调用严格限于夜间目前仅批量受夜间开关约束,交互全天增加明确的时段作用范围,API与推理worker一致判断;日间编排、审核和CPU后期保留可用
以实测夜间产量安排生产节拍人工查看任务、选片和资源状态汇总逐夜成功镜头、合格选片、执行耗时和审核积压,以有效历史样本给出区间估算
编导提交给另一个审核人、驳回意见、成片终审本人预览和确认,按账号隔离作为可选扩展增加版本化送审单与明确授权;不开放管理员对全部私有内容的默认访问

完整的代码落点、接口、数据保护、实施顺序及验收条件见生产流程完善方案。这些是待实施设计,当前页面没有的按钮不能按方案描述操作。教学数学验证、缺陷真值标注、多轨混音等也未实现,但它们是对应基础能力的后续专项,不把现有模型输出冒充这些成果。

12. 可编辑自动成片(代码版本007)

本节适用于已完成007迁移并启动新版API的环境。真实数据库和运行服务不会由代码更新自动迁移;先按发布清单完成联合备份、升级和业务API切换。自动流程继续使用现有队列及资源策略。

首次生成

  1. 从“故事”新建或打开故事,配置画面、场景、角色、镜头与时长,点“保存故事”,再点击“启用可编辑自动成片”。
  2. 在“02 分镜”编辑镜头,按需输入旁白。内容超出时在分镜编辑容器内滚动,移入显示滚动条、移出隐藏;故事只在“03 成片”显示音轨与字幕时间线。
  3. 声音选择静音、人工单音轨或生成旁白;字幕选择关闭、人工、旁白文案或AI补齐文案。配音需真实TTS服务通过部署验收,轻量健康检查不代替声音质量验收。
  4. 选择“交互队列”或“批量队列”,点击“自动生成初稿并成片”。系统保存版本、检查计划,再生成和校验素材、字幕及音轨,最后合成。正常阶段不等待逐镜头确认,关闭网页不取消后台运行。

局部修改与新版本

故事名称可在页面顶部修改,人工流程点击“保存故事”,自动模式点击“保存编辑”。自动模式的名称和分镜等编辑会一起保存;尚未保存或保存失败的名称仍保留在输入框中。

需要恢复逐步骤确认时,保存当前修改,再点击故事导航栏“返回逐步骤人工确认”。故事、镜头、素材和历史运行保留,自动素材作为待确认候选显示,仍需你确认首帧与视频。人工编辑和确认也会带回自动模式;点击“启用可编辑自动成片”即可再切换。存在未结束的运行、候选任务或未清理执行时会提示先处理,切换失败不会丢弃当前编辑。

修改镜头画面/运动、裁剪或选用私有素材,可“仅生成素材”,也可“生成修改部分并成片”。指定重新生成会创建新变体,实际种子显示在绑定详情,网络重试不重复创建。

  • 改运动重生成对应视频;改画面或参考图影响依赖首帧和视频;共享角色/场景可能影响多个镜头。
  • 重排或选用区间仍在实际源长内时复用源视频;源不够长时需重新生成。
  • 修改旁白段只重生成该段,再装配单音轨;修改字幕只改显示文字,明确同步到旁白才重新配音。
  • 字幕分别保护人工文字、人工时间,锚点可选全片、镜头、旁白段。冲突可保存,成片前须处理,不默默截配音或改写人工文字。
  • 编辑版本仍匹配时自动采用新结果;用户已经继续编辑时保留为运行成果并提示冲突,不能覆盖后来的输入。

恢复与失败

历史区分素材/成片。“从此版本恢复编辑”明确恢复整版冻结配置和实际成果,先处理当前未保存修改。“应用此运行成果”只接受源编辑版本仍匹配的成功Run;不匹配时使用明确的整版恢复。

素材运行和失败运行不会替换最近完成成片。原版本保留,新合成输出新文件;只重跑失效模型任务不代表最终MP4原地局部修改,CPU合成仍可能处理整片。

可暂停、继续、取消和安全重试;远端结果未知或清理未确认时不盲重发。旧Run归档仅释放自身引用,其他工程/版本仍引用的素材继续保护。账号禁用与删除规则保持不变。

版本:2026-11-13 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file diff --git a/frontend/public/help/manual.md b/frontend/public/help/manual.md index 0502890..9deec1b 100644 --- a/frontend/public/help/manual.md +++ b/frontend/public/help/manual.md @@ -1,12 +1,39 @@ # CMVR Visual 操作手册 -适用版本:2026-11-11的可配置时段、多镜头、私有内容删除与共享素材版本。模型在192.168.28.10运行,项目在`E:\workspace\hybrid\cmvr-visual`。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。 +“创作”新增多图参考的图生图和可选择多个人物的视频替换入口,操作步骤、模型区别及配置见[图生图与视频人物替换操作手册](图生图与视频人物替换操作手册_20261112.md)。 + +新增“故事”入口的基准板、跨镜头角色/形态引用、首帧与视频人工确认流程,见[锚定故事工作室操作手册](锚定工作室操作手册_20261111.md)。首次使用可从该手册第 0 节开始,按“两个 5 秒镜头 → 10 秒成片”逐步完成新建、保存、角色绑定、首帧确认、视频选片、字幕音轨和合成下载;故事编辑页顶部“使用手册”可直接打开网页版本。候选数是 1–4 的数值框,只影响下一次模型生成,人工导入每次为 1 个。希望一次自动生成并在之后局部修改时,在故事中启用“可编辑自动成片”,操作见第12节。独立“工作流”“批量”“成片”页面已移除;旧链接会转至故事或任务,既有数据与共享API保留。 + +适用版本:2026-11-13,含故事可编辑自动成片、容器内滚动、逻辑文件夹、批量整理、可配置时段、私有内容删除与共享素材。模型在192.168.28.10运行,项目在`E:\workspace\hybrid\cmvr-visual`。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。 + +## 0. 六项业务能力与生产流程对应关系 + +六项能力的基础功能、批量生成、人工编排与选片确认均已实现。这里的“审核”是创作者在自己的故事中查看候选、确认首帧、确认视频和检查成片;当前没有单独的“审核中心”、指定另一账号审批或成片终审发布状态。 + +| 功能需求 | 在哪里操作 | 当前实现与边界 | +| --- | --- | --- | +| 图像生成 | 左侧“创作”→“图片”;路径 `/create/image` | 输入提示词生成图片;多图参考编辑另见“图生图”。没有风格 LoRA 管理平台 | +| 视频生成 | “创作”→“视频”;路径 `/create/video` | 文生或首帧图生单镜头,最长约15秒;长故事使用“故事”。生成片段默认无声 | +| 数学推演 | 左侧“推演”;路径 `/math` | 输入问题,输出解题文字和文本/JSON素材;由模型作答,没有符号计算验证或形式化证明 | +| 缺陷样本生成 | “创作”→“缺陷样本”;路径 `/create/defect` | 参考图加缺陷描述,生成合成图与Canny控制图;控制图不是缺陷真值掩膜,不能当作完整标注数据集 | +| 素材结构化 | 左侧“理解”;路径 `/analyze`;声音转写在 `/audio` | 图片或视频抽帧输出主体、场景、OCR、标签和结构化JSON;语音转写是另一个任务。没有完整镜头切分或自动标签回写 | +| 成片合成 | “故事”→目标故事→“03 成片” | 视频排序、裁切、画幅适配、单音轨和人工字幕,输出MP4;不含多轨混音、自动配乐、转场编辑和PPTX课件导出 | + +| 要完成的工作 | 应使用的入口 | +| --- | --- | +| 角色/场景基准、首帧审核、视频候选比较、逐镜选片后合成 | “故事”→打开故事→“01 基准板 / 02 分镜 / 03 成片” | +| 填好一组镜头后自动生成并合成,完成后再审片 | “故事”→“启用可编辑自动成片”→“自动生成初稿并成片” | +| 故事自动生成按批量策略排队 | 可编辑自动成片中选择“批量队列”,再提交素材或成片生成 | +| 新故事的所有镜头批量生成首帧或视频候选 | 故事内“02 分镜”→“全故事候选计划” | +| 使用已有视频做后期 | 故事“02 分镜”导入视频并确认选片→“03 成片”调整时间线并合成 | + +当前开发环境关闭批量时段限制,可以全天提交并等待空闲资源。正式启用夜间开关后,现有规则只约束“批量队列”,交互队列仍全天可用;不能把现有开关理解为“所有模型调用只能夜间运行”。日间审核和后期本身不需要改这个开关。生产节拍统计、严格夜间模式及多人审批的完善方案见文末第11节。 ## 1. 登录与基本流程 -现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。 +当前网页入口为 http://127.0.0.1:5173 ,业务接口在本机 http://127.0.0.1:8000 运行。模型和配音分别通过内网 HTTP 入口 `192.168.28.10:18190`、`192.168.28.10:18192` 连接,使用本机项目无需建立 SSH 隧道。网页地址用于当前开发机本地访问;网页打不开时先检查本地前端和后端是否已启动,模型连接问题可在“创作服务状态”查看。 -使用分配的账号登录。默认管理员名为`admin`,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。 +使用分配的账号登录。默认管理员名为`admin`(可在头像菜单修改用户名),初始密码以私有部署配置为准;点击左下角头像,在“退出登录”上方选择“修改密码”。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。 一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。 @@ -18,14 +45,12 @@ | --- | --- | --- | | 创作:图片 | Qwen-Image文生图 | 提示词、尺寸、种子等 → 图片 | | 创作:视频 | Wan单镜头文生/图生视频 | 提示词、可选参考首帧 → 自选1–15秒无声片段,默认5秒,可选增强 | -| 创作:条件样本 | SDXL+Canny ControlNet | 参考图片、提示词、控制强度 → 合成图及Canny控制图 | -| 工作流 | 多镜头故事自动逐镜生成并合成 | 每镜头提示词/参考图/选用时长 → 一部多镜头影片 | +| 创作:缺陷样本 | SDXL+Canny ControlNet | 参考图片、提示词、控制强度 → 合成图及Canny控制图 | +| 故事 | 可编辑自动成片,或候选生成与人工审核 | 自动生成后局部修改,或基准板 → 首帧确认 → 视频选片;统一在“03 成片”处理时间线 | | 声音 | 中文配音、Whisper转写 | 文本 → WAV;音频/有声视频 → 转写结果 | | 推演 | 复用共享Qwen做文本推演 | 问题 → 文本解答 | | 理解 | 图片理解、视频抽帧分析 | 素材 → 场景、主体、OCR、标签等 | -| 成片 | 编辑已有视频素材 | 排序、裁切、单音轨、人工字幕 → MP4 | -| 批量 | 混合提交任务或已保存工作流 | 任务清单 → 持久批次,运行时段服从配置 | -| 素材 / 任务 / 账户 | 管理结果、进度、用户和令牌 | 见下文 | +| 素材 / 任务 / 账户 | 管理结果和进度;管理员在账户页管理用户 | 见下文 | ## 3. 图片、短视频和条件样本 @@ -34,77 +59,94 @@ 1. 进入“创作”,切换到图片。 2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。 3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。 -4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。 +4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为故事的参考图片使用。 ### 单镜头视频 1. 切换视频模式,写一个镜头中的主体动作与镜头运动。 2. 可选择参考图片作为首帧;文生视频可不选图。 3. 在视频时长中选择5秒、10秒、15秒,或输入1–15的整数秒,默认5秒。再按需要调整参数和1080p画质增强开关。当前单次接口最多361帧、24fps;增加提示词长度不会自动延长单镜头。 -4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。 +4. 需要更长故事时进入“故事”增加镜头;已有视频可在故事“02 分镜”导入并确认选片,再去“03 成片”拼接。 -2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过。网页现已接入最长15秒单镜头。原生源片段采用`4n+1`帧,选择15秒时输出361帧,实际约15.04秒;工作流合成会裁到选用的精确帧数。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。较长镜头通常需要更多时间和资源,增强另有耗时。 +2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过。网页现已接入最长15秒单镜头。原生源片段采用`4n+1`帧,选择15秒时输出361帧,实际约15.04秒;故事合成按设定裁到选用的精确帧数。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。较长镜头通常需要更多时间和资源,增强另有耗时。 ### 条件样本 选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。 -## 4. 多镜头工作流 +## 4. 故事中的多镜头创作 -### 新建、编辑和保存 +### 可编辑自动成片 -1. 打开“工作流”,点击“新建”,填写故事名称。 -2. 每个镜头填写提示词,选择种子和可选参考图片。 -3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。 -4. 每镜头选择1–15秒的选用时长,页面可按0.25秒调整;JSON接受24–360的整数帧。5秒以内继续生成121帧源片段再裁取,以兼容既有草稿和复用规则;超过5秒时按该镜头需要生成更长的原生片段,10秒/15秒分别生成241/361帧。不同镜头各用自己的生成长度,不会统一生成最长镜头。改变长镜头长度可能使原生成结果不再符合复用条件,需要重新生成。 -5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。 -6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。 +1. 打开左侧“故事”,新建或打开故事,填写名称、基准板和镜头并保存。 +2. 点击“启用可编辑自动成片”。在“02 分镜”编辑画面、运动、选用区间和旁白;在“03 成片”配置音轨与字幕,时间线只在这里显示。 +3. 在自动成片工具条选择“交互队列”或“批量队列”,点击“自动生成初稿并成片”。正常流程会生成所需素材再合成,不等待逐镜人工确认。 +4. 检查完成成片;需要修改时编辑对应镜头、旁白或字幕,点击“生成修改部分并成片”。运行进度与成果可在历史中的“查看运行进度与成果”或“任务”查看。 -总时长由镜头选用时长相加,24fps下`总秒数=总帧数÷24`。例如5秒、10秒、15秒三个镜头合计30秒、720帧;20个5秒镜头合计100秒。音轨和字幕需要匹配调整后的总时长。 +完整的局部重生成、字幕保护和版本恢复规则见第12节。自动与人工候选是两条创作路径,不要把自动生成按钮和人工“确认首帧 / 确认选片”步骤混用。 -默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。 +### 分镜滚动与时间范围 -### 音轨和字幕 +“02 分镜”内容超过工作区时,只在对应编辑容器内滚动,故事标题和步骤导航保持可见。鼠标移入容器时显示滚动条,移出后隐藏;键盘聚焦时也可显示,触屏直接滑动。鼠标放在需要查看的镜头列表、编辑区或候选区内再滚动;声音和字幕时间线在“03 成片”,不必寻找页面底部的独立成片入口。 -工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。 +总时长由镜头选用帧数相加,24fps下`总秒数=总帧数÷24`。例如5秒、10秒、15秒三个镜头合计30秒、720帧。音轨、旁白和字幕须匹配总时长;镜头数、磁盘、任务额度和超时仍受环境配置保护。 -- 源入点/出点单位是**毫秒**,表示取音频的哪一段。 -- 偏移单位是**帧**,表示从成片的哪一帧开始播放。24帧=1秒。 -- 选段长度加偏移必须放得进成片,源出点不能超过音频真实时长。过长不会被悄悄截断;应增加镜头、缩短旁白或重新配音。 -- 旁白比成片短时,尾部补静音。当前不提供多音轨混音、自动配乐或自动对齐旁白。 +### 编排审核在哪里,怎么操作 -人工字幕的开始/结束是整片帧号,区间为`[开始帧,结束帧)`。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。 +需要生成后由人把关再进入下一步时,使用故事的人工候选流程;本小节对应尚未启用可编辑自动成片的故事。推荐按下面顺序完成一部片子: -### 运行、复用与恢复 +1. 打开“故事”列表,新建故事或打开已有故事,设置故事归属文件夹和“成果保存到”。 +2. 在“01 基准板”填写故事共同设定,建立场景、角色和形态并选择参考图片,点“保存故事”。 +3. 在“02 分镜”添加镜头,填写画面与动作,设置镜头顺序、生成源长度和选用区间;调整后再次保存。这里的顺序和裁剪就是编排。 +4. 选择“1 首帧生成 / 导入 → 确认首帧”,生成或导入候选。任务完成显示“可复核”后,点缩略图预览,必要时点“对比”,在满意候选卡片上点“确认首帧”。仅预览不算确认。 +5. 选择“2 视频生成 / 导入 → 确认选片”,生成或导入视频候选。检查人物、动作、教学内容、实际源长度和选段后,点“确认选片”。已有人工视频可以直接导入复核,不必先生成首帧。 +6. 每个镜头都须确认有效视频。对不满意的结果,可重新生成当前镜头或导入替代视频;失败候选可点“重试为新候选”。需要撤销决定时点“清除确认”。生成成功不会自动确认,也不会替换之前的选择。 +7. 在“03 成片”设置画幅、裁剪适配、单音轨和人工字幕,展开“查看镜头选片检查”,确认没有“需要有效选片”,然后保存故事并点“冻结素材并合成”。合成沿用“02 分镜”选择的队列;正式夜间限制开启而日间要做CPU合成时,先在“02 分镜”切回“交互队列”,再进入“03 成片”提交。缺少有效选片时服务端会拒绝合成。 +8. 成功后在“成片预览”点“播放成片”“新窗口播放”或“下载成片”。再次编辑不会改变已冻结的历史成片;修改了会使选片过期的设定时,须重新复核。 -点击“保存并运行”。服务器冻结本次参数和修订,独立镜头按就绪顺序分配到空闲GPU并行生成,全部完成后再按镜头顺序合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。 +首帧/视频的确认、清除和替换会记录版本及操作者。现有权限仍按账号隔离:管理员不能直接审核另一账号的私有故事。当前也没有成片“送审、驳回、终审通过、发布”的独立流程。逐字段操作与失效规则见[锚定故事工作室操作手册](锚定工作室操作手册_20261111.md)。 -- “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。 -- “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。 -- “重试此阶段”:仅用于允许安全重试的失败步骤;其他成功镜头保留。 -- 修改草稿后再次运行,可在复用下拉框选择旧Run。只有生成输入一致、产物仍存在且校验通过的成功镜头可复用。提示词、参考图、种子、画幅变更会使对应镜头重新生成;单纯选用时长变更可复用原始生成片段再剪辑。 -- “同步”重新读取后台状态。结果未知/需人工确认表示远端执行结果未确认,不应靠反复提交规避。 +### 旧工作流兼容说明 -JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。 +原独立工作流页的草稿、冻结运行、镜头复用和JSON合同继续保留在后端;删除页面不会删除历史数据。旧三镜头和可变多镜头数据仍按原合同读取,详情见[API示例](API-examples.md)和[共享契约](api-contract.md)。旧工作流JSON不是当前故事页可直接导入的模板;新项目按上面的故事流程建立,旧运行进度与成果到“任务”查看。 ## 5. 声音、推演与理解 “声音”选择“配音生成”,输入不超过2000字,选择`zf_xiaobei`或`zm_yunxi`,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。 -转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。 +转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成故事分镜的功能,也不保证专业数学结论正确。 -“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。 +“推演”的具体步骤:进入左侧“推演”→填写问题和所需输出长度→点“开始推演”→在当前结果或“任务”查看解题内容→复核后下载文本/JSON,或将需要的文字用于文案、字幕和配音。当前没有把数学答案自动转换成分镜或PPTX的按钮。 + +“理解”的具体步骤:进入左侧“理解”→上传或选择本人的图片/视频→视频可设置1–12张采样帧→点“解析素材”→到当前结果或“任务”查看主体、场景、OCR、标签及采样时间→在“素材”查看或下载结构化JSON和抽帧结果。它只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。需要声音内容时,另外在“声音”选择转写。 + +理解结果中的标签不会自动回写源素材的检索标签;复核后,在源素材预览中编辑标签并保存,再用素材库的标签筛选。生成结果仍须人工检查,特别是教学数学结论和工业缺陷标注。 ## 6. 成片、素材与任务管理 -“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。 +已有视频片段时,进入故事“02 分镜”,导入视频候选并确认选片,调整顺序和选用范围,再到“03 成片”处理音轨、字幕并合成;无需独立成片页面。可编辑自动成片的素材绑定和时间线操作见第12节。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件;裁剪范围必须在真实媒体范围内。 ### 我的素材与共享素材库 -普通账号和`admin`在“我的素材”、任务、工作流和批量记录中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。 +普通账号和`admin`在“我的素材”、故事、任务及历史运行中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。 “我的素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找,也可修改名称和标签。“共享库导入”来源用于查找从共享库取得的个人副本。 +### 文件夹与批量整理 + +文件夹用于项目内分类。移动分类、改名不会移动磁盘文件,也不会改变素材编号和故事引用。旧素材、任务和故事先显示在“未分类”。 + +1. 在素材库顶部“浏览目录”选择文件夹。选择“全部文件夹”或“未分类”时,点击“新建文件夹”创建根目录;选择一个已有文件夹后,会出现“新增子文件夹”“编辑文件夹”“删除文件夹”三个操作。名称、父目录等字段在操作弹窗中填写。 +2. 进入一个文件夹后上传,素材自动归入该文件夹。整理已有素材时勾选卡片左上角;选中后才会显示“整理到”及批量按钮。“移动分类”替换原有文件夹归属,“加入文件夹”保留原归属,允许同一素材同时用于故事 A 和故事 B,无须复制原文件。 +3. 可逐项勾选,也可“选择本页”。点击“发布到共享库”或“批量删除素材”后,确认本次总数;完成后显示成功和失败数量。仍被任务或故事引用的素材不会被强行删除,失败项保持勾选,可展开“查看失败原因”。成功发布的是独立共享副本。 +4. 新建故事时填写故事名称,默认自动新建同名文件夹;取消“自动新建同名文件夹”后可选择已有目录或未分类。故事工作室顶部可修改“故事归属”,修改后保存故事。 +5. 创作、声音、推演、理解和故事生成均可选择“成果保存到”。故事默认使用自己的文件夹;候选、批量候选和成片也可另选目录。提交后目标已固定,之后再移动故事不会改变已排队任务的成果位置。 +6. 任务中心可以按目录筛选并整理任务;移动任务分类不会改写已冻结的成果目标。素材选择器也可按目录找图、找视频或音轨。共享素材导入时可选择放入哪个个人文件夹。 + +“删除文件夹”只删除分类及其子分类,保留素材、任务、故事和实际文件;仅归属该目录的内容回到未分类,同时属于其他目录的素材保留其他归属。删除实际素材仍使用素材删除操作和原有引用检查。 + +素材库默认每页 48 项,可以切换 24 / 48 / 96 项;素材卡片已缩小,窄屏自动换行并保留两列预览。没有选中素材时,批量工具会收起以留出更多浏览空间。 + 1. 分享时,在自己的素材卡片或预览中点击“发布到共享库”,阅读并确认发布范围。系统复制原件和当前名称、标签等信息,生成一份独立的共享副本;所有已登录用户均可查看、下载和导入。 2. 在“共享素材库”预览的内容是只读共享副本。点击“导入我的素材库”后,会创建属于当前账号的独立私有副本,可再编辑、删除或用于创作。创作中的素材选择器也可切到“共享素材”,选择后先导入,再将个人副本用于当前输入。 3. 发布者可通过“我发布的”筛选并打开预览,点击“撤回共享”。撤回后其他用户无法继续查看或导入该发布,已经导入的个人副本仍然保留。删除私有原件也不会删除已发布的共享副本或他人的导入副本;要停止共享,需要单独撤回。 @@ -113,15 +155,15 @@ JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本 ### 删除素材和记录 -自己的素材卡片/预览、任务卡片/详情、工作流草稿、运行卡片和批量记录均提供删除入口。删除记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复。 +自己的素材卡片/预览、任务卡片/详情及可管理的运行记录提供删除入口;历史工作流草稿和批次的删除合同仍保留在API。任务、工作流和批量记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复;素材删除则同步移除文件和数据库文件记录。 - 删除独立Job只删除任务记录,已经生成的素材继续保留在“我的素材”。要清理这些素材,需要再逐项删除素材。 -- 删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。 -- 工作流子任务或批量成员不能单独删除,按页面提示到父运行或批次管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。 +- 历史数据的API归档规则保持不变:删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。 +- 工作流子任务或批量成员不能单独删除,按提示通过父运行或批次的受支持接口管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。 - 活跃记录须先取消,等待执行退出及资源清理确认后再删。点过“取消”不表示已完成清理,仍显示排队、执行中或取消中时不能直接删除。 - 删除素材若返回409引用冲突,先从草稿解除引用并保存;冻结运行中的引用需要删除相关运行或父批次。活动任务使用中的素材应先取消任务、等待退出,再按依赖关系处理。不要直接去磁盘删除文件。 -素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做`dry-run`盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。 +素材删除成功后,会同步移除该素材的原文件、缩略图及数据库文件记录,释放对应素材占用。撤回共享时删除共享库中的独立快照;已经引用到个人素材库的副本继续保留,由引用者独立管理。文件被占用或暂时无法删除时会提示失败,可稍后重试。旧版本遗留的软删除文件仍由运维清理流程处理。 “任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。 @@ -133,7 +175,44 @@ JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本 ## 7. 批量与开发/生产配置 -“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。 +### 7.1 可编辑自动成片怎样使用批量队列 + +1. 打开“故事”并启用可编辑自动成片,完成需要生成的镜头、声音与字幕设定。 +2. 在自动成片工具条的执行方式中选择“批量队列”。选择队列本身不会提交任务。 +3. 按目标点击“自动生成初稿并成片”“生成修改部分并成片”或“仅生成素材”。实际生成前会保存并校验,后端继续按原资源和时段策略持久排队。 +4. 在版本与运行历史点击“查看运行进度与成果”,或进入“任务”跟踪;编辑与最终成片仍回原故事处理。 + +独立“批量”页面已移除,“批量队列”执行模式继续保留。关闭网页不会取消已经接受的任务;交互队列仍适用于全天等待空闲资源的提交。 + +### 7.2 旧通用批次与工作流API + +原提示词JSON清单、多个旧工作流混合批次及其历史数据仍由共享后端API保留,独立页面移除不改变接口合同。当前网页不再提供“快速整理”“加入已保存工作流”或“类型化清单JSON”表单;新手请使用故事流程,不要寻找这些旧按钮。 + +已有API集成继续使用原幂等键、版本校验及归属检查,通用批次仍为1–100个清单项,部分生图类型的单项`count`另有1–4限制。草稿、冻结运行和批次的控制/归档仍遵守父子引用规则;技术用法见[API示例](API-examples.md)和[共享契约](api-contract.md)。故事编号不能直接充当旧工作流编号。 + +### 7.3 怎样批量生成一个故事的所有镜头 + +1. 在故事的人工候选流程中打开“02 分镜”,完成所有镜头的设定并点“保存故事”;启用自动成片的故事使用7.1节。 +2. 在首帧阶段选择生成方式、候选数(1–4)和“批量队列”,点“全故事候选计划”。例如20个镜头、候选数2,会安排40个当前阶段的候选。 +3. 等首帧候选可复核后,逐镜预览并点“确认首帧”。不满意的镜头单独点“生成当前镜头”,避免为所有镜头重复付出生成时间。 +4. 各镜头首帧有效后,切到视频阶段,检查各镜头生成源长度覆盖选段;选择候选数和队列,再点“全故事候选计划”。 +5. 视频生成完成后逐镜“确认选片”,进入“03 成片”补音轨、字幕并冻结合成。 + +“全故事候选计划”一次只安排当前首帧或视频阶段,不自动确认,不自动接着生成下一阶段,也不自动跳过已经有候选的镜头。“全故事”指范围,“批量队列”指调度方式,两者必须分别选择;默认的交互队列不会因为点了“全故事”就变成夜间批量。 + +故事候选计划的上限由镜头数、候选数和账号容量共同决定,不套用通用JSON清单的100项上限。故事候选的查看与审核以原故事“02 分镜”为准;独立批量页已移除,不要把候选编号当普通任务编号使用。 + +### 7.4 暂停、继续、取消与日夜生产节拍 + +- 历史通用批次的暂停、继续和取消仍通过原批次控制API处理;独立“批量记录”页面已移除。暂停只阻止后续准入,当前已运行阶段自然完成;继续不自动重做失败成员。已取消的批次不能靠继续恢复。 +- 故事候选可在“任务”查看生成状态,回原故事复核;旧工作流运行还可在失败的可重试阶段使用“重试此阶段”。不明远端结果或清理未完成时,先查明状态,不能反复创建替代任务。 +- 时段限制关闭时,以上批量流程都可在开发日间运行。启用后,新批量任务/阶段只在21:00–次日08:00准入;08:00时已运行阶段继续完成,后续阶段等待下一窗口。 +- 这里的GPU执行单元包括同一个视频任务的生成与可选画质增强,08:00后可继续完成整条处理流程;不在生成与增强之间强制停下,下一镜头等新的执行单元才重新判断窗口。 +- 生产排期中,单人审核可以在日间完成,FFmpeg剪辑合成可采用交互方式。需要首帧人工把关的新故事通常是“第1天编排 → 第1夜首帧候选 → 第2天确认首帧 → 第2夜视频候选 → 第3天审片、字幕与合成”,不是同一夜自动越过人工确认。 +- 若已有批准首帧,可直接从视频批量阶段开始;若接受生成后再统一审片,可以在故事中使用可编辑自动成片和“批量队列”,次日再检查成片。 +- 当前没有按夜统计合格镜头产量、审核积压和次夜产能预测的生产看板。排期先依据任务实际耗时、合格选片数及其他用户占卡情况安排,不能把四张GPU当作每晚固定满额可用。 + +### 7.5 管理员怎样切换开发与生产时段 权威配置位于容器内: @@ -179,13 +258,19 @@ bye 切回开发模式时把上传源文件改为`runtime-policy.development.json`,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。 -## 8. 账号、令牌和未确认提交 +## 8. 用户管理与修改密码 -在“账户”修改密码;管理员可创建、停用用户。停用用户不代表去停止共享模型服务。包括`admin`在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。 +“账户”页面仅管理员可见,普通用户不能进入该页面或调用用户管理接口。页面只提供新增、禁用/启用和删除用户;不能禁用或删除当前登录的管理员账号。新增用户的初始密码允许6–256个字符,包括`123456`这样的6位数字。 -机器令牌用于外部系统调用,创建时按用途选择权限,令牌仅显示一次,立即安全保存;撤销后失效。不要把令牌放进截图、公共仓库或浏览器地址。 +禁用用户后,该账号不能登录,已有登录会话立即失效,相关任务暂停准入;素材、故事、工作流与任务记录仍保留。重新启用后,用户重新登录即可继续使用原资源;用户自己设置的暂停不会被自动解除。停用用户不会停止共享模型服务。 -“未确认提交”表示客户端没有确认服务器是否已接受。先查询原提交键,确认后再恢复;不要换一个键重复创建。接口细节见`docs/api-contract.md`和FastAPI接口文档。 +删除用户将永久清理该账号、自有素材(含共享发布)、故事、工作流、批量和任务记录及对应本地文件,无法恢复。其他用户已经独立导入的副本保留。若任务或上传尚未结束,会先停用账号并请求取消,提示等待清理;确认执行停止后点击“重试删除”,清理成功才会显示删除成功。 + +所有登录用户都可点击左下角头像,选择“修改密码”,输入当前密码、新密码和确认新密码后点击“确定”。新密码须为12–256个字符,修改成功后重新登录。账户页不再显示改密、API令牌或未确认提交管理区。 + +头像菜单还提供“修改用户名”:填写新的登录用户名和当前密码,确认后使用新用户名登录。用户名为3–64位小写字母、数字、点、下划线或横线,不能与已有账号重复;显示名保持独立。修改后当前登录会话、账号ID、角色及已有资源均保留。管理员修改用户名后,重启不会重新创建旧用户名的初始管理员。 + +包括`admin`在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。 记录删除后,原幂等提交的恢复或重放会返回`410 resource_purged`,表示原结果已归档,不能通过重放把已删除记录恢复。只有确实要创建一项新工作时,才发起新的提交。 @@ -194,10 +279,12 @@ bye | 数据 | 实际位置与用途 | | --- | --- | | 网站业务数据 | MySQL `192.168.28.10:3306/cmvr-visual`,保存用户、素材元数据、任务、工作流、批次、共享发布和审计等网站业务记录 | -| 媒体文件 | 服务器宿主机`/data/llmusers/llmuser/workspace/cmvr-visual/assets`,保存上传、生成、共享发布和导入副本的媒体原件/缩略图;容器内对应`/workspace/cmvr-visual/assets` | +| 当前本地媒体与任务工作文件 | `E:\workspace\hybrid\cmvr-visual\.local\workspace\cmvr-visual\assets` 和同级 `jobs`,保存网页上传、归档结果、共享发布及导入副本;访问通过受认证的业务API | +| 服务器推理工作文件 | 模型API管理自己的输入、尝试目录和输出,本地业务API通过HTTP上传/归档;它与本地素材目录是两份独立存储 | +| 业务交付副本 | `E:\workspace\hybrid\cmvr-visual\outputs`,例如保留的鲲鹏成片、音频与字幕;这里的副本不是网页素材库的数据库来源 | | GPU调度恢复 | 推理服务自己的SQLite,仅负责独立GPU执行队列与恢复,不是网站业务数据库,也不保存网站的用户、工作流和共享素材业务 | -网页所见的素材列表来自MySQL元数据,视频、图片、音频文件在上述媒体目录。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。 +网页所见的素材列表来自MySQL元数据,当前业务媒体存放在本机上述目录。后续正式部署的路径由当时配置决定,不能把旧服务器部署路径当作当前素材库位置。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。 ## 10. 常见问题 @@ -211,10 +298,56 @@ bye | 转写没有声音 | 检查源视频是否有音轨;模型生成片段默认无声 | | 结果未知/需要人工确认 | 运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止 | | 删除返回409 | 检查活动执行、父级控制和引用依赖,先取消并等待退出,或解除引用/删除相关父记录后重试 | -| 删除后磁盘没有立即下降 | 软删除保留文件;GC默认dry-run,默认14天保留期后仍需运维维护清理 | +| 素材删除失败或仍占空间 | 先解除任务和工作流引用;文件被占用时稍后重试。旧版本遗留文件由运维清理;模型临时缓存和共享副本独立管理 | | 找不到其他账号的旁白或参考图 | 请原作者发布到共享素材库,再导入自己的私有副本;管理员也不能直接读取他人的私有素材 | | 输出过大或空间不足 | 减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列 | -完整案例见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。模板在`frontend/public/examples/kunpeng-storyboard.json`,原文旁白在同目录的`kunpeng-narration.txt`。 +历史分镜、JSON格式与旁白实测参考见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。旧模板在`frontend/public/examples/kunpeng-storyboard.json`,当前故事页不提供直接导入;原文旁白在同目录的`kunpeng-narration.txt`。 另提供`kunpeng-storyboard-45s.json`,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。 + +## 11. 尚未覆盖的生产管理需求与完善方案 + +基础六项能力和“批量生成→人工编排审核→合成”的流程已经具备。以下是需要区分的完善项: + +| 尚未覆盖或需完善的部分 | 当前可用方式 | 落地方向 | +| --- | --- | --- | +| 后续若在任务中心展示候选批次的详情跳转 | 当前回故事“02 分镜”查看与审核,独立批量页已移除 | 保留候选所属故事、镜头和阶段信息,按成员类型跳转,候选尚未派发时也能查看计划 | +| 所有模型调用严格限于夜间 | 目前仅批量受夜间开关约束,交互全天 | 增加明确的时段作用范围,API与推理worker一致判断;日间编排、审核和CPU后期保留可用 | +| 以实测夜间产量安排生产节拍 | 人工查看任务、选片和资源状态 | 汇总逐夜成功镜头、合格选片、执行耗时和审核积压,以有效历史样本给出区间估算 | +| 编导提交给另一个审核人、驳回意见、成片终审 | 本人预览和确认,按账号隔离 | 作为可选扩展增加版本化送审单与明确授权;不开放管理员对全部私有内容的默认访问 | + +完整的代码落点、接口、数据保护、实施顺序及验收条件见[生产流程完善方案](design/2026-11-12-production-workflow-design.md)。这些是待实施设计,当前页面没有的按钮不能按方案描述操作。教学数学验证、缺陷真值标注、多轨混音等也未实现,但它们是对应基础能力的后续专项,不把现有模型输出冒充这些成果。 + +## 12. 可编辑自动成片(代码版本007) + +本节适用于已完成007迁移并启动新版API的环境。真实数据库和运行服务不会由代码更新自动迁移;先按发布清单完成联合备份、升级和业务API切换。自动流程继续使用现有队列及资源策略。 + +### 首次生成 + +1. 从“故事”新建或打开故事,配置画面、场景、角色、镜头与时长,点“保存故事”,再点击“启用可编辑自动成片”。 +2. 在“02 分镜”编辑镜头,按需输入旁白。内容超出时在分镜编辑容器内滚动,移入显示滚动条、移出隐藏;故事只在“03 成片”显示音轨与字幕时间线。 +3. 声音选择静音、人工单音轨或生成旁白;字幕选择关闭、人工、旁白文案或AI补齐文案。配音需真实TTS服务通过部署验收,轻量健康检查不代替声音质量验收。 +4. 选择“交互队列”或“批量队列”,点击“自动生成初稿并成片”。系统保存版本、检查计划,再生成和校验素材、字幕及音轨,最后合成。正常阶段不等待逐镜头确认,关闭网页不取消后台运行。 + +### 局部修改与新版本 + +故事名称可在页面顶部修改,人工流程点击“保存故事”,自动模式点击“保存编辑”。自动模式的名称和分镜等编辑会一起保存;尚未保存或保存失败的名称仍保留在输入框中。 + +需要恢复逐步骤确认时,保存当前修改,再点击故事导航栏“返回逐步骤人工确认”。故事、镜头、素材和历史运行保留,自动素材作为待确认候选显示,仍需你确认首帧与视频。人工编辑和确认也会带回自动模式;点击“启用可编辑自动成片”即可再切换。存在未结束的运行、候选任务或未清理执行时会提示先处理,切换失败不会丢弃当前编辑。 + +修改镜头画面/运动、裁剪或选用私有素材,可“仅生成素材”,也可“生成修改部分并成片”。指定重新生成会创建新变体,实际种子显示在绑定详情,网络重试不重复创建。 + +- 改运动重生成对应视频;改画面或参考图影响依赖首帧和视频;共享角色/场景可能影响多个镜头。 +- 重排或选用区间仍在实际源长内时复用源视频;源不够长时需重新生成。 +- 修改旁白段只重生成该段,再装配单音轨;修改字幕只改显示文字,明确同步到旁白才重新配音。 +- 字幕分别保护人工文字、人工时间,锚点可选全片、镜头、旁白段。冲突可保存,成片前须处理,不默默截配音或改写人工文字。 +- 编辑版本仍匹配时自动采用新结果;用户已经继续编辑时保留为运行成果并提示冲突,不能覆盖后来的输入。 + +### 恢复与失败 + +历史区分素材/成片。“从此版本恢复编辑”明确恢复整版冻结配置和实际成果,先处理当前未保存修改。“应用此运行成果”只接受源编辑版本仍匹配的成功Run;不匹配时使用明确的整版恢复。 + +素材运行和失败运行不会替换最近完成成片。原版本保留,新合成输出新文件;只重跑失效模型任务不代表最终MP4原地局部修改,CPU合成仍可能处理整片。 + +可暂停、继续、取消和安全重试;远端结果未知或清理未确认时不盲重发。旧Run归档仅释放自身引用,其他工程/版本仍引用的素材继续保护。账号禁用与删除规则保持不变。 diff --git a/frontend/public/help/production.html b/frontend/public/help/production.html new file mode 100644 index 0000000..1adb40f --- /dev/null +++ b/frontend/public/help/production.html @@ -0,0 +1 @@ +功能与生产流程完善方案 · CMVR Visual
CMVR Visual · 使用帮助

六项能力与生产流程完善方案

状态:2026-11-12编写的待实施方案,保留当时的代码与风险分析。2026-11-13已移除独立工作流、批量和成片页面;下文涉及旧页面的落点是历史背景,后续若实施应接入故事或任务中心,不能按旧页面名寻找入口。现有功能的操作步骤以操作手册功能与生产流程第0、4、7节为准;本文新增的接口、字段和页面尚未实施。当前开发全天运行的策略保持不变。

Goal: 保留现有六项基础能力及单人审核闭环,补齐故事批次导航和夜间产能依据;如正式生产要求所有模型任务仅夜间执行,提供统一策略扩展;多人审批另列可选阶段。

Architecture: 沿用Vue/Pinia、FastAPI/MySQL、单业务协调器和独立模型调度器。复用草稿、运行、任务、批次、候选、选择与执行记录,不另建任务引擎,不引入Redis/Celery。版本化增加合同和必要迁移,既有任务、素材及历史成片继续可用。

Tech Stack: Vue 3、TypeScript、Pinia、FastAPI、SQLAlchemy async、Alembic、MySQL、现有HTTP/SSE与FFmpeg。

Spec: 用户提出的“图像生成、视频生成、数学推演、缺陷样本生成、素材结构化、成片合成;夜间批量生成,日间编排审核,按夜间算力产出制定生产节拍”。开发环境暂不固定21:00–08:00。以下未获明确规定的统计口径和审批形式均为本方案建议,不视为用户已经选择。

1. 已实现的范围及依据

需求当前实现主要代码
图像、视频、缺陷样本提示词/参考图、参数校验、独立任务及结果归档frontend/src/views/WorkbenchView.vue;backend/app/adapters/provider/contracts.py、gpu.py;inference/llm_services/adapters.py
数学推演共享Qwen返回步骤与答案,输出文本及JSON,未做形式化验证backend/app/adapters/provider/cpu.py、qwen.py
素材结构化图片或均匀抽帧的视频理解,输出主体/场景/OCR/标签/JSON;ASR为单独任务frontend/src/views/ToolsView.vue;backend/app/adapters/provider/qwen.py
成片合成已有片段或故事选片的排序、裁剪、画幅、单音轨及人工字幕frontend/src/views/StoryStudioView.vue及components/EditableProduction.vue;backend/app/adapters/provider/composition.py;backend/app/services/stories/api.py:render
批量生成通用混合批次及故事候选计划,持久保存、幂等、暂停/继续/取消和有界补队backend/app/services/batches.py;services/stories/candidates.py;services/orchestration/workflow_engine.py
编排审核角色/场景基准、分镜顺序、候选比较、确认首帧/选片、确认失效和冻结合成frontend/src/views/StoryStudioView.vue;components/studio/StoryCandidates.vue;backend/app/models/stories.py
时段控制API和worker读取策略;批量在21:00–次日08:00准入,已准入执行单元继续完成backend/app/services/orchestration/resource_policy.py;inference/llm_services/scheduling.py

当前运行接口的批量时段开关为关闭,六项基础能力已开放,故事能力已启用。能力“可用”说明接口和配置具备,不等于所有题材的生成质量、数学正确率或工业标注准确率都已验收。

“审核”已有可追溯的本人选择记录:visual_shot_selections追加保存操作者、版本、上下文和素材校验信息;普通草稿不能伪造批准。它没有另外一名审核人、驳回意见或成片终审单。

“本地部署”目前为本机网站和业务API、局域网服务器模型与MySQL,不依赖公有云模型;不表示模型也装在当前Windows开发机。六项能力产出可供教学课件和视频使用,但没有一键生成/导出PPTX教学课件。

2. 哪些是缺口,哪些是可选扩展

编号结论实施范围
A原批量页的历史衔接问题旧批量总表曾将非run成员统一链接到Job详情;独立页面已移除。后续若在任务中心呈现候选批次,仍须正确定位原故事,不能把候选编号当Job编号
B严格解读原文时的策略缺口当前交互队列全天,不能仅打开现有开关就声称“所有生成仅夜间”;增加策略作用范围。若正式生产仍保留日间交互,可继续用现有策略
C生产节拍的管理缺口已有执行与选片记录,但没有逐夜产量、合格选片、积压和产能估算页面;增加有依据的统计
D可选组织流程若“审核”指编导送给其他人审批,再补多人送审和终审;它不是现有本人选片的别名,也不是六项基础能力必须先重建的前提

优先采用“在现有架构上补A与C,B按正式生产策略启用,D按组织需要选做”。重建通用工作流平台会重复现有持久任务和人工关卡;当前数据规模也不需要先引入新的消息队列或集群调度。

3. 全局约束

  • 只在本地修改和验证;本次不部署网站、不切换真实时段、不重启共享模型。
  • 四卡按就绪FIFO派发,每卡一个本项目任务;其他用户优先、内存预算、取消清理和幂等恢复保持原规则。
  • 21:00–次日08:00按Asia/Shanghai解释,边界为21:00包含、08:00不包含;窗口关闭不终止已准入执行单元。单个GPU runner内的生成与可选增强是一个单元,允许整条pipeline结束,不承诺在内部神经网络阶段之间跨夜暂停恢复。
  • 私有内容按账号隔离。新增统计、候选详情或审核授权不能把管理员变为所有用户私有内容的默认读者。
  • 历史迁移001–006保留;新增迁移顺序按实施时仓库最新版本确定,不覆盖后来新增的版本。
  • 已冻结运行不受草稿后改影响;新版本不能继承旧版本的审核结论;未知远端结果不能自动重新生成。
  • 不自动暂存、提交或推送。验证优先使用自动清理的隔离临时目录;通过后清理临时脚本、截图、媒体、数据库和打包文件,保留复用测试与最小夹具。

4. 重点验收风险

  1. 候选尚未派发,没有Job编号,或者不在第一页时,批量成员仍应准确打开所属故事候选。
  2. 交互/批量两条入口、后台恢复和远端worker必须执行相同的夜间策略;任务JSON不能自行改成另一模式绕过严格窗口。
  3. 新故事的首帧审核是人工关卡。视频批量不能在缺少有效首帧时偷偷越过审核,重连和重试也不能自动选片。
  4. 重排、失败重试和多阶段处理不能重复计算产量;未选候选不能直接当作“未审核”,开发数据不能冒充稳定生产产能。
  5. 审核人只能读取被明确授权的冻结包;调换ID、旧版本提交、重复决定和修改草稿均不能扩大读取范围或复用旧批准。

5. A:补齐批次导航和操作入口

代码落点: backend/app/services/snapshots.py、services/stories/api.py、api/routes/stories.py;frontend/src/types/workflows.ts、api/stories.ts、views/TasksView.vue、views/StoryStudioView.vue(原批量页已移除)、components/studio/StoryCandidates.vue。

合同: 保留现有Batch字段,在候选成员追加可空story_context:story_id、shot_id、candidate_kind(frame/video)、candidate_id、job_id、asset_id。在同一账号范围内读取候选归属,不能信任客户端提交的上下文。非候选成员返回空上下文,旧客户端继续读取原字段。

新增GET /stories/{story_id}/candidates/{candidate_id},返回已有CandidateDTO;同时校验故事、候选和当前账号的归属,已删除或跨账号返回404。该接口用于直接定位较早的候选,避免为了打开第25个以后的结果连续翻页扫全库。

  • [ ] 先补回归:run仍打开运行详情,job仍打开任务详情,candidate打开故事;未派发、已失败、已删除、跨账号、候选超过第一页分别检查。
  • [ ] 实现快照上下文和候选详情接口,不迁移数据库,不改变任务派发。
  • [ ] 后续若在任务中心或故事运行历史展示批次,按target_kind分别跳转:候选使用/studio/{story_id}?shot={shot_id}&stage={candidate_kind}&candidate={candidate_id}。不支持的类型显示可解释状态,不能退化成错误Job链接。
  • [ ] 故事页校验查询参数、定位镜头和阶段并加载目标候选;这些参数只定位,不生成、不确认、不重试。
  • [ ] 在“03 成片”增加明确的合成执行方式选择,复用现有executionMode和RenderCreate.execution_mode,便于日间直接选择交互CPU合成。
  • [ ] 通过后同步手册,删掉当前“回原故事查看”的导航限制说明。

6. B:让正式生产支持严格夜间模型任务

代码落点: backend/app/core/runtime_policy.py、domain/tasks.py、services/orchestration/resource_policy.py、admission_clock.py、coordinator.py、adapters/provider/runtime.py;inference/llm_services/scheduling.py、store.py、worker.py、remote_bridge.py、api.py;前端能力类型、服务状态和批量策略提示。

配置建议: 支持运行策略schema v2,新增model_window_scope,只接受batch_only和all_model_tasks。继续接受v1,并解释为当前batch_only;batch_window_enabled=false时两个范围都全天可执行。当前开发配置不变,正式严格模式是v2加true和all_model_tasks。

在API与worker分别实现纯规则window_applies(task_type: str, execution_mode: str, phase: str, policy: dict) -> bool,用同一组合同测试向量检查结果。模型阶段覆盖图像、参考图、视频、缺陷、语音生成、Whisper及Qwen推演/理解;上传、Pillow首帧规范化、FFmpeg抽音/裁剪/拼接、浏览/确认等日间编辑和审核操作继续开放。对其他项目调用共享Qwen不施加本项目策略。

本方案明确选择“执行单元准入”的边界:GPU worker一次启动的runner(包含该视频的生成与Real-ESRGAN增强)整体为一个单元;业务API已有独立资源阶段的租约也分别为单元。07:59准入的视频可在08:00后继续生成、增强和清理,但不能再开始另一镜头/新的runner。一次已准入的Qwen素材理解阶段可完成本阶段的抽帧理解调用。当前不引入内部阶段检查点,不以重排来假装续跑,否则会重生成已经完成的视频。all_model_tasks范围只约束模型执行单元,关联批次的纯CPU后期也允许日间处理;v1/batch_only保持原有批量阶段限制。

  • [ ] 补20:59:59、21:00、07:59:59、08:00边界及跨日、时钟回退、暂停、取消、服务恢复测试。分别覆盖两个模式、窗口范围和资源阶段。
  • [ ] 双端读取、远端运行状态传输及本地镜像都保留新增范围;不能只改一处JSON白名单。后台恢复与旧已排队任务也按当前生效策略重新判断新阶段准入。
  • [ ] 双端先支持并通告策略版本及范围,再允许管理员激活严格模式。版本不匹配或严格模式配置不可核实时关闭新模型准入并说明原因,不允许回退为日间交互执行;CPU后期保持可用。
  • [ ] 后端在申请新的Qwen/配音等模型执行租约之前校验,GPU worker在领取及实际spawn前再次校验,保持真正执行的二次保护。测试07:59启动的视频在08:00后完成增强、不重生成,而新的视频单元等到下一窗口;新的独立HTTP模型阶段也须重新判断。
  • [ ] 页面从服务端展示“开发全天 / 仅批量夜间 / 全部模型夜间”,并区别排队等待与故障。客户端任务体没有策略覆盖字段。
  • [ ] 隔离测试通过后提供管理员切换和回退步骤;实际启用属于后续正式生产操作,本次不改运行配置。

7. C:用实际夜间产出支持生产排期

代码落点: 新建backend/app/services/production.py、models/production.py、api/routes/production.py、schemas/production.py和frontend/src/views/ProductionView.vue;扩展inference/llm_services/store.py、worker.py、api.py、backend/app/adapters/provider/gpu.py和services/orchestration/executions.py。复用现有素材、选择校验及SSE,业务模型表实名为visual_job_executions。

必要的上游历史: 现有业务Execution开始/结束是本地观察时间,上游jobs.started_at是领取时间且重排会清空,runner_start只是进程身份值。它们都不能代表完整的真实执行历史。先在上游SQLite增加持久job_attempts表,按现有execution_id=job_id:attempt_count唯一保存claimed_at、admitted_at、runner_started_at、finished_at、outcome及admission_policy_snapshot。所有时间为上游UTC事实:准入时间与当次最后准入检查使用的快照一起持久化;runner开始只代表Popen成功,结束代表清理确认,不称GPU核函数运行时间。未启动延期、让卡、失败、取消、超时和未知结果均保留相应尝试,不能只保留最后一次。

在claim_next/admission/set_runner/defer_unlaunched/requeue_preempted/finish等生命周期写入历史,保持attempt/fence校验。新增受原鉴权保护的GET /jobs/{job_id}/executions?after_attempt=0&limit=100,并在能力接口声明execution_history_version=1。终态历史不可变并按attempt分页;未终态尝试单列为current、每次重取,避免分页游标漏掉运行到完成的变化。返回持久的store_instance_id、完整性及可用历史范围;旧版本无历史时明确标记unknown。

业务镜像与本地阶段: 新迁移增加visual_upstream_attempts,以(store_instance_id, upstream_execution_id)唯一镜像,关联本地Job与owner,并保留原始时间和策略。补录API离线期间的尝试只更新统计镜像,禁止用旧attempt调用当前Job的状态推进或替换fence。为visual_job_executions增加可空admission_policy_snapshot,记录本地Qwen/配音等执行租约的真实准入策略;既有started_at/finished_at继续作为本地观察字段,不改写其含义。历史空值为policy_unknown;Qwen HTTP耗时、runner存活/清理区间和网页观察耗时分别展示,不将任一项冒充精确GPU利用率。

观测覆盖: 在同一新增迁移中增加visual_production_observations,由现有协调器至多每分钟采一条owner_id/observed_at/policy_snapshot/service_online/eligible_gpu_count/backlog_by_profile。这是排期样本的覆盖证据,不是新调度器。首版建议有效夜次需要至少95%的分钟样本、连续缺口不超过2分钟、同规格至少90%的有效采样有待处理需求,且真实策略已知并启用窗口;阈值为方案建议,API中公开口径。空闲无需求、离线、开发全天、旧无历史等夜次仍展示事实,但不进入产能参考。没有覆盖证据不能把缺失夜次补成零或把少数繁忙夜当稳定产能。

读取合同: GET /production/summary?night=YYYY-MM-DD&days=7,仅当前账号,最多31夜。night代表当日21:00开始的一夜,返回时区、截止时间、指标、分组、覆盖缺口、有效样本夜数与估算依据;参数异常返回422。用受限SQL聚合执行和产物事实,再对涉及的故事有界复用preview/selections/selection_dto/readiness检查上下文、首帧依赖、素材及裁剪;不能仅凭非空candidate_id计合格。大量故事时分页返回确认统计和校验进度,未校验完的统计标为不完整,不能拿部分结果预测。沿用业务数据库,不增加独立统计数据库。

统计口径固定如下:

  • 产物按Job/候选唯一编号计算,执行尝试单独统计;让卡重排、增强阶段和重试不算新产物。
  • 按模型类型、profile、分辨率、源长度和主要生成参数分组,不把5秒视频与15秒视频混为相同产能。
  • 按最终成功尝试的真实准入夜次归属;08:00后完成的同一在途pipeline仍计入原夜次,单列延后完成时间。白天提交但夜间执行的任务不归到提交日白天;缺少上游时间或策略时显示归属未知。
  • 展示成功候选数量、源视频秒数、截至查询时当前确认的有效视频数量、无有效选片但已有可复核候选的镜头数、失败/取消/让卡尝试和等待时间。未选候选可能已被人工淘汰,不能全部标成待审。
  • “可用于成片秒数”依据有效选择的裁剪区间计算;生成的约15.04秒源片段不等于影片使用15.04秒。
  • 首版以最近最多7个同规格、策略已记录且窗口启用的有效夜次给出实际合格产出P25至中位数的参考区间;少于3夜显示“样本不足”。每夜人力确认速度、外部占卡和可用卡数会影响结果,不把区间写成承诺。
  • [ ] 先写跨午夜、08:00延后完成、API离线跨夜重排、分页中的运行尝试完成、重试去重、无历史、不同规格、空数据和账号隔离测试。
  • [ ] 增加上游逐attempt持久事实和版本化历史读取,再做业务镜像、本地策略快照与分钟观测迁移;冻结迁移不导入会变化的当前模型。同步重取或历史缺失不能改变当前任务/fence,不能触发重生成。
  • [ ] 实现执行事实聚合及有界有效选择校验,明示统计截止、完整性、样本不足;只读汇总不修改任务、候选或审核状态。
  • [ ] 新增“生产概览”入口,展示夜间产出、需选片镜头和排期参考;链接到已有任务/故事,不另造创作表单。
  • [ ] 用隔离数据验证口径;真实产能观察在正常业务运行中累计,不为填报表额外提交GPU测试任务。

8. D:有多人审批需要时再增加正式送审

该阶段是扩展选项。若当前本人编排、确认已满足审核需求,无须先实施D。

代码落点: 新建models/reviews.py、schemas/reviews.py、services/reviews.py、api/routes/reviews.py及前端审核列表/详情;在后续新迁移中创建visual_review_requests和visual_review_decisions,不改ShotSelection的已有含义。

送审单至少包括owner_id、reviewer_id、run_id、frozen_spec_hash、冻结素材清单、state和version。决定追加记录actor_id/decision/comment/expected_version/created_at。状态为pending -> approved/rejected,作者可撤回pending单;重送或换成片创建新单并关联前单,不覆盖审计。

接口为POST /review-requests、GET /review-requests、GET /review-requests/{id}、POST /review-requests/{id}/decisions和POST /review-requests/{id}/withdraw。写命令延用CSRF、幂等和CAS;决定只允许指定且仍启用的审核人,作者不可冒充审核人或借此批准另一个Run。

通过GET /review-requests/{id}/assets/{asset_id}/content提供冻结包内素材的受限预览/Range读取,复用现有安全媒体响应。审核人不能使用这次授权查询作者的其他素材或修改故事;撤回/替换送审单后收回该包访问,素材引用仍按审计与历史运行规则保护。管理权限不自动授予审核权限。

  • [ ] 写两个普通账号与第三个无关账号的权限测试,并覆盖停用账号、替换asset ID、重复决定、版本冲突和撤回后的读取。
  • [ ] 实现冻结送审包、受限读取和追加决定,保留本人原有私有下载/预览。
  • [ ] 增加“待我审核 / 我发起的”列表,给出通过、驳回意见与版本;明确显示审批针对哪份冻结成片。
  • [ ] “终审通过”只应用于该成片版本。若未来增加正式发布通道,在该通道校验批准;不能将已有共享库任意素材一概标成终审成片。
  • [ ] 更新双人操作手册,验证全部产物引用、撤销授权和历史批准可追溯后再启用。

9. 实施顺序、验收与回退

先做A,让现有业务入口连贯;再做C,积累真实夜间数据。正式生产确定严格夜间时实施并启用B;若选用多人审批,再做D。每阶段独立验证、交付,A不依赖新业务表,C与D各用新增迁移。

验收至少包括:通用混合批次和故事候选均可定位;多空闲GPU按FIFO接任务;首帧未经确认不能生成对应视频;候选过期不能直接确认;视频未选齐不能冻结;历史Run不被后续编辑改写;窗口关闭不误杀在途;CPU后期仍能日间执行;产量不重复且私有数据不串号。

实施时执行相关后端pytest、前端Vitest/类型检查及迁移检查。真实模型质量和产能观察独立报告,不把模拟Provider的回归当作新增模型实测。临时验证目录自动清理,不长期保存验收媒体或代理报告。

回退采用关闭新增入口/开关、保留新增数据和历史运行的方式。涉及真正线上组件升级时,先暂停本项目新准入并排空本项目执行,验证数据库与媒体联合备份,再按兼容版本回退;不清空队列,不停止其他用户服务,也不删除真实业务数据。

版本:2026-11-13 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file diff --git a/frontend/public/help/production.md b/frontend/public/help/production.md new file mode 100644 index 0000000..49fbfdf --- /dev/null +++ b/frontend/public/help/production.md @@ -0,0 +1,147 @@ +# 六项能力与生产流程完善方案 + +状态:2026-11-12编写的待实施方案,保留当时的代码与风险分析。2026-11-13已移除独立工作流、批量和成片页面;下文涉及旧页面的落点是历史背景,后续若实施应接入故事或任务中心,不能按旧页面名寻找入口。现有功能的操作步骤以[操作手册](../操作手册_20261111.md)第0、4、7节为准;本文新增的接口、字段和页面尚未实施。当前开发全天运行的策略保持不变。 + +**Goal:** 保留现有六项基础能力及单人审核闭环,补齐故事批次导航和夜间产能依据;如正式生产要求所有模型任务仅夜间执行,提供统一策略扩展;多人审批另列可选阶段。 + +**Architecture:** 沿用Vue/Pinia、FastAPI/MySQL、单业务协调器和独立模型调度器。复用草稿、运行、任务、批次、候选、选择与执行记录,不另建任务引擎,不引入Redis/Celery。版本化增加合同和必要迁移,既有任务、素材及历史成片继续可用。 + +**Tech Stack:** Vue 3、TypeScript、Pinia、FastAPI、SQLAlchemy async、Alembic、MySQL、现有HTTP/SSE与FFmpeg。 + +**Spec:** 用户提出的“图像生成、视频生成、数学推演、缺陷样本生成、素材结构化、成片合成;夜间批量生成,日间编排审核,按夜间算力产出制定生产节拍”。开发环境暂不固定21:00–08:00。以下未获明确规定的统计口径和审批形式均为本方案建议,不视为用户已经选择。 + +## 1. 已实现的范围及依据 + +| 需求 | 当前实现 | 主要代码 | +| --- | --- | --- | +| 图像、视频、缺陷样本 | 提示词/参考图、参数校验、独立任务及结果归档 | `frontend/src/views/WorkbenchView.vue`;`backend/app/adapters/provider/contracts.py`、`gpu.py`;`inference/llm_services/adapters.py` | +| 数学推演 | 共享Qwen返回步骤与答案,输出文本及JSON,未做形式化验证 | `backend/app/adapters/provider/cpu.py`、`qwen.py` | +| 素材结构化 | 图片或均匀抽帧的视频理解,输出主体/场景/OCR/标签/JSON;ASR为单独任务 | `frontend/src/views/ToolsView.vue`;`backend/app/adapters/provider/qwen.py` | +| 成片合成 | 已有片段或故事选片的排序、裁剪、画幅、单音轨及人工字幕 | `frontend/src/views/StoryStudioView.vue`及`components/EditableProduction.vue`;`backend/app/adapters/provider/composition.py`;`backend/app/services/stories/api.py:render` | +| 批量生成 | 通用混合批次及故事候选计划,持久保存、幂等、暂停/继续/取消和有界补队 | `backend/app/services/batches.py`;`services/stories/candidates.py`;`services/orchestration/workflow_engine.py` | +| 编排审核 | 角色/场景基准、分镜顺序、候选比较、确认首帧/选片、确认失效和冻结合成 | `frontend/src/views/StoryStudioView.vue`;`components/studio/StoryCandidates.vue`;`backend/app/models/stories.py` | +| 时段控制 | API和worker读取策略;批量在21:00–次日08:00准入,已准入执行单元继续完成 | `backend/app/services/orchestration/resource_policy.py`;`inference/llm_services/scheduling.py` | + +当前运行接口的批量时段开关为关闭,六项基础能力已开放,故事能力已启用。能力“可用”说明接口和配置具备,不等于所有题材的生成质量、数学正确率或工业标注准确率都已验收。 + +“审核”已有可追溯的本人选择记录:`visual_shot_selections`追加保存操作者、版本、上下文和素材校验信息;普通草稿不能伪造批准。它没有另外一名审核人、驳回意见或成片终审单。 + +“本地部署”目前为本机网站和业务API、局域网服务器模型与MySQL,不依赖公有云模型;不表示模型也装在当前Windows开发机。六项能力产出可供教学课件和视频使用,但没有一键生成/导出PPTX教学课件。 + +## 2. 哪些是缺口,哪些是可选扩展 + +| 编号 | 结论 | 实施范围 | +| --- | --- | --- | +| A | 原批量页的历史衔接问题 | 旧批量总表曾将非`run`成员统一链接到Job详情;独立页面已移除。后续若在任务中心呈现候选批次,仍须正确定位原故事,不能把候选编号当Job编号 | +| B | 严格解读原文时的策略缺口 | 当前交互队列全天,不能仅打开现有开关就声称“所有生成仅夜间”;增加策略作用范围。若正式生产仍保留日间交互,可继续用现有策略 | +| C | 生产节拍的管理缺口 | 已有执行与选片记录,但没有逐夜产量、合格选片、积压和产能估算页面;增加有依据的统计 | +| D | 可选组织流程 | 若“审核”指编导送给其他人审批,再补多人送审和终审;它不是现有本人选片的别名,也不是六项基础能力必须先重建的前提 | + +优先采用“在现有架构上补A与C,B按正式生产策略启用,D按组织需要选做”。重建通用工作流平台会重复现有持久任务和人工关卡;当前数据规模也不需要先引入新的消息队列或集群调度。 + +## 3. 全局约束 + +- 只在本地修改和验证;本次不部署网站、不切换真实时段、不重启共享模型。 +- 四卡按就绪FIFO派发,每卡一个本项目任务;其他用户优先、内存预算、取消清理和幂等恢复保持原规则。 +- 21:00–次日08:00按Asia/Shanghai解释,边界为21:00包含、08:00不包含;窗口关闭不终止已准入执行单元。单个GPU runner内的生成与可选增强是一个单元,允许整条pipeline结束,不承诺在内部神经网络阶段之间跨夜暂停恢复。 +- 私有内容按账号隔离。新增统计、候选详情或审核授权不能把管理员变为所有用户私有内容的默认读者。 +- 历史迁移001–006保留;新增迁移顺序按实施时仓库最新版本确定,不覆盖后来新增的版本。 +- 已冻结运行不受草稿后改影响;新版本不能继承旧版本的审核结论;未知远端结果不能自动重新生成。 +- 不自动暂存、提交或推送。验证优先使用自动清理的隔离临时目录;通过后清理临时脚本、截图、媒体、数据库和打包文件,保留复用测试与最小夹具。 + +## 4. 重点验收风险 + +1. 候选尚未派发,没有Job编号,或者不在第一页时,批量成员仍应准确打开所属故事候选。 +2. 交互/批量两条入口、后台恢复和远端worker必须执行相同的夜间策略;任务JSON不能自行改成另一模式绕过严格窗口。 +3. 新故事的首帧审核是人工关卡。视频批量不能在缺少有效首帧时偷偷越过审核,重连和重试也不能自动选片。 +4. 重排、失败重试和多阶段处理不能重复计算产量;未选候选不能直接当作“未审核”,开发数据不能冒充稳定生产产能。 +5. 审核人只能读取被明确授权的冻结包;调换ID、旧版本提交、重复决定和修改草稿均不能扩大读取范围或复用旧批准。 + +## 5. A:补齐批次导航和操作入口 + +**代码落点:** `backend/app/services/snapshots.py`、`services/stories/api.py`、`api/routes/stories.py`;`frontend/src/types/workflows.ts`、`api/stories.ts`、`views/TasksView.vue`、`views/StoryStudioView.vue`(原批量页已移除)、`components/studio/StoryCandidates.vue`。 + +**合同:** 保留现有Batch字段,在候选成员追加可空`story_context`:`story_id`、`shot_id`、`candidate_kind`(frame/video)、`candidate_id`、`job_id`、`asset_id`。在同一账号范围内读取候选归属,不能信任客户端提交的上下文。非候选成员返回空上下文,旧客户端继续读取原字段。 + +新增`GET /stories/{story_id}/candidates/{candidate_id}`,返回已有CandidateDTO;同时校验故事、候选和当前账号的归属,已删除或跨账号返回404。该接口用于直接定位较早的候选,避免为了打开第25个以后的结果连续翻页扫全库。 + +- [ ] 先补回归:`run`仍打开运行详情,`job`仍打开任务详情,`candidate`打开故事;未派发、已失败、已删除、跨账号、候选超过第一页分别检查。 +- [ ] 实现快照上下文和候选详情接口,不迁移数据库,不改变任务派发。 +- [ ] 后续若在任务中心或故事运行历史展示批次,按`target_kind`分别跳转:候选使用`/studio/{story_id}?shot={shot_id}&stage={candidate_kind}&candidate={candidate_id}`。不支持的类型显示可解释状态,不能退化成错误Job链接。 +- [ ] 故事页校验查询参数、定位镜头和阶段并加载目标候选;这些参数只定位,不生成、不确认、不重试。 +- [ ] 在“03 成片”增加明确的合成执行方式选择,复用现有`executionMode`和`RenderCreate.execution_mode`,便于日间直接选择交互CPU合成。 +- [ ] 通过后同步手册,删掉当前“回原故事查看”的导航限制说明。 + +## 6. B:让正式生产支持严格夜间模型任务 + +**代码落点:** `backend/app/core/runtime_policy.py`、`domain/tasks.py`、`services/orchestration/resource_policy.py`、`admission_clock.py`、`coordinator.py`、`adapters/provider/runtime.py`;`inference/llm_services/scheduling.py`、`store.py`、`worker.py`、`remote_bridge.py`、`api.py`;前端能力类型、服务状态和批量策略提示。 + +**配置建议:** 支持运行策略schema v2,新增`model_window_scope`,只接受`batch_only`和`all_model_tasks`。继续接受v1,并解释为当前`batch_only`;`batch_window_enabled=false`时两个范围都全天可执行。当前开发配置不变,正式严格模式是v2加`true`和`all_model_tasks`。 + +在API与worker分别实现纯规则`window_applies(task_type: str, execution_mode: str, phase: str, policy: dict) -> bool`,用同一组合同测试向量检查结果。模型阶段覆盖图像、参考图、视频、缺陷、语音生成、Whisper及Qwen推演/理解;上传、Pillow首帧规范化、FFmpeg抽音/裁剪/拼接、浏览/确认等日间编辑和审核操作继续开放。对其他项目调用共享Qwen不施加本项目策略。 + +本方案明确选择“执行单元准入”的边界:GPU worker一次启动的runner(包含该视频的生成与Real-ESRGAN增强)整体为一个单元;业务API已有独立资源阶段的租约也分别为单元。07:59准入的视频可在08:00后继续生成、增强和清理,但不能再开始另一镜头/新的runner。一次已准入的Qwen素材理解阶段可完成本阶段的抽帧理解调用。当前不引入内部阶段检查点,不以重排来假装续跑,否则会重生成已经完成的视频。`all_model_tasks`范围只约束模型执行单元,关联批次的纯CPU后期也允许日间处理;v1/`batch_only`保持原有批量阶段限制。 + +- [ ] 补20:59:59、21:00、07:59:59、08:00边界及跨日、时钟回退、暂停、取消、服务恢复测试。分别覆盖两个模式、窗口范围和资源阶段。 +- [ ] 双端读取、远端运行状态传输及本地镜像都保留新增范围;不能只改一处JSON白名单。后台恢复与旧已排队任务也按当前生效策略重新判断新阶段准入。 +- [ ] 双端先支持并通告策略版本及范围,再允许管理员激活严格模式。版本不匹配或严格模式配置不可核实时关闭新模型准入并说明原因,不允许回退为日间交互执行;CPU后期保持可用。 +- [ ] 后端在申请新的Qwen/配音等模型执行租约之前校验,GPU worker在领取及实际spawn前再次校验,保持真正执行的二次保护。测试07:59启动的视频在08:00后完成增强、不重生成,而新的视频单元等到下一窗口;新的独立HTTP模型阶段也须重新判断。 +- [ ] 页面从服务端展示“开发全天 / 仅批量夜间 / 全部模型夜间”,并区别排队等待与故障。客户端任务体没有策略覆盖字段。 +- [ ] 隔离测试通过后提供管理员切换和回退步骤;实际启用属于后续正式生产操作,本次不改运行配置。 + +## 7. C:用实际夜间产出支持生产排期 + +**代码落点:** 新建`backend/app/services/production.py`、`models/production.py`、`api/routes/production.py`、`schemas/production.py`和`frontend/src/views/ProductionView.vue`;扩展`inference/llm_services/store.py`、`worker.py`、`api.py`、`backend/app/adapters/provider/gpu.py`和`services/orchestration/executions.py`。复用现有素材、选择校验及SSE,业务模型表实名为`visual_job_executions`。 + +**必要的上游历史:** 现有业务Execution开始/结束是本地观察时间,上游`jobs.started_at`是领取时间且重排会清空,`runner_start`只是进程身份值。它们都不能代表完整的真实执行历史。先在上游SQLite增加持久`job_attempts`表,按现有`execution_id=job_id:attempt_count`唯一保存`claimed_at`、`admitted_at`、`runner_started_at`、`finished_at`、`outcome`及`admission_policy_snapshot`。所有时间为上游UTC事实:准入时间与当次最后准入检查使用的快照一起持久化;runner开始只代表Popen成功,结束代表清理确认,不称GPU核函数运行时间。未启动延期、让卡、失败、取消、超时和未知结果均保留相应尝试,不能只保留最后一次。 + +在`claim_next/admission/set_runner/defer_unlaunched/requeue_preempted/finish`等生命周期写入历史,保持attempt/fence校验。新增受原鉴权保护的`GET /jobs/{job_id}/executions?after_attempt=0&limit=100`,并在能力接口声明`execution_history_version=1`。终态历史不可变并按attempt分页;未终态尝试单列为`current`、每次重取,避免分页游标漏掉运行到完成的变化。返回持久的`store_instance_id`、完整性及可用历史范围;旧版本无历史时明确标记unknown。 + +**业务镜像与本地阶段:** 新迁移增加`visual_upstream_attempts`,以`(store_instance_id, upstream_execution_id)`唯一镜像,关联本地Job与owner,并保留原始时间和策略。补录API离线期间的尝试只更新统计镜像,禁止用旧attempt调用当前Job的状态推进或替换fence。为`visual_job_executions`增加可空`admission_policy_snapshot`,记录本地Qwen/配音等执行租约的真实准入策略;既有`started_at/finished_at`继续作为本地观察字段,不改写其含义。历史空值为`policy_unknown`;Qwen HTTP耗时、runner存活/清理区间和网页观察耗时分别展示,不将任一项冒充精确GPU利用率。 + +**观测覆盖:** 在同一新增迁移中增加`visual_production_observations`,由现有协调器至多每分钟采一条`owner_id/observed_at/policy_snapshot/service_online/eligible_gpu_count/backlog_by_profile`。这是排期样本的覆盖证据,不是新调度器。首版建议有效夜次需要至少95%的分钟样本、连续缺口不超过2分钟、同规格至少90%的有效采样有待处理需求,且真实策略已知并启用窗口;阈值为方案建议,API中公开口径。空闲无需求、离线、开发全天、旧无历史等夜次仍展示事实,但不进入产能参考。没有覆盖证据不能把缺失夜次补成零或把少数繁忙夜当稳定产能。 + +**读取合同:** `GET /production/summary?night=YYYY-MM-DD&days=7`,仅当前账号,最多31夜。`night`代表当日21:00开始的一夜,返回时区、截止时间、指标、分组、覆盖缺口、有效样本夜数与估算依据;参数异常返回422。用受限SQL聚合执行和产物事实,再对涉及的故事有界复用`preview/selections/selection_dto/readiness`检查上下文、首帧依赖、素材及裁剪;不能仅凭非空`candidate_id`计合格。大量故事时分页返回确认统计和校验进度,未校验完的统计标为不完整,不能拿部分结果预测。沿用业务数据库,不增加独立统计数据库。 + +统计口径固定如下: + +- 产物按Job/候选唯一编号计算,执行尝试单独统计;让卡重排、增强阶段和重试不算新产物。 +- 按模型类型、profile、分辨率、源长度和主要生成参数分组,不把5秒视频与15秒视频混为相同产能。 +- 按最终成功尝试的真实准入夜次归属;08:00后完成的同一在途pipeline仍计入原夜次,单列延后完成时间。白天提交但夜间执行的任务不归到提交日白天;缺少上游时间或策略时显示归属未知。 +- 展示成功候选数量、源视频秒数、截至查询时当前确认的有效视频数量、无有效选片但已有可复核候选的镜头数、失败/取消/让卡尝试和等待时间。未选候选可能已被人工淘汰,不能全部标成待审。 +- “可用于成片秒数”依据有效选择的裁剪区间计算;生成的约15.04秒源片段不等于影片使用15.04秒。 +- 首版以最近最多7个同规格、策略已记录且窗口启用的有效夜次给出实际合格产出P25至中位数的参考区间;少于3夜显示“样本不足”。每夜人力确认速度、外部占卡和可用卡数会影响结果,不把区间写成承诺。 + +- [ ] 先写跨午夜、08:00延后完成、API离线跨夜重排、分页中的运行尝试完成、重试去重、无历史、不同规格、空数据和账号隔离测试。 +- [ ] 增加上游逐attempt持久事实和版本化历史读取,再做业务镜像、本地策略快照与分钟观测迁移;冻结迁移不导入会变化的当前模型。同步重取或历史缺失不能改变当前任务/fence,不能触发重生成。 +- [ ] 实现执行事实聚合及有界有效选择校验,明示统计截止、完整性、样本不足;只读汇总不修改任务、候选或审核状态。 +- [ ] 新增“生产概览”入口,展示夜间产出、需选片镜头和排期参考;链接到已有任务/故事,不另造创作表单。 +- [ ] 用隔离数据验证口径;真实产能观察在正常业务运行中累计,不为填报表额外提交GPU测试任务。 + +## 8. D:有多人审批需要时再增加正式送审 + +该阶段是扩展选项。若当前本人编排、确认已满足审核需求,无须先实施D。 + +**代码落点:** 新建`models/reviews.py`、`schemas/reviews.py`、`services/reviews.py`、`api/routes/reviews.py`及前端审核列表/详情;在后续新迁移中创建`visual_review_requests`和`visual_review_decisions`,不改`ShotSelection`的已有含义。 + +送审单至少包括`owner_id`、`reviewer_id`、`run_id`、`frozen_spec_hash`、冻结素材清单、`state`和`version`。决定追加记录`actor_id/decision/comment/expected_version/created_at`。状态为`pending -> approved/rejected`,作者可撤回pending单;重送或换成片创建新单并关联前单,不覆盖审计。 + +接口为`POST /review-requests`、`GET /review-requests`、`GET /review-requests/{id}`、`POST /review-requests/{id}/decisions`和`POST /review-requests/{id}/withdraw`。写命令延用CSRF、幂等和CAS;决定只允许指定且仍启用的审核人,作者不可冒充审核人或借此批准另一个Run。 + +通过`GET /review-requests/{id}/assets/{asset_id}/content`提供冻结包内素材的受限预览/Range读取,复用现有安全媒体响应。审核人不能使用这次授权查询作者的其他素材或修改故事;撤回/替换送审单后收回该包访问,素材引用仍按审计与历史运行规则保护。管理权限不自动授予审核权限。 + +- [ ] 写两个普通账号与第三个无关账号的权限测试,并覆盖停用账号、替换asset ID、重复决定、版本冲突和撤回后的读取。 +- [ ] 实现冻结送审包、受限读取和追加决定,保留本人原有私有下载/预览。 +- [ ] 增加“待我审核 / 我发起的”列表,给出通过、驳回意见与版本;明确显示审批针对哪份冻结成片。 +- [ ] “终审通过”只应用于该成片版本。若未来增加正式发布通道,在该通道校验批准;不能将已有共享库任意素材一概标成终审成片。 +- [ ] 更新双人操作手册,验证全部产物引用、撤销授权和历史批准可追溯后再启用。 + +## 9. 实施顺序、验收与回退 + +先做A,让现有业务入口连贯;再做C,积累真实夜间数据。正式生产确定严格夜间时实施并启用B;若选用多人审批,再做D。每阶段独立验证、交付,A不依赖新业务表,C与D各用新增迁移。 + +验收至少包括:通用混合批次和故事候选均可定位;多空闲GPU按FIFO接任务;首帧未经确认不能生成对应视频;候选过期不能直接确认;视频未选齐不能冻结;历史Run不被后续编辑改写;窗口关闭不误杀在途;CPU后期仍能日间执行;产量不重复且私有数据不串号。 + +实施时执行相关后端pytest、前端Vitest/类型检查及迁移检查。真实模型质量和产能观察独立报告,不把模拟Provider的回归当作新增模型实测。临时验证目录自动清理,不长期保存验收媒体或代理报告。 + +回退采用关闭新增入口/开关、保留新增数据和历史运行的方式。涉及真正线上组件升级时,先暂停本项目新准入并排空本项目执行,验证数据库与媒体联合备份,再按兼容版本回退;不清空队列,不停止其他用户服务,也不删除真实业务数据。 diff --git a/frontend/public/help/story.html b/frontend/public/help/story.html new file mode 100644 index 0000000..27165da --- /dev/null +++ b/frontend/public/help/story.html @@ -0,0 +1 @@ +锚定工作室操作手册 · CMVR Visual
CMVR Visual · 使用帮助

锚定故事工作室操作手册

适用版本:2026-11-13 的“故事”工作室。入口为登录后的侧栏“故事”,页面路径 /studio;单个故事在 /studio/故事编号 编辑。多镜头自动生成、人工选片和“03 成片”统一在故事内进行;独立“工作流”“批量”“成片”页面已移除,既有数据和共享后端API保留。旧链接会转至故事或任务。

希望一次生成初稿并在之后局部修改时,先保存故事,再点击“启用可编辑自动成片”;具体步骤见主操作手册第12节。希望逐镜人工确认时,按本手册第0节先做完一个 2 镜头、10 秒的小故事,再增加镜头。实际操作顺序是:新建并命名 → 建基准板 → 写分镜并保存 → 逐镜确认首帧 → 逐镜确认视频 → 调整时间线 → 保存并合成 → 下载成片。只有已有视频、只需剪辑时,才可直接从视频导入开始。

验证状态:本次已通过 1、2、3 张参考图真实生成、1280×704 的5秒和15秒视频及增强,以及网站“三图首帧→确认→视频→页面选片→冻结合成”的真实闭环。当前开发环境已开放参考生成,验收故事名为“锚定模型全链路验收(真实生成)”。按钮是否开放仍以当前环境返回的能力状态为准;通过样例不代表每种题材、身份一致性、复杂变形或长镜头质量都已验收。

0. 人工候选流程:两个镜头完成第一个故事

本节适用于人工候选流程;自动生成路径使用主手册第12节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;已有自动素材会作为待确认候选保留,由你逐步确认,故事和历史运行不变。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。

第 1 步:进入故事并命名

  1. 登录网站,在左侧点击“故事”。这里会列出你自己的故事;继续旧作品时,点击对应故事卡片即可。
  2. 点击右上角“新建故事”。进入后,默认显示“02 分镜”,左侧已有一个“新镜头”,不需要再加第一个镜头。
  3. 点击顶部名称输入框,把“未命名故事”改成“青衣旅人走向山门”,再点“保存故事”。

应看到:顶部显示新名称和“版本 … · 已保存”;模式栏显示“1 镜头 · 5.00s”。以后修改故事内容,顶部会变成“未保存”,生成和确认会暂时不可用。

第 2 步:先定横竖屏,再填共同设定

  1. 本例使用默认横屏。若你要竖屏,先切到“03 成片”,把“画幅”改成“竖屏 1080 × 1920”,点“保存故事”,再开始首帧。生成后改变画幅可能使相关候选过期。
  2. 点击“01 基准板”。填写“时代”为“古代东方”,“视觉风格”为“写实电影,自然材质,完整主体”,“色彩”为“青绿山色,红围巾点缀”,“全局光线”为“柔和晨光,薄雾”,“负向提示词”为“多余肢体,重复人物,文字,水印”。
  3. 在“角色与道具”旁点击“添加角色 / 道具”。名称填“青衣旅人”,类型选“人物”,描述填“成年旅人,体型修长,黑色长发,青色长袍,红色围巾;两个镜头保持同一外观”。
  4. 如果需要管理多种身体形态或衣服,可在这名角色下面点“添加形态”和“添加造型”。本例可添加“人形”和“青衣红围巾”,分别填写身体特征与服装特征。只有一种外观时,也可以只写角色描述,不必为了生成强行增加形态。
  5. 在“场景”旁点击“添加场景”。名称填“山门晨雾”,环境描述填“石阶通向古朴山门,远处青山,低处薄雾”;地点填“山间石阶”,时间填“清晨”,天气填“晴,薄雾”,光线填“柔和晨光”。

应看到:基准板里有一张“青衣旅人”角色卡和一张“山门晨雾”场景卡。后续镜头引用这两张卡,不用每个镜头重新建同名角色或场景。

第 3 步:有参考图就挂图,没有图也能继续

  1. 如果已有旅人参考图,在角色卡点“添加参考图片”。弹窗“选择你的素材”中,点“我的素材”里的一张图片;本机图片则点“上传素材”,选文件并等上传完成。场景参考图同样添加到“山门晨雾”场景卡。
  2. 使用“共享素材”时,选择后会导入你的私有副本。选择器只显示当前入口可使用的素材类型;参考图入口选图片,不能选视频。
  3. 本例最多先放“角色 1 张 + 场景 1 张”。如果角色、形态、造型和场景都放了图,要按本镜头实际引用的不同图片合计,当前参考生成通道最多 3 张,以页面实际能力为准。
  4. 没有参考图时,跳过上传,后面使用“文字生成(不读取参考图)”。如果有图但参考生成能力未开放,也可人工导入首帧;不要把“已在基准板挂图”误认为文字生成已经读取了图片。
  5. 点击顶部“保存故事”。

应看到:已选参考图显示在对应卡片上;顶部恢复“已保存”。给基准板挂图还不等于镜头已绑定角色,下一步仍需选择场景并“加入镜头”。

第 4 步:编辑第一个镜头,真正加入角色

  1. 点击“02 分镜”,选中左侧第一个镜头。在右侧“当前镜头”把名称改为“山门远景”,在“场景”下拉框选择“山门晨雾”。
  2. “画面描述”填:“远景,青衣旅人背对镜头站在石阶下方,红围巾清晰可见,山门位于画面上方,青山和薄雾形成纵深,人物完整入画。”
  3. 将光标放到这段文字最后,键入一个 @,点击弹出列表中的“青衣旅人”。也可以在下面“选择角色 / 道具”下拉框选“青衣旅人”,再点“加入镜头”。选中后,右侧会出现角色卡;@ 不需要保留在正文里。
  4. 如果第 2 步建了形态、造型,在角色卡里分别选择“人形”“青衣红围巾”;“位置关系”填“画面下方中央,石阶前”,“动作 / 姿态”填“背对镜头站立”。
  5. “运动描述”填:“旅人缓慢迈上一级石阶,围巾轻轻摆动,镜头缓慢向前推进,保持人物外观和山门结构。”
  6. 右侧保留“生成源长度(秒,1–15)”为 5、“源起始帧(24fps)”为 0、“选用帧数(24–360)”为 120。点“保存故事”。

应看到:左侧镜头名变为“山门远景”,时长仍为 5.00s;右侧有一张“青衣旅人”角色卡。如果只有正文里的“@青衣旅人”文字、没有角色卡,还没有完成绑定。

第 5 步:增加第二个镜头

  1. 点击左侧“镜头”标题旁的“+”。新镜头会被选中;这次新建不会自动复制前一个镜头的角色、场景或提示词。
  2. 名称改为“旅人近景”,“场景”仍选“山门晨雾”。从下拉框选同一个“青衣旅人”,点“加入镜头”,并选择相同形态、造型。
  3. “画面描述”填:“中近景,从侧后方看青衣旅人,黑色长发和红围巾清晰,前方山门虚化,柔和晨光,同一人物、同一服装。”
  4. “位置关系”填“画面右侧,石阶中段”,“动作 / 姿态”填“停步,面向山门”;“运动描述”填:“旅人停下后轻轻抬头,围巾轻微摆动,镜头缓慢侧移,不改变服装和人物比例。”
  5. 同样保留生成长度 5、源起始 0、选用 120。点“保存故事”。如果顺序不对,选中镜头后用“上移”“下移”调整,再保存。

应看到:左侧有“1 · 山门远景”和“2 · 旅人近景”;模式栏显示“2 镜头 · 10.00s”,底部“时间线”显示“240 帧 / 10.00 秒”。

第 6 步:生成第一镜头首帧并确认

  1. 点击左侧“山门远景”,中间点“1 首帧生成 / 导入 → 确认首帧”。有参考图时检查生成方式是“参考图生成”;没有图时选“文字生成(不读取参考图)”。
  2. 在“候选数”用 + / − 或直接输入 1。当前模型生成可填 1–4 个整数;初次先用 1。选“交互队列”,点一次“生成当前镜头”。
  3. 等候候选卡从“排队中”“生成中”变为“可复核”。暂未更新时点“刷新”,也可去侧栏“任务”查看队列原因;不要因等待而重复生成。
  4. 点击候选缩略图,在弹窗检查人物、红围巾、构图和山门。关闭弹窗后,在这张卡上点“确认首帧”。如果不满意,可调整设定、保存后再生成;有两张候选时,分别点“对比”查看并排缩略图,需要放大时点击对应缩略图。

应看到:首帧候选区域显示“已有确认”,所选卡按钮显示“已确认”,左侧该镜头显示“已有首帧”。点缩略图只打开预览弹窗,不会完成确认。

如果想直接用自己的图片,在这一步改点“导入图片并规范化首帧”,选择或上传图片,等规范化产物成为“可复核”后再“确认首帧”。每次人工导入只新增 1 个候选,不受上面的“候选数”影响。

第 7 步:为第二镜头也确认首帧

  1. 点击左侧“旅人近景”,保持在首帧阶段。检查它自己的角色和场景都已绑定。
  2. 按上一小节选择生成方式、候选数、队列并点“生成当前镜头”;或导入自己的近景首帧。
  3. 检查它是否与第一镜头保持同一旅人、衣服和环境,再点“确认首帧”。

应看到:两个镜头各有自己的首帧确认。第一镜头确认过,不会自动替第二镜头确认。熟悉后可以用“全故事候选计划”一次安排当前阶段的候选;计划不会帮你逐镜选图,也不会接着自动生成视频。

第 8 步:逐镜生成视频并确认选片

  1. 选中“山门远景”,点“2 视频生成 / 导入 → 确认选片”。确保右侧“运动描述”已填、顶部是“已保存”、生成长度 5 秒能覆盖 0 + 120 帧的选段。
  2. 初次保留“高级生成参数”默认值。按需设“候选数”为 1,点“生成当前镜头”。视频生成只用该镜头已确认首帧作为图像起点;不会把基准板所有图再次作为多图输入。
  3. 等视频候选变为“可复核”。点缩略图,在弹窗中点击播放,完整看一遍动作、稳定性和片尾;关闭弹窗会停止播放。若启用“使用增强片作为候选产物”,需要等增强产物完成并校验。
  4. 满意后点此视频卡的“确认选片”。再选“旅人近景”,重复生成、播放和“确认选片”。

应看到:两个镜头左侧都显示“已有选片”;视频候选卡显示“已确认”。视频已经生成、能播放或已下载,都不等于已经选入成片。

如果已有两条合适视频,可分别给两个镜头点“上传 / 导入视频候选”,选入后预览并“确认选片”。这条路径不需要先生成或确认首帧,仍要符合素材权限、24fps 和实际视频长度要求。

第 9 步:检查选段,按需加声音和字幕

  1. 本例两个镜头都保留“源起始帧”0、“选用帧数”120,按时间线顺序拼为 10 秒。若想从视频第 1 秒开始选 4 秒,填起始 24、选用 96,同时确认实际源片足够长。
  2. 不需要声音或字幕可以直接下一步。需要配音时,在底部“声音与字幕”点“添加音轨”,选一条已有音频。本例 10 秒音轨可填“音频源开始 ms”0、“音频源结束 ms”10000、“成片偏移帧”0;源音频本身必须至少 10 秒。音频更长就手动缩短选段,短音轨尾部会补静音。
  3. 点“添加字幕”,填开始 0、结束 120、文字“晨雾中,他来到山门前。”;再添加一条,开始 120、结束 240、文字“抬头望去,新的旅程即将开始。”这两个时间都是整部成片的帧数。
  4. 点“保存故事”。如果改了镜头顺序或长度,重新调整字幕和音轨;它们不会自动跟着镜头移动。

应看到:时间线总长仍为 240 帧 / 10 秒;字幕列出两个时间段;顶部为“已保存”。如果有“超出范围”提示,先改选段或音轨、字幕时间,提示未解决前不要继续合成。

第 10 步:冻结合成并下载

  1. 点击“03 成片”,顶部是“成片预览”。展开下方“查看镜头选片检查”,确认两个镜头逐项显示“选片已确认”。确认“画幅”为“横屏 1920 × 1080”;“适配”选“完整显示(留边)”可保留整个画面,选“填充画幅(裁边)”会裁去边缘以铺满画布。
  2. 如有修改,先点“保存故事”,再点“冻结素材并合成”。系统会再次检查实际素材与选段;弹出“素材已冻结,合成任务已提交”后,等候成片历史更新。这个按钮只合成已确认视频,不会替你补生成缺少的镜头。
  3. 点顶部“刷新成片”同步结果。合成成功后,最新成片以缩略图显示在顶部,无需先翻过镜头清单。点击缩略图或“播放成片”,在弹窗中检查镜头顺序、转接处、字幕和声音;可拖动播放器进度条、调整音量或全屏查看。
  4. 想单独查看时点“新窗口播放”;保存最终文件时点“下载成片”。要查看旧版本或运行进度,展开下方“合成历史”,其中仍可播放、下载历史视频及查看冻结设定。

应看到:顶部“成片预览”显示最新完成的视频缩略图,点击后弹窗播放;“合成历史”有本次记录、冻结版本和处理阶段,历史视频也通过缩略图打开。之后再改故事,不会改变这次成片;需要新版时,保存新修改并再次合成。候选区的“下载此素材”下载的是单个首帧或源视频,最终成片使用这里的“下载成片”。

1. 先选择创作路径

你已有的素材操作路径是否需要首帧确认
只有故事设定,希望模型生成视频建基准板 → 引用场景与角色 → 生成或导入首帧 → 确认首帧 → 生成视频 → 确认选片 → 合成需要,生成视频使用已批准的单张首帧
已有满意图片,希望让画面动起来导入图片并规范化首帧 → 确认首帧 → 生成视频 → 确认选片 → 合成需要;图片导入不等于已经确认
已有视频,只需要选段、拼接、加音轨与字幕直接导入视频候选 → 确认选片 → 调整裁剪 → 合成不需要;也不要求填写文生图提示词

上表是人工候选流程:工作室将“生成结果”和“本次决定使用的结果”分开,任务完成只会增加或更新候选,不会自动确认或合成。可编辑自动成片则按保存版本自动生成素材并合成,之后在故事中局部修改;它不等待上述逐镜人工确认。

2. 新建故事与界面位置

  1. 点击侧栏“故事”,再点“新建故事”。如果按钮不可用,查看页面的能力或连接说明。
  2. 在工作室顶部修改故事名称,点“保存故事”。顶部显示服务器版本和“已保存 / 未保存”。
  3. 按需要切换三个模式:
模式主要操作
01 基准板设置时代、风格、角色、形态、造型、场景及参考图
02 分镜自动路径编辑镜头与旁白;人工路径选镜头、看候选与对比、编辑当前镜头
03 成片统一查看音轨与字幕时间线、成片预览和历史;人工路径检查选片并冻结合成

“保存故事”保存你填写的设定与剪辑;“确认首帧”“确认选片”会直接把这次选择记录到服务器,成功后不必再为同一个确认重复保存。后续又修改设定、提示词或时间值时,仍需先保存。单纯切换预览、模式或当前镜头不会替你保存。

分镜和成片模式下,左栏“+”增加镜头;选中卡片后用“上移”“下移”重排,用“删除当前镜头”移除。至少保留一个镜头。镜头数量上限由当前环境配置,默认通常为 120;页面达到上限后不再允许添加。

镜头名称和展示序号不是身份:重排不会把另一镜头的角色、候选或确认结果移到当前镜头。下方时间线中的镜头块也可点击,用于选中镜头;裁剪通过右侧数值输入完成。

3. 建立故事基准板

故事共同设定

在“基准板”填写“时代”“视觉风格”“色彩”“全局光线”“负向提示词”。例如:

字段鲲鹏示例
时代上古神话世界
视觉风格史诗电影、写实 CG、自然材质、完整主体
色彩青黑与冷蓝为主,淡金色细节
全局光线晨光、柔和逆光、体积雾
负向提示词多余肢体、主体重复、文字水印、明显现代建筑

这些文字会和镜头实际引用的场景、角色设定一起组织为首帧输入。系统不会自动把一段长故事改编成全部分镜,也不会通过隐藏的语言模型改写替代你的决定。

场景

点“添加场景”,填写场景名称、环境描述,以及“地点”“时间”“天气”“光线”。再点“添加参考图片”,选择私有素材或上传图片。

同一场景可以供多个镜头使用。每个镜头右侧的“场景”下拉框决定该镜头引用哪个场景;仅在基准板添加场景、没有在镜头中选中,不会让它自动进入该镜头的输入。

角色、形态与造型

  1. 点“添加角色 / 道具”,选择“人物”“生物”或“道具”,填写名称和共同特征。
  2. 用“添加形态”区分同一实体的身体形态,例如鲲形、鹏形、人形、原形。
  3. 用“添加造型”区分服装、装备或外观状态,例如常服、战甲、雨湿羽毛。造型不等同于另一个角色。
  4. 在实体、形态、造型各自的“添加参考图片”中,放入对应范围的参考图。

对“鲲变鹏”,建议只建一个生物实体“鲲鹏”,共同描述金色眼睛、青黑主色和淡金云纹;在它下面建“鲲形”和“鹏形”。鱼鳍、鱼腹写入鲲形,羽翼、羽缘写入鹏形,避免把互相矛盾的身体特征都写进共同描述。

修改名称不会让已有引用变成另一个角色。删除角色会同时清除当前草稿中对它的镜头引用;删除某个形态或造型,也会清除对应的镜头选择。删除前先检查相关镜头,历史成片仍按自己的冻结设定保存。

4. 在镜头中使用角色与覆盖设定

@ 与“加入镜头”是两条等价入口

在“分镜”右侧:

  1. 在“画面描述”末尾键入 @,从出现的列表选择实体;或使用“选择角色 / 道具”下拉框,再点“加入镜头”。
  2. 角色会出现在该镜头的角色卡片中。当前界面通过这张卡片保存稳定引用,不要求你在文字里手写素材编号;仅输入“@鲲鹏”几个字不等于完成绑定。
  3. 在卡片里选择“形态”“造型”,再填写“位置关系”和“动作 / 姿态”。同一角色不会因重复点击而被重复加入。
  4. 不需要该实体时,点角色卡片上的“移除”。

每个镜头只组织自己已加入的实体及选定的形态、造型。没有加入镜头的角色、其他镜头的参考图,不会因它们同属一个故事而自动送入模型。

“画面描述”适合写构图、景别、主体关系和静态画面;“运动描述”单独写动作、摄像机运动和节奏,供视频生成使用。先把一张首帧说明白,再设计它如何运动。

镜头覆盖与继承

展开“镜头覆盖与继承”,可单独调整“时间”“天气”“光线”“色彩”:

项目没有镜头覆盖时的来源
时间、天气当前场景
光线场景光线;场景未填时继承故事全局光线
色彩故事共同色彩

在输入框修改后,会变成“镜头覆盖”。把覆盖内容删为空白,表示这个镜头显式清空该值;要重新继承,必须点“恢复继承”。例如同一北海场景中,一个镜头可以覆盖为暴风雨,后面的镜头再恢复场景默认天气。

5. 参考图的数量与真实用途

当前参考图生成通道最多接收 3 张不同图片,不是“场景 3 张、角色再 3 张”。本镜头选定场景、已加入实体、选定形态与造型的参考图会合并计算;同一图片承担多个角色时按首次出现顺序只传一次。若当前环境返回的上限更低,以实际能力状态为准。

建议先用“当前形态 1 张 + 场景 1 张”,确有必要时再加入第三张造型图。鲲形镜头不要同时挂入完整鹏形参考,除非你明确需要它们共同约束一张画面。

操作图片实际用途
首帧方式选“参考图生成”本镜头汇入的参考图片作为真实图像输入,和文字一起生成新的首帧候选
首帧方式选“文字生成(不读取参考图)”只使用文字;基准板图片仅供人工比对,没有传给文生图模型
点“导入图片并规范化首帧”上传或选中的图片经过尺寸适配,生成独立的首帧素材,供确认后的视频生成使用
使用已确认首帧生成视频视频模型使用这张批准后的首帧;不是再把全部场景、角色参考图作为多图输入
点“上传 / 导入视频候选”使用已有视频做候选和后续合成,不会因此运行参考图生成

本镜头有参考图时,默认采用“参考图生成”。如果能力不可用,系统不会静默改为文生图。你可以选择人工导入首帧;也可以主动改选“文字生成(不读取参考图)”,接受“参考图仅人工比对,未传模型”的含义。

判断一个已有候选实际用了什么,先点它的缩略图,关闭预览弹窗后展开“此候选的冻结输入与图片真实用途”。这里显示该次请求的实际参考图片数量、图片编号,以及可用的实际首帧、种子、模型配置、文字输入。下方“查看当前草稿编译预览(非历史候选输入)”表示现在的草稿,不可据此倒推旧候选当时用了哪些图。

参考图约束和稳定角色引用能帮助保持一致,但不保证模型在所有镜头中完美保留身份、比例、脸部、服装细节或形态转换。相同种子也不能代替参考图或人工复核。

6. 首帧候选:生成、导入与确认

先点“保存故事”,再在“分镜”中选择“1 首帧生成 / 导入 → 确认首帧”。

“候选数”怎么用

  1. “候选数”是数值输入框,默认 1。点两侧 + / −,或点击中间数字后直接输入 1、2、3、4。它不是下拉菜单,当前只接受 1–4 的整数;到 1 时不能继续减,到 4 时不能继续加。
  2. 这个数字表示下一次模型生成命令为每个镜头新建几个候选。例如当前镜头设 3 再点“生成当前镜头”,会新增 3 个首帧或视频候选;2 个镜头设 3 再点“全故事候选计划”,会安排 6 个候选。
  3. 只改数字不会启动生成,不会删除已成功的候选、撤销确认或把现有候选变成该数量。列表可保留多次生成的结果,因此总数可能超过 4。只想多比较已有作品时,直接点缩略图或“对比”,无需重新生成。
  4. 候选数、首帧生成方式和队列是本次提交选项;只改它们不需要保存故事。角色、提示词、种子、时长、裁剪等故事内容改动则需要先保存。即使生成按钮因为未保存或缺少首帧而不可用,仍可先调整候选数。
  5. 人工图片、视频每次导入只增加 1 个候选;“重试为新候选”也针对失败的那一个候选。把候选数改成 4,不会把一张上传图片自动复制成四个版本。

模型生成

  1. 选择“参考图生成”或“文字生成(不读取参考图)”。文生图仍需要有效画面描述;参考图生成还要满足图片权限、数量和能力要求。
  2. 按上面的方式将“候选数”设为 1–4。初次检查建议先生成 1 张。
  3. 选择“交互队列”或“批量队列”,点“生成当前镜头”。队列是否立即执行取决于空闲资源及当前时段策略。
  4. “全故事候选计划”会为故事中的所有镜头安排当前首帧或视频阶段的候选,已有满意结果的镜头也在内;它不自动跳过已完成镜头,不自动确认,也不接着进入下一阶段。未明确选用文字方式时,各镜头按自己的参考图决定默认模式;显式选用文字方式时,要确认你愿意让整批只用文字。只补一个不满意的镜头时,用“生成当前镜头”。

人工图片导入

  1. 点“导入图片并规范化首帧”。
  2. 在素材选择器中使用“我的素材”,或点“上传素材”;也可以从“共享素材”先导入自己的私有副本。
  3. 导入后可能先显示“排队中”,此时还没有可确认的规范化产物。等状态成为“可复核”,再检查画面。

规范化首帧按故事画幅使用横屏 1280 × 704 或竖屏 704 × 1280。最终成片画布另有 1920 × 1080 / 1080 × 1920 设置;“导入首帧”不是直接把原图当作未经处理的模型输入,也不是已经生成视频。

人工复核

  • 点缩略图,在弹窗中检查主体、形态、服装、空间和构图;页面只保留紧凑缩略图,横竖画幅均完整显示。
  • 对两个候选分别点“对比”,在“并排对比(最多两个)”中查看缩略图;点“移出对比”取消。点击任一对比缩略图可弹窗查看或播放,不提供同步双路播放。
  • 选择满意、未过期且状态为“可复核”的候选,点“确认首帧”。
  • “清除确认”撤销当前决定,不等同于删除候选或素材。
  • 失败候选可点“重试为新候选”;旧候选的输入不被这次重试改写。

7. 视频候选:模型生成或直接导入

使用已批准首帧生成

  1. 先确认当前镜头有效首帧,再切到“2 视频生成 / 导入 → 确认选片”。
  2. 在右侧填写“运动描述”。展开“高级生成参数”,按需调整视频种子、步数、引导系数,以及“使用增强片作为候选产物”。
  3. 设置“生成源长度(秒,1–15)”,默认 5 秒,只接受整数秒。
  4. 检查当前裁剪区间能放入将生成的源片:源起始帧 + 选用帧数 ≤ 生成秒数 × 24。不满足时只会阻止这次生成,不会自动截断你填写的裁剪值。
  5. 点“生成当前镜头”;需要批量时再使用“全故事候选计划”。等待候选“可复核”,检查运动、外观与实际时长,点“确认选片”。

选择增强产物时,候选还要等待对应的最终产物校验。候选预览会显示实际源时长和尺寸;不要把“任务处理完成”当成已经选定可合成的视频。

种子和高级参数的操作顺序

  1. 在右侧展开“高级生成参数”。“首帧种子”只影响下一次首帧生成,“视频种子”只影响下一次视频生成;两项默认均为 42,范围为 0–4294967295 的整数。
  2. 网页新建镜头的“视频步数”为 20、“引导系数”为 5,默认勾选“使用增强片作为候选产物”。步数可设 1–100,引导系数采用 1–20;首次使用可保留默认值。更多步数或增强通常需要更多处理时间,不保证每次更满意。
  3. 修改这些镜头参数后,点“保存故事”,再生成。候选数为 3、该类种子为 42 时,同次新建候选依次使用 42、43、44;每张候选可展开“此候选的冻结输入与图片真实用途”查看自己的实际种子。
  4. 下一次提交不会因为上一批生成过就自动随机换种子。想尝试新变化,可改种子并保存后再生成;仅想重新比较或确认旧结果时,不必修改种子或重生成。新增候选不会自动取代已确认的成功结果。
  5. 全故事视频计划要求各镜头已确认有效首帧,且每个镜头生成长度都能覆盖选用区间;当前镜头能生成,不代表其他镜头也已满足。先逐镜补齐,再提交全故事计划。

已有视频直接导入

  1. 切到“2 视频生成 / 导入 → 确认选片”,点“上传 / 导入视频候选”。
  2. 选择私有视频、上传视频,或从共享库导入私有副本。
  3. 人工视频不需要先确认首帧,也不要求填写文生图提示词。仍需满足素材权限、完整性、24fps 及实际解码帧数等检查。
  4. 检查实际画面及选段,点“确认选片”。每个镜头都要明确确认自己使用哪个候选。

当前草稿的编译预览可能仍显示缺少画面提示词的生成诊断。这不等同于人工视频不能合成;最终看已选视频与“冻结素材并合成”前的就绪检查。其他问题,例如不存在的参考素材、无权访问的素材,仍须解决。

8. 实际源长度、裁剪与长故事

三个数值含义不同:

字段含义与范围
生成源长度下一次模型生成视频的目标长度,1–15 秒;不代表已导入视频的长度
源起始帧从已选视频的哪一帧开始取,0 起计的非负整数;长视频允许从更靠后的位置取段
选用帧数当前镜头进入成片的长度,24–360 整数帧,即 1–15 秒

24fps 下,24 帧为 1 秒,240 帧为 10 秒。区间按 [源起始帧, 源起始帧 + 选用帧数) 计算。右侧会显示已选视频实际秒数和近似帧数;最终边界以服务端解码检查为准。

素材或操作参数示例结果
导入实际 15 秒视频,生成参数仍为默认 5 秒起始 0,选用 240 帧可取 10 秒,不必把生成参数改为 10 秒
导入实际 60 秒视频起始 1000,选用 240 帧取约第 41.67–51.67 秒,允许从长素材后段取片
实际源只有 3 秒起始 24,选用 120 帧超过真实范围;保留数值并提示,须手动修正
点击生成 5 秒视频起始 24,选用 120 帧将生成的 120 帧覆盖不了结束帧 144;应增加生成长度或修改选段

只改裁剪会改变合成选段,不会自动重生视频。实际视频仍要足够长;若改后的选段越界,就绪检查会阻止合成。旁白、字幕和音轨偏移也不会随镜头改动被悄悄截短或平移。

“长视频故事”通常指很多镜头合成后的总长,不等于模型一次生成一条长镜头:6 个 5 秒镜头共 30 秒;20 个 5 秒镜头共 100 秒。一个 60 秒已有视频也可以分别导入不同镜头,给每个镜头设置不同起点,每镜头最多选用 15 秒。上传格式、容量和总资源仍以当前环境限制为准。

9. 鲲鹏形态切换:六镜头操作实例

以下为手动搭建示例,不是点击后自动生成的模板,也不代表这六镜头已经完成真实视频验收。鲲鹏旧JSON仅作历史分镜参考,独立工作流入口已移除,不会自动变成故事基准板。

先建可复用设定

  • 实体“鲲鹏”:类型选“生物”;共同特征写“金色眼睛、青黑主色、淡金云纹,同一神话生命,身体特征由当前形态决定”。
  • 形态“鲲形”:青黑巨鱼、银白腹部、宽阔鱼鳍;放一张满意的鲲形参考。
  • 形态“鹏形”:青黑巨鹏、淡金羽缘、完整双翼;放一张满意的鹏形参考。
  • 造型“云纹本相”:淡金云纹贯穿身体,避免新加互相冲突的肢体描述;可先只填文字。
  • 场景“北海晨雾”:冷蓝海面、低云、淡金晨光,放一张北海参考;再建“高空云海”和“南方天光”。

每个镜头用 @ 或“加入镜头”引用同一个“鲲鹏”,再选择该镜头的形态,不要为每个镜头重新建立同名角色。通常“当前形态图 + 当前场景图”共两张,留意合计上限。

镜头名称场景 / 形态画面描述重点运动描述重点选用
北冥全景北海晨雾 / 鲲形巨鲲在海面下,完整鱼形,远景表现尺度海浪缓慢起伏,镜头平稳前推120 帧
金眼特写北海晨雾 / 鲲形金色眼睛、青黑鳞片和淡金云纹眼睛轻微转动,镜头缓慢侧移120 帧
大风水幕北海晨雾 / 鲲形鲲跃近水面,逆光与水幕遮挡身体只做一次缓慢抬升,水雾遮住画面120 帧
鹏出云层北海晨雾 / 鹏形水雾后露出完整鹏鸟,保留共同色彩和眼睛完整双翼缓慢展开,不要求暴露连续解剖变形120 帧
展翼上升高空云海 / 鹏形全身鸟形、淡金羽缘、云层作比例参照平稳上升,镜头侧向跟随120 帧
南迁远影南方天光 / 鹏形巨鹏面向南方,北海退到远处远景缓慢离开,留出收尾空间120 帧

第三镜头可在“镜头覆盖与继承”里把天气改为大风、光线改为逆光;第四镜头点“恢复继承”回到场景默认。保存后逐镜定首帧,用“对比”检查鲲形与鹏形是否保留相同的关键识别特征,再开始视频候选。

鲲变鹏是高难度形变。采用“水幕遮挡 → 切到完整鹏形”更容易人工控制;只有视频实际表现合格时,才选用暴露身体连续变形的版本。角色身份引用相同,不等于模型已经学会稳定的鱼鸟变形。

六镜头总长 720 帧、30 秒。要扩展到 100 秒,可进一步拆解北海、鲲形、遮挡、鹏形、南迁等镜头,并按实际旁白长度安排节奏。不要仅把所有镜头设为 15 秒,就认为复杂动作和画面连续性会自动改善。

10. 声音、字幕与冻结合成

  1. 在底部“声音与字幕”点“添加音轨”,选择一条已有配音或外部合成好的音频;已有音轨可点“更换音轨”或“移除音轨”。
  2. “音频源开始 ms / 音频源结束 ms”是音频内的毫秒位置;“成片偏移帧”是这段声音从整片哪一帧开始。短音轨尾部补静音;长音轨不会自动截断,需要缩短选段、增加成片长度或重新处理声音。
  3. 点“添加字幕”,填整片的“开始帧”“结束帧”和文字。字幕使用成片绝对帧:例如第 5–10 秒是 120–240,不是某个镜头内部的局部时间。当前没有自动旁白对齐功能。
  4. 更改镜头顺序、长度后,重新试听并检查音轨和字幕;系统保留原时间值,不自动平移。
  5. 切到“03 成片”,选择“横屏 1920 × 1080”或“竖屏 1080 × 1920”,以及“完整显示(留边)”或“填充画幅(裁边)”。这会影响画面适配;修改后保存并留意相关候选是否需要重新复核。
  6. 每个镜头都确认有效选片后,点“保存故事”,再点“冻结素材并合成”。服务端会复核实际素材、裁剪区间、音轨和字幕;有问题时按提示修正,不会静默截断。

本次合成冻结当前选片及版本、素材校验信息、镜头顺序、裁剪、画幅、音轨和字幕。它只合成已选视频,不会在后台自动补生成缺失镜头。之后再改草稿、换片或清除确认,不会改变历史运行的冻结输入。

进入“03 成片”后,顶部“成片预览”显示最新完成的视频缩略图。点缩略图或“播放成片”打开弹窗播放,也可用“新窗口播放”单独查看,或点“下载成片”保存文件。新任务仍在合成时,可以先预览上一次已完成的视频;点“刷新成片”同步最新结果。展开“合成历史”可点击旧版本缩略图播放、查看进度和下载入口,再展开“查看此次冻结设定”查看该次设定。运行中按可用按钮“暂停”“继续”“取消”控制本次运行;取消不能视为可随时恢复的暂停。

11. 失效、重新复核与删除

改动应怎样检查
改故事风格、场景、实体、当前形态、造型或相关参考图相关视觉候选可能“设定已变化”;重新生成或显式重新导入复核
改运动描述或换批准首帧检查视频选择是否过期;首帧本身不因只改运动而必然失效
改生成长度模型生成的视频受其输入变化影响;人工导入视频的真实长度不由这个参数决定
只改裁剪、镜头顺序、字幕保留已有视频;重新检查实际范围及成片时间,不会自动重生素材
换种子生成更多候选不会把其他已有候选自动选中;查看每个候选自己的冻结输入

过期候选仍可预览和下载,但不能直接点确认。确实要沿用旧画面时,下载后用“导入图片并规范化首帧”或“上传 / 导入视频候选”重新作为人工素材复核;这表示你主动认可它在当前设定下的用途,不是修改旧候选历史。

候选卡片上的“删除”用于移除候选记录;当前确认中的候选,先点“清除确认”再操作。正在执行的候选需要先到“任务”取消,并等待终态及执行清理确认,不能用删除按钮强行打断未知的远端执行。

故事列表中的“删除故事”会要求确认,并由服务端处理候选、运行等关联记录。独立素材仍由素材库管理;删除候选或故事不等于立即物理删除所有图片、视频。当前选择、候选和冻结运行的引用分别保护素材;素材库提示仍被引用时,应按实际关联记录处理,不要绕过保护去删服务器文件。

私有故事与素材按账号隔离。共享素材选择后会先导入本账号的私有副本;发布者撤回共享不会改写已经导入的副本,也不会自动向别人复制你的故事。

12. 保存、断线恢复与移动端

“保存故事”保存到服务器。“未保存”内容仍在当前编辑页面,切换三个模式或当前镜头会保留,但不是已上传的备份。返回故事列表、切到其他页面、换故事、退出登录或关闭页面时会提示未保存内容;不要依赖浏览器强制关闭后自动恢复。生成、确认和冻结合成前先保存。

如果提示“服务器已有新版本”或版本冲突,当前输入会保留供处理。先把尚未保存的重要文字、时间值等复制留存,再返回故事列表,按提示决定是否放弃本地修改,重新打开服务器版本并合并;不要反复点击保存覆盖他处更新。故事当前不提供旧工作流JSON的直接导入、导出;旧独立页面已移除,历史JSON和API合同仍保留。

HTTP/SSE 断线、关闭网页或切换页面不会取消已经保存提交的任务,也不会停止共享模型。恢复连接后会重取故事及已加载候选的快照,补齐候选状态和离线期间删除的记录;不会因为重连自动再生成一次,也不会替你做确认。需要人工同步时用分镜“刷新”或成片“刷新历史”。

如果提交时断网、结果未知,先恢复连接并查看原候选、任务与当前确认状态。系统保留原提交意图用于幂等恢复;重复点击或重新创建一批任务不是确认执行结果的方法。

等待、时段和额度怎么看

  1. 在网页右上角打开“创作服务状态”,刷新查看服务连接、运行策略和资源状态;再到“任务”查看具体任务的排队原因。页面上的“刷新”是同步结果,不是重新发起生成。
  2. “交互队列”全天可提交并等待空闲资源;“批量队列”按当前环境的时段策略启动。启用批量时段限制时,新阶段仅在北京时间 21:00–次日 08:00 启动;开发环境关闭限制时可全天等待执行。以状态面板当前生效的策略为准。
  3. “全故事候选计划”描述的是覆盖哪些镜头,“交互队列 / 批量队列”描述的是执行方式,两者独立。提交全故事计划前仍要检查当前队列选项。
  4. 排队不等于失败。空闲 GPU、系统资源和其他用户优先规则决定实际开始时间;浏览器开着不会占到更多 GPU。已开始任务在服务器执行,关闭浏览器、离开故事页、HTTP/SSE 断线都不会取消它。需要停止任务时,使用“任务”或对应运行里的明确取消入口,并等执行清理完成。
  5. 当前默认没有“累计只能生成 8 个视频”的限制。创建频率、未完成任务、故事候选计划、活动运行和素材空间仍分别受额度约束。默认创建频率为每分钟 6 次,已有其他创作提交也会共用这项额度;遇到 429 或额度提示,先看具体原因,等任务完成或按提示清理后再试。
  6. 候选数越多,新安排的候选和资源消耗越多;不代表能同时运行相同数量的 GPU。已有成功结果仍可预览和下载,未过期且满足确认条件的可继续确认;不要为了验证候选数控件是否可点,额外发起一批真实生成。

“02 分镜”的自动编辑面板、镜头列表、候选或属性区内容超出时,只在对应容器内滚动;故事标题和步骤导航保持可见。鼠标移入显示滚动条,移出隐藏,键盘聚焦时也可显示;触屏直接在容器内滑动。窄屏会重排镜头卡和对比区域,底部内容仍通过容器内滚动到达。声音、字幕和唯一时间线请切到“03 成片”查看;时间线较长时在该区域横向滚动。手机和电脑使用相同的版本校验、保存和人工流程确认规则;移动端不是离线剪辑模式。

13. 常见提示

提示或现象处理
“新建故事”或生成按钮不可用先看故事能力、连接说明;等读取完成。编辑中先保存;生成过程中等本次提交结束,具体限制看页面提示
“保存故事”不可用检查名称是否为空、页面是否还在读取,以及字幕、音轨、裁剪等是否触发校验错误;修正提示后再保存
想选“候选数”,找不到下拉选项这是数值框,用 + / − 或直接输入 1–4;只调整数量不触发生成,也不要求先确认首帧
候选数改成 3,已有作品仍只有 1 个正常;数量只作用于下一次模型生成,不补齐、不重生、不复制旧结果。人工导入每次始终是 1 个
“参考图生成”不可选查看当前能力原因;即使模型 PoC 已通过,未开放或上游离线的环境仍会禁用。可人工导入,或明确选择文字方式
参考图数量超限检查本镜头场景、实体、当前形态、造型汇入的不同图片总数,减少到当前上限内
首帧导入后看不到图片、暂不能确认等待规范化任务完成并成为“可复核”;查看候选错误和任务状态
点缩略图后仍提示没有确认缩略图只打开预览弹窗;关闭后在对应卡片点“确认首帧”或“确认选片”,并检查是否显示“已确认”
“确认首帧 / 确认选片”不可用先保存;候选须有可用素材、状态为“可复核”且没有“设定已变化”。过期候选按第 11 节重新导入或生成
生成视频按钮不可用先保存,确认有效首帧,再检查“生成源长度”能否覆盖选用区间;人工视频导入仍走独立路径
当前镜头可生成,“全故事候选计划”不可用检查其他镜头的生成长度、选段和首帧确认;一个镜头满足条件不能代表全部镜头
“冻结素材并合成”不可用或提交被拒绝先保存,检查每个镜头都有有效选片,再根据就绪提示修正真实长度、音轨和字幕;缺少视频不会被自动补生成
编译预览提示缺少画面文字,但已有人工视频这是生成诊断;人工视频无需文生图提示词,继续检查有效选片和合成就绪状态
“选用区间超过已选视频实际范围”根据实际视频时长调整起始帧或选用帧数;仅修改生成长度不能把已有视频变长
修改镜头后字幕、旁白越界它们使用整片时间且原值会保留,手动调整或增加成片长度
旧候选变灰或显示设定变化查看它的冻结输入;重新生成,或明确导入为人工素材再复核
删除被拒绝查看是否仍在执行、等待执行清理、或素材仍被候选/选择/历史运行引用;先处理对应记录
一直排队或提示等待窗口看“创作服务状态”的批量策略和“任务”的等待原因;切换页面或反复生成不会消除资源、时段和额度限制
任务完成后没有最终成片下载先逐镜“确认选片”,再去故事内“03 成片”冻结合成;成功后在顶部“成片预览”点“下载成片”,旧版本在“合成历史”中

相关入口说明见主操作手册;旧工作流的长故事与旁白示例见鲲鹏长视频制作指南。后者的旧模板、独立模型实测结果不能替代新版锚定工作室链路的验收结论。

14. 本工作室对应的“编排审核”和“批量生成”

需求中的日间“编排审核”,在这里对应“01 基准板”的共同设定、“02 分镜”的顺序与裁剪、候选比较,以及明确点击“确认首帧 / 确认选片”。确认会记录操作者和版本;当前操作人是故事所属账号,没有指定另一个审核账号、送审单或成片终审按钮。

故事的批量入口是“02 分镜”中的“全故事候选计划”。先选当前首帧或视频阶段、候选数和“批量队列”,再提交;它一次只安排当前阶段,不自动确认或进入下一阶段。候选仍回原故事查看和审核。启用可编辑自动成片后,在自动工具条选择“批量队列”再提交素材或成片生成。独立“批量”页面已移除;两条故事路径仍沿用原批量执行策略。

需要逐镜审核的新故事,正式排期通常为:第1天编排,第1夜生成首帧,第2天确认首帧,第2夜生成视频,第3天选片与合成。已有有效首帧时,可直接从视频批量开始。当前开发全天模式允许在同一天依次完成上述步骤,但人工确认关卡保持不变。

日间完成视频选片后,若要立即进行CPU合成,先在“02 分镜”将执行模式改为“交互队列”,再进“03 成片”冻结合成;成片提交沿用该选择。若仍为“批量队列”,正式时段限制开启时会等夜间窗口。仅切换队列不会发起生成或确认。

主手册第0节列出六项能力的实际入口和边界,第4节说明人工审核步骤,第7节说明故事自动成片的批量模式、人工候选计划、历史API兼容及日夜节拍。严格夜间执行、夜间产能统计和可选多人审批的待实施设计见生产流程完善方案。

版本:2026-11-13 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file diff --git a/frontend/public/help/story.md b/frontend/public/help/story.md new file mode 100644 index 0000000..d9ef653 --- /dev/null +++ b/frontend/public/help/story.md @@ -0,0 +1,422 @@ +# 锚定故事工作室操作手册 + +适用版本:2026-11-13 的“故事”工作室。入口为登录后的侧栏“故事”,页面路径 `/studio`;单个故事在 `/studio/故事编号` 编辑。多镜头自动生成、人工选片和“03 成片”统一在故事内进行;独立“工作流”“批量”“成片”页面已移除,既有数据和共享后端API保留。旧链接会转至故事或任务。 + +希望一次生成初稿并在之后局部修改时,先保存故事,再点击“启用可编辑自动成片”;具体步骤见[主操作手册](操作手册_20261111.md)第12节。希望逐镜人工确认时,按本手册第0节先做完一个 **2 镜头、10 秒**的小故事,再增加镜头。实际操作顺序是:**新建并命名 → 建基准板 → 写分镜并保存 → 逐镜确认首帧 → 逐镜确认视频 → 调整时间线 → 保存并合成 → 下载成片**。只有已有视频、只需剪辑时,才可直接从视频导入开始。 + +**验证状态:**本次已通过 **1、2、3 张参考图真实生成**、**1280×704 的5秒和15秒视频及增强**,以及网站“三图首帧→确认→视频→页面选片→冻结合成”的真实闭环。当前开发环境已开放参考生成,验收故事名为“锚定模型全链路验收(真实生成)”。按钮是否开放仍以当前环境返回的能力状态为准;通过样例不代表每种题材、身份一致性、复杂变形或长镜头质量都已验收。 + +## 0. 人工候选流程:两个镜头完成第一个故事 + +本节适用于人工候选流程;自动生成路径使用主手册第12节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;已有自动素材会作为待确认候选保留,由你逐步确认,故事和历史运行不变。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。 + +### 第 1 步:进入故事并命名 + +1. 登录网站,在左侧点击“故事”。这里会列出你自己的故事;继续旧作品时,点击对应故事卡片即可。 +2. 点击右上角“新建故事”。进入后,默认显示“02 分镜”,左侧已有一个“新镜头”,不需要再加第一个镜头。 +3. 点击顶部名称输入框,把“未命名故事”改成“青衣旅人走向山门”,再点“保存故事”。 + +**应看到:**顶部显示新名称和“版本 … · 已保存”;模式栏显示“1 镜头 · 5.00s”。以后修改故事内容,顶部会变成“未保存”,生成和确认会暂时不可用。 + +### 第 2 步:先定横竖屏,再填共同设定 + +1. 本例使用默认横屏。若你要竖屏,先切到“03 成片”,把“画幅”改成“竖屏 1080 × 1920”,点“保存故事”,再开始首帧。生成后改变画幅可能使相关候选过期。 +2. 点击“01 基准板”。填写“时代”为“古代东方”,“视觉风格”为“写实电影,自然材质,完整主体”,“色彩”为“青绿山色,红围巾点缀”,“全局光线”为“柔和晨光,薄雾”,“负向提示词”为“多余肢体,重复人物,文字,水印”。 +3. 在“角色与道具”旁点击“添加角色 / 道具”。名称填“青衣旅人”,类型选“人物”,描述填“成年旅人,体型修长,黑色长发,青色长袍,红色围巾;两个镜头保持同一外观”。 +4. 如果需要管理多种身体形态或衣服,可在这名角色下面点“添加形态”和“添加造型”。本例可添加“人形”和“青衣红围巾”,分别填写身体特征与服装特征。只有一种外观时,也可以只写角色描述,不必为了生成强行增加形态。 +5. 在“场景”旁点击“添加场景”。名称填“山门晨雾”,环境描述填“石阶通向古朴山门,远处青山,低处薄雾”;地点填“山间石阶”,时间填“清晨”,天气填“晴,薄雾”,光线填“柔和晨光”。 + +**应看到:**基准板里有一张“青衣旅人”角色卡和一张“山门晨雾”场景卡。后续镜头引用这两张卡,不用每个镜头重新建同名角色或场景。 + +### 第 3 步:有参考图就挂图,没有图也能继续 + +1. 如果已有旅人参考图,在角色卡点“添加参考图片”。弹窗“选择你的素材”中,点“我的素材”里的一张图片;本机图片则点“上传素材”,选文件并等上传完成。场景参考图同样添加到“山门晨雾”场景卡。 +2. 使用“共享素材”时,选择后会导入你的私有副本。选择器只显示当前入口可使用的素材类型;参考图入口选图片,不能选视频。 +3. 本例最多先放“角色 1 张 + 场景 1 张”。如果角色、形态、造型和场景都放了图,要按本镜头实际引用的不同图片合计,当前参考生成通道最多 3 张,以页面实际能力为准。 +4. 没有参考图时,跳过上传,后面使用“文字生成(不读取参考图)”。如果有图但参考生成能力未开放,也可人工导入首帧;不要把“已在基准板挂图”误认为文字生成已经读取了图片。 +5. 点击顶部“保存故事”。 + +**应看到:**已选参考图显示在对应卡片上;顶部恢复“已保存”。给基准板挂图还不等于镜头已绑定角色,下一步仍需选择场景并“加入镜头”。 + +### 第 4 步:编辑第一个镜头,真正加入角色 + +1. 点击“02 分镜”,选中左侧第一个镜头。在右侧“当前镜头”把名称改为“山门远景”,在“场景”下拉框选择“山门晨雾”。 +2. “画面描述”填:“远景,青衣旅人背对镜头站在石阶下方,红围巾清晰可见,山门位于画面上方,青山和薄雾形成纵深,人物完整入画。” +3. 将光标放到这段文字**最后**,键入一个 `@`,点击弹出列表中的“青衣旅人”。也可以在下面“选择角色 / 道具”下拉框选“青衣旅人”,再点“加入镜头”。选中后,右侧会出现角色卡;`@` 不需要保留在正文里。 +4. 如果第 2 步建了形态、造型,在角色卡里分别选择“人形”“青衣红围巾”;“位置关系”填“画面下方中央,石阶前”,“动作 / 姿态”填“背对镜头站立”。 +5. “运动描述”填:“旅人缓慢迈上一级石阶,围巾轻轻摆动,镜头缓慢向前推进,保持人物外观和山门结构。” +6. 右侧保留“生成源长度(秒,1–15)”为 `5`、“源起始帧(24fps)”为 `0`、“选用帧数(24–360)”为 `120`。点“保存故事”。 + +**应看到:**左侧镜头名变为“山门远景”,时长仍为 5.00s;右侧有一张“青衣旅人”角色卡。如果只有正文里的“@青衣旅人”文字、没有角色卡,还没有完成绑定。 + +### 第 5 步:增加第二个镜头 + +1. 点击左侧“镜头”标题旁的“+”。新镜头会被选中;这次新建不会自动复制前一个镜头的角色、场景或提示词。 +2. 名称改为“旅人近景”,“场景”仍选“山门晨雾”。从下拉框选同一个“青衣旅人”,点“加入镜头”,并选择相同形态、造型。 +3. “画面描述”填:“中近景,从侧后方看青衣旅人,黑色长发和红围巾清晰,前方山门虚化,柔和晨光,同一人物、同一服装。” +4. “位置关系”填“画面右侧,石阶中段”,“动作 / 姿态”填“停步,面向山门”;“运动描述”填:“旅人停下后轻轻抬头,围巾轻微摆动,镜头缓慢侧移,不改变服装和人物比例。” +5. 同样保留生成长度 `5`、源起始 `0`、选用 `120`。点“保存故事”。如果顺序不对,选中镜头后用“上移”“下移”调整,再保存。 + +**应看到:**左侧有“1 · 山门远景”和“2 · 旅人近景”;模式栏显示“2 镜头 · 10.00s”,底部“时间线”显示“240 帧 / 10.00 秒”。 + +### 第 6 步:生成第一镜头首帧并确认 + +1. 点击左侧“山门远景”,中间点“1 首帧生成 / 导入 → 确认首帧”。有参考图时检查生成方式是“参考图生成”;没有图时选“文字生成(不读取参考图)”。 +2. 在“候选数”用 `+ / −` 或直接输入 `1`。当前模型生成可填 `1–4` 个整数;初次先用 `1`。选“交互队列”,点一次“生成当前镜头”。 +3. 等候候选卡从“排队中”“生成中”变为“可复核”。暂未更新时点“刷新”,也可去侧栏“任务”查看队列原因;不要因等待而重复生成。 +4. 点击候选**缩略图**,在弹窗检查人物、红围巾、构图和山门。关闭弹窗后,在这张卡上点“确认首帧”。如果不满意,可调整设定、保存后再生成;有两张候选时,分别点“对比”查看并排缩略图,需要放大时点击对应缩略图。 + +**应看到:**首帧候选区域显示“已有确认”,所选卡按钮显示“已确认”,左侧该镜头显示“已有首帧”。点缩略图只打开预览弹窗,不会完成确认。 + +如果想直接用自己的图片,在这一步改点“导入图片并规范化首帧”,选择或上传图片,等规范化产物成为“可复核”后再“确认首帧”。每次人工导入只新增 1 个候选,不受上面的“候选数”影响。 + +### 第 7 步:为第二镜头也确认首帧 + +1. 点击左侧“旅人近景”,保持在首帧阶段。检查它自己的角色和场景都已绑定。 +2. 按上一小节选择生成方式、候选数、队列并点“生成当前镜头”;或导入自己的近景首帧。 +3. 检查它是否与第一镜头保持同一旅人、衣服和环境,再点“确认首帧”。 + +**应看到:**两个镜头各有自己的首帧确认。第一镜头确认过,不会自动替第二镜头确认。熟悉后可以用“全故事候选计划”一次安排当前阶段的候选;计划不会帮你逐镜选图,也不会接着自动生成视频。 + +### 第 8 步:逐镜生成视频并确认选片 + +1. 选中“山门远景”,点“2 视频生成 / 导入 → 确认选片”。确保右侧“运动描述”已填、顶部是“已保存”、生成长度 `5` 秒能覆盖 `0 + 120` 帧的选段。 +2. 初次保留“高级生成参数”默认值。按需设“候选数”为 `1`,点“生成当前镜头”。视频生成只用该镜头**已确认首帧**作为图像起点;不会把基准板所有图再次作为多图输入。 +3. 等视频候选变为“可复核”。点缩略图,在弹窗中点击播放,完整看一遍动作、稳定性和片尾;关闭弹窗会停止播放。若启用“使用增强片作为候选产物”,需要等增强产物完成并校验。 +4. 满意后点此视频卡的“确认选片”。再选“旅人近景”,重复生成、播放和“确认选片”。 + +**应看到:**两个镜头左侧都显示“已有选片”;视频候选卡显示“已确认”。视频已经生成、能播放或已下载,都不等于已经选入成片。 + +如果已有两条合适视频,可分别给两个镜头点“上传 / 导入视频候选”,选入后预览并“确认选片”。这条路径不需要先生成或确认首帧,仍要符合素材权限、24fps 和实际视频长度要求。 + +### 第 9 步:检查选段,按需加声音和字幕 + +1. 本例两个镜头都保留“源起始帧”`0`、“选用帧数”`120`,按时间线顺序拼为 10 秒。若想从视频第 1 秒开始选 4 秒,填起始 `24`、选用 `96`,同时确认实际源片足够长。 +2. 不需要声音或字幕可以直接下一步。需要配音时,在底部“声音与字幕”点“添加音轨”,选一条已有音频。本例 10 秒音轨可填“音频源开始 ms”`0`、“音频源结束 ms”`10000`、“成片偏移帧”`0`;源音频本身必须至少 10 秒。音频更长就手动缩短选段,短音轨尾部会补静音。 +3. 点“添加字幕”,填开始 `0`、结束 `120`、文字“晨雾中,他来到山门前。”;再添加一条,开始 `120`、结束 `240`、文字“抬头望去,新的旅程即将开始。”这两个时间都是**整部成片**的帧数。 +4. 点“保存故事”。如果改了镜头顺序或长度,重新调整字幕和音轨;它们不会自动跟着镜头移动。 + +**应看到:**时间线总长仍为 240 帧 / 10 秒;字幕列出两个时间段;顶部为“已保存”。如果有“超出范围”提示,先改选段或音轨、字幕时间,提示未解决前不要继续合成。 + +### 第 10 步:冻结合成并下载 + +1. 点击“03 成片”,顶部是“成片预览”。展开下方“查看镜头选片检查”,确认两个镜头逐项显示“选片已确认”。确认“画幅”为“横屏 1920 × 1080”;“适配”选“完整显示(留边)”可保留整个画面,选“填充画幅(裁边)”会裁去边缘以铺满画布。 +2. 如有修改,先点“保存故事”,再点“冻结素材并合成”。系统会再次检查实际素材与选段;弹出“素材已冻结,合成任务已提交”后,等候成片历史更新。这个按钮只合成已确认视频,不会替你补生成缺少的镜头。 +3. 点顶部“刷新成片”同步结果。合成成功后,最新成片以缩略图显示在顶部,无需先翻过镜头清单。点击缩略图或“播放成片”,在弹窗中检查镜头顺序、转接处、字幕和声音;可拖动播放器进度条、调整音量或全屏查看。 +4. 想单独查看时点“新窗口播放”;保存最终文件时点“下载成片”。要查看旧版本或运行进度,展开下方“合成历史”,其中仍可播放、下载历史视频及查看冻结设定。 + +**应看到:**顶部“成片预览”显示最新完成的视频缩略图,点击后弹窗播放;“合成历史”有本次记录、冻结版本和处理阶段,历史视频也通过缩略图打开。之后再改故事,不会改变这次成片;需要新版时,保存新修改并再次合成。候选区的“下载此素材”下载的是单个首帧或源视频,最终成片使用这里的“下载成片”。 + +## 1. 先选择创作路径 + +| 你已有的素材 | 操作路径 | 是否需要首帧确认 | +| ---------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------- | +| 只有故事设定,希望模型生成视频 | 建基准板 → 引用场景与角色 → 生成或导入首帧 → 确认首帧 → 生成视频 → 确认选片 → 合成 | 需要,生成视频使用已批准的单张首帧 | +| 已有满意图片,希望让画面动起来 | 导入图片并规范化首帧 → 确认首帧 → 生成视频 → 确认选片 → 合成 | 需要;图片导入不等于已经确认 | +| 已有视频,只需要选段、拼接、加音轨与字幕 | 直接导入视频候选 → 确认选片 → 调整裁剪 → 合成 | 不需要;也不要求填写文生图提示词 | + +上表是人工候选流程:工作室将“生成结果”和“本次决定使用的结果”分开,任务完成只会增加或更新候选,不会自动确认或合成。可编辑自动成片则按保存版本自动生成素材并合成,之后在故事中局部修改;它不等待上述逐镜人工确认。 + +## 2. 新建故事与界面位置 + +1. 点击侧栏“故事”,再点“新建故事”。如果按钮不可用,查看页面的能力或连接说明。 +2. 在工作室顶部修改故事名称,点“保存故事”。顶部显示服务器版本和“已保存 / 未保存”。 +3. 按需要切换三个模式: + +| 模式 | 主要操作 | +| ----------- | ------------------------------------------------ | +| `01 基准板` | 设置时代、风格、角色、形态、造型、场景及参考图 | +| `02 分镜` | 自动路径编辑镜头与旁白;人工路径选镜头、看候选与对比、编辑当前镜头 | +| `03 成片` | 统一查看音轨与字幕时间线、成片预览和历史;人工路径检查选片并冻结合成 | + +“保存故事”保存你填写的设定与剪辑;“确认首帧”“确认选片”会直接把这次选择记录到服务器,成功后不必再为同一个确认重复保存。后续又修改设定、提示词或时间值时,仍需先保存。单纯切换预览、模式或当前镜头不会替你保存。 + +分镜和成片模式下,左栏“+”增加镜头;选中卡片后用“上移”“下移”重排,用“删除当前镜头”移除。至少保留一个镜头。镜头数量上限由当前环境配置,默认通常为 120;页面达到上限后不再允许添加。 + +镜头名称和展示序号不是身份:重排不会把另一镜头的角色、候选或确认结果移到当前镜头。下方时间线中的镜头块也可点击,用于选中镜头;裁剪通过右侧数值输入完成。 + +## 3. 建立故事基准板 + +### 故事共同设定 + +在“基准板”填写“时代”“视觉风格”“色彩”“全局光线”“负向提示词”。例如: + +| 字段 | 鲲鹏示例 | +| ---------- | ------------------------------------------ | +| 时代 | 上古神话世界 | +| 视觉风格 | 史诗电影、写实 CG、自然材质、完整主体 | +| 色彩 | 青黑与冷蓝为主,淡金色细节 | +| 全局光线 | 晨光、柔和逆光、体积雾 | +| 负向提示词 | 多余肢体、主体重复、文字水印、明显现代建筑 | + +这些文字会和镜头实际引用的场景、角色设定一起组织为首帧输入。系统不会自动把一段长故事改编成全部分镜,也不会通过隐藏的语言模型改写替代你的决定。 + +### 场景 + +点“添加场景”,填写场景名称、环境描述,以及“地点”“时间”“天气”“光线”。再点“添加参考图片”,选择私有素材或上传图片。 + +同一场景可以供多个镜头使用。每个镜头右侧的“场景”下拉框决定该镜头引用哪个场景;仅在基准板添加场景、没有在镜头中选中,不会让它自动进入该镜头的输入。 + +### 角色、形态与造型 + +1. 点“添加角色 / 道具”,选择“人物”“生物”或“道具”,填写名称和共同特征。 +2. 用“添加形态”区分同一实体的身体形态,例如鲲形、鹏形、人形、原形。 +3. 用“添加造型”区分服装、装备或外观状态,例如常服、战甲、雨湿羽毛。造型不等同于另一个角色。 +4. 在实体、形态、造型各自的“添加参考图片”中,放入对应范围的参考图。 + +对“鲲变鹏”,建议只建一个生物实体“鲲鹏”,共同描述金色眼睛、青黑主色和淡金云纹;在它下面建“鲲形”和“鹏形”。鱼鳍、鱼腹写入鲲形,羽翼、羽缘写入鹏形,避免把互相矛盾的身体特征都写进共同描述。 + +修改名称不会让已有引用变成另一个角色。删除角色会同时清除当前草稿中对它的镜头引用;删除某个形态或造型,也会清除对应的镜头选择。删除前先检查相关镜头,历史成片仍按自己的冻结设定保存。 + +## 4. 在镜头中使用角色与覆盖设定 + +### `@` 与“加入镜头”是两条等价入口 + +在“分镜”右侧: + +1. 在“画面描述”末尾键入 `@`,从出现的列表选择实体;或使用“选择角色 / 道具”下拉框,再点“加入镜头”。 +2. 角色会出现在该镜头的角色卡片中。当前界面通过这张卡片保存稳定引用,不要求你在文字里手写素材编号;仅输入“@鲲鹏”几个字不等于完成绑定。 +3. 在卡片里选择“形态”“造型”,再填写“位置关系”和“动作 / 姿态”。同一角色不会因重复点击而被重复加入。 +4. 不需要该实体时,点角色卡片上的“移除”。 + +每个镜头只组织自己已加入的实体及选定的形态、造型。没有加入镜头的角色、其他镜头的参考图,不会因它们同属一个故事而自动送入模型。 + +“画面描述”适合写构图、景别、主体关系和静态画面;“运动描述”单独写动作、摄像机运动和节奏,供视频生成使用。先把一张首帧说明白,再设计它如何运动。 + +### 镜头覆盖与继承 + +展开“镜头覆盖与继承”,可单独调整“时间”“天气”“光线”“色彩”: + +| 项目 | 没有镜头覆盖时的来源 | +| ---------- | ------------------------------------ | +| 时间、天气 | 当前场景 | +| 光线 | 场景光线;场景未填时继承故事全局光线 | +| 色彩 | 故事共同色彩 | + +在输入框修改后,会变成“镜头覆盖”。**把覆盖内容删为空白,表示这个镜头显式清空该值;要重新继承,必须点“恢复继承”。**例如同一北海场景中,一个镜头可以覆盖为暴风雨,后面的镜头再恢复场景默认天气。 + +## 5. 参考图的数量与真实用途 + +当前参考图生成通道最多接收 **3 张不同图片**,不是“场景 3 张、角色再 3 张”。本镜头选定场景、已加入实体、选定形态与造型的参考图会合并计算;同一图片承担多个角色时按首次出现顺序只传一次。若当前环境返回的上限更低,以实际能力状态为准。 + +建议先用“当前形态 1 张 + 场景 1 张”,确有必要时再加入第三张造型图。鲲形镜头不要同时挂入完整鹏形参考,除非你明确需要它们共同约束一张画面。 + +| 操作 | 图片实际用途 | +| ------------------------------------ | ------------------------------------------------------------------------ | +| 首帧方式选“参考图生成” | 本镜头汇入的参考图片作为真实图像输入,和文字一起生成新的首帧候选 | +| 首帧方式选“文字生成(不读取参考图)” | 只使用文字;基准板图片仅供人工比对,没有传给文生图模型 | +| 点“导入图片并规范化首帧” | 上传或选中的图片经过尺寸适配,生成独立的首帧素材,供确认后的视频生成使用 | +| 使用已确认首帧生成视频 | 视频模型使用这张批准后的首帧;不是再把全部场景、角色参考图作为多图输入 | +| 点“上传 / 导入视频候选” | 使用已有视频做候选和后续合成,不会因此运行参考图生成 | + +本镜头有参考图时,默认采用“参考图生成”。如果能力不可用,系统不会静默改为文生图。你可以选择人工导入首帧;也可以**主动**改选“文字生成(不读取参考图)”,接受“参考图仅人工比对,未传模型”的含义。 + +判断一个已有候选实际用了什么,先点它的缩略图,关闭预览弹窗后展开“此候选的冻结输入与图片真实用途”。这里显示该次请求的实际参考图片数量、图片编号,以及可用的实际首帧、种子、模型配置、文字输入。下方“查看当前草稿编译预览(非历史候选输入)”表示现在的草稿,不可据此倒推旧候选当时用了哪些图。 + +参考图约束和稳定角色引用能帮助保持一致,但**不保证模型在所有镜头中完美保留身份、比例、脸部、服装细节或形态转换**。相同种子也不能代替参考图或人工复核。 + +## 6. 首帧候选:生成、导入与确认 + +先点“保存故事”,再在“分镜”中选择“1 首帧生成 / 导入 → 确认首帧”。 + +### “候选数”怎么用 + +1. “候选数”是数值输入框,默认 `1`。点两侧 `+ / −`,或点击中间数字后直接输入 `1`、`2`、`3`、`4`。它不是下拉菜单,当前只接受 1–4 的整数;到 1 时不能继续减,到 4 时不能继续加。 +2. 这个数字表示**下一次模型生成命令为每个镜头新建几个候选**。例如当前镜头设 `3` 再点“生成当前镜头”,会新增 3 个首帧或视频候选;2 个镜头设 `3` 再点“全故事候选计划”,会安排 6 个候选。 +3. 只改数字不会启动生成,不会删除已成功的候选、撤销确认或把现有候选变成该数量。列表可保留多次生成的结果,因此总数可能超过 4。只想多比较已有作品时,直接点缩略图或“对比”,无需重新生成。 +4. 候选数、首帧生成方式和队列是本次提交选项;只改它们不需要保存故事。角色、提示词、种子、时长、裁剪等故事内容改动则需要先保存。即使生成按钮因为未保存或缺少首帧而不可用,仍可先调整候选数。 +5. 人工图片、视频每次导入只增加 **1 个**候选;“重试为新候选”也针对失败的那一个候选。把候选数改成 `4`,不会把一张上传图片自动复制成四个版本。 + +### 模型生成 + +1. 选择“参考图生成”或“文字生成(不读取参考图)”。文生图仍需要有效画面描述;参考图生成还要满足图片权限、数量和能力要求。 +2. 按上面的方式将“候选数”设为 1–4。初次检查建议先生成 1 张。 +3. 选择“交互队列”或“批量队列”,点“生成当前镜头”。队列是否立即执行取决于空闲资源及当前时段策略。 +4. “全故事候选计划”会为故事中的所有镜头安排**当前首帧或视频阶段**的候选,已有满意结果的镜头也在内;它不自动跳过已完成镜头,不自动确认,也不接着进入下一阶段。未明确选用文字方式时,各镜头按自己的参考图决定默认模式;显式选用文字方式时,要确认你愿意让整批只用文字。只补一个不满意的镜头时,用“生成当前镜头”。 + +### 人工图片导入 + +1. 点“导入图片并规范化首帧”。 +2. 在素材选择器中使用“我的素材”,或点“上传素材”;也可以从“共享素材”先导入自己的私有副本。 +3. 导入后可能先显示“排队中”,此时还没有可确认的规范化产物。等状态成为“可复核”,再检查画面。 + +规范化首帧按故事画幅使用横屏 1280 × 704 或竖屏 704 × 1280。最终成片画布另有 1920 × 1080 / 1080 × 1920 设置;“导入首帧”不是直接把原图当作未经处理的模型输入,也不是已经生成视频。 + +### 人工复核 + +- 点缩略图,在弹窗中检查主体、形态、服装、空间和构图;页面只保留紧凑缩略图,横竖画幅均完整显示。 +- 对两个候选分别点“对比”,在“并排对比(最多两个)”中查看缩略图;点“移出对比”取消。点击任一对比缩略图可弹窗查看或播放,不提供同步双路播放。 +- 选择满意、未过期且状态为“可复核”的候选,点“确认首帧”。 +- “清除确认”撤销当前决定,不等同于删除候选或素材。 +- 失败候选可点“重试为新候选”;旧候选的输入不被这次重试改写。 + +## 7. 视频候选:模型生成或直接导入 + +### 使用已批准首帧生成 + +1. 先确认当前镜头有效首帧,再切到“2 视频生成 / 导入 → 确认选片”。 +2. 在右侧填写“运动描述”。展开“高级生成参数”,按需调整视频种子、步数、引导系数,以及“使用增强片作为候选产物”。 +3. 设置“生成源长度(秒,1–15)”,默认 5 秒,只接受整数秒。 +4. 检查当前裁剪区间能放入将生成的源片:`源起始帧 + 选用帧数 ≤ 生成秒数 × 24`。不满足时只会阻止这次生成,不会自动截断你填写的裁剪值。 +5. 点“生成当前镜头”;需要批量时再使用“全故事候选计划”。等待候选“可复核”,检查运动、外观与实际时长,点“确认选片”。 + +选择增强产物时,候选还要等待对应的最终产物校验。候选预览会显示实际源时长和尺寸;不要把“任务处理完成”当成已经选定可合成的视频。 + +### 种子和高级参数的操作顺序 + +1. 在右侧展开“高级生成参数”。“首帧种子”只影响下一次首帧生成,“视频种子”只影响下一次视频生成;两项默认均为 `42`,范围为 `0–4294967295` 的整数。 +2. 网页新建镜头的“视频步数”为 `20`、“引导系数”为 `5`,默认勾选“使用增强片作为候选产物”。步数可设 1–100,引导系数采用 1–20;首次使用可保留默认值。更多步数或增强通常需要更多处理时间,不保证每次更满意。 +3. 修改这些镜头参数后,点“保存故事”,再生成。候选数为 3、该类种子为 42 时,同次新建候选依次使用 42、43、44;每张候选可展开“此候选的冻结输入与图片真实用途”查看自己的实际种子。 +4. 下一次提交不会因为上一批生成过就自动随机换种子。想尝试新变化,可改种子并保存后再生成;仅想重新比较或确认旧结果时,不必修改种子或重生成。新增候选不会自动取代已确认的成功结果。 +5. 全故事视频计划要求各镜头已确认有效首帧,且每个镜头生成长度都能覆盖选用区间;当前镜头能生成,不代表其他镜头也已满足。先逐镜补齐,再提交全故事计划。 + +### 已有视频直接导入 + +1. 切到“2 视频生成 / 导入 → 确认选片”,点“上传 / 导入视频候选”。 +2. 选择私有视频、上传视频,或从共享库导入私有副本。 +3. 人工视频不需要先确认首帧,也不要求填写文生图提示词。仍需满足素材权限、完整性、24fps 及实际解码帧数等检查。 +4. 检查实际画面及选段,点“确认选片”。每个镜头都要明确确认自己使用哪个候选。 + +当前草稿的编译预览可能仍显示缺少画面提示词的生成诊断。这不等同于人工视频不能合成;最终看已选视频与“冻结素材并合成”前的就绪检查。其他问题,例如不存在的参考素材、无权访问的素材,仍须解决。 + +## 8. 实际源长度、裁剪与长故事 + +三个数值含义不同: + +| 字段 | 含义与范围 | +| ---------- | ------------------------------------------------------------------------ | +| 生成源长度 | 下一次模型生成视频的目标长度,1–15 秒;不代表已导入视频的长度 | +| 源起始帧 | 从已选视频的哪一帧开始取,0 起计的非负整数;长视频允许从更靠后的位置取段 | +| 选用帧数 | 当前镜头进入成片的长度,24–360 整数帧,即 1–15 秒 | + +24fps 下,24 帧为 1 秒,240 帧为 10 秒。区间按 `[源起始帧, 源起始帧 + 选用帧数)` 计算。右侧会显示已选视频实际秒数和近似帧数;最终边界以服务端解码检查为准。 + +| 素材或操作 | 参数示例 | 结果 | +| ----------------------------------------- | ---------------------- | ----------------------------------------------------------- | +| 导入实际 15 秒视频,生成参数仍为默认 5 秒 | 起始 0,选用 240 帧 | 可取 10 秒,不必把生成参数改为 10 秒 | +| 导入实际 60 秒视频 | 起始 1000,选用 240 帧 | 取约第 41.67–51.67 秒,允许从长素材后段取片 | +| 实际源只有 3 秒 | 起始 24,选用 120 帧 | 超过真实范围;保留数值并提示,须手动修正 | +| 点击生成 5 秒视频 | 起始 24,选用 120 帧 | 将生成的 120 帧覆盖不了结束帧 144;应增加生成长度或修改选段 | + +**只改裁剪会改变合成选段,不会自动重生视频。**实际视频仍要足够长;若改后的选段越界,就绪检查会阻止合成。旁白、字幕和音轨偏移也不会随镜头改动被悄悄截短或平移。 + +“长视频故事”通常指很多镜头合成后的总长,不等于模型一次生成一条长镜头:6 个 5 秒镜头共 30 秒;20 个 5 秒镜头共 100 秒。一个 60 秒已有视频也可以分别导入不同镜头,给每个镜头设置不同起点,每镜头最多选用 15 秒。上传格式、容量和总资源仍以当前环境限制为准。 + +## 9. 鲲鹏形态切换:六镜头操作实例 + +以下为**手动搭建示例**,不是点击后自动生成的模板,也不代表这六镜头已经完成真实视频验收。鲲鹏旧JSON仅作历史分镜参考,独立工作流入口已移除,不会自动变成故事基准板。 + +### 先建可复用设定 + +- 实体“鲲鹏”:类型选“生物”;共同特征写“金色眼睛、青黑主色、淡金云纹,同一神话生命,身体特征由当前形态决定”。 +- 形态“鲲形”:青黑巨鱼、银白腹部、宽阔鱼鳍;放一张满意的鲲形参考。 +- 形态“鹏形”:青黑巨鹏、淡金羽缘、完整双翼;放一张满意的鹏形参考。 +- 造型“云纹本相”:淡金云纹贯穿身体,避免新加互相冲突的肢体描述;可先只填文字。 +- 场景“北海晨雾”:冷蓝海面、低云、淡金晨光,放一张北海参考;再建“高空云海”和“南方天光”。 + +每个镜头用 `@` 或“加入镜头”引用同一个“鲲鹏”,再选择该镜头的形态,不要为每个镜头重新建立同名角色。通常“当前形态图 + 当前场景图”共两张,留意合计上限。 + +| 镜头名称 | 场景 / 形态 | 画面描述重点 | 运动描述重点 | 选用 | +| -------- | --------------- | -------------------------------------- | ---------------------------------------- | ------ | +| 北冥全景 | 北海晨雾 / 鲲形 | 巨鲲在海面下,完整鱼形,远景表现尺度 | 海浪缓慢起伏,镜头平稳前推 | 120 帧 | +| 金眼特写 | 北海晨雾 / 鲲形 | 金色眼睛、青黑鳞片和淡金云纹 | 眼睛轻微转动,镜头缓慢侧移 | 120 帧 | +| 大风水幕 | 北海晨雾 / 鲲形 | 鲲跃近水面,逆光与水幕遮挡身体 | 只做一次缓慢抬升,水雾遮住画面 | 120 帧 | +| 鹏出云层 | 北海晨雾 / 鹏形 | 水雾后露出完整鹏鸟,保留共同色彩和眼睛 | 完整双翼缓慢展开,不要求暴露连续解剖变形 | 120 帧 | +| 展翼上升 | 高空云海 / 鹏形 | 全身鸟形、淡金羽缘、云层作比例参照 | 平稳上升,镜头侧向跟随 | 120 帧 | +| 南迁远影 | 南方天光 / 鹏形 | 巨鹏面向南方,北海退到远处 | 远景缓慢离开,留出收尾空间 | 120 帧 | + +第三镜头可在“镜头覆盖与继承”里把天气改为大风、光线改为逆光;第四镜头点“恢复继承”回到场景默认。保存后逐镜定首帧,用“对比”检查鲲形与鹏形是否保留相同的关键识别特征,再开始视频候选。 + +鲲变鹏是高难度形变。采用“水幕遮挡 → 切到完整鹏形”更容易人工控制;只有视频实际表现合格时,才选用暴露身体连续变形的版本。角色身份引用相同,不等于模型已经学会稳定的鱼鸟变形。 + +六镜头总长 720 帧、30 秒。要扩展到 100 秒,可进一步拆解北海、鲲形、遮挡、鹏形、南迁等镜头,并按实际旁白长度安排节奏。不要仅把所有镜头设为 15 秒,就认为复杂动作和画面连续性会自动改善。 + +## 10. 声音、字幕与冻结合成 + +1. 在底部“声音与字幕”点“添加音轨”,选择一条已有配音或外部合成好的音频;已有音轨可点“更换音轨”或“移除音轨”。 +2. “音频源开始 ms / 音频源结束 ms”是音频内的毫秒位置;“成片偏移帧”是这段声音从整片哪一帧开始。短音轨尾部补静音;长音轨不会自动截断,需要缩短选段、增加成片长度或重新处理声音。 +3. 点“添加字幕”,填整片的“开始帧”“结束帧”和文字。字幕使用成片绝对帧:例如第 5–10 秒是 120–240,不是某个镜头内部的局部时间。当前没有自动旁白对齐功能。 +4. 更改镜头顺序、长度后,重新试听并检查音轨和字幕;系统保留原时间值,不自动平移。 +5. 切到“03 成片”,选择“横屏 1920 × 1080”或“竖屏 1080 × 1920”,以及“完整显示(留边)”或“填充画幅(裁边)”。这会影响画面适配;修改后保存并留意相关候选是否需要重新复核。 +6. 每个镜头都确认有效选片后,点“保存故事”,再点“冻结素材并合成”。服务端会复核实际素材、裁剪区间、音轨和字幕;有问题时按提示修正,不会静默截断。 + +本次合成冻结当前选片及版本、素材校验信息、镜头顺序、裁剪、画幅、音轨和字幕。它只合成已选视频,不会在后台自动补生成缺失镜头。之后再改草稿、换片或清除确认,不会改变历史运行的冻结输入。 + +进入“03 成片”后,顶部“成片预览”显示最新完成的视频缩略图。点缩略图或“播放成片”打开弹窗播放,也可用“新窗口播放”单独查看,或点“下载成片”保存文件。新任务仍在合成时,可以先预览上一次已完成的视频;点“刷新成片”同步最新结果。展开“合成历史”可点击旧版本缩略图播放、查看进度和下载入口,再展开“查看此次冻结设定”查看该次设定。运行中按可用按钮“暂停”“继续”“取消”控制本次运行;取消不能视为可随时恢复的暂停。 + +## 11. 失效、重新复核与删除 + +| 改动 | 应怎样检查 | +| -------------------------------------------------- | ---------------------------------------------------------------------- | +| 改故事风格、场景、实体、当前形态、造型或相关参考图 | 相关视觉候选可能“设定已变化”;重新生成或显式重新导入复核 | +| 改运动描述或换批准首帧 | 检查视频选择是否过期;首帧本身不因只改运动而必然失效 | +| 改生成长度 | 模型生成的视频受其输入变化影响;人工导入视频的真实长度不由这个参数决定 | +| 只改裁剪、镜头顺序、字幕 | 保留已有视频;重新检查实际范围及成片时间,不会自动重生素材 | +| 换种子生成更多候选 | 不会把其他已有候选自动选中;查看每个候选自己的冻结输入 | + +过期候选仍可预览和下载,但不能直接点确认。确实要沿用旧画面时,下载后用“导入图片并规范化首帧”或“上传 / 导入视频候选”重新作为人工素材复核;这表示你主动认可它在当前设定下的用途,不是修改旧候选历史。 + +候选卡片上的“删除”用于移除候选记录;当前确认中的候选,先点“清除确认”再操作。正在执行的候选需要先到“任务”取消,并等待终态及执行清理确认,不能用删除按钮强行打断未知的远端执行。 + +故事列表中的“删除故事”会要求确认,并由服务端处理候选、运行等关联记录。独立素材仍由素材库管理;删除候选或故事不等于立即物理删除所有图片、视频。当前选择、候选和冻结运行的引用分别保护素材;素材库提示仍被引用时,应按实际关联记录处理,不要绕过保护去删服务器文件。 + +私有故事与素材按账号隔离。共享素材选择后会先导入本账号的私有副本;发布者撤回共享不会改写已经导入的副本,也不会自动向别人复制你的故事。 + +## 12. 保存、断线恢复与移动端 + +“保存故事”保存到服务器。“未保存”内容仍在当前编辑页面,切换三个模式或当前镜头会保留,但不是已上传的备份。返回故事列表、切到其他页面、换故事、退出登录或关闭页面时会提示未保存内容;不要依赖浏览器强制关闭后自动恢复。生成、确认和冻结合成前先保存。 + +如果提示“服务器已有新版本”或版本冲突,当前输入会保留供处理。先把尚未保存的重要文字、时间值等复制留存,再返回故事列表,按提示决定是否放弃本地修改,重新打开服务器版本并合并;不要反复点击保存覆盖他处更新。故事当前不提供旧工作流JSON的直接导入、导出;旧独立页面已移除,历史JSON和API合同仍保留。 + +HTTP/SSE 断线、关闭网页或切换页面不会取消已经保存提交的任务,也不会停止共享模型。恢复连接后会重取故事及已加载候选的快照,补齐候选状态和离线期间删除的记录;不会因为重连自动再生成一次,也不会替你做确认。需要人工同步时用分镜“刷新”或成片“刷新历史”。 + +如果提交时断网、结果未知,先恢复连接并查看原候选、任务与当前确认状态。系统保留原提交意图用于幂等恢复;重复点击或重新创建一批任务不是确认执行结果的方法。 + +### 等待、时段和额度怎么看 + +1. 在网页右上角打开“创作服务状态”,刷新查看服务连接、运行策略和资源状态;再到“任务”查看具体任务的排队原因。页面上的“刷新”是同步结果,不是重新发起生成。 +2. “交互队列”全天可提交并等待空闲资源;“批量队列”按当前环境的时段策略启动。启用批量时段限制时,新阶段仅在北京时间 **21:00–次日 08:00** 启动;开发环境关闭限制时可全天等待执行。以状态面板当前生效的策略为准。 +3. “全故事候选计划”描述的是覆盖哪些镜头,“交互队列 / 批量队列”描述的是执行方式,两者独立。提交全故事计划前仍要检查当前队列选项。 +4. 排队不等于失败。空闲 GPU、系统资源和其他用户优先规则决定实际开始时间;浏览器开着不会占到更多 GPU。已开始任务在服务器执行,关闭浏览器、离开故事页、HTTP/SSE 断线都不会取消它。需要停止任务时,使用“任务”或对应运行里的明确取消入口,并等执行清理完成。 +5. 当前默认没有“累计只能生成 8 个视频”的限制。创建频率、未完成任务、故事候选计划、活动运行和素材空间仍分别受额度约束。默认创建频率为每分钟 6 次,已有其他创作提交也会共用这项额度;遇到 429 或额度提示,先看具体原因,等任务完成或按提示清理后再试。 +6. 候选数越多,新安排的候选和资源消耗越多;不代表能同时运行相同数量的 GPU。已有成功结果仍可预览和下载,未过期且满足确认条件的可继续确认;不要为了验证候选数控件是否可点,额外发起一批真实生成。 + +“02 分镜”的自动编辑面板、镜头列表、候选或属性区内容超出时,只在对应容器内滚动;故事标题和步骤导航保持可见。鼠标移入显示滚动条,移出隐藏,键盘聚焦时也可显示;触屏直接在容器内滑动。窄屏会重排镜头卡和对比区域,底部内容仍通过容器内滚动到达。声音、字幕和唯一时间线请切到“03 成片”查看;时间线较长时在该区域横向滚动。手机和电脑使用相同的版本校验、保存和人工流程确认规则;移动端不是离线剪辑模式。 + +## 13. 常见提示 + +| 提示或现象 | 处理 | +| ---------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| “新建故事”或生成按钮不可用 | 先看故事能力、连接说明;等读取完成。编辑中先保存;生成过程中等本次提交结束,具体限制看页面提示 | +| “保存故事”不可用 | 检查名称是否为空、页面是否还在读取,以及字幕、音轨、裁剪等是否触发校验错误;修正提示后再保存 | +| 想选“候选数”,找不到下拉选项 | 这是数值框,用 `+ / −` 或直接输入 1–4;只调整数量不触发生成,也不要求先确认首帧 | +| 候选数改成 3,已有作品仍只有 1 个 | 正常;数量只作用于下一次模型生成,不补齐、不重生、不复制旧结果。人工导入每次始终是 1 个 | +| “参考图生成”不可选 | 查看当前能力原因;即使模型 PoC 已通过,未开放或上游离线的环境仍会禁用。可人工导入,或明确选择文字方式 | +| 参考图数量超限 | 检查本镜头场景、实体、当前形态、造型汇入的不同图片总数,减少到当前上限内 | +| 首帧导入后看不到图片、暂不能确认 | 等待规范化任务完成并成为“可复核”;查看候选错误和任务状态 | +| 点缩略图后仍提示没有确认 | 缩略图只打开预览弹窗;关闭后在对应卡片点“确认首帧”或“确认选片”,并检查是否显示“已确认” | +| “确认首帧 / 确认选片”不可用 | 先保存;候选须有可用素材、状态为“可复核”且没有“设定已变化”。过期候选按第 11 节重新导入或生成 | +| 生成视频按钮不可用 | 先保存,确认有效首帧,再检查“生成源长度”能否覆盖选用区间;人工视频导入仍走独立路径 | +| 当前镜头可生成,“全故事候选计划”不可用 | 检查其他镜头的生成长度、选段和首帧确认;一个镜头满足条件不能代表全部镜头 | +| “冻结素材并合成”不可用或提交被拒绝 | 先保存,检查每个镜头都有有效选片,再根据就绪提示修正真实长度、音轨和字幕;缺少视频不会被自动补生成 | +| 编译预览提示缺少画面文字,但已有人工视频 | 这是生成诊断;人工视频无需文生图提示词,继续检查有效选片和合成就绪状态 | +| “选用区间超过已选视频实际范围” | 根据实际视频时长调整起始帧或选用帧数;仅修改生成长度不能把已有视频变长 | +| 修改镜头后字幕、旁白越界 | 它们使用整片时间且原值会保留,手动调整或增加成片长度 | +| 旧候选变灰或显示设定变化 | 查看它的冻结输入;重新生成,或明确导入为人工素材再复核 | +| 删除被拒绝 | 查看是否仍在执行、等待执行清理、或素材仍被候选/选择/历史运行引用;先处理对应记录 | +| 一直排队或提示等待窗口 | 看“创作服务状态”的批量策略和“任务”的等待原因;切换页面或反复生成不会消除资源、时段和额度限制 | +| 任务完成后没有最终成片下载 | 先逐镜“确认选片”,再去故事内“03 成片”冻结合成;成功后在顶部“成片预览”点“下载成片”,旧版本在“合成历史”中 | + +相关入口说明见[主操作手册](操作手册_20261111.md);旧工作流的长故事与旁白示例见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。后者的旧模板、独立模型实测结果不能替代新版锚定工作室链路的验收结论。 + +## 14. 本工作室对应的“编排审核”和“批量生成” + +需求中的日间“编排审核”,在这里对应“01 基准板”的共同设定、“02 分镜”的顺序与裁剪、候选比较,以及明确点击“确认首帧 / 确认选片”。确认会记录操作者和版本;当前操作人是故事所属账号,没有指定另一个审核账号、送审单或成片终审按钮。 + +故事的批量入口是“02 分镜”中的“全故事候选计划”。先选当前首帧或视频阶段、候选数和“批量队列”,再提交;它一次只安排当前阶段,不自动确认或进入下一阶段。候选仍回原故事查看和审核。启用可编辑自动成片后,在自动工具条选择“批量队列”再提交素材或成片生成。独立“批量”页面已移除;两条故事路径仍沿用原批量执行策略。 + +需要逐镜审核的新故事,正式排期通常为:第1天编排,第1夜生成首帧,第2天确认首帧,第2夜生成视频,第3天选片与合成。已有有效首帧时,可直接从视频批量开始。当前开发全天模式允许在同一天依次完成上述步骤,但人工确认关卡保持不变。 + +日间完成视频选片后,若要立即进行CPU合成,先在“02 分镜”将执行模式改为“交互队列”,再进“03 成片”冻结合成;成片提交沿用该选择。若仍为“批量队列”,正式时段限制开启时会等夜间窗口。仅切换队列不会发起生成或确认。 + +主手册第0节列出六项能力的实际入口和边界,第4节说明人工审核步骤,第7节说明故事自动成片的批量模式、人工候选计划、历史API兼容及日夜节拍。严格夜间执行、夜间产能统计和可选多人审批的待实施设计见[生产流程完善方案](design/2026-11-12-production-workflow-design.md)。 diff --git a/frontend/src/App.vue b/frontend/src/App.vue index d2bde57..f251ba3 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,32 +1,362 @@ diff --git a/frontend/src/api.test.ts b/frontend/src/api.test.ts deleted file mode 100644 index 2edc99b..0000000 --- a/frontend/src/api.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import {beforeEach,afterEach,describe,expect,it,vi} from 'vitest' -import {api,setCsrfToken} from './api' -import {pendingSubmissions,setStorageOwner} from './outbox' -import {emptyWorkflow} from './v2types' -const saved=new Map() -beforeEach(()=>{saved.clear();vi.stubGlobal('localStorage',{getItem:(k:string)=>saved.get(k)??null,setItem:(k:string,v:string)=>saved.set(k,v)});setStorageOwner('alice');setCsrfToken('csrf-test')}) -afterEach(()=>vi.unstubAllGlobals()) -describe('API recovery wire contract',()=>{ - it('creates new variable workflows with the multi_shot kind',async()=>{const fetcher=vi.fn().mockResolvedValue({ok:true,status:200,json:async()=>({})});vi.stubGlobal('fetch',fetcher);await api.createWorkflow('长片',emptyWorkflow());expect(JSON.parse(fetcher.mock.calls[0]![1].body).kind).toBe('multi_shot')}) - it('replays exact explicit retry nonce after a lost HTTP response',async()=>{const fetcher=vi.fn().mockRejectedValueOnce(new Error('lost')).mockResolvedValue({ok:true,status:200,json:async()=>({jobs:[]})});vi.stubGlobal('fetch',fetcher);await expect(api.retry('job-1')).rejects.toThrow();const original=pendingSubmissions()[0]!;await api.retry('job-1');const first=fetcher.mock.calls[0]![1],second=fetcher.mock.calls[1]![1];expect(first.headers.get('Idempotency-Key')).toBe(original.key);expect(second.headers.get('Idempotency-Key')).toBe(original.key);expect(second.headers.get('X-CSRF-Token')).toBe('csrf-test');expect(second.body).toBe(first.body);expect(original.operation).toBe('jobs.retry')}) - it('persists run revision and version for recovery rather than deriving from current draft',async()=>{vi.stubGlobal('fetch',vi.fn().mockRejectedValue(new Error('lost')));await api.recover({operation:'workflow.run',path:'/workflows/d/runs',body:'{"draft_revision":2,"expected_version":3,"execution_mode":"interactive"}'}).catch(()=>{});expect(pendingSubmissions()[0]?.body).toBe('{"draft_revision":2,"expected_version":3,"execution_mode":"interactive"}')}) -}) diff --git a/frontend/src/api.ts b/frontend/src/api.ts deleted file mode 100644 index bd96dea..0000000 --- a/frontend/src/api.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { durableRequest } from './outbox' -import type { DraftDTO, RunSnapshot, RunDTO, BatchSnapshot, BatchDTO, WorkflowSpec, TokenRecord } from './v2types' -import type { Asset, SharedAsset, DeleteResult, AuthResponse, CapabilitiesResponse, Job, JobRequest, JobsPage, Page, Scheduler, Capability,ExecutionPolicy,WorkflowLimits } from './types' - -let csrfToken = '' -export function setCsrfToken(token: string) { csrfToken = token } -export class ApiError extends Error { - constructor(public code: string, message: string, public status = 0) { super(message) } -} -export function queryString(values: Record = {}) { - const search = new URLSearchParams() - for (const [key, value] of Object.entries(values)) if (value !== undefined && value !== null && value !== '') search.set(key, String(value)) - return search.size ? `?${search}` : '' -} -export function newRequestId() { return globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}` } -export async function request(path: string, options: RequestInit = {}): Promise { - const method = (options.method || 'GET').toUpperCase() - const headers = new Headers(options.headers) - if (options.body && !(options.body instanceof FormData)) headers.set('Content-Type', 'application/json') - if (!['GET', 'HEAD'].includes(method) && path !== '/auth/login') { - if (!csrfToken) throw new ApiError('session_required', '登录状态已失效,请重新登录', 401) - headers.set('X-CSRF-Token', csrfToken) - } - let response: Response - try { response = await fetch(`/api${path}`, { ...options, headers, credentials: 'include' }) } - catch { throw new ApiError('network_error', '暂时无法连接服务,请检查网络后重试') } - if (!response.ok) { - const data = await response.json().catch(() => null) - const detail = data?.detail - const message = typeof detail === 'string' ? detail : Array.isArray(detail) - ? detail.map((item: { msg: string }) => item.msg).join(';') : detail?.message || `请求失败(${response.status})` - if (response.status === 401 && path !== '/auth/login' && typeof window !== 'undefined') window.dispatchEvent(new Event('cmvr:unauthorized')) - throw new ApiError(detail?.code || 'request_failed', message, response.status) - } - if (response.status === 204) return undefined as T - return response.json() as Promise -} -export const api = { - deleteJob: (id:string,version?:number) => removeRecord(`/jobs/${encodeURIComponent(id)}`,version), - deleteWorkflow: (id:string,version?:number) => removeRecord(`/workflows/${encodeURIComponent(id)}`,version), - deleteRun: (id:string,version?:number) => removeRecord(`/workflow-runs/${encodeURIComponent(id)}`,version), - deleteBatch: (id:string,version?:number) => removeRecord(`/batches/${encodeURIComponent(id)}`,version), - sharedAssets: (filters:Record={}) => request>(`/shared-assets${queryString(filters)}`), - sharedAsset: (id:string) => request(`/shared-assets/${encodeURIComponent(id)}`), - publishAsset: (id:string) => request(`/assets/${encodeURIComponent(id)}/publish`,{method:'POST'}), - importSharedAsset: (id:string) => request(`/shared-assets/${encodeURIComponent(id)}/import`,{method:'POST'}), - withdrawSharedAsset: (id:string) => request(`/shared-assets/${encodeURIComponent(id)}`,{method:'DELETE'}), - workflows: (filters:Record={}) => request>(`/workflows${queryString(filters)}`), - workflow: (id:string) => request(`/workflows/${id}`), - createWorkflow: (name:string,spec:WorkflowSpec) => request('/workflows',{method:'POST',body:JSON.stringify({name,spec,kind:spec.schema_version===1?'three_shot':'multi_shot'})}), - saveWorkflow: (draft:DraftDTO,name:string,spec:WorkflowSpec) => request(`/workflows/${draft.id}`,{method:'PATCH',headers:{'If-Match':String(draft.version)},body:JSON.stringify({name,spec})}), - startRun: (draft:DraftDTO,execution_mode='interactive',reuse_run_id?:string) => durable('workflow.run',`/workflows/${draft.id}/runs`,{draft_revision:draft.revision,expected_version:draft.version,execution_mode,...(reuse_run_id?{reuse_run_id}:{})}), - runs: (filters:Record={}) => request>(`/workflow-runs${queryString(filters)}`), - run: (id:string) => request(`/workflow-runs/${id}`), - controlRun: (run:RunDTO,action:'pause'|'resume'|'cancel') => durable(`workflow.${action}`,`/workflow-runs/${run.id}/${action}`,{expected_version:run.version}), - retryStep: (run:RunDTO,key:string,jobId:string) => durable('workflow.retry',`/workflow-runs/${run.id}/steps/${key}/retry`,{expected_run_version:run.version,target_job_id:jobId}), - batches: (filters:Record={}) => request>(`/batches${queryString(filters)}`), - batch: (id:string) => request(`/batches/${id}`), - createBatch: (body:unknown) => durable('batch.create','/batches',body), - controlBatch: (batch:BatchDTO,desired_state:string) => durable('batch.control',`/batches/${batch.id}/control`,{desired_state,expected_version:batch.version}), - submission: (key:string,operation:string) => request(`/submissions/${encodeURIComponent(key)}${queryString({operation})}`), - recover: (entry:{operation:string;path:string;body:string}) => durable(entry.operation,entry.path,JSON.parse(entry.body)), - users: (page=1) => request>(`/auth/users?page=${page}&page_size=20`), - createUser: (body:unknown) => request('/auth/users',{method:'POST',body:JSON.stringify(body)}), - updateUser: (id:string,body:unknown) => request(`/auth/users/${id}`,{method:'PATCH',body:JSON.stringify(body)}), - password: (current_password:string,new_password:string) => request<{requires_relogin:boolean}>('/auth/password',{method:'POST',body:JSON.stringify({current_password,new_password})}), - tokens: () => request<{items:TokenRecord[]}>('/auth/tokens'), - createToken: (body:unknown) => request<{token:string;record:TokenRecord}>('/auth/tokens',{method:'POST',body:JSON.stringify(body)}), - revokeToken: (id:string) => request(`/auth/tokens/${id}`,{method:'DELETE'}), - me: () => request('/auth/me'), - login: (username: string, password: string) => request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }), - logout: () => request('/auth/logout', { method: 'POST' }), - capabilities: () => request('/capabilities'), - systemStatus: () => request<{ execution_policy?:ExecutionPolicy;workflow_limits?:WorkflowLimits; inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'), - jobs: (filters: Record = {}) => request(`/jobs${queryString(filters)}`), - job: (id: string) => request(`/jobs/${encodeURIComponent(id)}`), - submit: (body: JobRequest) => durable<{jobs:Job[]}>('jobs.create','/jobs',body), - cancel: (id: string) => request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }), - retry: (id: string) => durable<{jobs:Job[]}>('jobs.retry',`/jobs/${encodeURIComponent(id)}/retry`,{}), - assets: (filters: Record = {}) => request>(`/assets${queryString(filters)}`), - asset: (id: string) => request(`/assets/${encodeURIComponent(id)}`), - upload: (file: File) => { const form = new FormData(); form.set('file', file); return request('/assets', { method: 'POST', body: form }) }, - updateAsset: (id: string, patch: { name?: string; tags?: string[]; favorite?: boolean }) => request(`/assets/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }), - deleteAsset: (id: string) => request(`/assets/${encodeURIComponent(id)}`, { method: 'DELETE' }), -} -function removeRecord(path:string,version?:number){return request(path,{method:'DELETE',...(version===undefined?{}:{headers:{'If-Match':String(version)}})})} -export function errorMessage(error: unknown) { return error instanceof Error ? error.message : '操作未完成,请稍后重试' } - -function durable(operation:string,path:string,body:unknown){return durableRequest(operation,path,body,(url,key,payload)=>request(url,{method:"POST",headers:{"Idempotency-Key":key},body:payload}))} diff --git a/frontend/src/api/account.test.ts b/frontend/src/api/account.test.ts new file mode 100644 index 0000000..db084e4 --- /dev/null +++ b/frontend/src/api/account.test.ts @@ -0,0 +1,68 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { api, setCsrfToken } from './index' + +beforeEach(() => setCsrfToken('admin-test-csrf')) +afterEach(() => vi.unstubAllGlobals()) + +it('deletes a user with CSRF and accepts an empty 204 response', async () => { + const fetcher = vi.fn().mockResolvedValue({ ok: true, status: 204 }) + vi.stubGlobal('fetch', fetcher) + await expect(api.deleteUser('user/one')).resolves.toBeUndefined() + expect(fetcher.mock.calls[0]?.[0]).toBe('/api/auth/users/user%2Fone') + expect(fetcher.mock.calls[0]?.[1].method).toBe('DELETE') + expect(fetcher.mock.calls[0]?.[1].headers.get('X-CSRF-Token')).toBe('admin-test-csrf') +}) + +it('preserves cleanup_pending as a rejected operation for retry', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: false, + status: 409, + json: async () => ({ detail: { code: 'cleanup_pending', message: 'pending' } }), + }), + ) + await expect(api.deleteUser('user-one')).rejects.toMatchObject({ + code: 'cleanup_pending', + status: 409, + }) +}) + +it('changes the login username with the current password and CSRF, returning the same user DTO', async () => { + const user = { id: 'member-one', username: 'alice.new', display_name: 'Alice', role: 'user' } + const fetcher = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => user }) + vi.stubGlobal('fetch', fetcher) + + await expect(api.changeUsername('alice.new', 'current-password-123')).resolves.toEqual(user) + + expect(fetcher).toHaveBeenCalledTimes(1) + const [path, options] = fetcher.mock.calls[0]! + expect(path).toBe('/api/auth/username') + expect(options.method).toBe('POST') + expect(options.credentials).toBe('include') + expect(options.headers.get('X-CSRF-Token')).toBe('admin-test-csrf') + expect(options.headers.get('Content-Type')).toBe('application/json') + expect(JSON.parse(options.body)).toEqual({ + username: 'alice.new', + current_password: 'current-password-123', + }) +}) + +it.each([ + { status: 409, code: 'username_exists', message: '用户名已存在' }, + { status: 403, code: 'invalid_password', message: '当前密码不正确' }, +])('preserves username-change errors: $code', async ({ status, code, message }) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: false, + status, + json: async () => ({ detail: { code, message } }), + }), + ) + await expect(api.changeUsername('alice.new', 'wrong-password')).rejects.toMatchObject({ + status, + code, + message, + }) +}) diff --git a/frontend/src/api/account.ts b/frontend/src/api/account.ts new file mode 100644 index 0000000..832642d --- /dev/null +++ b/frontend/src/api/account.ts @@ -0,0 +1,36 @@ +import type { User, AuthResponse, Page, TokenRecord } from '../types' +import { request } from './client' + +export const accountApi = { + users: (page = 1) => request>(`/auth/users?page=${page}&page_size=20`), + createUser: (body: unknown) => + request('/auth/users', { method: 'POST', body: JSON.stringify(body) }), + updateUser: (id: string, body: unknown) => + request(`/auth/users/${id}`, { method: 'PATCH', body: JSON.stringify(body) }), + deleteUser: (id: string) => + request(`/auth/users/${encodeURIComponent(id)}`, { method: 'DELETE' }), + password: (current_password: string, new_password: string) => + request<{ requires_relogin: boolean }>('/auth/password', { + method: 'POST', + body: JSON.stringify({ current_password, new_password }), + }), + changeUsername: (username: string, current_password: string) => + request('/auth/username', { + method: 'POST', + body: JSON.stringify({ username, current_password }), + }), + tokens: () => request<{ items: TokenRecord[] }>('/auth/tokens'), + createToken: (body: unknown) => + request<{ token: string; record: TokenRecord }>('/auth/tokens', { + method: 'POST', + body: JSON.stringify(body), + }), + revokeToken: (id: string) => request(`/auth/tokens/${id}`, { method: 'DELETE' }), + me: () => request('/auth/me'), + login: (username: string, password: string) => + request('/auth/login', { + method: 'POST', + body: JSON.stringify({ username, password }), + }), + logout: () => request('/auth/logout', { method: 'POST' }), +} diff --git a/frontend/src/api/assets.ts b/frontend/src/api/assets.ts new file mode 100644 index 0000000..2e79bcf --- /dev/null +++ b/frontend/src/api/assets.ts @@ -0,0 +1,38 @@ +import type { Asset, SharedAsset, Page } from '../types' +import { request, queryString } from './client' + +// 共享发布和导入会创建独立副本,普通 HTTP 调用不自动重放这些写入。 + +export const assetsApi = { + sharedAssets: (filters: Record = {}) => + request>(`/shared-assets${queryString(filters)}`), + sharedAsset: (id: string) => request(`/shared-assets/${encodeURIComponent(id)}`), + publishAsset: (id: string) => + request(`/assets/${encodeURIComponent(id)}/publish`, { method: 'POST' }), + importSharedAsset: (id: string, folder_id?: string | null) => + request(`/shared-assets/${encodeURIComponent(id)}/import`, { + method: 'POST', + ...(folder_id !== undefined ? { body: JSON.stringify({ folder_id }) } : {}), + }), + withdrawSharedAsset: (id: string) => + request(`/shared-assets/${encodeURIComponent(id)}`, { method: 'DELETE' }), + assets: (filters: Record = {}) => + request>(`/assets${queryString(filters)}`), + asset: (id: string) => request(`/assets/${encodeURIComponent(id)}`), + upload: (file: File, folder_id?: string | null) => { + const form = new FormData() + form.set('file', file) + if (folder_id) form.set('folder_id', folder_id) + return request('/assets', { method: 'POST', body: form }) + }, + updateAsset: ( + id: string, + patch: { name?: string; tags?: string[]; favorite?: boolean; folder_ids?: string[] }, + ) => + request(`/assets/${encodeURIComponent(id)}`, { + method: 'PATCH', + body: JSON.stringify(patch), + }), + deleteAsset: (id: string) => + request(`/assets/${encodeURIComponent(id)}`, { method: 'DELETE' }), +} diff --git a/frontend/src/api/batches.ts b/frontend/src/api/batches.ts new file mode 100644 index 0000000..a105856 --- /dev/null +++ b/frontend/src/api/batches.ts @@ -0,0 +1,17 @@ +import type { Page, BatchDTO, BatchSnapshot } from '../types' +import { request, queryString, removeRecord } from './client' +import { durable } from './durable' + +export const batchesApi = { + deleteBatch: (id: string, version?: number) => + removeRecord(`/batches/${encodeURIComponent(id)}`, version), + batches: (filters: Record = {}) => + request>(`/batches${queryString(filters)}`), + batch: (id: string) => request(`/batches/${id}`), + createBatch: (body: unknown) => durable('batch.create', '/batches', body), + controlBatch: (batch: BatchDTO, desired_state: string) => + durable('batch.control', `/batches/${batch.id}/control`, { + desired_state, + expected_version: batch.version, + }), +} diff --git a/frontend/src/api/client.session.test.ts b/frontend/src/api/client.session.test.ts new file mode 100644 index 0000000..297bd11 --- /dev/null +++ b/frontend/src/api/client.session.test.ts @@ -0,0 +1,39 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { ApiError, request, setCsrfToken } from './client' +afterEach(() => vi.unstubAllGlobals()) + +it('does not expire a new session when an old request returns unauthorized', async () => { + setCsrfToken('old-session') + const dispatch = vi.fn() + vi.stubGlobal('window', { dispatchEvent: dispatch }) + let finish!: (value: unknown) => void + vi.stubGlobal( + 'fetch', + vi.fn( + () => + new Promise((resolve) => { + finish = resolve + }), + ), + ) + const pending = request('/auth/users') + setCsrfToken('new-session') + finish({ + ok: false, + status: 401, + json: async () => ({ detail: { code: 'session_expired', message: 'expired' } }), + }) + await expect(pending).rejects.toBeInstanceOf(ApiError) + expect(dispatch).not.toHaveBeenCalled() +}) +it('still expires the current session on its own unauthorized response', async () => { + setCsrfToken('current-session') + const dispatch = vi.fn() + vi.stubGlobal('window', { dispatchEvent: dispatch }) + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ ok: false, status: 401, json: async () => null })), + ) + await expect(request('/auth/users')).rejects.toBeInstanceOf(ApiError) + expect(dispatch).toHaveBeenCalledOnce() +}) diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts new file mode 100644 index 0000000..798a5e1 --- /dev/null +++ b/frontend/src/api/client.ts @@ -0,0 +1,73 @@ +import type { DeleteResult } from '../types' + +// 所有端点共用同一 CSRF 状态;cookie 会话、401 通知和空响应处理必须保持一致。 +let csrfToken = '' +let sessionGeneration = 0 +export const getSessionGeneration = () => sessionGeneration +export function setCsrfToken(token: string) { + csrfToken = token + sessionGeneration++ +} +export class ApiError extends Error { + constructor( + public code: string, + message: string, + public status = 0, + ) { + super(message) + } +} +export function queryString(values: Record = {}) { + const search = new URLSearchParams() + for (const [key, value] of Object.entries(values)) + if (value !== undefined && value !== null && value !== '') search.set(key, String(value)) + return search.size ? `?${search}` : '' +} +export async function request(path: string, options: RequestInit = {}): Promise { + const generation = sessionGeneration + const method = (options.method || 'GET').toUpperCase() + const headers = new Headers(options.headers) + if (options.body && !(options.body instanceof FormData)) + headers.set('Content-Type', 'application/json') + if (!['GET', 'HEAD'].includes(method) && path !== '/auth/login') { + if (!csrfToken) throw new ApiError('session_required', '登录状态已失效,请重新登录', 401) + headers.set('X-CSRF-Token', csrfToken) + } + let response: Response + try { + response = await fetch(`/api${path}`, { ...options, headers, credentials: 'include' }) + } catch { + throw new ApiError('network_error', '暂时无法连接服务,请检查网络后重试') + } + if (!response.ok) { + const data = await response.json().catch(() => null) + const detail = data?.detail + const message = + typeof detail === 'string' + ? detail + : Array.isArray(detail) + ? detail.map((item: { msg: string }) => item.msg).join(';') + : detail?.message || `请求失败(${response.status})` + // 旧会话的失败响应可能晚于重新登录,不能据此清除新会话。 + if ( + response.status === 401 && + path !== '/auth/login' && + typeof window !== 'undefined' && + generation === sessionGeneration + ) + window.dispatchEvent(new Event('cmvr:unauthorized')) + throw new ApiError(detail?.code || 'request_failed', message, response.status) + } + if (response.status === 204) return undefined as T + return response.json() as Promise +} + +export function removeRecord(path: string, version?: number) { + return request(path, { + method: 'DELETE', + ...(version === undefined ? {} : { headers: { 'If-Match': String(version) } }), + }) +} +export function errorMessage(error: unknown) { + return error instanceof Error ? error.message : '操作未完成,请稍后重试' +} diff --git a/frontend/src/api/durable.ts b/frontend/src/api/durable.ts new file mode 100644 index 0000000..2f5e416 --- /dev/null +++ b/frontend/src/api/durable.ts @@ -0,0 +1,9 @@ +import { durableRequest } from '../services/submissionOutbox' +import { request } from './client' + +// 幂等操作名、请求路径与 JSON 字段顺序属于恢复合同,不能在重试时重新生成。 +export function durable(operation: string, path: string, body: unknown) { + return durableRequest(operation, path, body, (url, key, payload) => + request(url, { method: 'POST', headers: { 'Idempotency-Key': key }, body: payload }), + ) +} diff --git a/frontend/src/api/editors.test.ts b/frontend/src/api/editors.test.ts new file mode 100644 index 0000000..7e2b33c --- /dev/null +++ b/frontend/src/api/editors.test.ts @@ -0,0 +1,58 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api, setCsrfToken } from './index' +import { setStorageOwner, pendingSubmissions } from '../services/submissionOutbox' +beforeEach(() => { + const values = new Map() + vi.stubGlobal('localStorage', { + getItem: (k: string) => values.get(k) || null, + setItem: (k: string, v: string) => values.set(k, v), + }) + setStorageOwner('editor-test') + setCsrfToken('csrf') +}) +describe('editor durable API', () => { + it('retries exact save body with original key', async () => { + const fetch = vi + .fn() + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue({ ok: true, status: 200, json: async () => ({ version: 2 }) }) + vi.stubGlobal('fetch', fetch) + const manifest = { schema_version: 1 } as any + await expect(api.saveEditor('draft', 1, manifest)).rejects.toThrow() + expect(pendingSubmissions()[0]?.operation).toBe('editor.save') + await api.saveEditor('draft', 1, manifest) + expect(fetch.mock.calls[0]?.[1].body).toBe(JSON.stringify({ expected_version: 1, manifest })) + expect(fetch.mock.calls[0]?.[1].headers.get('Idempotency-Key')).toBe( + fetch.mock.calls[1]?.[1].headers.get('Idempotency-Key'), + ) + expect(pendingSubmissions()).toEqual([]) + }) +}) + +it('persists exact mode command and reuses the same key when retrying', async () => { + const fetch = vi + .fn() + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue({ ok: true, status: 200, json: async () => ({ editing_mode: 'manual' }) }) + vi.stubGlobal('fetch', fetch) + await expect(api.setEditorMode('d', 4, 'manual')).rejects.toThrow() + expect(pendingSubmissions()[0]?.operation).toBe('editor.mode') + await api.setEditorMode('d', 4, 'manual') + expect(fetch.mock.calls[0]?.[1].body).toBe( + JSON.stringify({ expected_version: 4, mode: 'manual' }), + ) + expect(fetch.mock.calls[0]?.[1].headers.get('Idempotency-Key')).toBe( + fetch.mock.calls[1]?.[1].headers.get('Idempotency-Key'), + ) +}) + +it('includes an explicit title with the manifest in the durable save body', async () => { + const fetch = vi + .fn() + .mockResolvedValue({ ok: true, status: 200, json: async () => ({ name: 'new title' }) }) + vi.stubGlobal('fetch', fetch) + await api.saveEditor('d', 3, { schema_version: 1 } as any, 'new title') + expect(fetch.mock.calls[0]?.[1].body).toBe( + JSON.stringify({ expected_version: 3, manifest: { schema_version: 1 }, name: 'new title' }), + ) +}) diff --git a/frontend/src/api/editors.ts b/frontend/src/api/editors.ts new file mode 100644 index 0000000..d2493da --- /dev/null +++ b/frontend/src/api/editors.ts @@ -0,0 +1,35 @@ +import { request } from './client' +import { durable } from './durable' +import type { + EditorDTO, + EditorManifest, + EditorPlan, + EditorPlanInput, + EditingMode, +} from '../types/editors' +import type { RunSnapshot } from '../types/workflows' +const path = (id: string) => `/editors/${encodeURIComponent(id)}` +export const editorsApi = { + setEditorMode: (id: string, expected_version: number, mode: EditingMode) => + durable('editor.mode', `${path(id)}/mode`, { expected_version, mode }), + editor: (id: string) => request(path(id)), + saveEditor: ( + id: string, + expected_version: number, + manifest: EditorManifest, + name?: string | null, + ) => + durable('editor.save', `${path(id)}/save`, { + expected_version, + manifest, + ...(name !== undefined ? { name } : {}), + }), + editorFromRun: (id: string, expected_version: number, run_id: string) => + durable('editor.from_run', `${path(id)}/from-run`, { expected_version, run_id }), + planEditor: (id: string, input: EditorPlanInput) => + request(`${path(id)}/plan`, { method: 'POST', body: JSON.stringify(input) }), + runEditor: (id: string, input: EditorPlanInput & { expected_plan_hash: string }) => + durable('editor.run', `${path(id)}/runs`, input), + applyEditor: (id: string, expected_version: number, run_id: string) => + durable('editor.apply', `${path(id)}/apply`, { expected_version, run_id }), +} diff --git a/frontend/src/api/folders.test.ts b/frontend/src/api/folders.test.ts new file mode 100644 index 0000000..175887c --- /dev/null +++ b/frontend/src/api/folders.test.ts @@ -0,0 +1,36 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import { api, setCsrfToken } from './index' +import { emptyStory } from '../domain/stories/rules' +let fetcher: ReturnType +beforeEach(() => { + setCsrfToken('test') + fetcher = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({ items: [] }) }) + vi.stubGlobal('fetch', fetcher) +}) +it('exposes folders and preserves move/add and explicit unclassified on the wire', async () => { + await api.folders() + expect(fetcher.mock.calls[0]![0]).toBe('/api/folders') + await api.assignFolder('assets', ['a'], 'f', 'add') + expect(JSON.parse(fetcher.mock.calls[1]![1].body)).toEqual({ + kind: 'assets', + ids: ['a'], + folder_id: 'f', + mode: 'add', + }) + await api.assignFolder('jobs', ['j'], null, 'move') + expect(JSON.parse(fetcher.mock.calls[2]![1].body).folder_id).toBeNull() +}) +it('keeps story automatic folder distinct from explicit null', async () => { + await api.createStory('故事', emptyStory()) + expect(JSON.parse(fetcher.mock.calls[0]![1].body)).not.toHaveProperty('folder_id') + await api.createStory('故事', emptyStory(), { folder_id: null }) + expect(JSON.parse(fetcher.mock.calls[1]![1].body).folder_id).toBeNull() +}) +it('carries asset folder queries, import body and upload multipart', async () => { + await api.assets({ folder_id: 'unclassified' }) + expect(fetcher.mock.calls[0]![0]).toContain('folder_id=unclassified') + await api.importSharedAsset('s', 'f') + expect(JSON.parse(fetcher.mock.calls[1]![1].body)).toEqual({ folder_id: 'f' }) + await api.upload(new File(['a'], 'a.txt'), 'f') + expect(fetcher.mock.calls[2]![1].body.get('folder_id')).toBe('f') +}) diff --git a/frontend/src/api/folders.ts b/frontend/src/api/folders.ts new file mode 100644 index 0000000..fd3608a --- /dev/null +++ b/frontend/src/api/folders.ts @@ -0,0 +1,24 @@ +import { request } from './client' +import type { Folder, FolderKind } from '../types/folders' +export const foldersApi = { + folders: () => request<{ items: Folder[] }>('/folders'), + createFolder: (name: string, parent_id: string | null = null) => + request('/folders', { method: 'POST', body: JSON.stringify({ name, parent_id }) }), + updateFolder: (id: string, patch: { name?: string; parent_id?: string | null }) => + request(`/folders/${encodeURIComponent(id)}`, { + method: 'PATCH', + body: JSON.stringify(patch), + }), + deleteFolder: (id: string) => + request(`/folders/${encodeURIComponent(id)}`, { method: 'DELETE' }), + assignFolder: ( + kind: FolderKind, + ids: string[], + folder_id: string | null, + mode: 'move' | 'add' = 'move', + ) => + request<{ updated: number; kind: FolderKind; folder_id: string | null }>('/folders/assign', { + method: 'POST', + body: JSON.stringify({ kind, ids, folder_id, mode }), + }), +} diff --git a/frontend/src/api/index.test.ts b/frontend/src/api/index.test.ts new file mode 100644 index 0000000..784afaa --- /dev/null +++ b/frontend/src/api/index.test.ts @@ -0,0 +1,53 @@ +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' +import { api, setCsrfToken } from './index' +import { pendingSubmissions, setStorageOwner } from '../services/submissionOutbox' +import { emptyWorkflow } from '../domain/workflows/timeline' +const saved = new Map() +beforeEach(() => { + saved.clear() + vi.stubGlobal('localStorage', { + getItem: (k: string) => saved.get(k) ?? null, + setItem: (k: string, v: string) => saved.set(k, v), + }) + setStorageOwner('alice') + setCsrfToken('csrf-test') +}) +afterEach(() => vi.unstubAllGlobals()) +describe('API recovery wire contract', () => { + it('creates new variable workflows with the multi_shot kind', async () => { + const fetcher = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({}) }) + vi.stubGlobal('fetch', fetcher) + await api.createWorkflow('长片', emptyWorkflow()) + expect(JSON.parse(fetcher.mock.calls[0]![1].body).kind).toBe('multi_shot') + }) + it('replays exact explicit retry nonce after a lost HTTP response', async () => { + const fetcher = vi + .fn() + .mockRejectedValueOnce(new Error('lost')) + .mockResolvedValue({ ok: true, status: 200, json: async () => ({ jobs: [] }) }) + vi.stubGlobal('fetch', fetcher) + await expect(api.retry('job-1')).rejects.toThrow() + const original = pendingSubmissions()[0]! + await api.retry('job-1') + const first = fetcher.mock.calls[0]![1], + second = fetcher.mock.calls[1]![1] + expect(first.headers.get('Idempotency-Key')).toBe(original.key) + expect(second.headers.get('Idempotency-Key')).toBe(original.key) + expect(second.headers.get('X-CSRF-Token')).toBe('csrf-test') + expect(second.body).toBe(first.body) + expect(original.operation).toBe('jobs.retry') + }) + it('persists run revision and version for recovery rather than deriving from current draft', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('lost'))) + await api + .recover({ + operation: 'workflow.run', + path: '/workflows/d/runs', + body: '{"draft_revision":2,"expected_version":3,"execution_mode":"interactive"}', + }) + .catch(() => {}) + expect(pendingSubmissions()[0]?.body).toBe( + '{"draft_revision":2,"expected_version":3,"execution_mode":"interactive"}', + ) + }) +}) diff --git a/frontend/src/api/index.ts b/frontend/src/api/index.ts new file mode 100644 index 0000000..c473ba8 --- /dev/null +++ b/frontend/src/api/index.ts @@ -0,0 +1,67 @@ +import { editorsApi } from './editors' +import { foldersApi } from './folders' +import { jobsApi } from './jobs' +import { assetsApi } from './assets' +import { workflowsApi } from './workflows' +import { batchesApi } from './batches' +import { accountApi } from './account' +import { systemApi } from './system' +import { submissionsApi } from './submissions' +import { storiesApi } from './stories' + +export { ApiError, errorMessage, queryString, request, setCsrfToken } from './client' + +// 业务与测试共用这一个可替换方法的对象;模块内部不再创建第二份 facade。 +export const api = { + ...foldersApi, + ...editorsApi, + ...storiesApi, + deleteJob: jobsApi.deleteJob, + deleteWorkflow: workflowsApi.deleteWorkflow, + deleteRun: workflowsApi.deleteRun, + deleteBatch: batchesApi.deleteBatch, + sharedAssets: assetsApi.sharedAssets, + sharedAsset: assetsApi.sharedAsset, + publishAsset: assetsApi.publishAsset, + importSharedAsset: assetsApi.importSharedAsset, + withdrawSharedAsset: assetsApi.withdrawSharedAsset, + workflows: workflowsApi.workflows, + workflow: workflowsApi.workflow, + createWorkflow: workflowsApi.createWorkflow, + saveWorkflow: workflowsApi.saveWorkflow, + startRun: workflowsApi.startRun, + runs: workflowsApi.runs, + run: workflowsApi.run, + controlRun: workflowsApi.controlRun, + retryStep: workflowsApi.retryStep, + batches: batchesApi.batches, + batch: batchesApi.batch, + createBatch: batchesApi.createBatch, + controlBatch: batchesApi.controlBatch, + submission: submissionsApi.submission, + recover: submissionsApi.recover, + users: accountApi.users, + createUser: accountApi.createUser, + updateUser: accountApi.updateUser, + deleteUser: accountApi.deleteUser, + password: accountApi.password, + changeUsername: accountApi.changeUsername, + tokens: accountApi.tokens, + createToken: accountApi.createToken, + revokeToken: accountApi.revokeToken, + me: accountApi.me, + login: accountApi.login, + logout: accountApi.logout, + capabilities: systemApi.capabilities, + systemStatus: systemApi.systemStatus, + jobs: jobsApi.jobs, + job: jobsApi.job, + submit: jobsApi.submit, + cancel: jobsApi.cancel, + retry: jobsApi.retry, + assets: assetsApi.assets, + asset: assetsApi.asset, + upload: assetsApi.upload, + updateAsset: assetsApi.updateAsset, + deleteAsset: assetsApi.deleteAsset, +} diff --git a/frontend/src/api/jobs.ts b/frontend/src/api/jobs.ts new file mode 100644 index 0000000..0547e17 --- /dev/null +++ b/frontend/src/api/jobs.ts @@ -0,0 +1,16 @@ +import type { Job, JobRequest, JobsPage } from '../types' +import { request, queryString, removeRecord } from './client' +import { durable } from './durable' + +export const jobsApi = { + deleteJob: (id: string, version?: number) => + removeRecord(`/jobs/${encodeURIComponent(id)}`, version), + jobs: (filters: Record = {}) => + request(`/jobs${queryString(filters)}`), + job: (id: string) => request(`/jobs/${encodeURIComponent(id)}`), + submit: (body: JobRequest) => durable<{ jobs: Job[] }>('jobs.create', '/jobs', body), + cancel: (id: string) => + request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }), + retry: (id: string) => + durable<{ jobs: Job[] }>('jobs.retry', `/jobs/${encodeURIComponent(id)}/retry`, {}), +} diff --git a/frontend/src/api/stories.test.ts b/frontend/src/api/stories.test.ts new file mode 100644 index 0000000..21ac88a --- /dev/null +++ b/frontend/src/api/stories.test.ts @@ -0,0 +1,33 @@ +import { beforeEach, afterEach, expect, it, vi } from 'vitest' +import { api, setCsrfToken } from './index' +import { setStorageOwner } from '../services/submissionOutbox' +beforeEach(() => { + const data = new Map() + vi.stubGlobal('localStorage', { + getItem: (k: string) => data.get(k) || null, + setItem: (k: string, v: string) => data.set(k, v), + }) + setStorageOwner('owner') + setCsrfToken('csrf') +}) +afterEach(() => vi.unstubAllGlobals()) +it('uses one facade, shared CSRF, frozen expected version and a durable idempotency key', async () => { + const fetcher = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({}) }) + vi.stubGlobal('fetch', fetcher) + await api.createStoryCandidates('story/id', { + expected_version: 7, + shot_id: 'shot', + kind: 'frame', + count: 1, + source_kind: 'manual', + asset_id: 'image', + execution_mode: 'interactive', + }) + const [url, options] = fetcher.mock.calls[0]! + expect(url).toBe('/api/stories/story%2Fid/candidates') + expect(options.headers.get('X-CSRF-Token')).toBe('csrf') + expect(options.headers.get('Idempotency-Key')).toBeTruthy() + expect(JSON.parse(options.body).expected_version).toBe(7) + await api.saveStory({ id: 'story/id', version: 7 } as any, '保存', {} as any) + expect(fetcher.mock.calls[1]![1].headers.get('If-Match')).toBe('7') +}) diff --git a/frontend/src/api/stories.ts b/frontend/src/api/stories.ts new file mode 100644 index 0000000..f7ce9a1 --- /dev/null +++ b/frontend/src/api/stories.ts @@ -0,0 +1,94 @@ +import type { FolderOptions } from '../types/folders' +import type { Page } from '../types/common' +import type { + StoryDTO, + StorySpecV3, + StoryCapabilities, + StoryPreview, + CandidateDTO, + CandidateInput, + CandidateResult, + CandidateBatchInput, + StoryReadiness, + StoryRunDTO, + StoryRunSnapshot, + CandidateKind, +} from '../types/stories' +import { request, queryString, removeRecord } from './client' +import { durable } from './durable' +const path = (id: string) => `/stories/${encodeURIComponent(id)}` +export const storiesApi = { + storyCapabilities: () => request('/stories/capabilities'), + stories: (filters: Record = {}) => + request>(`/stories${queryString(filters)}`), + story: (id: string) => request(path(id)), + createStory: (name: string, spec: StorySpecV3, folders: FolderOptions = {}) => + request('/stories', { + method: 'POST', + body: JSON.stringify({ name, spec, ...folders }), + }), + saveStory: (story: StoryDTO, name: string, spec: StorySpecV3, folders: FolderOptions = {}) => + request(path(story.id), { + method: 'PATCH', + headers: { 'If-Match': String(story.version) }, + body: JSON.stringify({ name, spec, ...folders }), + }), + deleteStory: (id: string, version: number) => removeRecord(path(id), version), + storyPreview: (id: string) => request(`${path(id)}/preview`), + storyCandidates: (id: string, filters: Record = {}) => + request>(`${path(id)}/candidates${queryString(filters)}`), + createStoryCandidates: (id: string, input: CandidateInput) => + durable('story.candidates', `${path(id)}/candidates`, input), + createStoryCandidateBatch: (id: string, input: CandidateBatchInput) => + durable( + 'story.candidate-batch', + `${path(id)}/candidate-batches`, + input, + ), + retryStoryCandidate: (id: string, candidateId: string, expected_version: number) => + durable( + 'story.candidate-retry', + `${path(id)}/candidates/${encodeURIComponent(candidateId)}/retry`, + { expected_version }, + ), + deleteStoryCandidate: (id: string, candidateId: string, version: number) => + removeRecord(`${path(id)}/candidates/${encodeURIComponent(candidateId)}`, version), + selectStoryCandidate: ( + id: string, + expected_version: number, + shot_id: string, + kind: CandidateKind, + candidate_id: string, + ) => + durable('story.select', `${path(id)}/selections`, { + expected_version, + shot_id, + kind, + candidate_id, + }), + clearStorySelection: ( + id: string, + expected_version: number, + shot_id: string, + kind: CandidateKind, + ) => + durable('story.clear-selection', `${path(id)}/selections/clear`, { + expected_version, + shot_id, + kind, + }), + storyReadiness: (id: string) => request(`${path(id)}/readiness`), + renderStory: ( + id: string, + expected_version: number, + execution_mode: 'interactive' | 'batch', + output_folder_id?: string | null, + ) => + durable('story.render', `${path(id)}/renders`, { + expected_version, + execution_mode, + ...(output_folder_id !== undefined ? { output_folder_id } : {}), + }), + storyRuns: (id: string, filters: Record = {}) => + request>(`${path(id)}/runs${queryString(filters)}`), +} diff --git a/frontend/src/api/submissions.ts b/frontend/src/api/submissions.ts new file mode 100644 index 0000000..5da64e9 --- /dev/null +++ b/frontend/src/api/submissions.ts @@ -0,0 +1,9 @@ +import { request, queryString } from './client' +import { durable } from './durable' + +export const submissionsApi = { + submission: (key: string, operation: string) => + request(`/submissions/${encodeURIComponent(key)}${queryString({ operation })}`), + recover: (entry: { operation: string; path: string; body: string }) => + durable(entry.operation, entry.path, JSON.parse(entry.body)), +} diff --git a/frontend/src/api/system.ts b/frontend/src/api/system.ts new file mode 100644 index 0000000..4336800 --- /dev/null +++ b/frontend/src/api/system.ts @@ -0,0 +1,22 @@ +import type { + Capability, + Scheduler, + ExecutionPolicy, + WorkflowLimits, + CapabilitiesResponse, +} from '../types' +import { request } from './client' + +export const systemApi = { + capabilities: () => request('/capabilities'), + systemStatus: () => + request<{ + execution_policy?: ExecutionPolicy + workflow_limits?: WorkflowLimits + inference_online: boolean + scheduler: Scheduler + models: Capability[] + environment: 'production' | 'preview' | 'test' + database_backend: 'mysql' | 'sqlite' + }>('/system/status'), +} diff --git a/frontend/src/api/workflows.ts b/frontend/src/api/workflows.ts new file mode 100644 index 0000000..75055d2 --- /dev/null +++ b/frontend/src/api/workflows.ts @@ -0,0 +1,54 @@ +import type { Page, WorkflowSpec, DraftDTO, RunDTO, RunSnapshot } from '../types' +import { request, queryString, removeRecord } from './client' +import { durable } from './durable' + +export const workflowsApi = { + deleteWorkflow: (id: string, version?: number) => + removeRecord(`/workflows/${encodeURIComponent(id)}`, version), + deleteRun: (id: string, version?: number) => + removeRecord(`/workflow-runs/${encodeURIComponent(id)}`, version), + workflows: (filters: Record = {}) => + request>(`/workflows${queryString(filters)}`), + workflow: (id: string) => request(`/workflows/${id}`), + createWorkflow: (name: string, spec: WorkflowSpec, folder_id?: string | null) => + request('/workflows', { + method: 'POST', + body: JSON.stringify({ + name, + spec, + ...(folder_id !== undefined ? { folder_id } : {}), + kind: spec.schema_version === 1 ? 'three_shot' : 'multi_shot', + }), + }), + saveWorkflow: (draft: DraftDTO, name: string, spec: WorkflowSpec, folder_id?: string | null) => + request(`/workflows/${draft.id}`, { + method: 'PATCH', + headers: { 'If-Match': String(draft.version) }, + body: JSON.stringify({ name, spec, ...(folder_id !== undefined ? { folder_id } : {}) }), + }), + startRun: ( + draft: DraftDTO, + execution_mode = 'interactive', + reuse_run_id?: string, + output_folder_id?: string | null, + ) => + durable('workflow.run', `/workflows/${draft.id}/runs`, { + ...(output_folder_id !== undefined ? { output_folder_id } : {}), + draft_revision: draft.revision, + expected_version: draft.version, + execution_mode, + ...(reuse_run_id ? { reuse_run_id } : {}), + }), + runs: (filters: Record = {}) => + request>(`/workflow-runs${queryString(filters)}`), + run: (id: string) => request(`/workflow-runs/${id}`), + controlRun: (run: RunDTO, action: 'pause' | 'resume' | 'cancel') => + durable(`workflow.${action}`, `/workflow-runs/${run.id}/${action}`, { + expected_version: run.version, + }), + retryStep: (run: RunDTO, key: string, jobId: string) => + durable('workflow.retry', `/workflow-runs/${run.id}/steps/${key}/retry`, { + expected_run_version: run.version, + target_job_id: jobId, + }), +} diff --git a/frontend/src/architecture.test.ts b/frontend/src/architecture.test.ts new file mode 100644 index 0000000..adb5252 --- /dev/null +++ b/frontend/src/architecture.test.ts @@ -0,0 +1,83 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createPinia, setActivePinia } from 'pinia' +import { useJobsStore } from './stores/jobs' + +const modules = import.meta.glob>([ + './api/index.ts', + './api/client.ts', + './domain/workflows/timeline.ts', + './domain/creation/videoDuration.ts', + './domain/creation/taskForms.ts', + './types/*.ts', +]) +async function load(path: string) { + expect(modules[path], `缺少规范模块入口 ${path}`).toBeTypeOf('function') + return modules[path]!() +} +beforeEach(() => setActivePinia(createPinia())) +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +describe('canonical frontend module boundaries', () => { + it('keeps stores on the single API facade so method replacement drives real reconciliation', async () => { + const { api } = await load('./api/index.ts') + vi.spyOn(api, 'jobs').mockResolvedValue({ + items: [], + cursor: 71, + total: 0, + page: 1, + page_size: 48, + }) + const store = useJobsStore() + await store.refresh() + expect(store.cursor).toBe(71) + expect(store.loaded).toBe(true) + }) + + it('shares one CSRF transport between the public client and domain endpoints', async () => { + const { api } = await load('./api/index.ts') + const client = await load('./api/client.ts') + client.setCsrfToken('contract-csrf') + const fetcher = vi.fn().mockResolvedValue({ ok: true, status: 204 }) + vi.stubGlobal('fetch', fetcher) + await api.deleteAsset('asset/one') + expect(fetcher.mock.calls[0]?.[0]).toBe('/api/assets/asset%2Fone') + expect(fetcher.mock.calls[0]?.[1].headers.get('X-CSRF-Token')).toBe('contract-csrf') + expect(fetcher.mock.calls[0]?.[1].credentials).toBe('include') + }) + + it('exposes native duration and timeline rules independently from transport', async () => { + const timeline = await load('./domain/workflows/timeline.ts') + const video = await load('./domain/creation/videoDuration.ts') + const tools = await load('./domain/creation/taskForms.ts') + const spec = timeline.emptyWorkflow() + spec.shots.forEach((shot: any, index: number) => { + shot.prompt = 'scene' + shot.duration_frames = [120, 240, 360][index] + }) + spec.render.total_frames = 720 + expect(() => timeline.validateWorkflow(spec)).not.toThrow() + expect(timeline.workflowFrames(spec)).toBe(720) + expect( + video.videoParameters( + { num_frames: 361, fps: 24 }, + { constraints: { num_frames: { min: 5, max: 361, step: 4 } }, defaults: {} }, + ), + ).toEqual({ num_frames: 361, fps: 24 }) + expect( + tools.buildToolRequest('audio.speech', ' hello ', { + voice: 'voice', + speed: 1, + frame_count: 8, + }).parameters, + ).toEqual({ voice: 'voice', speed: 1 }) + }) + + it('keeps DTO modules free of runtime rules and state', async () => { + const dtoPaths = Object.keys(modules).filter((path) => path.startsWith('./types')) + expect(dtoPaths.length).toBeGreaterThan(1) + for (const path of dtoPaths) expect(Object.keys(await load(path))).toEqual([]) + }) +}) diff --git a/frontend/src/components/AssetInput.vue b/frontend/src/components/AssetInput.vue index 9cd6375..a2a2006 100644 --- a/frontend/src/components/AssetInput.vue +++ b/frontend/src/components/AssetInput.vue @@ -1,38 +1,127 @@ diff --git a/frontend/src/components/AssetLifecycle.test.ts b/frontend/src/components/AssetLifecycle.test.ts index 6d0c611..0897044 100644 --- a/frontend/src/components/AssetLifecycle.test.ts +++ b/frontend/src/components/AssetLifecycle.test.ts @@ -1,74 +1,236 @@ -import {afterEach,beforeEach,describe,expect,it,vi} from 'vitest' -import {createRenderer,h,nextTick,shallowRef,ssrContextKey} from 'vue' -import {createPinia,setActivePinia} from 'pinia' -import {createMemoryHistory,createRouter} from 'vue-router' -import {ElMessage} from 'element-plus' -import {api,ApiError} from '../api' -import {useAssetsStore} from '../stores/assets' -import {useJobsStore} from '../stores/jobs' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createRenderer, h, nextTick, shallowRef, ssrContextKey } from 'vue' +import { createPinia, setActivePinia } from 'pinia' +import { createMemoryHistory, createRouter } from 'vue-router' +import { ElMessage } from 'element-plus' +import { api, ApiError } from '../api' +import { useAssetsStore } from '../stores/assets' +import { useJobsStore } from '../stores/jobs' import AssetPicker from './AssetPicker.vue' import AssetPreview from './AssetPreview.vue' -import type {Asset,Job} from '../types' +import type { Asset, Job } from '../types' -const asset:Asset={id:'frame',name:'frame',kind:'image',mime_type:'image/png',size_bytes:4,width:1,height:1,duration_seconds:null,preview_url:'/frame',thumbnail_url:null,download_url:'/frame',source_job_id:'source-job',origin:'generated',tags:[],favorite:false,created_at:'2026-11-11T00:00:00Z'} -const source:Job={id:'source-job',version:1,task_type:'image.generate',state:'succeeded',phase:'completed',prompt:'frame',parameters:{},input_asset_ids:[],result_assets:[asset],result:null,progress:null,queue_position:null,upstream_id:null,attempt_count:1,preemptions:0,last_preempted_reason:null,cancel_requested:false,error:null,sync_warning:null,created_at:'2026-11-11T00:00:00Z',scheduled_at:null,started_at:null,finished_at:null} -const mounted:{unmount:()=>void}[]=[] -async function setupComponent(component:any,initialProps:Record){ - const renderer=createRenderer({createElement:()=>({}),createText:()=>({}),createComment:()=>({}),setText(){},setElementText(){},parentNode:()=>null,nextSibling:()=>null,patchProp(){},insert(){},remove(){}}) - const pinia=createPinia();setActivePinia(pinia);const props=shallowRef(initialProps);let bindings:any - const wrapped={...component,setup(p:any,context:any){bindings=component.setup(p,context);return()=>h('section')}} - const router=createRouter({history:createMemoryHistory(),routes:[{path:'/',component:{render:()=>null}}]});await router.push('/') - const app=renderer.createApp({render:()=>h(wrapped,props.value)});app.use(pinia);app.use(router);app.provide(ssrContextKey,{modules:new Set()});app.mount({});mounted.push(app) - return {bindings,pinia,update:async(next:Record)=>{props.value={...props.value,...next};await nextTick()}} +const asset: Asset = { + id: 'frame', + name: 'frame', + kind: 'image', + mime_type: 'image/png', + size_bytes: 4, + width: 1, + height: 1, + duration_seconds: null, + preview_url: '/frame', + thumbnail_url: null, + download_url: '/frame', + source_job_id: 'source-job', + origin: 'generated', + tags: [], + favorite: false, + created_at: '2026-11-11T00:00:00Z', +} +const source: Job = { + id: 'source-job', + version: 1, + task_type: 'image.generate', + state: 'succeeded', + phase: 'completed', + prompt: 'frame', + parameters: {}, + input_asset_ids: [], + result_assets: [asset], + result: null, + progress: null, + queue_position: null, + upstream_id: null, + attempt_count: 1, + preemptions: 0, + last_preempted_reason: null, + cancel_requested: false, + error: null, + sync_warning: null, + created_at: '2026-11-11T00:00:00Z', + scheduled_at: null, + started_at: null, + finished_at: null, +} +const mounted: { unmount: () => void }[] = [] +async function setupComponent(component: any, initialProps: Record) { + const renderer = createRenderer({ + createElement: () => ({}), + createText: () => ({}), + createComment: () => ({}), + setText() {}, + setElementText() {}, + parentNode: () => null, + nextSibling: () => null, + patchProp() {}, + insert() {}, + remove() {}, + }) + const pinia = createPinia() + setActivePinia(pinia) + const props = shallowRef(initialProps) + let bindings: any + const wrapped = { + ...component, + setup(p: any, context: any) { + bindings = component.setup(p, context) + return () => h('section') + }, + } + const router = createRouter({ + history: createMemoryHistory(), + routes: [{ path: '/', component: { render: () => null } }], + }) + await router.push('/') + const app = renderer.createApp({ render: () => h(wrapped, props.value) }) + app.use(pinia) + app.use(router) + app.provide(ssrContextKey, { modules: new Set() }) + app.mount({}) + mounted.push(app) + return { + bindings, + pinia, + update: async (next: Record) => { + props.value = { ...props.value, ...next } + await nextTick() + }, + } +} +async function settle() { + await Promise.resolve() + await nextTick() + await Promise.resolve() + await nextTick() } -async function settle(){await Promise.resolve();await nextTick();await Promise.resolve();await nextTick()} class Source { - static current:Source - onopen=null;onerror=null;listeners:Recordvoid>={} - constructor(){Source.current=this} - addEventListener(name:string,listener:(event:any)=>void){this.listeners[name]=listener} - close(){} + static current: Source + onopen = null + onerror = null + listeners: Record void> = {} + constructor() { + Source.current = this + } + addEventListener(name: string, listener: (event: any) => void) { + this.listeners[name] = listener + } + close() {} } -beforeEach(()=>{vi.spyOn(ElMessage,'error').mockImplementation(()=>({close(){}}) as any)}) -afterEach(()=>{mounted.splice(0).forEach(app=>app.unmount());vi.restoreAllMocks();vi.unstubAllGlobals()}) +beforeEach(() => { + vi.spyOn(ElMessage, 'error').mockImplementation(() => ({ close() {} }) as any) +}) +afterEach(() => { + mounted.splice(0).forEach((app) => app.unmount()) + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) -describe('asset preview source availability',()=>{ - it('hides a source link immediately when its job is archived in this session',async()=>{ - vi.spyOn(api,'job').mockResolvedValue(source) - const view=await setupComponent(AssetPreview,{asset});await settle() - expect(view.bindings.sourceAvailable?.value).toBe(true) - useJobsStore(view.pinia).forget(source.id);await settle() - expect(view.bindings.sourceAvailable?.value).toBe(false) - }) - it('silently omits an archived source after reloading with no local tombstone',async()=>{ - const request=vi.spyOn(api,'job').mockRejectedValue(new ApiError('job_not_found','任务不存在',404)) - const view=await setupComponent(AssetPreview,{asset});await settle() - expect(request).toHaveBeenCalledExactlyOnceWith('source-job') - expect(view.bindings.sourceAvailable?.value).toBe(false);expect(ElMessage.error).not.toHaveBeenCalled() - }) - it('does not let an old asset source response enable the link for a different asset',async()=>{ - let resolve!:(value:Job)=>void - vi.spyOn(api,'job').mockImplementationOnce(()=>new Promise(r=>resolve=r)).mockRejectedValue(new ApiError('job_not_found','任务不存在',404)) - const view=await setupComponent(AssetPreview,{asset});await view.update({asset:{...asset,id:'other-frame',source_job_id:'other-job'}});await settle() - resolve(source);await settle() - expect(view.bindings.sourceAvailable?.value).toBe(false);expect(ElMessage.error).not.toHaveBeenCalled() - }) - it('rejects a source availability response after the user session changes',async()=>{ - let resolve!:(value:Job)=>void;vi.spyOn(api,'job').mockImplementation(()=>new Promise(r=>resolve=r)) - const view=await setupComponent(AssetPreview,{asset});useAssetsStore(view.pinia).clear();resolve(source);await settle() - expect(view.bindings.sourceAvailable?.value).toBe(false);expect(ElMessage.error).not.toHaveBeenCalled() - }) +describe('asset preview source availability', () => { + it('hides a source link immediately when its job is archived in this session', async () => { + vi.spyOn(api, 'job').mockResolvedValue(source) + const view = await setupComponent(AssetPreview, { asset }) + await settle() + expect(view.bindings.sourceAvailable?.value).toBe(true) + useJobsStore(view.pinia).forget(source.id) + await settle() + expect(view.bindings.sourceAvailable?.value).toBe(false) + }) + it('silently omits an archived source after reloading with no local tombstone', async () => { + const request = vi + .spyOn(api, 'job') + .mockRejectedValue(new ApiError('job_not_found', '任务不存在', 404)) + const view = await setupComponent(AssetPreview, { asset }) + await settle() + expect(request).toHaveBeenCalledExactlyOnceWith('source-job') + expect(view.bindings.sourceAvailable?.value).toBe(false) + expect(ElMessage.error).not.toHaveBeenCalled() + }) + it('does not let an old asset source response enable the link for a different asset', async () => { + let resolve!: (value: Job) => void + vi.spyOn(api, 'job') + .mockImplementationOnce(() => new Promise((r) => (resolve = r))) + .mockRejectedValue(new ApiError('job_not_found', '任务不存在', 404)) + const view = await setupComponent(AssetPreview, { asset }) + await view.update({ asset: { ...asset, id: 'other-frame', source_job_id: 'other-job' } }) + await settle() + resolve(source) + await settle() + expect(view.bindings.sourceAvailable?.value).toBe(false) + expect(ElMessage.error).not.toHaveBeenCalled() + }) + it('rejects a source availability response after the user session changes', async () => { + let resolve!: (value: Job) => void + vi.spyOn(api, 'job').mockImplementation(() => new Promise((r) => (resolve = r))) + const view = await setupComponent(AssetPreview, { asset }) + useAssetsStore(view.pinia).clear() + resolve(source) + await settle() + expect(view.bindings.sourceAvailable?.value).toBe(false) + expect(ElMessage.error).not.toHaveBeenCalled() + }) }) -describe('open private material picker',()=>{ - it('removes an SSE-deleted asset from its visible items while retaining selectable surviving items',async()=>{ - const surviving={...asset,id:'surviving',name:'surviving'},selected:Asset[]=[] - vi.spyOn(api,'assets').mockResolvedValue({items:[asset,surviving],total:2,page:1,page_size:12}) - const view=await setupComponent(AssetPicker,{modelValue:true,onSelect:(value:Asset)=>selected.push(value)});await settle() - expect(view.bindings.items.value.map((value:Asset)=>value.id)).toEqual(['frame','surviving']) - vi.stubGlobal('EventSource',Source);vi.spyOn(api,'jobs').mockResolvedValue({items:[],cursor:4,total:0,page:1,page_size:48}) - const jobs=useJobsStore(view.pinia);await jobs.connect() - Source.current.listeners['asset.deleted']!({data:JSON.stringify({id:'frame'}),lastEventId:'5'});await settle() - expect(view.bindings.items.value.map((value:Asset)=>value.id)).toEqual(['surviving']) - view.bindings.choose(surviving);expect(selected).toEqual([surviving]);jobs.reset() - }) +describe('open private material picker', () => { + it('does not deliver a previous opening upload into a newly opened picker target', async () => { + const selected: Asset[] = [] + vi.spyOn(api, 'assets').mockResolvedValue({ items: [], total: 0, page: 1, page_size: 12 }) + const view = await setupComponent(AssetPicker, { + modelValue: true, + onSelect: (value: Asset) => selected.push(value), + }) + let resolve!: (value: Asset) => void + vi.spyOn(useAssetsStore(view.pinia), 'upload').mockImplementation( + () => new Promise((r) => (resolve = r)), + ) + const upload = view.bindings.upload({ target: { files: [{}], value: 'file' } }) + await view.update({ modelValue: false }) + await view.update({ modelValue: true }) + resolve(asset) + await upload + expect(selected).toEqual([]) + }) + it('removes an SSE-deleted asset from its visible items while retaining selectable surviving items', async () => { + const surviving = { ...asset, id: 'surviving', name: 'surviving' }, + selected: Asset[] = [] + vi.spyOn(api, 'assets').mockResolvedValue({ + items: [asset, surviving], + total: 2, + page: 1, + page_size: 12, + }) + const view = await setupComponent(AssetPicker, { + modelValue: true, + onSelect: (value: Asset) => selected.push(value), + }) + await settle() + expect(view.bindings.items.value.map((value: Asset) => value.id)).toEqual([ + 'frame', + 'surviving', + ]) + vi.stubGlobal('EventSource', Source) + vi.spyOn(api, 'jobs').mockResolvedValue({ + items: [], + cursor: 4, + total: 0, + page: 1, + page_size: 48, + }) + const jobs = useJobsStore(view.pinia) + await jobs.connect() + Source.current.listeners['asset.deleted']!({ + data: JSON.stringify({ id: 'frame' }), + lastEventId: '5', + }) + await settle() + expect(view.bindings.items.value.map((value: Asset) => value.id)).toEqual(['surviving']) + view.bindings.choose(surviving) + expect(selected).toEqual([surviving]) + jobs.reset() + }) +}) +it('keeps explicit unclassified picker context distinct from browsing all', async () => { + vi.spyOn(api, 'assets').mockResolvedValue({ items: [], total: 0, page: 1, page_size: 12 }) + const view = await setupComponent(AssetPicker, { modelValue: true, folderId: null }) + await Promise.resolve() + expect(vi.mocked(api.assets).mock.calls.at(-1)?.[0]).toMatchObject({ folder_id: 'unclassified' }) }) diff --git a/frontend/src/components/AssetPicker.vue b/frontend/src/components/AssetPicker.vue index 2dca90a..19211bc 100644 --- a/frontend/src/components/AssetPicker.vue +++ b/frontend/src/components/AssetPicker.vue @@ -1,59 +1,228 @@