feat: deliver persistent multimodal workflows and night queues

This commit is contained in:
Codex 2026-11-10 23:56:50 +08:00
parent 9b6a6a4bd5
commit 373e7e2250
165 changed files with 12825 additions and 178 deletions

View File

@ -10,6 +10,18 @@ ADMIN_DISPLAY_NAME=管理员
ADMIN_PASSWORD=
# Set true behind public HTTPS. False is only for loopback HTTP/SSH preview.
COOKIE_SECURE=false
PUBLIC_ACCESS=false
MAX_INTERACTIVE_GPU_JOBS=8
MAX_CREATION_COMMANDS_PER_MINUTE=6
MAX_OWNER_JOBS=500
MAX_GLOBAL_JOBS=2000
MAX_OWNER_RUNS=100
MAX_GLOBAL_RUNS=1000
MAX_OWNER_BATCHES=20
MAX_GLOBAL_BATCHES=200
MAX_OWNER_ASSET_BYTES=107374182400
MAX_DATA_BYTES=2199023255552
MIN_FREE_BYTES=53687091200
TTS_API_KEY=
WORKSPACE_HOST=/data/llmusers/llmuser/workspace
WEB_PORT=18193

1
.gitignore vendored
View File

@ -18,3 +18,4 @@
/.deploy/
/.cache-models/
/.local/
/qa/generated/

View File

@ -5,18 +5,22 @@
## 当前交付状态
- 工程目录:`E:\workspace\hybrid\cmvr-visual`;服务器源码目录:`/workspace/projects/cmvr-visual`。
- 已连接用户指定的正式数据库 `192.168.28.10:3306/cmvr-visual`,按本次要求暂用 root;创建六张本应用 `visual_*` 表和默认网站管理员。`/api/system/status` 返回 `environment=production`、`database_backend=mysql`。
- 默认管理员为 `admin`,初始密码按用户指定的本次私有配置设置;初始管理员支持六位密码,普通用户创建仍要求12位以上。重启不会重置已有密码。后续补账号维护、改密与专用数据库账号,详见复核方案。
- 已连接用户指定的正式数据库 `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 隧道本地访问;不直接向局域网或互联网公开。
执行结果以实际验收记录及接口状态为准。单元测试、模拟上游边界和构建成功分别验证各自范围,不等同于真实模型生成或正式数据库验收。
本轮交付见 [V2开发与验收记录](docs/V2开发与验收记录_20261110.md):默认规格真实三镜头成片、窗口/队列、迁移恢复及当前公开发布边界均有单独记录。
历史功能基线见 [验收报告](docs/验收报告.md):75项自动化测试、八类真实服务调用及桌面/手机验证。正式库接入后新增初始账号回归,后端52项通过;[实际接入记录](qa/mysql-integration-20261110.json)验证正式库登录、读写与SSE。
最新 [需求复核与落地方案](docs/需求复核与落地方案_20261110.md) 已纳入用户确认的“三分镜合成15秒”和“交互全天/批量夜间”。这两项与审计修复仍为待实施计划;当前视频生成单任务仍约5秒,调度仍只有单次预约。
V2 增加三分镜工作流、夜间批量、持久草稿、提交恢复、父子任务事件、版本锁和资源阶段。三镜头各取120帧,输出360帧/24fps的15秒多镜头成片;单模型原生视频任务仍约5秒。设计见 [实施方案V2](docs/实施方案V2_20261110.md)。
二次可实施性复审见 [实施方案V2](docs/实施方案V2_20261110.md) 和 [12项执行计划](docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md):补齐上游协议、执行代次、分镜依赖、夜间停止确认、批次/资源阶段、时间轴、迁移与恢复。V2尚未实施,Qwen批量须先验证单请求停止能力。
批量计算窗口为北京时间21:00–08:00。全天接受并持久保存任务;08:00关闭新镜头/新处理阶段准入,当前已执行阶段自然完成,后续排队。Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源。关闭浏览器、SSE或HTTP连接不会取消持久任务,更不会停止共享Qwen服务。显式取消已发出的Qwen/Kokoro请求时等待当前响应再丢弃结果;完成状态未知则隔离本应用相应资源池,等待运维对账。
初始额度:每用户未结束叶任务500、全局2000;每用户未结束Run100、Batch20,全局Run1000、Batch200;每批最多100项。创建Job/Run/Batch共用每用户每分钟6次命令额度,内部子步骤不重复扣命令数,原键重放不扣额。所有数字可通过配置调整。
## 八项能力与实际限制
@ -46,7 +50,7 @@ Nginx → FastAPI 业务 API → MySQL visual_* 表
└─ CPU FFmpeg / 独立 CPU Kokoro
```
`frontend/` 为界面;`backend/app/` 为账号、素材、任务、事件和协调器;`providers.py`、`media.py` 为数据库无关的模型与媒体适配;`tts/` 为 CPU 配音服务;`deploy/`、`compose.yaml` 为部署文件;[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。
`frontend/` 为界面;`backend/app/` 为账号、素材、任务、工作流和协调器;`backend/alembic/` 为迁移;`inference/` 保存既有唯一GPU服务的版本化源码;`tts/` 为CPU配音;`deploy/`、`compose.yaml` 为部署文件。[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。
任务提交是短 HTTP 请求,长任务通过 SSE 单向通知浏览器,不需要双向 WebSocket。事件先和数据库状态一起提交;`Last-Event-ID` 用于重连重放,Cookie 使原生 EventSource 无需把令牌放进 URL。SSE 断开不会取消生成,重连后还会重新获取 HTTP 状态快照。[SSE 标准](https://html.spec.whatwg.org/multipage/server-sent-events.html)
@ -71,7 +75,7 @@ Nginx → FastAPI 业务 API → MySQL visual_* 表
用户只提交素材 ID;服务器校验 owner 后解析共享工作区路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。被任务引用的已删除输入仍保留物理文件。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。
API 和 TTS 容器不挂 GPU、宿主 `/proc`、Docker socket,不使用 privileged;根文件系统只读,工作数据只写入配置的工作区。现有 GPU 权重、模型队列、守护与其他用户服务**不由此工程重新部署**。
API 和 TTS 容器不挂GPU、宿主`/proc`或Docker socket,根文件系统只读;API仅挂本应用数据、只读模型认证和调度状态目录。模型权重不随网站镜像打包。`inference/` 的更新部署到既有模型服务路径,保留原队列和监管,不启动第二个GPU worker,不修改共享Qwen容器。
## 本地开发
@ -125,7 +129,15 @@ pnpm build
私有 `.env` 至少配置 `CMVR_MODE=production`、`MYSQL_HOST`、`MYSQL_PORT`、`MYSQL_DATABASE`、`MYSQL_USER`、`MYSQL_PASSWORD` 及管理员初始化信息。推荐这些分离字段,后端用 `URL.create` 处理数据库名与密码特殊字符;不要手工拼接连接串。正式库不可达时启动失败,不会切换 SQLite。
应用仅创建以下表:`visual_users`、`visual_sessions`、`visual_assets`、`visual_jobs`、`visual_job_assets`、`visual_job_events`。当前启动使用 `create_all`,**没有自动迁移工具**:它不会删除现有数据,也不会替已有表添加新字段。升级前备份并审查 schema 差异,在独立库演练迁移;不能靠删表、删库或清队列解决字段不一致。
现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold。生产启动要求003,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行:
```bash
# 仅匹配的、尚未版本化的旧六表数据库执行一次:
python ../scripts/schema_preflight.py --stamp-legacy
alembic -c alembic.ini upgrade head
```
空库直接`upgrade head`。已有003库无需stamp。迁移不提供破坏性downgrade;MySQL DDL可能已提交,失败时保持维护并使用已演练的联合恢复点或修复迁移。
## Docker Compose 启动
@ -193,7 +205,7 @@ ssh -N -L 127.0.0.1:18193:127.0.0.1:18193 root@192.168.28.10
## 备份与排查
备份必须包含正式库中的 `visual_*` 表、`/workspace/cmvr-visual/assets`、`jobs` 和 `state`;后两者含持久请求引用的预处理输入。秘密配置单独安全保管。网站备份不包含 GPU 模型权重或上游队列,相关结果保留策略由既有模型服务管理。
联合备份应先关闭新计算准入、等待本应用活动任务完成,再停止自己的协调器和模型worker。保存本应用数据库(含Alembic版本)、assets/jobs/state、上游SQLite backup及必要模型输出/manifest,记录同一checkpoint和校验值;秘密配置单独保护,模型权重无需重复打包。恢复后先核对上游ID和执行代次,再开放计算。
使用 DBA 的受保护客户端配置文件,不把密码作为命令参数。以下仅为备份步骤示例,需先准备兼容的 MySQL 客户端及安全目录:
@ -202,7 +214,7 @@ docker compose stop api
# /secure/cmvr-visual-backup.cnf 由运维安全创建,权限600,不属于源码。
mysqldump --defaults-extra-file=/secure/cmvr-visual-backup.cnf \
--single-transaction --no-tablespaces --set-gtid-purged=OFF \
cmvr-visual visual_users visual_sessions visual_jobs visual_assets visual_job_assets visual_job_events \
cmvr-visual \
> /secure/backups/cmvr-visual.sql
tar -czf /secure/backups/cmvr-visual-files.tar.gz \
-C /data/llmusers/llmuser/workspace/cmvr-visual assets jobs state
@ -218,3 +230,6 @@ docker compose up -d api
- collecting:推理已完成,正在归档;当前不再接受新的取消。归档之前已提交的取消仍有事务优先保护。
- SSE 不更新:检查外层代理缓冲/超时、会话是否有效,重新获取 HTTP 快照;不要为了重连再次生成。
- `stale`/上游执行器异常:检查日志并交运维确认,不能删除数据库、锁或守护状态强制运行。
- `/api/live` 为进程活性,`/api/ready` 检查数据库、协调器心跳、上游协议与维护状态;GPU繁忙不判为应用故障。
- 公网发布前在私有入口改掉初始管理员密码、改用本库专用MySQL业务账号,再配置HTTPS、`COOKIE_SECURE=true`和`PUBLIC_ACCESS=true`;服务端拒绝公开运行仍使用初始密码或MySQL root的配置。当前私有验收保持用户指定的数据库root配置。Nginx登录入口已有限流,不信任客户端任意X-Forwarded-For。
- `needs_attention`或未知HTTP执行需要运维确认远端请求已结束;不能仅清除数据库状态来恢复,更不能重启共享Qwen服务作为处理办法。

View File

@ -1,9 +1,11 @@
FROM python:3.12-slim
FROM python:3.12-slim@sha256:5e2bdb1b0d542d5039cffb8181c65930093949194a65c365dfb1b0fe13a4fa5b
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_NO_CACHE_DIR=1
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-noto-cjk && rm -rf /var/lib/apt/lists/*
WORKDIR /opt/app
COPY requirements.txt ./requirements.txt
RUN pip install -r requirements.txt
COPY requirements.lock ./requirements.lock
RUN pip install -r requirements.lock
COPY app ./app
COPY alembic.ini ./alembic.ini
COPY alembic ./alembic
USER 1013:1014
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--timeout-graceful-shutdown", "20"]

4
backend/alembic.ini Normal file
View File

@ -0,0 +1,4 @@
[alembic]
script_location = %(here)s/alembic
path_separator = os
prepend_sys_path = %(here)s

26
backend/alembic/env.py Normal file
View File

@ -0,0 +1,26 @@
import asyncio,os
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
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()
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)
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())

View File

@ -0,0 +1,120 @@
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")
def utcnow():
return datetime.now(timezone.utc).replace(tzinfo=None)
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)
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")
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 Job(Base):
__tablename__ = "visual_jobs"
__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)
owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True)
task_type: Mapped[str] = mapped_column(String(48))
state: Mapped[str] = mapped_column(String(24))
phase: Mapped[str] = mapped_column(String(48))
version: Mapped[int] = mapped_column(Integer, default=1)
input_json: Mapped[dict] = mapped_column(JSON)
parameters: Mapped[dict] = mapped_column(JSON)
request_key: Mapped[str | None] = mapped_column(String(128), nullable=True)
request_hash: Mapped[str] = mapped_column(String(64))
batch_index: Mapped[int] = mapped_column(Integer, default=0)
upstream_key: Mapped[str] = mapped_column(String(128), unique=True)
upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True, unique=True)
upstream_payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
upstream_result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
cancel_requested: Mapped[bool] = mapped_column(Boolean, default=False)
attempt_count: Mapped[int] = mapped_column(Integer, default=0)
work_attempt: Mapped[int] = mapped_column(Integer, default=0)
preemptions: Mapped[int] = mapped_column(Integer, default=0)
last_preempted_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
sync_warning: Mapped[str | None] = mapped_column(String(512), nullable=True)
sync_failures: Mapped[int] = mapped_column(Integer, default=0)
next_action_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True)
scheduled_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
class JobAsset(Base):
__tablename__ = "visual_job_assets"
job_id: Mapped[str] = mapped_column(ForeignKey("visual_jobs.id"), primary_key=True)
asset_id: Mapped[str] = mapped_column(ForeignKey("visual_assets.id"), primary_key=True)
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)
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)

View File

@ -0,0 +1,154 @@
from datetime import datetime
from sqlalchemy import String, Integer, JSON, ForeignKey, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from frozen_v2_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)
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)
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"
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)
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))

View File

@ -0,0 +1,132 @@
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")
def utcnow():
return datetime.now(timezone.utc).replace(tzinfo=None)
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")
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 Job(Base):
__tablename__ = "visual_jobs"
__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)
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")
policy_version: Mapped[str] = mapped_column(String(32), default="night-v1")
run_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
step_key: Mapped[str | None] = mapped_column(String(32), nullable=True)
batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
batch_item_index: Mapped[int | None] = mapped_column(Integer, nullable=True)
explicit_attempt: Mapped[int] = mapped_column(Integer, default=1)
desired_state: Mapped[str] = mapped_column(String(16), default="run")
hold_reasons: Mapped[list] = mapped_column(JSON, default=list)
current_execution_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
admitted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
state: Mapped[str] = mapped_column(String(24))
phase: Mapped[str] = mapped_column(String(48))
version: Mapped[int] = mapped_column(Integer, default=1)
input_json: Mapped[dict] = mapped_column(JSON)
parameters: Mapped[dict] = mapped_column(JSON)
request_key: Mapped[str | None] = mapped_column(String(128), nullable=True)
request_hash: Mapped[str] = mapped_column(String(64))
batch_index: Mapped[int] = mapped_column(Integer, default=0)
upstream_key: Mapped[str] = mapped_column(String(128), unique=True)
upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True, unique=True)
upstream_payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
upstream_result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
cancel_requested: Mapped[bool] = mapped_column(Boolean, default=False)
attempt_count: Mapped[int] = mapped_column(Integer, default=0)
work_attempt: Mapped[int] = mapped_column(Integer, default=0)
preemptions: Mapped[int] = mapped_column(Integer, default=0)
last_preempted_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
sync_warning: Mapped[str | None] = mapped_column(String(512), nullable=True)
sync_failures: Mapped[int] = mapped_column(Integer, default=0)
next_action_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True)
scheduled_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
class JobAsset(Base):
__tablename__ = "visual_job_assets"
job_id: Mapped[str] = mapped_column(ForeignKey("visual_jobs.id"), primary_key=True)
asset_id: Mapped[str] = mapped_column(ForeignKey("visual_assets.id"), primary_key=True)
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)
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)

View File

@ -0,0 +1,16 @@
"""Frozen six-table legacy baseline; existing databases must pass schema_preflight before stamp."""
from alembic import op
import importlib.util
from pathlib import Path
revision="001"
down_revision=None
branch_labels=None
depends_on=None
def metadata():
spec=importlib.util.spec_from_file_location("legacy_schema",Path(__file__).parents[1]/"legacy_schema.py")
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
return module.Base.metadata
def upgrade():metadata().create_all(op.get_bind(),checkfirst=False)
def downgrade():raise RuntimeError("Destructive downgrade is unsupported; restore a verified checkpoint")

View File

@ -0,0 +1,43 @@
"""Additive V2 schema, frozen independently of runtime application models."""
from alembic import op
import sqlalchemy as sa
import importlib.util,sys
from pathlib import Path
revision="002"
down_revision="001"
branch_labels=None
depends_on=None
def metadata():
for name,file in [("frozen_v2_models","v2_schema_models.py"),("frozen_v2_schema","v2_schema.py")]:
spec=importlib.util.spec_from_file_location(name,Path(__file__).parents[1]/file)
module=importlib.util.module_from_spec(spec);sys.modules[name]=module;spec.loader.exec_module(module)
return sys.modules["frozen_v2_models"].Base.metadata
def upgrade():
bind=op.get_bind();meta=metadata()
# All new fields have explicit server backfill defaults, including historical jobs.
defaults={"must_change_password":sa.false(),"execution_mode":"interactive","policy_version":"night-v1","explicit_attempt":"1","desired_state":"run","hold_reasons":"[]"}
inspector=sa.inspect(bind)
for name in ["visual_users","visual_jobs"]:
existing={col["name"] for col in inspector.get_columns(name)}
for column in meta.tables[name].columns:
if column.name not in existing:
copied=column._copy()
if column.name in defaults:
value=sa.text("('[]')") if column.name=="hold_reasons" and bind.dialect.name=="mysql" else defaults[column.name]
copied.server_default=sa.DefaultClause(value)
op.add_column(name,copied)
existing=set(inspector.get_table_names())
meta.create_all(bind,tables=[table for table in meta.sorted_tables if table.name not in existing],checkfirst=False)
# Preserve searchable historical JSON tags while switching pagination to SQL.
import uuid
assets=meta.tables["visual_assets"];tags=meta.tables["visual_asset_tags"]
present={(row.asset_id,row.tag) for row in bind.execute(sa.select(tags.c.asset_id,tags.c.tag))}
for row in bind.execute(sa.select(assets.c.id,assets.c.owner_id,assets.c.tags)):
for tag in row.tags or []:
if isinstance(tag,str) and (row.id,tag) not in present:
bind.execute(tags.insert().values(id=uuid.uuid4().hex,owner_id=row.owner_id,asset_id=row.id,tag=tag))
present.add((row.id,tag))
def downgrade():raise RuntimeError("Destructive downgrade is unsupported; restore a verified checkpoint")

View File

@ -0,0 +1,15 @@
"""Persist administrative batch holds independently of user intent."""
from alembic import op
import sqlalchemy as sa
revision="003"
down_revision="002"
branch_labels=None
depends_on=None
def upgrade():
bind=op.get_bind()
if "hold_reasons" not in {col["name"] for col in sa.inspect(bind).get_columns("visual_batches")}:
default=sa.text("('[]')") if bind.dialect.name=="mysql" else "[]"
op.add_column("visual_batches",sa.Column("hold_reasons",sa.JSON(),nullable=False,server_default=default))
def downgrade():raise RuntimeError("Destructive downgrade unsupported")

View File

@ -0,0 +1,68 @@
"""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

43
backend/app/artifacts.py Normal file
View File

@ -0,0 +1,43 @@
"""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":[]}

View File

@ -9,7 +9,7 @@ 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 func, select
from sqlalchemy import delete, func, select
from starlette.background import BackgroundTask
from .auth import Actor, csrf_actor, current_actor
from .dto import asset_dto
@ -47,7 +47,7 @@ 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.ready.is_(True))
if not include_deleted:
query = query.where(Asset.deleted_at.is_(None))
asset = await session.scalar(query)
asset = await session.scalar(query.with_for_update())
if asset is None:
fail(404, "asset_not_found", "素材不存在")
return asset
@ -80,14 +80,30 @@ async def build_asset(settings, owner_id, asset_id, path, name, **fields):
duration_seconds=metadata.get("duration_seconds"), tags=[], favorite=False, **fields)
async def import_output(db, settings, job, source, index):
async def import_output(db, settings, job, source, index, *, execution_fence=None):
async with db.session() as session:
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
Asset.source_output_index == index))
if existing:
if execution_fence:
from .v2_models import AssetReference
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==existing.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==execution_fence["execution_id"]))
if not binding:raise ValueError("Output belongs to a different execution")
from .artifacts import digest_file
path=confined(settings.asset_root,existing.storage_key,exists=True)
with safe_file(settings.asset_root,path):pass
if path.stat().st_size!=existing.size_bytes or digest_file(path)!=existing.sha256:
raise ValueError("Imported artifact is missing or corrupt")
return existing
asset_id = new_id()
source = confined(settings.job_work_root, source, exists=True)
if source.stat().st_size>settings.max_output_bytes:
raise ValueError("Output exceeds reserved asset limit; retained for operator reconciliation")
if job.run_id and job.step_key != "compose" and job.task_type == "video.generate":
from .media import inspect_video_track
track=await inspect_video_track(source,settings)
if track["frames"]<120 or track["fps"]!=24 or (track["width"],track["height"])!=(job.parameters.get("upscale_width"),job.parameters.get("upscale_height")):
raise ValueError("Workflow shot does not meet frozen decoded video specification")
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"
@ -101,12 +117,21 @@ async def import_output(db, settings, job, source, index):
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:
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:
shutil.rmtree(directory, ignore_errors=True)
# Commit may have succeeded despite lost ACK; retain for reconciliation.
raise
@ -114,6 +139,11 @@ async def import_output(db, settings, job, source, index):
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)
@ -122,6 +152,7 @@ async def upload(request: Request, file: UploadFile = File(), name: str | None =
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):
@ -135,13 +166,17 @@ async def upload(request: Request, file: UploadFile = File(), name: str | None =
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:
shutil.rmtree(directory, ignore_errors=True)
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
@ -150,7 +185,7 @@ async def upload(request: Request, file: UploadFile = File(), name: str | None =
@router.get("")
async def list_assets(request: Request, page: int = 1, page_size: int = 24, kind: str = "", q: str = "", tag: str = "",
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", "分页参数无效")
@ -160,12 +195,14 @@ async def list_assets(request: Request, page: int = 1, page_size: int = 24, kind
query = query.where(Asset.kind == kind)
if q:
query = query.where(Asset.name.contains(q[:255], autoescape=True))
# JSON tags are filtered in Python for equivalent MySQL/SQLite preview semantics.
rows = (await session.scalars(query.order_by(Asset.created_at.desc(), Asset.id.desc()))).all()
if tag:
rows = [asset for asset in rows if tag in (asset.tags or [])]
return {"items": [asset_dto(a) for a in rows[(page - 1) * page_size:page * page_size]],
"total": len(rows), "page": page, "page_size": page_size}
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}")
@ -190,6 +227,9 @@ async def patch_asset(asset_id: str, body: AssetPatch, request: Request, actor:
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)})
@ -202,18 +242,17 @@ async def patch_asset(asset_id: str, body: AssetPatch, request: Request, actor:
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)
from .v2_models import AssetReference
ref = await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==asset_id,AssetReference.ref_kind!="execution").limit(1))
if ref:
fail(409,"asset_in_use","Asset is referenced by a workflow")
asset.deleted_at = utcnow()
referenced = await session.scalar(select(JobAsset.job_id).where(JobAsset.asset_id == asset_id).limit(1))
storage = asset.storage_key
emit_asset(session, actor.id, "asset.deleted", {"id": asset.id})
await touch_source_job(session, asset)
await session.commit()
if referenced is None:
try:
path = confined(request.app.state.settings.asset_root, storage)
shutil.rmtree(path.parent)
except (OSError, ValueError):
pass
# Physical deletion is exclusively handled by the dry-run-first retention service.
return Response(status_code=204)

View File

@ -1,5 +1,5 @@
import asyncio
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import timedelta
import hashlib
import hmac
@ -7,7 +7,7 @@ import re
import secrets
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel, Field
from sqlalchemy import delete, select
from sqlalchemy import delete, select, func
from sqlalchemy.exc import IntegrityError
from .errors import fail
from .models import Session, User, utcnow
@ -43,7 +43,7 @@ def validate_password(password, *, minimum=12):
def user_dto(user):
return {"id": user.id, "username": user.username, "display_name": user.display_name, "role": user.role}
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
@ -54,9 +54,16 @@ class Actor:
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", "请先登录")
@ -67,10 +74,14 @@ async def current_actor(request: Request):
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)
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", "请求校验失败,请刷新登录状态")
@ -102,7 +113,7 @@ async def bootstrap_admin(db, settings):
if exists is not None:
return
session.add(User(username=settings.admin_username.strip().lower(), display_name=settings.admin_display_name,
role="admin", password_hash=await asyncio.to_thread(hash_password, settings.admin_password)))
role="admin", must_change_password=True, password_hash=await asyncio.to_thread(hash_password, settings.admin_password)))
await session.commit()
@ -125,7 +136,7 @@ async def login(body: Login, request: Request, response: Response):
@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},
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}
@ -141,7 +152,7 @@ async def logout(request: Request, actor: Actor = Depends(csrf_actor)):
@router.post("/users", status_code=201)
async def create_user(body: CreateUser, request: Request, actor: Actor = Depends(csrf_actor)):
if actor.role != "admin":
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):
@ -156,3 +167,73 @@ async def create_user(body: CreateUser, request: Request, actor: Actor = Depends
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}

193
backend/app/batches.py Normal file
View File

@ -0,0 +1,193 @@
"""Persistent mixed workflow/job batches with one eligible member at a time."""
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))
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):
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 '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:return set(r.hold_reasons or [])|{'batch_wait'}
items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all()
active=await active_member(s,items)
return member_holds(r.hold_reasons,b,active is not None and active.target_id!=r.id)
async def advance_batches(s,settings):
batches=(await s.scalars(select(Batch).where(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,item!=active))
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,item!=active)
if item.target_kind=='run':holds|=set(target.hold_reasons or [])
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
if idx:j.hold_reasons=['batch_wait']
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.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

View File

@ -26,6 +26,18 @@ class Settings:
admin_display_name: str = "管理员"
cookie_secure: bool = True
session_hours: int = 12
public_access: bool = False
max_interactive_gpu_jobs: int = 8
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
@ -94,13 +106,13 @@ class Settings:
"gpu_status_path", "gpu_scheduler_path"):
if field.upper() in env:
values[field] = Path(env[field.upper()]) if env[field.upper()] else None
for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes"):
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"):
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")

View File

@ -2,6 +2,7 @@ import asyncio
from datetime import timedelta
import json
import logging
import time
from pathlib import Path
import re
from filelock import FileLock
@ -10,9 +11,14 @@ from .assets import confined, import_output, safe_file
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, utcnow
from .models import Asset, Job, JobAsset, User, utcnow
LOG = logging.getLogger(__name__)
GPU_FENCE_UNSET = object()
class PhaseDeferred(Exception):
pass
class Coordinator:
@ -20,10 +26,23 @@ class Coordinator:
self.settings, self.db, self.provider = settings, db, provider
self._task = None
self._cpu = {}
# 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()
@ -35,12 +54,39 @@ class Coordinator:
# 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.state.notin_(TERMINAL),
Job.task_type.notin_(GPU_TYPES), Job.phase == "cpu_running"))).all()
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:
job.state = "cancelled" if job.cancel_requested else "failed"
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:
@ -62,6 +108,7 @@ class Coordinator:
while True:
try:
await self.run_once()
self.last_tick_success=time.monotonic()
except asyncio.CancelledError:
raise
except Exception:
@ -76,11 +123,21 @@ class Coordinator:
async with self.db.session() as session:
return await session.get(Job, job_id)
async def _update(self, job_id, *, fresh_dispatch=False, **changes):
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.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
@ -89,7 +146,7 @@ class Coordinator:
"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 = False
changed = execution_changed
for key, value in changes.items():
if getattr(job, key) != value:
setattr(job, key, value)
@ -121,17 +178,32 @@ class Coordinator:
async def _failure(self, job_id, exc):
job = await self._job(job_id)
from .v2_models import Execution
async with self.db.session() as session:
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):
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.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
@ -144,6 +216,10 @@ class Coordinator:
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)})
@ -152,11 +228,16 @@ class Coordinator:
await emit_job(session, job)
await session.commit()
def _clock_allows(self,job):
return job.execution_mode!="batch" or self._admission_clock.observe()
async def run_once(self, *, force=False):
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)
async with self.db.session() as session:
query = select(Job).where(Job.state.notin_(TERMINAL))
@ -173,6 +254,7 @@ class Coordinator:
# 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
for job in jobs:
if job.scheduled_at and job.scheduled_at > utcnow():
continue
@ -181,9 +263,26 @@ class Coordinator:
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":
self._cpu[job.id].cancel()
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) or not self._clock_allows(job) or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id)):
continue
if job.task_type in GPU_TYPES:
await self._gpu(job)
@ -192,8 +291,17 @@ class Coordinator:
await self._collect_cpu(job)
except Exception as exc:
await self._warning(job.id, exc)
elif not self._cpu:
self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{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.after_tick is not None:
await self.after_tick()
async def _gpu(self, job):
try:
@ -207,8 +315,23 @@ class Coordinator:
if job.upstream_payload is None:
job = await self._update(job.id, phase="preparing", state="submitting")
job, work = await self._workdir(job)
payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters,
await self._assets(job), work)
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):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:
@ -220,20 +343,40 @@ class Coordinator:
if job.cancel_requested:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
from .resource_policy import admits
if not job.cancel_requested and (not admits(job) 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:
remote = await self.provider.cancel(job.upstream_id) if job.cancel_requested else await self.provider.query(job.upstream_id)
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)
except PhaseDeferred:
await self._update(job.id,state="submitting",phase="waiting_phase")
except asyncio.CancelledError:
raise
except Exception as exc:
if not job.upstream_id and getattr(exc, "code", None) == "upstream_rejected":
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)
@ -243,7 +386,7 @@ class Coordinator:
async def _apply_remote(self, job_id, remote):
state = remote.get("state")
if state not in {"queued", "running", "succeeded", "failed", "cancelled", "timed_out"}:
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,
@ -260,22 +403,44 @@ class Coordinator:
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, **changes)
job = await self._update(job_id, remote_observation=remote, **changes)
if job.state == "collecting":
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.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")
assets.append(existing)
continue
raw = output.get("path", "") if isinstance(output, dict) else str(output)
@ -284,7 +449,7 @@ class Coordinator:
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))
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:
@ -293,21 +458,104 @@ class Coordinator:
transcript = json.load(stream)
result = {"text": transcript.get("text", ""), "segments": transcript.get("segments", [])}
break
await self._complete(job.id, result)
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.cancel_requested:raise asyncio.CancelledError()
if admits(job) 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.cancel_requested or not admits(job) 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:
if job.cancel_requested:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(),
attempt_count=job.attempt_count + 1)
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())
@ -320,6 +568,24 @@ class Coordinator:
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",
@ -327,11 +593,22 @@ class Coordinator:
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":
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)
await self._failure(job.id, exc)
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):
private = job.upstream_result or {}

View File

@ -3,10 +3,12 @@ from sqlalchemy import event
import asyncio
from contextlib import asynccontextmanager
from .models import Base
from . import v2_models
class Database:
def __init__(self, settings):
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")
@ -28,7 +30,11 @@ class Database:
async def initialize(self):
async with self.engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
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, {"003"})
async def close(self):
await self.engine.dispose()

View File

@ -35,7 +35,7 @@ async def job_dto(session, job):
.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, "prompt": job.input_json.get("prompt", ""), "parameters": job.parameters,
"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,

View File

@ -34,6 +34,10 @@ async def event_batch(db, owner_id, after, limit=100):
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
@ -48,10 +52,12 @@ async def event_stream(request, owner_id, token, after):
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
if after > maximum:
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)
@ -73,5 +79,8 @@ async def events(request: Request, after: int = 0, actor: Actor = Depends(curren
raise ValueError
except ValueError:
fail(422, "invalid_cursor", "事件游标必须为非负整数")
return StreamingResponse(event_stream(request, actor.id, request.cookies.get(COOKIE), 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

100
backend/app/executions.py Normal file
View File

@ -0,0 +1,100 @@
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)
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 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 (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 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(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 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")

View File

@ -2,7 +2,8 @@ from datetime import datetime, timezone
import hashlib
import json
from fastapi import APIRouter, Depends, Header, Request
from pydantic import BaseModel, Field
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
@ -19,6 +20,8 @@ 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)
@ -103,10 +106,12 @@ async def validate_submission(session, body, owner_id, settings):
return ids
async def create_jobs(session, body, actor, settings, key=None):
async def create_jobs(session, body, actor, settings, key=None, internal=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()
@ -118,7 +123,23 @@ async def create_jobs(session, body, actor, settings, key=None):
if existing:
if existing[0].request_hash != fingerprint:
fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数")
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 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)
scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None
jobs = []
@ -130,7 +151,7 @@ async def create_jobs(session, body, actor, settings, key=None):
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",
version=1, input_json=body.input, parameters=parameters, request_key=key,
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)
@ -139,6 +160,8 @@ async def create_jobs(session, body, actor, settings, key=None):
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
@ -149,6 +172,15 @@ def wake(request):
@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)
@ -156,18 +188,21 @@ async def submit(body: Submit, request: Request, idempotency_key: str | None = H
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 = "",
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)
if root_only:
query = query.where(Job.run_id.is_(None))
if task_type:
query = query.where(Job.task_type == task_type)
if state:
@ -204,13 +239,27 @@ async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_acto
@router.post("/{job_id}/retry", status_code=202)
async def retry(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
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", "请先等待或取消当前任务")
body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters)
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.id.in_(record.resource_json["job_ids"])))).all())
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)

View File

@ -1,11 +1,12 @@
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
from . import assets, auth, events, jobs, submissions, tokens, workflows, batches
from .config import Settings
from .coordinator import Coordinator
from .database import Database
@ -26,18 +27,39 @@ def create_app(settings=None, *, provider=None):
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__)
@ -47,7 +69,8 @@ def create_app(settings=None, *, provider=None):
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, jobs.router, events.router):
for router in (auth.router, assets.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")
@ -56,19 +79,52 @@ def create_app(settings=None, *, provider=None):
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
return {"items": provider_capabilities(app.state.settings),
"scheduler": await app.state.provider.scheduler_status()}
"scheduler": await app.state.provider.scheduler_status(), "execution_policy": execution_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
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()}
"database_backend": app.state.settings.sqlalchemy_url.get_backend_name(),
"execution_policy": execution_policy(),
"public_access": getattr(app.state.settings, "public_access", False)}
return app

View File

@ -0,0 +1,8 @@
"""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")

View File

@ -233,3 +233,75 @@ async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None
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):
"""Fixed three-shot CPU renderer. Paths are internal resolved asset paths only."""
from .providers import CpuResult
if len(sources)!=3:raise MediaError('invalid_timeline','Exactly three source videos required.')
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 in sources:
info=await inspect_video_track(source,settings)
if info['frames']<120:raise MediaError('short_source','Each source needs at least 120 decoded video frames.')
if info['fps']!=24 or (info['width'],info['height'])!=expected: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 in enumerate(sources):
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='trim=start_frame=0:end_frame=120,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','120','-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=15'
else:af='atrim=duration=15'
command+=['-map','0:v:0','-map','1:a:0']
if filters:command+=['-vf',','.join(filters)]
command+=['-af',af,'-frames:v','360','-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=600,cwd=work)
info=await inspect_video_track(target,settings)
if info['frames']!=360 or info['fps']!=24 or (info['width'],info['height'])!=plan.canvas or abs(info['duration']-15)>.10 or target.stat().st_size>=settings.max_output_bytes:
raise MediaError('composition_incomplete','Final video must be 360 frames at 24fps and 15 seconds.')
result={'frames':360,'fps':24,'duration_seconds':15,'width':width,'height':height,'clip_count':3,'subtitle_count':len(filters)}
return CpuResult([target],result,{'provider':'ffmpeg-cpu','profile':plan.spec['profile'],'template_version':'plain-v1'})

View File

@ -29,6 +29,7 @@ class User(Base):
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)
@ -75,6 +76,17 @@ class Job(Base):
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)
task_type: Mapped[str] = mapped_column(String(48))
execution_mode: Mapped[str] = mapped_column(String(16), default="interactive")
policy_version: Mapped[str] = mapped_column(String(32), default="night-v1")
run_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
step_key: Mapped[str | None] = mapped_column(String(32), nullable=True)
batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
batch_item_index: Mapped[int | None] = mapped_column(Integer, nullable=True)
explicit_attempt: Mapped[int] = mapped_column(Integer, default=1)
desired_state: Mapped[str] = mapped_column(String(16), default="run")
hold_reasons: Mapped[list] = mapped_column(JSON, default=list)
current_execution_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
admitted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
state: Mapped[str] = mapped_column(String(24))
phase: Mapped[str] = mapped_column(String(48))
version: Mapped[int] = mapped_column(Integer, default=1)

View File

@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
from contextvars import ContextVar
import base64
from dataclasses import dataclass
from datetime import datetime, timezone
@ -23,6 +24,15 @@ 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')
@ -204,6 +214,25 @@ def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=
_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) != 3:
raise _invalid('Exactly three workflow clips required.')
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')
@ -407,6 +436,7 @@ class Provider:
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:
@ -419,6 +449,7 @@ class Provider:
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'))
@ -480,6 +511,28 @@ class Provider:
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()))
@ -561,6 +614,7 @@ class Provider:
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)
@ -577,8 +631,10 @@ class Provider:
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:
@ -607,6 +663,7 @@ class Provider:
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
@ -629,9 +686,11 @@ class Provider:
frames = []
prompt = ('仅根据画面可见内容输出JSON对象,不要Markdown。字段 subjects 为字符串数组,scene 为字符串,'
'ocr 为画面实际可见文字的字符串数组,tags 为字符串数组。看不清请写不确定,不要臆测人物身份。')
for timestamp, frame in samples:
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': await self._image_uri(frame)}},
{'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)
@ -676,6 +735,18 @@ class Provider:
{'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')

View File

@ -0,0 +1,28 @@
"""Fail closed when the operator explicitly enables Internet access."""
import asyncio
from sqlalchemy import select
from .auth import verify_password
from .models import User
async def require_public_ready(db, settings):
if not settings.public_access:
return
if not settings.cookie_secure:
raise ValueError("PUBLIC_ACCESS requires COOKIE_SECURE and HTTPS")
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()
if not admins:
raise ValueError("Public access requires an enabled administrator")
initial_passwords = {"123456"}
if settings.admin_password:
initial_passwords.add(settings.admin_password)
for user in admins:
unchanged = user.must_change_password
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")

70
backend/app/quotas.py Normal file
View File

@ -0,0 +1,70 @@
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))
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_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))
if size+incoming_bytes>getattr(settings,"max_owner_asset_bytes",100*1024**3):raise AssetBudgetError()

View File

@ -0,0 +1,24 @@
"""Admission is evaluated at phase boundaries. A closing window never cancels work."""
from datetime import datetime,timezone,timedelta
# fixed UTC+8 has no DST; avoids depending on OS IANA data on Windows.
SHANGHAI=timezone(timedelta(hours=8))
def execution_policy(now=None):
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)
return {"timezone":"Asia/Shanghai","start":"21:00","end":"08:00","batch_open":opened,"next_batch_at":next_at.astimezone(timezone.utc).isoformat(),"close_behavior":"finish_current"}
def admits(job,now=None):
if job.cancel_requested or job.desired_state!="run": return False
if set(job.hold_reasons or [])-{"window"}: return False
return job.execution_mode!="batch" 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")]

31
backend/app/retention.py Normal file
View File

@ -0,0 +1,31 @@
"""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
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<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))
if referenced or snapshot or not asset.ready:
report["protected"].append(asset.id);continue
report["candidates"].append(asset.id)
# Physical deletion disabled unless maintenance is explicitly active.
if not dry_run:
from .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()
report["deleted"].append(asset.id)
return report

64
backend/app/schema.py Normal file
View File

@ -0,0 +1,64 @@
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 .models import Base
from . import v2_models
diff=schema_preflight(connection,Base.metadata)
if not diff.matches:raise RuntimeError("Schema drift: "+"; ".join(diff.differences))

View File

@ -0,0 +1,83 @@
"""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:
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}

86
backend/app/timeline.py Normal file
View File

@ -0,0 +1,86 @@
"""Versioned, strict three-shot contract. Public fields contain no executable paths."""
from dataclasses import dataclass
from typing import Literal
import re
from pydantic import BaseModel, ConfigDict, Field, model_validator
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: Literal['shot_1','shot_2','shot_3']
prompt: str = Field(min_length=1,max_length=8000)
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,lt=360)
end_frame: int = Field(gt=0,le=360)
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,lt=360)
short_policy: Literal['silence'] = 'silence'
@model_validator(mode='after')
def fits(self):
if self.source_end_ms <= self.source_start_ms or (self.source_end_ms-self.source_start_ms)*24 > (360-self.offset_frame)*1000:
raise ValueError('invalid_timeline: audio exceeds canvas')
return self
class Render(Strict):
fps: Literal[24] = 24
total_frames: Literal[360] = 360
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] = 1
shots: list[Shot] = Field(min_length=3,max_length=3)
profile: Literal['landscape_1080_v1','portrait_1080_v1'] = 'landscape_1080_v1'
render: Render = Field(default_factory=Render)
@model_validator(mode='after')
def exact_keys(self):
if [s.key for s in self.shots] != ['shot_1','shot_2','shot_3']:
raise ValueError('exact ordered shot_1,shot_2,shot_3 required')
return self
@dataclass(frozen=True)
class TimelinePlan:
spec: dict
generation_parameters: dict
canvas: tuple[int,int]
frames: int = 360
clip_frames: int = 120
fps: int = 24
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=121,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)
return TimelinePlan(spec.model_dump(mode='json'),parameters,(1080,1920) if portrait else (1920,1080))

70
backend/app/tokens.py Normal file
View File

@ -0,0 +1,70 @@
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="workflows" if operation.startswith("workflow") else "batches" if operation.startswith("batch") else "jobs"
scope={"workflow-runs":"workflows"}.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)

View File

@ -0,0 +1,94 @@
"""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()

155
backend/app/v2_models.py Normal file
View File

@ -0,0 +1,155 @@
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)
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)
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)
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))

View File

@ -0,0 +1,99 @@
"""Durable orchestration only: never execute a model or a media process here."""
import logging
from fastapi import HTTPException
from sqlalchemy import select
from .models import Job, utcnow
from .v2_models import WorkflowRun, WorkflowStep, AssetReference
from .jobs import TERMINAL
from .workflows import RUN_TERMINAL, create_child, emit_run, selected_output
log=logging.getLogger(__name__)
AUTOMATIC_HOLDS={'quota','storage'}
async def advance_run(session,run_id,settings):
r=await session.scalar(select(WorkflowRun).where(WorkflowRun.id==run_id).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: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()
for key in ('shot_1','shot_2','shot_3','compose'):
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
await create_child(session,r,step,settings);changed=True
break
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.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).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()

323
backend/app/workflows.py Normal file
View File

@ -0,0 +1,323 @@
"""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
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']='three_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).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).order_by(WorkflowStep.step_key))).all()
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(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.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=4)
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 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):
spec=spec if isinstance(spec,WorkflowSpec) else WorkflowSpec.model_validate(spec)
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.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','草稿已更新,请刷新版本')
if mode=='interactive':
active=await session.scalar(select(WorkflowRun.id).where(WorkflowRun.owner_id==owner_id,WorkflowRun.execution_mode=='interactive',WorkflowRun.state.not_in(RUN_TERMINAL)))
if active:fail(429,'quota_exceeded','已有活动交互工作流')
plan,assets=await validate_spec(session,owner_id,d.spec)
snapshot={**plan.spec,'compiled':{'generation_parameters':plan.generation_parameters,'canvas':list(plan.canvas),'preset_version':'wan-three-shot-v1'}}
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'))
h=digest({'shot':shot,'generation_parameters':plan.generation_parameters,'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.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_1','shot_2','shot_3'],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.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):
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={**snapshot['compiled']['generation_parameters'],**shot['parameters']}
else:
steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id,WorkflowStep.kind=='video.generate').order_by(WorkflowStep.step_key))).all()
ids=[];hashes=[]
for s in steps:
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)
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.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.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)
d=WorkflowDraft(owner_id=actor.id,name=body.name,kind=body.kind,spec=body.spec.model_dump(mode='json'));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)
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.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)
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=body.spec.model_dump(mode='json');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.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 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)

47
backend/requirements.lock Normal file
View File

@ -0,0 +1,47 @@
aiomysql==0.3.2
aiosqlite==0.22.1
alembic==1.20.1
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.16.0
certifi==2026.10.23
cffi==2.1.1
charset-normalizer==3.5.2
click==8.5.1
cryptography==50.0.2
fastapi==0.162.2
filelock==4.2.10
greenlet==3.5.6
h11==0.16.0
httpcore==1.0.9
httptools==0.9.0
httpx==0.28.1
idna==3.20
iniconfig==2.3.1
mako==1.4.3
markupsafe==3.0.4
numpy==2.5.4
opentelemetry-api==1.45.2
packaging==26.3
pillow==13.0.0
pluggy==1.7.0
pycparser==3.12
pydantic==2.14.3
pydantic-core==2.50.4
pygments==2.21.0
pymysql==1.2.4
pytest==9.2.0
pytest-asyncio==1.4.1.post1
python-dotenv==1.2.4
python-multipart==0.0.33
pyyaml==6.0.3
requests==2.34.2
sqlalchemy==2.1.8
starlette==1.10.0
typing-extensions==4.16.0
typing-inspection==0.4.5
urllib3==2.8.0
uvicorn==0.54.0
uvloop==0.23.0
watchfiles==1.3.0
websockets==17.4

View File

@ -10,3 +10,4 @@ filelock>=3.16,<5
Pillow>=10.4
pytest>=8,<10
pytest-asyncio>=0.24,<2
alembic>=1.14,<2

View File

@ -0,0 +1,39 @@
"""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 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)])
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
# Decode full output, not just the muxer metadata.
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)

View File

@ -0,0 +1,59 @@
"""Opt-in MySQL API regression, restricted to the isolated verification host."""
import asyncio
import os
from pathlib import Path
from types import SimpleNamespace
import uuid
import httpx
import pytest_asyncio
from sqlalchemy import text
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.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_workflows_v2 import (
test_snapshot_version_idempotency_owner,
test_engine_durable_sequential_cancel_and_no_new_job,
test_batch_mixed_persistent_one_active_member,
test_parallel_run_and_patch_versions_accept_one,
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!='cmvr-visual-v2-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

View File

@ -0,0 +1,34 @@
from datetime import datetime
from pathlib import Path
import pytest
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'))
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'
@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'

View File

@ -0,0 +1,49 @@
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
@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"}})
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()
await system.app.state.coordinator.run_once(force=True)
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
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
@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
await system.app.state.coordinator.run_once(force=True)
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

View File

@ -0,0 +1,303 @@
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
@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]
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",{})
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],{}, {})
source.write_text("changed")
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 fail_provider(*args):
nonlocal calls
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)
await c.run_once(force=True)
await asyncio.gather(*c._cpu.values())
monkeypatch.setattr(c,"_failure",original)
await c.run_once(force=True)
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"
@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
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):
nonlocal opened
await enter_phase("sample_frames","cpu_media")
entered.append("sample")
sampled.set()
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"}})
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()
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
# 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"]
@pytest.mark.asyncio
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"]
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
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())
await original(session)
if trigger:
lost=True
raise RuntimeError("commit succeeded; ACK lost")
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
@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"]
await c.run_once(force=True)
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
@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 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)
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"
@pytest.mark.asyncio
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
async def tracked_acquire():
if c._pools["qwen_http"].locked():second_waiting.set()
return await 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}})
await c.run_once(force=True)
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"]
@pytest.mark.asyncio
async def test_cpu_media_cancel_records_cleanup_and_allows_explicit_retry(system,monkeypatch):
from app.v2_models import Execution
from sqlalchemy import select
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"]
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())
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
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
@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 prepare(*args):
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)
await c._pools["cpu_media"].acquire()
try:
await asyncio.wait_for(c.run_once(force=True),1)
assert not system.provider.accepted
finally:c._pools["cpu_media"].release()
@pytest.mark.asyncio
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
async def race():
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()
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
@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"
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):
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):
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"]
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"
@pytest.mark.asyncio
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())
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"
assert "cpu_media" in c._blocked_pools

View File

@ -0,0 +1,120 @@
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
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
@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)
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
# 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)
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
@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})
async with system.app.state.db.session() as session:
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 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 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)
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"
@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"})
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"
@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 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"}]}})
async with system.app.state.db.session() as session:
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"
@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"

View File

@ -237,6 +237,9 @@ async def test_final_publication_reloads_committed_cancel_and_keeps_pending_priv
async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(system):
# This fixture exercises a 52-job scheduler backlog, independently of admission caps.
system.settings.max_interactive_gpu_jobs = 100
system.settings.max_creation_commands_per_minute = 100
ids = []
for _ in range(13):
ids.extend(job["id"] for job in await submit(system, count=4))

View File

@ -0,0 +1,18 @@
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
await coordinator.run_once(force=True)
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()
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

View File

@ -0,0 +1,42 @@
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
return response.json()
def workflow_item(d):
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']
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
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
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

View File

@ -0,0 +1,34 @@
import asyncio
from types import SimpleNamespace
import pytest
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"]
# 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))
await session.commit()
c._blocked_pools.add("qwen_http")
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"
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)
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
await c.run_once(force=True)
await asyncio.wait_for(started.wait(),5)
assert calls==["audio.speech"]
assert len(c._cpu)<=50
assert "qwen_http" in c._blocked_pools

View File

@ -0,0 +1,73 @@
import asyncio
import pytest
from sqlalchemy import select
from app.models import Job
from app.v2_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}"},
})
assert response.status_code == 202, response.text
jobs.append(response.json()["jobs"][0]["id"])
return jobs
@pytest.mark.asyncio
async def test_fifty_quarantined_qwen_jobs_cannot_block_new_speech(system, monkeypatch):
system.settings.max_creation_commands_per_minute = 100
system.settings.tts_base_url = "http://fake-private-tts"
coordinator = system.app.state.coordinator
coordinator._blocked_pools.add("qwen_http")
qwen_jobs = await submit_jobs(system, "math.solve", 50)
await coordinator.run_once(force=True)
async with system.app.state.db.session() as session:
assert not (await session.scalars(select(Execution))).all()
waiting = (await session.scalars(select(Job).where(Job.id.in_(qwen_jobs)))).all()
assert all(job.current_execution_id is None for job in waiting)
started = asyncio.Event()
boundary = system.provider.run_cpu
calls = []
async def speech_boundary(task_type, *args):
calls.append(task_type)
assert task_type == "audio.speech", "Quarantined Qwen must not execute"
started.set()
return await boundary(task_type, *args)
monkeypatch.setattr(system.provider, "run_cpu", speech_boundary)
speech_job = (await submit_jobs(system, "audio.speech", 1))[0]
await coordinator.run_once(force=True)
await asyncio.wait_for(started.wait(), 3)
await asyncio.wait_for(coordinator._cpu[speech_job], 3)
assert calls == ["audio.speech"]
assert "qwen_http" in coordinator._blocked_pools
assert len(set(qwen_jobs).intersection(coordinator._cpu)) <= 25
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()
@pytest.mark.asyncio
async def test_one_pool_has_a_bounded_pending_coroutine_queue(system):
system.settings.max_creation_commands_per_minute = 100
coordinator = system.app.state.coordinator
coordinator._blocked_pools.add("qwen_http")
jobs = await submit_jobs(system, "math.solve", 26)
await coordinator.run_once(force=True)
assert len(coordinator._cpu) == 25
assert system.provider.cpu_runs == 0
async with system.app.state.db.session() as session:
assert len((await session.scalars(select(Job).where(Job.id.in_(jobs)))).all()) == 26
assert not (await session.scalars(select(Execution))).all()

View File

@ -0,0 +1,46 @@
import pytest
from sqlalchemy import select
from app.models import User
from conftest import PASSWORD
async def test_public_preflight_refuses_insecure_cookie_and_legacy_default(system):
from app.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
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")
await session.commit()
settings.admin_password = "" # Clearing bootstrap env must not bypass it.
with pytest.raises(ValueError, match="administrator password"):
await require_public_ready(system.app.state.db, settings)
async def test_public_preflight_allows_changed_admin_and_private_initial_login(system):
from app.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
system.settings.admin_password = "123456"
async with system.app.state.db.session() as session:
user = await session.scalar(select(User).where(User.username == "admin"))
user.must_change_password = False
await session.commit()
await require_public_ready(system.app.state.db, system.settings)
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)

View File

@ -0,0 +1,22 @@
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
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

View File

@ -0,0 +1,19 @@
from datetime import timedelta
import pytest
from app.models import Asset,utcnow
from app.v2_models import AssetReference
from app.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 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"))
await session.commit()
report=await collect_garbage(system.app.state.db,system.settings)
assert report["protected"]==[asset_id]
assert report["deleted"]==[]

View File

@ -0,0 +1,53 @@
import importlib.util
from pathlib import Path
import pytest
from sqlalchemy import create_engine,text
from app.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)
return module
def test_legacy_baseline_and_drift():
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
c.execute(text("DROP INDEX visual_jobs_dispatch"))
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))
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")
with engine.begin() as c:
check_schema_revision(c,{"003"})
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"})
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)

View File

@ -0,0 +1,25 @@
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
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)
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
assert waiter.current_execution_id is None
assert system.provider.cpu_runs==1

View File

@ -0,0 +1,42 @@
"""Every visual request is a separate finish-current admission boundary."""
import json
import httpx
import pytest
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)
await provider.client.aclose()
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)
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()
finally:
providers.current_phase_callback.reset(token)
await provider.aclose()

View File

@ -0,0 +1,112 @@
import copy
import pytest
from pydantic import ValidationError
from app.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'}
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)
def test_freezes_profiles_and_frame_boundaries():
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.frames == 360 and plan.clip_frames == 120
body['profile'] = 'portrait_1080_v1'
plan = compile_timeline(body, {})
assert plan.canvas == (1080,1920)
assert plan.generation_parameters['upscale_width'] == 1056
@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'}}
if valid:
compile_timeline(body, {'audio': {'kind':'audio','duration_seconds':10}})
else:
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)
@pytest.mark.asyncio
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=[]
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)
@pytest.mark.asyncio
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=[]
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
@pytest.mark.asyncio
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)
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()
@pytest.mark.asyncio
async def test_phase_callback_is_context_local():
import asyncio
from app.providers 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')]

View File

@ -0,0 +1,58 @@
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
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")
@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
@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"]
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"}))
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
@pytest.mark.asyncio
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"
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))
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"

View File

@ -0,0 +1,50 @@
import httpx
import asyncio
from types import SimpleNamespace
async def test_unauthenticated_upload_does_not_consume_or_parse_body(system):
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==[]
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()
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))
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'
finally:
release.set()
await first

View File

@ -0,0 +1,28 @@
from types import SimpleNamespace
from unittest.mock import AsyncMock
from sqlalchemy import select
from app.models import Job
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'})
assert response.status_code == 202
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]}}
await session.commit()
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())
await coordinator._collect_gpu(job)
assert imported==[1]
assert system.provider.download_count==1

View File

@ -0,0 +1,283 @@
"""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 test_workflows_v2 import wf, draft, run, publish_video
async def tick(wf):
from app.workflow_engine import advance_workflows
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
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})
assert response.status_code == 202, response.text
return response.json()
@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'})
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'
@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']
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'))
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']
await s.commit()
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
@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']
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 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
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)
@pytest.mark.asyncio
async def test_retry_old_batch_member_waits_for_later_active_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']
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()
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' 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()
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
@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')
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()
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' not in (await s.get(WorkflowRun,two['items'][0]['target_id'])).hold_reasons
@pytest.mark.asyncio
async def test_retry_waits_for_active_sibling_when_batch_representative_finished_held(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']
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'
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')
await tick(wf)
async with wf.app.state.db.session() as s:
assert 'batch_wait' 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):
nonlocal calls
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']))
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))
@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)
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
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
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
@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.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'}}])
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()
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']
@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'})
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
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'
@pytest.mark.asyncio
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)
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']
@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']
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)
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
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')

View File

@ -0,0 +1,271 @@
import copy
import pytest
from sqlalchemy import select
from app.models import Job, Asset
from app.v2_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')
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
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
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 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'
@pytest.mark.asyncio
async def test_engine_durable_sequential_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']) == 1 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']) == 1
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)
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'])==1
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'])==2
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
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']
@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)
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
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'])==2
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']==[]
@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
@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)
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'
@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
@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
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
@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')
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']
@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)
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'])==1
@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]
@pytest.mark.asyncio
async def test_batch_does_not_advance_while_previous_cleanup_unknown(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']
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)
async with wf.app.state.db.session() as s:
j=await s.get(Job,items[1]['target_id']);assert 'batch_wait' 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)
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'])==1
@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')
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()
@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'
@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']

View File

@ -2,7 +2,7 @@ name: cmvr-visual
services:
api:
build: ./backend
image: cmvr-visual-api:20261110
image: cmvr-visual-api:v2-20261110
container_name: cmvr-visual-api
env_file: .env
environment:
@ -19,7 +19,12 @@ services:
TTS_VOICES: zf_xiaobei,zm_yunxi
TMPDIR: /workspace/cmvr-visual/tmp
volumes:
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}:/workspace
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/assets:/workspace/cmvr-visual/assets
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/jobs:/workspace/cmvr-visual/jobs
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/state:/workspace/cmvr-visual/state
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tmp:/workspace/cmvr-visual/tmp
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/projects/llm-services/config:/workspace/projects/llm-services/config:ro
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/projects/llm-services/state:/workspace/projects/llm-services/state:ro
- /var/lib/llmuser-gpu-policy:/run/llm-gpu-policy:ro
networks: [visual]
user: '1013:1014'
@ -36,7 +41,7 @@ services:
logging: {driver: json-file, options: {max-size: 10m, max-file: '3'}}
frontend:
build: {context: ., dockerfile: deploy/Dockerfile.frontend}
image: cmvr-visual-frontend:20261110
image: cmvr-visual-frontend:v2-20261110
container_name: cmvr-visual-frontend
ports: ['127.0.0.1:${WEB_PORT:-18193}:8080']
depends_on: [api]

View File

@ -1,5 +1,6 @@
FROM nginx:1.30.6-alpine
COPY deploy/nginx.conf /etc/nginx/nginx.conf
COPY deploy/api-proxy.conf /etc/nginx/api-proxy.conf
COPY frontend/dist /usr/share/nginx/html
USER 1013:1014
EXPOSE 8080

12
deploy/api-proxy.conf Normal file
View File

@ -0,0 +1,12 @@
set $api_upstream http://cmvr-visual-api:8000;
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
proxy_request_buffering off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;

View File

@ -7,6 +7,10 @@ http {
default_type application/octet-stream;
access_log /dev/stdout;
sendfile on;
resolver 127.0.0.11 valid=10s ipv6=off;
resolver_timeout 3s;
limit_req_zone $binary_remote_addr zone=cmvr_login:1m rate=10r/m;
limit_req_status 429;
server_tokens off;
client_body_temp_path /tmp/client_temp;
proxy_temp_path /tmp/proxy_temp;
@ -23,19 +27,11 @@ http {
add_header Referrer-Policy same-origin always;
add_header X-Frame-Options SAMEORIGIN always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; font-src 'self' data:; frame-ancestors 'self'; object-src 'none'; base-uri 'self'" always;
location /api/ {
proxy_pass http://cmvr-visual-api:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
proxy_request_buffering off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
location = /api/auth/login {
limit_req zone=cmvr_login burst=20 nodelay;
include /etc/nginx/api-proxy.conf;
}
location /api/ { include /etc/nginx/api-proxy.conf; }
# The library SPA route shares the build directory's name. Serve the
# entry point explicitly so Nginx cannot redirect it to container :8080.
location = /assets { try_files /index.html =404; expires -1; }

View File

@ -0,0 +1,14 @@
# 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、管理员改密与专用数据库业务账号:当前保持私有入口,待公开发布时配置。
操作顺序为维护闭准入→确认本应用执行结束→联合备份→兼容上游/迁移→API/前端→真实验收→开放本项目准入。不得停止其它用户服务或以清队列代替恢复。镜像、备份哈希及检查结果见 `qa/v2-deployment.json`;实际边界见 `docs/V2开发与验收记录_20261110.md`。

View File

@ -0,0 +1,76 @@
# 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。

View File

@ -68,3 +68,25 @@ Implemented in `app/providers.py` and `app/media.py`, independent of database mo
- `capabilities(settings)->list[dict]` returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible `/audio/speech` if selected later.
Production files live under `/workspace/cmvr-visual`. Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt.
## V2 additions
HTTP remains the command/query channel, SSE the owner-scoped notification channel. `execution_policy` is returned by capabilities/status: `{timezone:'Asia/Shanghai',start:'21:00',end:'08:00',batch_open,next_batch_at,close_behavior:'finish_current'}`. The server accepts and persists batch commands all day; only new compute phases are gated. Current work is never killed by the clock or a browser disconnect.
- 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.
- 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.
- GET `/submissions/{key}?operation=jobs.create|jobs.retry|workflow.run|workflow.retry|workflow.pause|workflow.resume|workflow.cancel|batch.create|batch.control` recovers owned resources. Replaying the original key and immutable JSON is safe after a lost response; 404 alone does not prove an in-flight command was rejected.
- POST/GET `/workflows`; GET/PATCH `/workflows/{id}`. PATCH requires `If-Match: <version>`. Draft edits increment revision; new Runs freeze a snapshot.
- POST `/workflows/{id}/runs` `{draft_revision,expected_version,execution_mode?,reuse_run_id?}` plus Idempotency-Key → `{draft,run,steps,jobs,cursor}`. GET `/workflow-runs` is paginated; GET `/{id}` returns the consistent snapshot.
- POST `/workflow-runs/{id}/pause|resume|cancel` `{expected_version?}` plus Idempotency-Key. Pause closes future admission and drains current work. Cancel remains pending until cleanup/completion is known.
- POST `/workflow-runs/{id}/steps/{step_key}/retry` `{expected_run_version,target_job_id}` plus Idempotency-Key retries only the selected failed step, preserving other successful shots and inherited mode/holds.
- POST `/batches` `{name?,items:[{kind:'workflow',draft_id,draft_revision,expected_version}|{kind:'job',task_type,input,parameters?,count?}]}` plus Idempotency-Key. Maximum100 items, fixed `batch` mode, one active member per batch. GET list and `/{id}` snapshots; POST `/{id}/control` `{desired_state:'run'|'pause'|'cancel',expected_version?}` plus Idempotency-Key.
- Asset list additionally accepts `favorite` and `origin` SQL filters. Workflow references protect frozen inputs/outputs from physical deletion.
- SSE adds `draft.updated:{draft}`, `workflow.updated:{run,steps,jobs}`, `batch.updated:{batch,items}` with object versions. Ignore older/equal versions; reconnect/reset refreshes HTTP snapshots. Machine SSE requires `events:read` and Authorization, never tokens in URLs.
Workflow spec schema1: exactly ordered `shot_1,shot_2,shot_3`, each `{key,prompt,image_asset_id:null|string,parameters:{seed}}`; `profile=landscape_1080_v1|portrait_1080_v1`; `render={fps:24,total_frames:360,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'}`. Video track is exactly360 frames. Each enhanced shot contributes120 frames; short sources fail. Audio must fit the timeline explicitly, subtitles use whole-film half-open frame intervals.
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.

View File

@ -1,5 +1,7 @@
# 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秒工作流及交互/夜间批量调度。
@ -13,11 +15,11 @@
## Global Constraints
- 主工程根目录 `E:\workspace\hybrid\cmvr-visual`,下文无前缀的路径均相对此根。
- `GPU/`前缀指另一个现有源码根 `C:\Users\Administrator\Documents\ChatGPT\大模型部署到服务器\llm-services`,部署到既有 `/workspace/projects/llm-services`;不创建另一套GPU worker。
- `GPU/`为规划时前缀;实现源码已纳入本仓库 `inference/`,仍部署到既有 `/workspace/projects/llm-services`,不创建另一套GPU worker。原源码保留作基线。
- 正式MySQL及admin已存在,不重复初始化、不覆盖密码、不迁移旧验收样例。
- 三段各120个成片帧,最终360帧、24fps;保持多镜头定义。
- Asia/Shanghai `[21:00,次日08:00)`;外部用户优先、新GPU任务全局1个。
- 现有Qwen批量必须先通过单请求停止确认;未通过就关闭该项,不能杀共享服务PID。
- 现有Qwen按新请求准入排队,当前调用自然完成;不发送abort、不杀共享服务PID。
- 不读写其他项目数据库,不全局重启Docker/驱动,不修改宿主时钟;秘密不进入源码、命令行参数或测试输出。
- 每任务先写有意义的失败测试,再最小实现、回归、独立审查并提交;只有对应验收通过才勾选。生产操作只在任务12执行。
@ -96,21 +98,20 @@ profile由服务器编译成冻结的模型默认参数/版本,横版1280×704
**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;所有未知新字段不能静默忽略。
- [ ] 测试窗口 `[21:00,08:00)`、最后30秒禁新batch、07:59领取08点spawn被挡、关闭窗口回拨不重新开放;不改宿主时钟,注入Clock。
- [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:独立监管、CPU窗口与Qwen前置验证
## Task 6:阶段资源、自然完成和共享Qwen隔离
**Files:** 修改 `GPU/admin/gpu_guard.py`、`GPU/llm_services/gpu_policy.py`、`GPU/tests/test_gpu_guard.py`;新建 `GPU/tests/test_deadline_guardian.py`、`backend/app/resource_policy.py`、`backend/tests/test_resource_policy.py`、`scripts/probe_qwen_control.py`;修改 `tts/app.py`及生命周期测试。
**Files:** `backend/app/resource_policy.py`、`coordinator.py`、`providers.py`、`media.py`及相应资源/断连回归;既有 `inference/admin/gpu_guard.py`只保留外部优先的原有安全职责。
**Interfaces:** `register_execution(identity, policy) -> LeaseAck`;`stop_execution(execution_id, fence_token) -> StopAck`;`resource_plan(task_type, input_kind) -> list[PhaseRequirement]`;`acquire_phase(execution_id, phase_key) -> SlotLease`。PhaseRequirement含phase_key与pool,分阶段checkpoint后释放再取得下一槽。探测报告必须区分“连接关闭”与“服务端计算结束ACK”。
**Interfaces:** `resource_plan(task_type,input_kind)`;在NEW阶段准入检查window/hold,已开始的provider调用独立于HTTP请求继续执行。
- [ ] 用自有隔离进程夹具测试cgroup/UID、PID重用、starttime/boot_id、旧fence和任意宿主PID均不能误杀;worker07:59:59退出后监管仍对已登记batch截止。
- [ ] 清理ACK加清理后的新GPU快照才释放槽;旧快照、尾进程、监控丢失、超15秒未ACK保持blocked。外部占用时不要求总显存回旧基线。
- [ ] 将CPU编码/Kokoro pause和cancel分开,作业/子进程带Execution身份;按Spec实现TTS私有异步execution v2、control ACK和音频获取,原同步交互接口兼容。同ID重试不再次启动,登记/监管许可前不运行模型。batch停止依然保留已完成步骤,三个资源池各1,未知Qwen请求只挡新的Qwen请求。
- [ ] 对现有Qwen的request_id/abort/结束确认及低优先能力只做获准的可控验证;没有证据输出false并禁用Qwen batch。不得通过停止共享进程让测试“通过”。
- [ ] 视频ASR抽音与GPU转写、视频理解抽帧与Qwen请求分别计入对应槽;两任务交错不出现cpu_media并发2或槽互等死锁。暂停发生在阶段间时不运行下一阶段。
- [ ] 固定时钟07:59:59开始、08:00后完成的任务成功归档;第二镜头/下一阶段等待21点,interactive可运行。
- [ ] 视频ASR抽音→GPU、视频理解抽帧→Qwen分阶段持久结果,阶段间释放资源并重新准入;资源池不互相持有等待。
- [ ] 网页/SSE断开不停止后台Job,不对共享Qwen发送abort或操作PID。当前请求超时/结果不明进入needs_attention而不是偷偷再调用。
- [ ] 外部GPU抢占仍停止自己的GPU任务并重排,08点后的重排batch不立即重启;新旧控制命令幂等并保护执行代次。
## Task 7:15秒媒体规范化
@ -180,4 +181,4 @@ profile由服务器编译成冻结的模型默认参数/版本,横版1280×704
开发环境:在`backend/`执行 `.venv/Scripts/python.exe -m pytest tests -q`;在`frontend/`执行 `pnpm test`、`pnpm build`。Linux媒体/迁移/监管与GPU仓库测试在各自隔离环境执行。只运行本任务对应检查,新的失败或依赖变更才扩大回归。
每任务记录:变更文件、失败→通过的测试、MySQL/媒体/真实GPU分别覆盖什么、剩余阻塞、回退版本。审查批准后再提交相应变更;当前清单保持未勾选,表示**尚未实施V2**。
原清单保留为设计验收目标,不凭代码存在全部勾选。V2已开发并部署到私有入口,逐项实施证据、真实模型结果及保留边界见 [V2开发与验收记录](../../V2开发与验收记录_20261110.md)。文件命名与规划原稿有少量调整,以实际仓库及该记录为准。

View File

@ -1,6 +1,6 @@
# CMVR Visual 实施方案 V2
日期:2026-11-10,Asia/Shanghai。状态:**方案复审完成,待实施;本轮未修改运行中的应用或服务器**。
日期:2026-11-10,Asia/Shanghai。状态:**已开发、部署并通过私有入口验收**。本文件按用户最新执行规则修订:08:00关闭新批量执行准入,当前已运行的镜头/处理阶段继续完成,后续阶段排队。实际交付与边界见 [V2开发与验收记录](V2开发与验收记录_20261110.md)。
本方案承接[上一版复核](需求复核与落地方案_20261110.md),保留其中R1–R12和业务质量专项;以下规则解决上一版尚未明确的实施边界。发生冲突时以本方案为准。已完成的正式MySQL接入和默认管理员不重复执行。
@ -8,11 +8,11 @@
技术上可落地,现有Vue3/Element Plus/Pinia、FastAPI/MySQL、HTTP+SSE与独立GPU队列继续复用。上一版仍缺少上游调度协议、状态竞争、依赖失效、迁移回退和资源边界,不能直接按其概述并行开发。
用户已经确认:三段约5秒分镜合成15秒多镜头成片;交互创作全天使用空闲卡,批量任务仅21:00–08:00;新GPU任务全局最多一个,外部用户优先。保持这些决定。
用户已经确认:三段约5秒分镜合成15秒多镜头成片;交互创作全天使用空闲卡,批量任务的新阶段仅21:00–08:00;新GPU任务全局最多一个,外部用户优先。保持这些决定。
一期验收范围:现有八种单任务能力、可靠提交与恢复、账号维护、持久草稿、三分镜工作流、夜间批量、标签/历史检索和受控对外API。基础质量检查使用固定文件规则;LoRA、数学专业指标、真实缺陷mask、镜头切分、热度预测和音乐生成仍按独立数据专项评测,不作为一期已具备能力。
**一个必须先验证的条件:**现有Qwen HTTP服务没有已实现的单请求取消及停止确认。关闭HTTP连接不能证明服务端GPU已停止。本期先验证该能力;未通过时,数学/视觉理解保持交互可用,Qwen批量明确标记不可用,不承诺其08:00硬截止,也不杀共享服务进程或重部署其模型。其它自管GPU与CPU批量可独立交付。如果必须一期同时包含Qwen夜间批量,则此验证是该项的放行阻塞。
共享Qwen继续通过HTTP复用。网页或HTTP断开不取消后台业务任务,不发送abort、不停止共享服务进程;Qwen可以使用相同的夜间准入规则,已开始调用允许跨08:00完成。外部用户占卡时仅对自管GPU执行保留既有让卡重排机制。
## 2. 再次审查发现的九类遗漏
@ -89,7 +89,7 @@ Run使用第5节的八种状态;Step使用waiting/ready/running/paused/blocked
### 4.2 窗口和队列
窗口为Asia/Shanghai的 `[21:00,次日08:00)`,以UTC存储绝对时间及window_id;执行计时使用monotonic。claim、spawn前和运行循环重新校验资格。已关闭window_id持久记录,时间回拨不得重新打开;检测到明显时钟偏移先暂停batch admission并告警。
窗口为Asia/Shanghai的 `[21:00,次日08:00)`。claim、spawn前检查资格,运行后不因时间关闭而中止。执行超时使用monotonic;已关闭窗口日期和时间水位持久保存,回拨或状态损坏只关闭新batch准入,不阻止交互和当前任务同步。
interactive定义为一次受限单任务(图片1–4张或单个其它任务),或一次三分镜Run;多Run/清单批次只能由batch入口创建。服务端给子任务、重试和重做继承mode,客户端不能覆盖父关系或借普通retry降为interactive。
@ -107,31 +107,27 @@ GPU原子领取时跳过不具执行资格的任务,白天batch队首不能堵
| 取消与暂停同时发生 | cancel优先;清理结束后才能cancelled |
| 取消先提交、尚未领取 | 不派发新的步骤 |
| 已领取后取消 | 可有已在途执行,必须发停止并等待ACK,不再领取下一步 |
| 暂停先提交、完成尚未登记 | 当前Execution结果按暂停裁决,不发布过期结果;清理后排队 |
| 暂停先提交、完成尚未登记 | 当前已开始Execution允许自然完成并归档,只阻止后续领取 |
| 完成先提交、随后暂停 | 保留成功素材,暂停后续步骤 |
| 旧回调迟到 | execution_id、fence_token或控制版本不匹配即拒绝,不能停止/覆盖新执行 |
API新增内部控制命令 `PUT /jobs/{id}/control`,含唯一command_id、expected_execution_id、control_version及desired_state。命令幂等;不存在当前执行时只登记意图。worker清理后返回带相同执行代次的ACK。已有 `/cancel` 保持用户取消终态语义,不能拿它冒充夜间暂停。
### 4.4 08:00与故障
### 4.4 08:00关闭准入、当前执行自然完成
所有标为batch的计算步骤受窗口限制:自管GPU、Whisper、CPU编码、Kokoro,以及经验证可停止的远端HTTP推理。08:00后禁止新计算;运行中的步骤请求停止并释放,下一窗口恢复未完成步骤。状态同步、清理、文件归档可以白天继续,它们不得启动新的模型或编码。
08:00之后不再领取新的batch镜头/处理阶段,任务持久排队至下一窗口;已经开始的镜头或处理阶段继续到成功/失败。父Run正在运行不授予剩余镜头或合成白天自动执行的权限。阶段之间先持久化结果再重新检查窗口。
初始配置:窗口检查0.5秒,独立监管检查1秒,最后30秒不启动新的batch执行,清理ACK等待15秒;这些是待实测的工程默认值。截止触发不等于显存已经释放;超15秒未确认则cleanup_pending/blocked并告警,不能宣称零延迟或继续领取新任务。
窗口关闭本身绝不发送kill、cancel或共享Qwen abort。手工暂停也只关闭后续准入,当前执行自然完成;用户显式取消仍可清理自己的CPU/GPU作业。外部用户占用同GPU时,原有自管GPU让卡规则高于自然完成,被抢占后的batch重启须等待下个窗口。排队顺序为持久FIFO与明确公平策略,不按LIFO“栈”执行。
worker在启动计算前登记带执行代次的本地lease/deadline,并取得监管确认。API或worker卡死后,监管仍能终止已登记的自有执行。监管只接受固定允许容器/cgroup/UID,并核验PID、starttime、boot_id、execution/fence;不从可写metadata接受任意宿主PID。CPU/TTS的batch子进程同样需要单执行标识与停止确认。
worker须在claim和spawn前复核窗口;已spawn之后不再因08:00检查停止。监控/进程身份、硬崩溃fail-closed与清理确认规则继续用于自管进程安全,而不是夜间强制终止。CPU/Kokoro继续使用现有同步私有接口,无需新增截止/abort协议。
停止确认需进程清理ACK和清理动作之后的新监控快照证明自己的GPU PID已消失;进程组为空、TTL过期或显存数值下降都不能单独当释放证明。若外部用户正在用卡,不要求显存回到原基线,只确认自有资源消失。异常时保留全局槽并blocked,不进行双运行。
Kokoro私有服务增加execution v2能力:`POST /internal/executions/{id}/speech`登记后返回202,`GET /internal/executions/{id}`查询,`PUT .../control`停止并返回执行代次ACK,`GET .../audio`仅在完成后取WAV;全部沿用私有Bearer认证。登记、deadline、结果manifest在本地持久化,确认监管接管前不启动模型子进程;同ID不同请求409。现有同步 `/v1/audio/speech` 保持交互兼容,网站未检测到v2能力时不把同步断连当成batch停止。FFmpeg启动前也使用同样的登记/许可门槛。
上述承诺覆盖网站/API登记的任务;它不能替代整个服务器所有用户的统一准入系统。现有Qwen请求若没有request_id、abort与结束ACK,则batch能力保持关闭;交互调用继续复用且单独限额。
共享Qwen只管理本应用请求,不操作其服务PID。网络结果不明进入恢复/待确认状态,不重复发起新推理;HTTP连接关闭不作为共享服务停止证明。这里不承诺所有用户的硬件统一调度,也不承诺强制08:00释放正在运行的资源。
## 5. 工作流、时间轴与前后端契约
### 5.1 一期固定工作流
三镜头提示词和参考图在提交前确认。若需要Qwen辅助写脚本,先作为交互步骤完成并写入草稿;不在未验证可取消的batch中隐式调用Qwen。
三镜头提示词和参考图在提交前确认。Qwen写脚本和配音可先作为独立任务完成后填入草稿。按最新自然完成规则,Qwen理解/推演及Kokoro也支持显式batch;每次新HTTP处理阶段检查窗口,当前请求继续完成,不要求共享服务abort能力。
Run状态:queued/running/paused/blocked/cancelling/succeeded/cancelled/failed。blocked/step_failed表示需要重试某一步,不能自动合成;failed用于不可恢复错误,用户结束使用cancel。succeeded/cancelled/failed均为终态。
@ -212,11 +208,11 @@ SSE事件保留30天,最小可重放cursor单独记录;早于它的客户端
| 里程碑 | 依赖和交付 | 必须通过 |
| --- | --- | --- |
| M0 | 协议/取消能力验证、数据基线与可恢复备份 | 旧请求恢复不重复;Qwen batch明确支持或禁用;恢复点可对账 |
| M0 | 协议/夜间准入验证、数据基线与可恢复备份 | 旧请求恢复不重复;运行跨08自然完成;恢复点可对账 |
| M1 | R1–R5、幂等提交、Execution/manifest、资产对账、停机 | 响应丢失、DB提交结果不明、重启、重复cancel、旧结果迟到故障注入 |
| M2 | 上游v2、窗口/监管/公平领取、CPU暂停 | 21/08边界、worker07:59:59硬杀、时钟变化、尾进程/旧快照、全卡长期忙;无双运行 |
| M2 | 上游v2、窗口/公平领取、阶段资源 | 21/08边界、当前执行跨界完成、后续排队、时钟变化、崩溃无双运行 |
| M3 | Draft/Run/Step、父子事务与API、三镜头媒体规范化 | 失败镜头单独重试、旧Run不覆盖、父取消竞争、360帧、横竖版与音轨/字幕边界 |
| M4 | Vue草稿/任务中心/批量入口、账号/标签/分页 | 多标签冲突、断网刷新、额度拒绝、跨账号不可读、父子事件乱序 |
| M5 | 公网接入与上线演练 | 真实MySQL及小规格模型端到端、真实默认规格三镜头、恢复演练、配额和外部Token;HTTPS入口SSE/Range通过 |
实施文件、接口签名和分任务回归见[执行计划](superpowers/plans/2026-11-10-cmvr-visual-v2.md)。先完成M0–M2,再并行前后端业务;不要先开放批量页面后补上游约束。所有生产迁移、监管升级和公网配置仍需在实际实施阶段执行,本次仅补充方案。
实施文件、接口签名和分任务回归见[执行计划](superpowers/plans/2026-11-10-cmvr-visual-v2.md)。当前已完成上游协议升级、正式库003迁移和私有网站部署;公网域名/HTTPS及专用数据库账号仍留在公开发布门槛内,实际验收记录与原设计目标分别列明。

View File

@ -128,7 +128,7 @@ HTTP适合上传、任务命令和结果下载,SSE负责状态、让卡与结
| 批量任务 | 仅Asia/Shanghai 21:00–次日08:00具备执行资格,白天明确显示等待窗口 |
| 同用户有多个等待任务 | 交互优先选取,批量之间按批次公平和创建顺序;不因新交互请求无条件打断已经执行的自身任务 |
| 其他用户开始占卡 | 停止自己的当前GPU推理、等待显存回收后重排,同一上游任务ID继续跟踪 |
| 到08:00仍有批量执行 | 暂停当前批量步骤并清理/释放资源,保留已完成步骤,下一窗口重新执行未完成步骤;白天不能以“恢复中”为由继续批量生成 |
| 到08:00仍有批量执行 | 按用户后续修订:当前已启动镜头/处理阶段自然完成,后续阶段持久排队至下一窗口;不因窗口关闭停止共享Qwen |
| 夜间中断/抢占 | 当前模型推理进度可能丢失;已完成镜头不重跑。这里的恢复是工作流步骤级,不承诺保存扩散latent或模型计算断点 |
不能简单用现有 `/cancel` 模拟夜间暂停:cancel是终态,同幂等键会返回已取消任务。应在既有GPU worker补可重排的窗口资格与暂停原因,并让被时间窗口挡住的批量任务不阻塞交互任务;网页显示等待时间与原因。

View File

@ -8,23 +8,24 @@ import { useJobsStore } from './stores/jobs'
import { useAssetsStore } from './stores/assets'
import { useDraftsStore } from './stores/drafts'
import { useCapabilitiesStore } from './stores/capabilities'
import {useWorkflowsStore} from './stores/workflows'
import { errorMessage } from './api'
import { phaseLabel,stateLabel } from './format'
const route=useRoute(),router=useRouter(),auth=useAuthStore(),jobs=useJobsStore(),assets=useAssetsStore(),drafts=useDraftsStore(),caps=useCapabilitiesStore(),systemOpen=ref(false)
const nav=[{path:'/create/image',label:'创作',icon:MagicStick},{path:'/audio',label:'声音',icon:Headset},{path:'/math',label:'推演',icon:Document},{path:'/analyze',label:'理解',icon:DataAnalysis},{path:'/compose',label:'成片',icon:Scissor},{path:'/assets',label:'素材',icon:FolderOpened},{path:'/tasks',label:'任务',icon:Clock}]
const nav=[{path:'/workflow',label:'工作流',icon:MagicStick},{path:'/batch',label:'批量',icon:Clock},{path:'/account',label:'账户',icon:Document},{path:'/create/image',label:'创作',icon:MagicStick},{path:'/audio',label:'声音',icon:Headset},{path:'/math',label:'推演',icon:Document},{path:'/analyze',label:'理解',icon:DataAnalysis},{path:'/compose',label:'成片',icon:Scissor},{path:'/assets',label:'素材',icon:FolderOpened},{path:'/tasks',label:'任务',icon:Clock}]
const ongoing=computed(()=>jobs.active.find(job=>['running','collecting','cancelling'].includes(job.state))||jobs.active.find(job=>job.state==='queued'))
const connectionLabel=computed(()=>jobs.connection==='live'?'实时同步':jobs.connection==='connecting'?'连接中':'正在恢复连接')
let poll:ReturnType<typeof setInterval>|undefined
function clearSession(){jobs.reset();assets.clear();drafts.clear();caps.items=[];clearInterval(poll)}
function clearSession(){jobs.reset();assets.clear();drafts.clear();caps.items=[];useWorkflowsStore().reset();clearInterval(poll)}
function expired(){auth.clear();clearSession();if(route.path!=='/login')void router.replace({path:'/login',query:{redirect:route.fullPath}})}
watch(()=>auth.user?.id,id=>{clearInterval(poll);if(id){void caps.load();void jobs.connect();poll=setInterval(()=>{void caps.load()},30000)}else clearSession()},{immediate:true})
watch(()=>auth.user?.id,id=>{clearInterval(poll);if(id){drafts.setOwner(id);void useWorkflowsStore().refresh().catch(()=>undefined);void caps.load();void jobs.connect();poll=setInterval(()=>{void caps.load()},30000)}else clearSession()},{immediate:true})
async function logout(){try{await auth.logout();clearSession();await router.replace('/login')}catch(error){ElMessage.error(errorMessage(error))}}
onMounted(()=>window.addEventListener('cmvr:unauthorized',expired));onBeforeUnmount(()=>{window.removeEventListener('cmvr:unauthorized',expired);clearInterval(poll);jobs.disconnect()})
</script>
<template>
<RouterView v-if="route.path==='/login'" />
<div v-else class="app-shell"><aside class="sidebar"><router-link to="/create/image" class="brand" aria-label="CMVR Visual 创作首页"><span class="brand-glyph">V</span><span class="brand-caption">CMVR</span></router-link><nav class="side-nav"><router-link v-for="item in nav" :key="item.path" :to="item.path" :class="{selected:item.path==='/create/image'?route.path.startsWith('/create'):route.path.startsWith(item.path)}"><el-icon><component :is="item.icon" /></el-icon><span>{{ item.label }}</span><i v-if="item.path==='/tasks'&&jobs.active.length" class="nav-notification"/></router-link></nav><div class="sidebar-bottom"><el-tooltip content="服务状态" placement="right"><button aria-label="服务状态" @click="systemOpen=true"><el-icon><Connection /></el-icon></button></el-tooltip><el-dropdown trigger="click" placement="right-end"><button class="avatar-button" :aria-label="auth.user?.display_name||'账户'">{{ (auth.user?.display_name||auth.user?.username||'U').slice(0,1) }}</button><template #dropdown><el-dropdown-menu><el-dropdown-item disabled>{{ auth.user?.display_name||auth.user?.username }}</el-dropdown-item><el-dropdown-item divided :icon="SwitchButton" @click="logout">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div></aside>
<div class="app-main"><header class="app-header"><div class="header-breadcrumb"><span>CMVR Visual</span><span class="breadcrumb-separator">/</span><strong>{{ route.meta.title }}</strong></div><div class="header-actions"><button class="connection-status" :class="jobs.connection" @click="systemOpen=true"><span class="live-dot"/>{{ connectionLabel }}</button><span class="header-divider"/><span class="local-label">{{ caps.environment === 'production' ? '本地创作空间' : caps.environment ? '验收环境' : '环境待确认' }}<template v-if="caps.environment && caps.environment !== 'production'"> · {{ caps.databaseBackend === 'mysql' ? 'MySQL' : 'SQLite' }}</template></span></div></header><div v-if="jobs.connection==='reconnecting'" class="connection-banner"><el-icon><Warning /></el-icon>连接恢复中,任务状态待同步。<button @click="jobs.refresh().catch(()=>undefined)">重新同步</button></div><main class="page-content"><RouterView /></main><button v-if="ongoing" class="global-queue-bar" @click="router.push({path:'/tasks',query:{job:ongoing.id}})"><span class="queue-spinner"/><strong>{{ stateLabel(ongoing) }}</strong><span>{{ phaseLabel(ongoing) }}</span><small v-if="jobs.active.length>1">另有 {{ jobs.active.length-1 }} 项活动任务</small><el-icon><ArrowRight /></el-icon></button></div>
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>模型能力</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p class="muted">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
<div class="app-main"><header class="app-header"><div class="header-breadcrumb"><span>CMVR Visual</span><span class="breadcrumb-separator">/</span><strong>{{ route.meta.title }}</strong></div><div class="header-actions"><button class="connection-status" :class="jobs.connection" @click="systemOpen=true"><span class="live-dot"/>{{ connectionLabel }}</button><span class="header-divider"/><span class="local-label">{{ caps.environment === 'production' ? '本地创作空间' : caps.environment ? '验收环境' : '环境待确认' }}<template v-if="caps.environment && caps.environment !== 'production'"> · {{ caps.databaseBackend === 'mysql' ? 'MySQL' : 'SQLite' }}</template></span></div></header><div v-if="jobs.connection==='reconnecting'" class="connection-banner"><el-icon><Warning /></el-icon>连接恢复中,任务状态待同步。<button @click="jobs.refresh().catch(()=>undefined)">重新同步</button></div><main class="page-content"><div v-if="auth.user?.must_change_password" class="notice warning">请先到 <router-link to="/account">账户设置</router-link> 修改初始密码。</div><RouterView /></main><button v-if="ongoing" class="global-queue-bar" @click="router.push({path:'/tasks',query:{job:ongoing.id}})"><span class="queue-spinner"/><strong>{{ stateLabel(ongoing) }}</strong><span>{{ phaseLabel(ongoing) }}</span><small v-if="jobs.active.length>1">另有 {{ jobs.active.length-1 }} 项活动任务</small><el-icon><ArrowRight /></el-icon></button></div>
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>连接与调度</h3><p>推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}</p><p v-if="caps.executionPolicy">批量窗口:{{ caps.executionPolicy.timezone }} {{ caps.executionPolicy.start }}–{{ caps.executionPolicy.end }} · {{ caps.executionPolicy.batch_open?"开放":"等待下一窗口" }}<br/>08:00 后当前阶段继续完成,新阶段等待下一窗口。<br/>下次窗口 {{ caps.executionPolicy.next_batch_at }}</p><h3>模型能力配置</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p class="muted">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
</div>
</template>

10
frontend/src/api.test.ts Normal file
View File

@ -0,0 +1,10 @@
import {beforeEach,afterEach,describe,expect,it,vi} from 'vitest'
import {api,setCsrfToken} from './api'
import {pendingSubmissions,setStorageOwner} from './outbox'
const saved=new Map<string,string>()
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('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"}')})
})

View File

@ -1,3 +1,5 @@
import { durableRequest } from './outbox'
import type { DraftDTO, RunSnapshot, RunDTO, BatchSnapshot, BatchDTO, WorkflowSpec, TokenRecord } from './v2types'
import type { Asset, AuthResponse, CapabilitiesResponse, Job, JobRequest, JobsPage, Page, Scheduler, Capability } from './types'
let csrfToken = ''
@ -11,7 +13,7 @@ export function queryString(values: Record<string, unknown> = {}) {
return search.size ? `?${search}` : ''
}
export function newRequestId() { return globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}` }
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
export async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
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')
@ -34,16 +36,38 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
return response.json() as Promise<T>
}
export const api = {
workflows: (filters:Record<string,unknown>={}) => request<Page<DraftDTO>>(`/workflows${queryString(filters)}`),
workflow: (id:string) => request<DraftDTO>(`/workflows/${id}`),
createWorkflow: (name:string,spec:WorkflowSpec) => request<DraftDTO>('/workflows',{method:'POST',body:JSON.stringify({name,spec,kind:'three_shot'})}),
saveWorkflow: (draft:DraftDTO,name:string,spec:WorkflowSpec) => request<DraftDTO>(`/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<RunSnapshot>('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<string,unknown>={}) => request<Page<RunDTO>>(`/workflow-runs${queryString(filters)}`),
run: (id:string) => request<RunSnapshot>(`/workflow-runs/${id}`),
controlRun: (run:RunDTO,action:'pause'|'resume'|'cancel') => durable<RunSnapshot>(`workflow.${action}`,`/workflow-runs/${run.id}/${action}`,{expected_version:run.version}),
retryStep: (run:RunDTO,key:string,jobId:string) => durable<RunSnapshot>('workflow.retry',`/workflow-runs/${run.id}/steps/${key}/retry`,{expected_run_version:run.version,target_job_id:jobId}),
batches: (filters:Record<string,unknown>={}) => request<Page<BatchDTO>>(`/batches${queryString(filters)}`),
batch: (id:string) => request<BatchSnapshot>(`/batches/${id}`),
createBatch: (body:unknown) => durable<BatchSnapshot>('batch.create','/batches',body),
controlBatch: (batch:BatchDTO,desired_state:string) => durable<BatchSnapshot>('batch.control',`/batches/${batch.id}/control`,{desired_state,expected_version:batch.version}),
submission: (key:string,operation:string) => request<unknown>(`/submissions/${encodeURIComponent(key)}${queryString({operation})}`),
recover: (entry:{operation:string;path:string;body:string}) => durable<unknown>(entry.operation,entry.path,JSON.parse(entry.body)),
users: (page=1) => request<Page<import('./types').User>>(`/auth/users?page=${page}&page_size=20`),
createUser: (body:unknown) => request<import('./types').User>('/auth/users',{method:'POST',body:JSON.stringify(body)}),
updateUser: (id:string,body:unknown) => request<import('./types').User>(`/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<void>(`/auth/tokens/${id}`,{method:'DELETE'}),
me: () => request<AuthResponse>('/auth/me'),
login: (username: string, password: string) => request<AuthResponse>('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),
logout: () => request<void>('/auth/logout', { method: 'POST' }),
capabilities: () => request<CapabilitiesResponse>('/capabilities'),
systemStatus: () => request<{ inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'),
systemStatus: () => request<{ execution_policy?: {timezone:string;start:string;end:string;batch_open:boolean;next_batch_at:string;close_behavior:string}; inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'),
jobs: (filters: Record<string, unknown> = {}) => request<JobsPage>(`/jobs${queryString(filters)}`),
job: (id: string) => request<Job>(`/jobs/${encodeURIComponent(id)}`),
submit: (body: JobRequest) => request<{ jobs: Job[] }>('/jobs', { method: 'POST', headers: { 'Idempotency-Key': newRequestId() }, body: JSON.stringify(body) }),
submit: (body: JobRequest) => durable<{jobs:Job[]}>('jobs.create','/jobs',body),
cancel: (id: string) => request<Job>(`/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }),
retry: (id: string) => request<{ jobs: Job[] }>(`/jobs/${encodeURIComponent(id)}/retry`, { method: 'POST' }),
retry: (id: string) => durable<{jobs:Job[]}>('jobs.retry',`/jobs/${encodeURIComponent(id)}/retry`,{}),
assets: (filters: Record<string, unknown> = {}) => request<Page<Asset>>(`/assets${queryString(filters)}`),
asset: (id: string) => request<Asset>(`/assets/${encodeURIComponent(id)}`),
upload: (file: File) => { const form = new FormData(); form.set('file', file); return request<Asset>('/assets', { method: 'POST', body: form }) },
@ -51,3 +75,5 @@ export const api = {
deleteAsset: (id: string) => request<void>(`/assets/${encodeURIComponent(id)}`, { method: 'DELETE' }),
}
export function errorMessage(error: unknown) { return error instanceof Error ? error.message : '操作未完成,请稍后重试' }
function durable<T>(operation:string,path:string,body:unknown){return durableRequest<T>(operation,path,body,(url,key,payload)=>request<T>(url,{method:"POST",headers:{"Idempotency-Key":key},body:payload}))}

View File

@ -22,9 +22,9 @@ async function copy(value: string) { try { await copyText(value); ElMessage.succ
<div v-loading="loading" class="job-detail">
<template v-if="job">
<div class="detail-heading"><span class="status-pill" :class="job.state">{{ stateLabel(job) }}</span><small>{{ taskLabels[job.task_type] }}</small></div>
<h2>{{ job.prompt || taskLabels[job.task_type] }}</h2><p class="muted">{{ phaseLabel(job) }}</p>
<p v-if="job.run_id" class="notice">工作流子任务 · {{ job.step_key }}<br/>请在父工作流中重试此阶段。</p><h2>{{ job.prompt || taskLabels[job.task_type] }}</h2><p class="muted">{{ phaseLabel(job) }}</p>
<el-progress v-if="job.progress !== null && isActive(job)" :percentage="Math.max(0, Math.min(100, job.progress))" :stroke-width="5" :show-text="true" />
<div class="detail-actions"><el-button v-if="isActive(job)" :icon="Close" :loading="busy" :disabled="job.cancel_requested" @click="cancel">{{ job.cancel_requested ? '正在取消' : '取消任务' }}</el-button><el-button v-else type="primary" :icon="RefreshRight" :loading="busy" @click="retry">{{ job.state === 'succeeded' ? '再生成一次' : '重新提交' }}</el-button><el-button text :icon="CopyDocument" @click="copy(job.prompt)">复制提示词</el-button></div>
<div class="detail-actions"><el-button v-if="isActive(job)" :icon="Close" :loading="busy" :disabled="job.cancel_requested" @click="cancel">{{ job.cancel_requested ? '正在取消' : '取消任务' }}</el-button><el-button v-else-if="!job.run_id" type="primary" :icon="RefreshRight" :loading="busy" @click="retry">{{ job.state === 'succeeded' ? '再生成一次' : '重新提交' }}</el-button><el-button text :icon="CopyDocument" @click="copy(job.prompt)">复制提示词</el-button></div>
<div v-if="job.sync_warning" class="notice warning">{{ job.sync_warning }}<br />尚未将同步中断视为生成失败。</div>
<div v-if="job.error" class="notice danger"><strong>{{ job.error.code }}</strong><p>{{ job.error.message }}</p></div>
<section v-if="job.result_assets.length" class="detail-section"><h3>最终产物 <span>{{ job.result_assets.length }}</span></h3><div class="detail-assets"><button v-for="asset in job.result_assets" :key="asset.id" @click="selected = asset"><img v-if="asset.kind === 'image' || asset.thumbnail_url" :src="asset.thumbnail_url || asset.preview_url" :alt="asset.name" /><span v-else class="file-cover">{{ asset.kind.toUpperCase() }}</span><strong>{{ asset.name }}</strong></button></div></section>

View File

@ -0,0 +1,30 @@
import {describe,expect,it,vi} from 'vitest'
import {createSSRApp,defineComponent,h} from 'vue'
import {renderToString} from 'vue/server-renderer'
import {createPinia} from 'pinia'
import RunCard from './RunCard.vue'
import type {RunDTO,RunSnapshot,StepDTO} from '../v2types'
vi.mock('./AssetPreview.vue',()=>({default:{render:()=>null}}))
vi.mock('./JobDetail.vue',()=>({default:{render:()=>null}}))
const run:RunDTO={id:'run',draft_id:'draft',draft_revision:1,state:'running',desired_state:'run',execution_mode:'interactive',version:1,result_assets:[],created_at:'now',completed_steps:0,total_steps:4}
function step(key:string):StepDTO{return {id:key,run_id:run.id,step_key:key,kind:key==='compose'?'video.compose':'video.generate',state:'waiting',selected_job_id:null,explicit_attempt:0,dependencies:[],semantic_input_hash:'hash'}}
async function render(snapshot:RunSnapshot){const app=createSSRApp(RunCard,{snapshot});app.use(createPinia());app.component('ElButton',defineComponent({setup(_,{slots}){return()=>h('button',slots.default?.())}}));app.component('ElTag',{render:()=>null});return renderToString(app)}
describe('RunCard presentation',()=>{
it('shows shots one to three then compose even if API steps are lexicographically ordered, without mutating the snapshot',async()=>{
const snapshot:RunSnapshot={run,steps:['compose','shot_1','shot_2','shot_3'].map(step),jobs:[]}
const html=await render(snapshot),labels=['镜头一','镜头二','镜头三','成片渲染']
expect(labels.map(label=>html.indexOf(label))).toEqual([...labels.map(label=>html.indexOf(label))].sort((a,b)=>a-b))
expect(snapshot.steps.map(s=>s.step_key)).toEqual(['compose','shot_1','shot_2','shot_3'])
})
it('gives a code-only failed step a visible Chinese error notice',async()=>{
const html=await render({run:{...run,error:{code:'step_failed',step_key:'shot_2'}},steps:[],jobs:[]})
expect(html).toContain('class="notice danger">镜头二执行失败,请查看子任务详情。')
})
it.each([['storage_insufficient','存储空间不足'],['owner_disabled','账户已被管理员停用'],['dependency_changed','依赖素材或阶段已变更']])('explains backend code %s with no message',async(code,text)=>{
expect(await render({run:{...run,error:{code,message:' '}},steps:[],jobs:[]})).toContain(text)
})
it('uses a meaningful generic notice for unknown error codes and preserves explicit messages',async()=>{
expect(await render({run:{...run,error:{code:'new_error'}},steps:[],jobs:[]})).toContain('工作流暂时无法继续,请查看任务详情或同步后重试。')
expect(await render({run:{...run,error:{code:'step_failed',message:'素材缺失'}},steps:[],jobs:[]})).toContain('class="notice danger">素材缺失')
})
})

View File

@ -0,0 +1,32 @@
import {afterEach,describe,expect,it,vi} from 'vitest'
import {createSSRApp,defineComponent,h} from 'vue'
import {renderToString} from 'vue/server-renderer'
import {createPinia,setActivePinia} from 'pinia'
import {api} from '../api'
import {useWorkflowsStore} from '../stores/workflows'
import type {RunSnapshot} from '../v2types'
import RunCard from './RunCard.vue'
vi.mock('./AssetPreview.vue',()=>({default:{render:()=>null}}))
vi.mock('./JobDetail.vue',()=>({default:{render:()=>null}}))
afterEach(()=>vi.restoreAllMocks())
const snapshot:RunSnapshot={run:{id:'alice-private-run',draft_id:'alice-private-draft',draft_revision:1,state:'running',desired_state:'run',execution_mode:'interactive',version:1,result_assets:[],created_at:'now',completed_steps:0,total_steps:4},steps:[],jobs:[]}
async function pauseButton(){
const pinia=createPinia();setActivePinia(pinia);const clicks:(()=>Promise<void>)[]=[]
const application=createSSRApp(RunCard,{snapshot});application.use(pinia)
application.component('ElButton',defineComponent({setup(_,{attrs,slots}){if(typeof attrs.onClick==='function')clicks.push(attrs.onClick as ()=>Promise<void>);return()=>h('button',slots.default?.())}}))
application.component('ElTag',{render:()=>null})
await renderToString(application)
return {click:clicks[1]!,store:useWorkflowsStore(pinia)}
}
describe('compiled RunCard auth isolation',()=>{
it('cannot apply a late Alice control response after reset and Bob login',async()=>{
let resolve!:(value:RunSnapshot)=>void;vi.spyOn(api,'controlRun').mockImplementation(()=>new Promise(r=>resolve=r))
const {click,store}=await pauseButton(),pending=click();store.reset();resolve(snapshot);await pending
expect(store.runs).toEqual({});expect(store.drafts).toEqual({})
})
it('does not refetch Alice run under Bob after delayed failure',async()=>{
let reject!:(error:Error)=>void;vi.spyOn(api,'controlRun').mockImplementation(()=>new Promise((_r,j)=>reject=j));const reload=vi.spyOn(api,'run')
const {click,store}=await pauseButton(),pending=click();store.reset();reject(new Error('alice failure'));await pending
expect(reload).not.toHaveBeenCalled();expect(store.runs).toEqual({});expect(store.drafts).toEqual({})
})
})

View File

@ -0,0 +1,19 @@
<script setup lang="ts">
import {computed,ref} from 'vue'
import {ElMessage} from 'element-plus'
import {workflowState,holdLabel,workflowStepLabel,workflowErrorLabel} from '../format'
import {errorMessage} from '../api'
import {useWorkflowsStore} from '../stores/workflows'
import {useJobsStore} from '../stores/jobs'
import type {RunSnapshot,StepDTO} from '../v2types'
import AssetPreview from './AssetPreview.vue'
import JobDetail from './JobDetail.vue'
import type {Asset} from '../types'
const props=defineProps<{snapshot:RunSnapshot}>(),store=useWorkflowsStore(),jobs=useJobsStore(),busy=ref(false),preview=ref<Asset|null>(null),detail=ref<string|null>(null)
const run=computed(()=>props.snapshot.run)
const orderedSteps=computed(()=>{const order:Record<string,number>={shot_1:0,shot_2:1,shot_3:2,compose:3,render:3};return [...props.snapshot.steps].sort((a,b)=>(order[a.step_key]??4)-(order[b.step_key]??4))})
async function control(action:'pause'|'resume'|'cancel'){busy.value=true;try{await store.controlRun(run.value,action)}catch(e){ElMessage.error(errorMessage(e))}finally{busy.value=false}}
async function retry(step:StepDTO){if(!step.selected_job_id)return;busy.value=true;try{await store.retryStep(run.value,step.step_key,step.selected_job_id)}catch(e){ElMessage.error(errorMessage(e))}finally{busy.value=false}}
function selectedState(step:StepDTO){const snapshot=props.snapshot.jobs.find(j=>j.id===step.selected_job_id),live=jobs.byId[step.selected_job_id||''];return (live&&(!snapshot||live.version>snapshot.version)?live:snapshot)?.state||step.state}
</script>
<template><article class="surface v2-panel"><div class="v2-toolbar"><strong>工作流 · {{ run.id.slice(0,8) }}</strong><span class="status-pill">{{ workflowState(run.state) }}</span><small>r{{ run.draft_revision }} · v{{ run.version }} · {{ run.execution_mode==='batch'?'夜间批量':'全天交互' }}</small><el-tag v-if="store.drafts[run.draft_id]&&store.drafts[run.draft_id]!.revision!==run.draft_revision" type="info">历史修订产物</el-tag><el-tag v-if="store.drafts[run.draft_id]?.current_run_id&&store.drafts[run.draft_id]!.current_run_id!==run.id" type="info">历史运行</el-tag><span>{{ run.completed_steps }}/{{ run.total_steps }}</span><el-button :loading="busy" @click="store.fetchRun(run.id)">同步</el-button><template v-if="!['succeeded','cancelled'].includes(run.state)"><el-button :disabled="busy" @click="control(run.desired_state==='pause'?'resume':'pause')">{{ run.desired_state==='pause'?'继续':'暂停后续阶段' }}</el-button><el-button type="danger" text :disabled="busy" @click="control('cancel')">取消</el-button></template></div><p v-if="run.hold_reasons?.length" class="notice warning">等待条件:{{ run.hold_reasons.map(holdLabel).join('、') }}</p><p v-if="run.desired_state==='pause'" class="muted">当前执行阶段完成后暂停后续阶段。</p><p v-if="run.error" class="notice danger">{{ workflowErrorLabel(run.error) }}</p><div class="v2-steps"><div v-for="step in orderedSteps" :key="step.id" class="v2-step"><strong>{{ workflowStepLabel(step.step_key) }}</strong><span>{{ workflowState(selectedState(step)) }}</span><small>显式尝试 {{ step.explicit_attempt }}</small><button v-if="step.selected_job_id" class="text-link" @click="detail=step.selected_job_id">子任务 {{ step.selected_job_id.slice(0,8) }}</button><el-button v-if="step.selected_job_id&&['failed','timed_out','needs_attention'].includes(selectedState(step))" text :disabled="busy" @click="retry(step)">重试此阶段</el-button></div></div><div class="v2-actions"><el-button v-for="asset in run.result_assets||[]" :key="asset.id" type="primary" @click="preview=asset">预览 {{ asset.name }}</el-button></div><AssetPreview v-model:asset="preview"/><JobDetail v-model:job-id="detail"/></article></template>

View File

@ -0,0 +1,13 @@
import {computed,onBeforeUnmount,ref,watch} from 'vue'
import type {Ref} from 'vue'
import type {TaskType} from '../types'
import {api,errorMessage} from '../api'
import {useJobsStore} from '../stores/jobs'
export function useTaskHistory(type:Ref<TaskType>,pageSize=20){
const store=useJobsStore(),ids=ref<string[]>([]),page=ref(1),total=ref(0),error=ref('');let version=0,timer:ReturnType<typeof setTimeout>|undefined
const items=computed(()=>ids.value.map(id=>store.byId[id]).filter(Boolean))
async function load(){const generation=++version;try{const result=await api.jobs({task_type:type.value,page:page.value,page_size:pageSize,root_only:true});if(version!==generation)return;store.ingestSnapshot(result.items,result.cursor);ids.value=result.items.map(j=>j.id);total.value=result.total;error.value=''}catch(e){if(generation===version)error.value=errorMessage(e)}}
watch(type,()=>{page.value=1;ids.value=[];void load()},{immediate:true});watch(page,()=>void load());watch(()=>store.cursor,()=>{clearTimeout(timer);timer=setTimeout(()=>void load(),400)})
onBeforeUnmount(()=>{version++;clearTimeout(timer)})
return {items,page,total,error,load}
}

View File

@ -0,0 +1,6 @@
import {describe,expect,it} from 'vitest'
import {holdLabel,workflowState} from './format'
describe('workflow waiting and job state copy',()=>{
it.each([['ready','就绪'],['submitting','正在提交'],['collecting','正在归档'],['scheduled','预约中'],['pausing','正在暂停']])('translates %s', (value,label)=>expect(workflowState(value)).toBe(label))
it.each([['admin_suspend','管理员已暂停任务'],['quota','等待可用配额'],['storage','等待可用存储空间']])('explains %s hold', (value,label)=>expect(holdLabel(value)).toBe(label))
})

View File

@ -4,12 +4,12 @@ export const taskLabels: Record<TaskType, string> = {
'audio.transcribe': '语音转写', 'audio.speech': '语音生成', 'math.solve': '数学推演',
'media.structure': '素材理解', 'video.compose': '成片合成',
}
export const activeStates = new Set(['scheduled', 'submitting', 'queued', 'running', 'collecting', 'cancelling'])
export const activeStates = new Set(['scheduled', 'submitting', 'queued', 'running', 'collecting', 'cancelling','paused','waiting_window','needs_attention'])
export function isActive(job: Job) { return activeStates.has(job.state) }
export function stateLabel(job: Job) {
if (job.cancel_requested && isActive(job)) return '正在取消'
if (job.state === 'queued' && job.preemptions > 0) return '等待自动重试'
return { scheduled: '预约中', submitting: '正在提交', queued: '等待算力', running: '正在创作', collecting: '正在归档', cancelling: '正在取消', succeeded: '已完成', failed: '未完成', cancelled: '已取消', timed_out: '已超时' }[job.state]
return { needs_attention:'需要处理',paused:'已暂停',waiting_window:'等待夜间窗口',scheduled: '预约中', submitting: '正在提交', queued: '等待算力', running: '正在创作', collecting: '正在归档', cancelling: '正在取消', succeeded: '已完成', failed: '未完成', cancelled: '已取消', timed_out: '已超时' }[job.state]
}
export function reasonText(reason: string | null) {
if (!reason) return ''
@ -18,6 +18,7 @@ export function reasonText(reason: string | null) {
return reason
}
export function phaseLabel(job: Job) {
if(job.hold_reasons?.length)return job.hold_reasons.map(holdLabel).join(';')
if (job.error) return job.error.message
if (job.sync_warning) return job.sync_warning
if (job.cancel_requested && isActive(job)) return '等待当前进程释放资源'
@ -32,3 +33,15 @@ export function formatDate(value: string | null) { return value ? new Intl.DateT
export function formatBytes(bytes: number) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1048576).toFixed(1)} MB` }
export function formatDuration(value: number | null) { if (value === null) return '—'; return value >= 60 ? `${Math.floor(value / 60)}:${Math.round(value % 60).toString().padStart(2, '0')}` : `${value.toFixed(1)} 秒` }
export async function copyText(value: string) { await navigator.clipboard.writeText(value) }
export function workflowState(value:string){return ({ready:"就绪",submitting:"正在提交",collecting:"正在归档",scheduled:"预约中",pausing:"正在暂停",waiting:"等待依赖",queued:"排队中",running:"执行中",paused:"已暂停",waiting_window:"等待夜间窗口",needs_attention:"需要处理",succeeded:"已完成",failed:"失败",cancelled:"已取消",cancelling:"取消中",completed_with_errors:"完成(含失败)",blocked:"等待处理",timed_out:"超时"} as Record<string,string>)[value]||value}
export function holdLabel(value:string){return ({admin_suspend:"管理员已暂停任务",quota:"等待可用配额",storage:"等待可用存储空间",window:"等待夜间窗口;当前阶段完成后再等待",batch_pause:"批量已暂停",batch_fifo:"等待前序任务",batch_wait:"等待批量前序任务",manual:"手动暂停",maintenance:"维护中",external_gpu_usage:"外部 GPU 使用优先",disabled_user:"账户已禁用"} as Record<string,string>)[value]||value}
export function workflowStepLabel(key:string){return ({shot_1:'镜头一',shot_2:'镜头二',shot_3:'镜头三',render:'成片渲染',compose:'成片渲染'} as Record<string,string>)[key]||key}
export function workflowErrorLabel(error:{code:string;message?:string;step_key?:string}){
if(error.message?.trim())return error.message
const step=error.step_key?workflowStepLabel(error.step_key):'工作流阶段'
if(error.code==='step_failed')return `${step}执行失败,请查看子任务详情。`
if(error.code==='step_cancelled')return `${step}已取消,工作流等待处理。`
return ({dependency_changed:'依赖素材或阶段已变更,请检查工作流后重新提交。',quota_exceeded:'可用配额不足,工作流等待配额恢复。',storage_full:'存储空间不足,请清理素材或联系管理员。',storage_insufficient:'存储空间不足,请清理素材或联系管理员。',owner_disabled:'账户已被管理员停用,工作流等待处理。',workflow_admission_failed:'工作流暂时无法开始下一阶段,请同步状态后重试。',workflow_orchestration_failed:'工作流阶段衔接失败,请查看任务详情或同步后重试。',storage_quota_exceeded:'存储配额不足,请清理素材或联系管理员。'} as Record<string,string>)[error.code]||'工作流暂时无法继续,请查看任务详情或同步后重试。'
}

View File

@ -0,0 +1,21 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { durableRequest, pendingSubmissions, setStorageOwner } from './outbox'
const data = new Map<string,string>()
beforeEach(()=>{data.clear();vi.stubGlobal('localStorage',{getItem:(k:string)=>data.get(k)??null,setItem:(k:string,v:string)=>data.set(k,v),removeItem:(k:string)=>data.delete(k)});setStorageOwner('alice')})
describe('persistent submission identity',()=>{
it('keeps exact body and nonce after lost response and reload',async()=>{const send=vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue({ok:true});await expect(durableRequest('jobs.create','/jobs',{prompt:'a'},send)).rejects.toThrow();const first=pendingSubmissions()[0]!;setStorageOwner('alice');await durableRequest('jobs.create','/jobs',{prompt:'a'},send);expect(send.mock.calls[1]![1]).toBe(first.key);expect(send.mock.calls[1]![2]).toBe(first.body);expect(pendingSubmissions()).toHaveLength(0)})
it('isolates users and keeps explicit retry separate',async()=>{const send=vi.fn().mockRejectedValue(new Error('offline'));await durableRequest('job.retry','/jobs/a/retry',{},send).catch(()=>{});setStorageOwner('bob');expect(pendingSubmissions()).toHaveLength(0);setStorageOwner('alice');expect(pendingSubmissions()[0]?.path).toBe('/jobs/a/retry')})
it.each([401,403])('retains committed-but-unconfirmed intent through auth failure %s and relogin',async(status)=>{
const send=vi.fn().mockRejectedValueOnce(new Error('accepted response lost')).mockRejectedValueOnce(Object.assign(new Error('session expired'),{status})).mockResolvedValue({jobs:[{id:'existing-job'}]})
await durableRequest('jobs.create','/jobs',{prompt:'private'},send).catch(()=>{})
const original=pendingSubmissions()[0]!
await durableRequest('jobs.create','/jobs',{prompt:'private'},send).catch(()=>{})
expect(pendingSubmissions()).toEqual([original])
setStorageOwner('');setStorageOwner('alice')
await durableRequest('jobs.create','/jobs',{prompt:'private'},send)
expect(send.mock.calls.map(call=>call[1])).toEqual([original.key,original.key,original.key])
expect(send.mock.calls.map(call=>call[2])).toEqual([original.body,original.body,original.body])
expect(pendingSubmissions()).toHaveLength(0)
})
it('does not silently send after storage failure',async()=>{vi.stubGlobal('localStorage',{getItem:()=>null,setItem:()=>{throw new Error('full')}});const send=vi.fn();await expect(durableRequest('run.create','/runs',{},send)).rejects.toThrow();expect(send).not.toHaveBeenCalled()})
})

14
frontend/src/outbox.ts Normal file
View File

@ -0,0 +1,14 @@
import { newRequestId } from './api'
export interface PendingSubmission { key:string; operation:string; path:string; body:string; created_at:string }
let owner = ''
export function setStorageOwner(id:string) { owner=id }
function storageKey(){if(!owner)throw new Error('请先登录');return `cmvr:v2:outbox:${owner}`}
export function pendingSubmissions():PendingSubmission[]{try{return JSON.parse(localStorage.getItem(storageKey())||'[]')}catch{return []}}
function save(items:PendingSubmission[]){localStorage.setItem(storageKey(),JSON.stringify(items))}
export async function durableRequest<T>(operation:string,path:string,body:unknown,send:(path:string,key:string,body:string)=>Promise<T>):Promise<T>{
const serialized=JSON.stringify(body), storage=storageKey()
let items=pendingSubmissions(), entry=items.find(x=>x.operation===operation&&x.path===path&&x.body===serialized)
if(!entry){entry={key:newRequestId(),operation,path,body:serialized,created_at:new Date().toISOString()};items.push(entry);save(items)}
try{const result=await send(entry.path,entry.key,entry.body);const current:PendingSubmission[]=JSON.parse(localStorage.getItem(storage)||'[]');localStorage.setItem(storage,JSON.stringify(current.filter(x=>x.key!==entry!.key)));return result}
catch(error){const status=(error as {status?:number}).status;if(status&&status>=400&&status<500&&status!==409&&status!==401&&status!==403){const current:PendingSubmission[]=JSON.parse(localStorage.getItem(storage)||'[]');localStorage.setItem(storage,JSON.stringify(current.filter(x=>x.key!==entry!.key)))}throw error}
}

View File

@ -8,6 +8,9 @@ export const router=createRouter({history:createWebHistory(),routes:[
{path:'/math',component:()=>import('./views/ToolsView.vue'),meta:{title:'数学推演'}},
{path:'/analyze',component:()=>import('./views/ToolsView.vue'),meta:{title:'素材理解'}},
{path:'/compose',component:()=>import('./views/ComposeView.vue'),meta:{title:'成片编排'}},
{path:'/workflow',component:()=>import('./views/WorkflowView.vue'),meta:{title:'三镜头工作流'}},
{path:'/batch',component:()=>import('./views/BatchView.vue'),meta:{title:'夜间批量'}},
{path:'/account',component:()=>import('./views/AccountView.vue'),meta:{title:'账户设置'}},
{path:'/assets',component:()=>import('./views/AssetsView.vue'),meta:{title:'素材库'}},
{path:'/tasks',component:()=>import('./views/TasksView.vue'),meta:{title:'任务中心'}},
{path:'/:pathMatch(.*)*',redirect:'/create/image'},

View File

@ -1,3 +1,4 @@
import {setStorageOwner} from '../outbox'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api, setCsrfToken } from '../api'
@ -6,15 +7,15 @@ import type { User } from '../types'
export const useAuthStore = defineStore('auth', () => {
const user = ref<User | null>(null)
const checked = ref(false)
function clear() { user.value = null; checked.value = true; setCsrfToken('') }
function clear() { user.value = null; checked.value = true; setCsrfToken(''); setStorageOwner('') }
async function load() {
try { const response = await api.me(); user.value = response.user; setCsrfToken(response.csrf_token) }
try { const response = await api.me(); user.value = response.user; setCsrfToken(response.csrf_token); setStorageOwner(response.user.id) }
catch { clear() }
finally { checked.value = true }
}
async function login(username: string, password: string) {
const response = await api.login(username, password)
user.value = response.user; checked.value = true; setCsrfToken(response.csrf_token)
user.value = response.user; checked.value = true; setCsrfToken(response.csrf_token); setStorageOwner(response.user.id)
}
async function logout() { await api.logout(); clear() }
return { user, checked, clear, load, login, logout }

View File

@ -8,14 +8,16 @@ export const useCapabilitiesStore = defineStore('capabilities', () => {
const scheduler = ref<Scheduler | null>(null)
const loading = ref(false)
const error = ref('')
const inferenceOnline = ref<boolean|null>(null)
const executionPolicy = ref<{timezone:string;start:string;end:string;batch_open:boolean;next_batch_at:string;close_behavior:string}|null>(null)
const environment = ref<'production' | 'preview' | 'test' | null>(null)
const databaseBackend = ref<'mysql' | 'sqlite' | null>(null)
async function load() {
loading.value = true
try { const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()]); items.value = response.items; scheduler.value = status.scheduler || response.scheduler; environment.value = status.environment; databaseBackend.value = status.database_backend; error.value = '' }
try { const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()]); items.value = response.items; scheduler.value = status.scheduler || response.scheduler; environment.value = status.environment; databaseBackend.value = status.database_backend; inferenceOnline.value=status.inference_online;executionPolicy.value=status.execution_policy||null; error.value = '' }
catch (caught) { error.value = caught instanceof Error ? caught.message : '无法读取模型能力' }
finally { loading.value = false }
}
function forTask(type: TaskType) { return items.value.find(item => item.task_type === type) }
return { items, scheduler, loading, error, environment, databaseBackend, load, forTask }
return { inferenceOnline, executionPolicy, items, scheduler, loading, error, environment, databaseBackend, load, forTask }
})

View File

@ -0,0 +1,10 @@
import {beforeEach,describe,expect,it,vi} from 'vitest'
import {createPinia,setActivePinia} from 'pinia'
import {useDraftsStore} from './drafts'
const saved=new Map<string,string>()
beforeEach(()=>{saved.clear();setActivePinia(createPinia());vi.stubGlobal('localStorage',{getItem:(k:string)=>saved.get(k)??null,setItem:(k:string,v:string)=>saved.set(k,v)})})
describe('user-local draft recovery',()=>{
it('restores tools and compose clips/audio/subtitles across store recreation',()=>{let s=useDraftsStore();s.setOwner('alice');s.forTask('image.generate').prompt='night garden';const compose=s.page('compose',()=>({clips:[] as string[],audio:'voice',subtitles:[{start:0,end:4,text:'hello'}]}));compose.clips.push('clip1');setActivePinia(createPinia());s=useDraftsStore();s.setOwner('alice');expect(s.forTask('image.generate').prompt).toBe('night garden');expect(s.page<any>('compose',()=>({}))).toEqual({clips:['clip1'],audio:'voice',subtitles:[{start:0,end:4,text:'hello'}]})})
it('keeps drafts on logout but never exposes one owner to another',()=>{const s=useDraftsStore();s.setOwner('alice');s.forTask('video.generate').prompt='private';s.clear();s.setOwner('bob');expect(s.forTask('video.generate').prompt).toBe('');s.setOwner('alice');expect(s.forTask('video.generate').prompt).toBe('private')})
it('recovers safely from invalid saved JSON',()=>{saved.set('cmvr:v2:drafts:alice','{broken');const s=useDraftsStore();s.setOwner('alice');expect(s.forTask('image.generate').prompt).toBe('')})
})

View File

@ -1,14 +1,14 @@
import { defineStore } from 'pinia'
import { reactive } from 'vue'
import type { TaskType } from '../types'
export interface Draft { prompt: string; negative_prompt: string; parameters: Record<string, any>; imageAssetId: string | null; count: number; scheduledAt: string | null }
export const useDraftsStore = defineStore('drafts', () => {
const drafts = reactive<Record<string, Draft>>({})
function forTask(type: TaskType, defaults: Record<string, any> = {}) {
if (!drafts[type]) drafts[type] = { prompt: '', negative_prompt: '', parameters: { ...defaults }, imageAssetId: null, count: 1, scheduledAt: null }
for (const [key, value] of Object.entries(defaults)) if (drafts[type]!.parameters[key] === undefined) drafts[type]!.parameters[key] = value
return drafts[type]!
}
function clear() { for (const key of Object.keys(drafts)) delete drafts[key] }
return { drafts, forTask, clear }
import {defineStore} from 'pinia'
import {reactive,watch} from 'vue'
import type {TaskType} from '../types'
export interface Draft { prompt:string;negative_prompt:string;parameters:Record<string,any>;imageAssetId:string|null;count:number;scheduledAt:string|null }
export const useDraftsStore=defineStore('drafts',()=>{
const drafts=reactive<Record<string,Draft>>({}),pages=reactive<Record<string,any>>({});let owner='';let hydrating=false
function persist(){if(owner&&!hydrating)localStorage.setItem(`cmvr:v2:drafts:${owner}`,JSON.stringify({drafts,pages}))}
watch([drafts,pages],persist,{deep:true,flush:'sync'})
function clear(){hydrating=true;Object.keys(drafts).forEach(k=>delete drafts[k]);Object.keys(pages).forEach(k=>delete pages[k]);owner='';hydrating=false}
function setOwner(id:string){if(owner===id)return;clear();owner=id;hydrating=true;try{const saved=JSON.parse(localStorage.getItem(`cmvr:v2:drafts:${id}`)||'{}');Object.assign(drafts,saved.drafts||{});Object.assign(pages,saved.pages||{})}catch{}finally{hydrating=false}}
function forTask(type:TaskType,defaults:Record<string,any>={}){if(!drafts[type])drafts[type]={prompt:'',negative_prompt:'',parameters:{...defaults},imageAssetId:null,count:1,scheduledAt:null};for(const [key,value] of Object.entries(defaults))if(drafts[type]!.parameters[key]===undefined)drafts[type]!.parameters[key]=value;return drafts[type]!}
function page<T>(key:string,initial:()=>T):T{if(!pages[key])pages[key]=initial();return pages[key] as T}
return {drafts,pages,forTask,page,clear,setOwner}
})

View File

@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useJobsStore } from './jobs'
import type { Job } from '../types'
import {useWorkflowsStore} from './workflows'
import { api } from '../api'
class FakeEventSource {
@ -92,6 +93,20 @@ describe('durable task updates', () => {
expect(store.cursor).toBe(41)
})
it('routes workflow events and reconciles workflow snapshots on SSE reset', async () => {
vi.stubGlobal('EventSource', FakeEventSource)
vi.spyOn(api, 'jobs').mockResolvedValue({items:[],cursor:8,total:0,page:1,page_size:48})
const workflows=useWorkflowsStore(),apply=vi.spyOn(workflows,'applyRun'),refresh=vi.spyOn(workflows,'refresh').mockResolvedValue()
await useJobsStore().connect()
const source=FakeEventSource.instances[0]!
const snapshot={run:{id:'run',version:4},steps:[],jobs:[]}
source.listeners['workflow.updated']!({data:JSON.stringify(snapshot),lastEventId:'9'})
expect(apply).toHaveBeenCalledWith(snapshot)
source.listeners['reset']!({data:'{}',lastEventId:'10'})
expect(refresh).toHaveBeenCalledOnce()
expect(useJobsStore().cursor).toBe(9)
})
it('closes the stream and rejects late events after signing out', async () => {
vi.stubGlobal('EventSource', FakeEventSource)
vi.spyOn(api, 'jobs').mockResolvedValue({ items: [job()], cursor: 40, total: 1, page: 1, page_size: 48 })

View File

@ -1,3 +1,4 @@
import {useWorkflowsStore} from './workflows'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { api } from '../api'
@ -68,7 +69,7 @@ export const useJobsStore = defineStore('jobs', () => {
source.onopen = () => {
if (session !== epoch) return
connection.value = 'live'
if (opened) { void refresh().catch(() => undefined); useAssetsStore().notifyRemote() }
if (opened) { void useWorkflowsStore().refresh().catch(()=>undefined); void refresh().catch(() => undefined); useAssetsStore().notifyRemote() }
opened = true
}
const listen = (event: string, operation: (value: any, id: number) => void) => {
@ -78,11 +79,14 @@ export const useJobsStore = defineStore('jobs', () => {
catch { void refresh().catch(() => undefined) }
}) as EventListener)
}
listen('workflow.updated', (value,id) => { useWorkflowsStore().applyRun(value); (value.jobs||[]).forEach(applyJob); cursor.value=Math.max(cursor.value,id) })
listen('draft.updated', (value,id) => { if(value.draft)useWorkflowsStore().applyDraft(value.draft); cursor.value=Math.max(cursor.value,id) })
listen('batch.updated', (value,id) => { useWorkflowsStore().applyBatch(value); cursor.value=Math.max(cursor.value,id) })
listen('job.updated', (value, id) => { if (value.job) applyEvent(value.job, id) })
listen('asset.created', (value, id) => { useAssetsStore().upsert(value.asset); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) })
listen('asset.updated', (value, id) => { useAssetsStore().upsert(value.asset); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) })
listen('asset.deleted', (value, id) => { useAssetsStore().forget(value.id); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) })
listen('reset', () => { void refresh().catch(() => undefined); useAssetsStore().notifyRemote() })
listen('reset', () => { void useWorkflowsStore().refresh().catch(()=>undefined); void refresh().catch(() => undefined); useAssetsStore().notifyRemote() })
source.onerror = () => {
if (session !== epoch) return
connection.value = 'reconnecting'

View File

@ -0,0 +1,53 @@
import {api} from '../api'
import {beforeEach,describe,expect,it,vi} from 'vitest'
import {createPinia,setActivePinia} from 'pinia'
import {useWorkflowsStore} from './workflows'
import {emptyWorkflow} from '../v2types'
import type {DraftDTO,RunSnapshot,BatchSnapshot} from '../v2types'
const draft:DraftDTO={id:'alice-draft',name:'alice private',spec:emptyWorkflow(),kind:'three_shot',version:1,revision:1,created_at:'now',updated_at:'now'}
const snapshot:RunSnapshot={draft,run:{id:'alice-run',draft_id:draft.id,draft_revision:1,state:'running',desired_state:'run',execution_mode:'interactive',version:1,result_assets:[],completed_steps:0,total_steps:4,created_at:'now'},steps:[],jobs:[]}
const batch:BatchSnapshot={batch:{id:'alice-batch',name:'alice private',state:'queued',desired_state:'run',version:1,created_at:'now'},items:[]}
beforeEach(()=>{setActivePinia(createPinia());vi.restoreAllMocks()})
const actions=[
{method:'controlRun',result:snapshot,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.controlRun(snapshot.run,'pause')},
{method:'retryStep',result:snapshot,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.retryStep(snapshot.run,'shot_1','alice-job')},
{method:'startRun',result:snapshot,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.startRun(draft)},
{method:'workflow',result:draft,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.fetchDraft(draft.id)},
{method:'createWorkflow',result:draft,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.saveDraft(undefined,draft.name,draft.spec)},
{method:'saveWorkflow',result:draft,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.saveDraft(draft,draft.name,draft.spec)},
{method:'createBatch',result:batch,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.createBatch({name:'alice',items:[]})},
{method:'controlBatch',result:batch,invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.controlBatch(batch.batch,'pause')},
{method:'batches',result:{items:[batch.batch],total:1,page:1,page_size:20},invoke:(s:ReturnType<typeof useWorkflowsStore>)=>s.listBatches({})},
] as const
describe('component request actions cannot cross an auth epoch',()=>{
for(const action of actions){
it(`${action.method}: discards Alice delayed success after Bob signs in`,async()=>{
let resolve!:(value:any)=>void
vi.spyOn(api,action.method).mockImplementation((()=>new Promise(r=>resolve=r)) as any)
const followup=vi.spyOn(api,'run'),batchFollowup=vi.spyOn(api,'batch'),s=useWorkflowsStore(),pending=action.invoke(s)
s.reset();s.applyDraft({...draft,id:'bob-draft',name:'bob private'})
resolve(action.result)
expect(await pending).toBeUndefined()
expect(Object.keys(s.drafts)).toEqual(['bob-draft']);expect(s.runs).toEqual({});expect(s.batches).toEqual({})
expect(followup).not.toHaveBeenCalled();expect(batchFollowup).not.toHaveBeenCalled()
})
it(`${action.method}: swallows Alice delayed error and never reconciles under Bob`,async()=>{
let reject!:(value:unknown)=>void
vi.spyOn(api,action.method).mockImplementation((()=>new Promise((_r,j)=>reject=j)) as any)
const followup=vi.spyOn(api,'run'),batchFollowup=vi.spyOn(api,'batch'),s=useWorkflowsStore(),pending=action.invoke(s)
s.reset();reject(new Error('alice private failure'))
expect(await pending).toBeUndefined();expect(followup).not.toHaveBeenCalled();expect(batchFollowup).not.toHaveBeenCalled();expect(s.runs).toEqual({});expect(s.drafts).toEqual({});expect(s.batches).toEqual({})
})
}
it('guards a reconciliation response when the session changes during error refetch',async()=>{
vi.spyOn(api,'controlRun').mockRejectedValue(new Error('version conflict'))
let resolve!:(value:RunSnapshot)=>void;vi.spyOn(api,'run').mockImplementation(()=>new Promise(r=>resolve=r))
const s=useWorkflowsStore(),pending=s.controlRun(snapshot.run,'pause')
await vi.waitFor(()=>expect(resolve).toBeDefined());s.reset();resolve(snapshot)
expect(await pending).toBeUndefined();expect(s.runs).toEqual({});expect(s.drafts).toEqual({})
})
it('does not start a saved-draft followup run after a session change',async()=>{
const s=useWorkflowsStore(),session=s.sessionId(),request=vi.spyOn(api,'startRun');s.reset();expect(await s.startRun(draft,undefined,session)).toBeUndefined();expect(request).not.toHaveBeenCalled()
})
})

View File

@ -0,0 +1,15 @@
import {beforeEach,describe,expect,it,vi} from 'vitest'
import {createPinia,setActivePinia} from 'pinia'
import {useWorkflowsStore} from './workflows'
import {emptyWorkflow} from '../v2types'
import type {DraftDTO,RunSnapshot} from '../v2types'
import {api} from '../api'
const draft=(version=1,current_run_id='new'):DraftDTO=>({id:'d',name:'story',kind:'three_shot',revision:1,version,current_run_id,spec:emptyWorkflow(),created_at:'now',updated_at:'now'})
const snap=(id='new',version=1,selected='new-job'):RunSnapshot=>({run:{id,draft_id:'d',draft_revision:1,state:'running',desired_state:'run',execution_mode:'interactive',version,result_assets:[],created_at:'now',completed_steps:0,total_steps:4},steps:[{id:`s-${id}`,run_id:id,step_key:'shot_1',kind:'video.generate',state:'running',selected_job_id:selected,explicit_attempt:2,dependencies:[],semantic_input_hash:'hash'}],jobs:[]})
beforeEach(()=>{setActivePinia(createPinia());vi.restoreAllMocks()})
describe('workflow event ordering',()=>{
it('rejects stale snapshots and keeps the explicit replacement job pointer',()=>{const s=useWorkflowsStore();s.applyRun(snap('new',4));s.applyRun(snap('new',3,'old-job'));expect(s.runs.new?.steps[0]?.selected_job_id).toBe('new-job')})
it('an event for an old run cannot switch the current draft or overwrite the new run',()=>{const s=useWorkflowsStore();s.applyDraft(draft(4));s.applyRun(snap());s.applyRun({...snap('old',30,'old-job'),draft:draft(3,'old')});expect(s.drafts.d?.current_run_id).toBe('new');expect(s.runs.new?.steps[0]?.selected_job_id).toBe('new-job');expect(s.runs.old?.run.version).toBe(30)})
it('rejects stale batch control snapshots',()=>{const s=useWorkflowsStore();s.applyBatch({batch:{id:'b',name:'night',state:'paused',desired_state:'pause',version:4,created_at:'now'},items:[]});s.applyBatch({batch:{id:'b',name:'night',state:'running',desired_state:'run',version:3,created_at:'now'},items:[]});expect(s.batches.b?.batch.state).toBe('paused')})
it('does not repopulate another user after a late HTTP snapshot',async()=>{let resolve:any;vi.spyOn(api,'run').mockImplementation(()=>new Promise(r=>resolve=r));const s=useWorkflowsStore(),pending=s.fetchRun('new');s.reset();resolve(snap());await pending;expect(s.runs).toEqual({})})
})

View File

@ -0,0 +1,43 @@
import {defineStore} from 'pinia'
import {ref} from 'vue'
import {api} from '../api'
import type {BatchDTO,BatchSnapshot,DraftDTO,RunDTO,RunSnapshot,WorkflowSpec} from '../v2types'
export const useWorkflowsStore=defineStore('workflows',()=>{
const drafts=ref<Record<string,DraftDTO>>({}),runs=ref<Record<string,RunSnapshot>>({}),batches=ref<Record<string,BatchSnapshot>>({});let epoch=0
function sessionId(){return epoch}
function applyDraft(draft:DraftDTO){if(!drafts.value[draft.id]||draft.version>drafts.value[draft.id]!.version)drafts.value[draft.id]=draft}
function applyRun(snapshot:RunSnapshot){const old=runs.value[snapshot.run.id];if(snapshot.draft)applyDraft(snapshot.draft);if(old&&old.run.version>=snapshot.run.version)return false;runs.value[snapshot.run.id]=snapshot;return true}
function applyBatch(snapshot:BatchSnapshot){const old=batches.value[snapshot.batch.id];if(old&&old.batch.version>=snapshot.batch.version)return false;batches.value[snapshot.batch.id]=snapshot;return true}
// A stale response is never returned to a component, including stale errors.
async function guarded<T>(request:()=>Promise<T>,apply?:(result:T)=>unknown,session=epoch):Promise<T|undefined>{
if(session!==epoch)return
try{const result=await request();if(session!==epoch)return;apply?.(result);return result}
catch(error){if(session===epoch)throw error}
}
async function fetchRun(id:string,session=epoch){return guarded(()=>api.run(id),applyRun,session)}
async function listRuns(filters:Record<string,unknown>,session=epoch){return guarded(()=>api.runs(filters),undefined,session)}
async function fetchDraft(id:string,session=epoch){return guarded(()=>api.workflow(id),applyDraft,session)}
async function saveDraft(current:DraftDTO|undefined,name:string,spec:WorkflowSpec,session=epoch){return guarded(()=>current?api.saveWorkflow(current,name,spec):api.createWorkflow(name,spec),applyDraft,session)}
async function startRun(draft:DraftDTO,reuse?:string,session=epoch){return guarded(()=>api.startRun(draft,'interactive',reuse),applyRun,session)}
async function fetchBatch(id:string,session=epoch){return guarded(()=>api.batch(id),applyBatch,session)}
async function listBatches(filters:Record<string,unknown>,session=epoch){
return guarded(async()=>{const page=await api.batches(filters);if(session===epoch)await Promise.all(page.items.map(b=>fetchBatch(b.id,session)));return page},undefined,session)
}
async function createBatch(body:unknown,session=epoch){return guarded(()=>api.createBatch(body),applyBatch,session)}
async function reconcile<T>(request:()=>Promise<T>,apply:(result:T)=>unknown,reload:()=>Promise<unknown>,session:number){
try{return await guarded(request,apply,session)}catch(error){
if(session!==epoch)return
await reload().catch(()=>undefined)
if(session===epoch)throw error
}
}
async function controlRun(run:RunDTO,action:'pause'|'resume'|'cancel',session=epoch){return reconcile(()=>api.controlRun(run,action),applyRun,()=>fetchRun(run.id,session),session)}
async function retryStep(run:RunDTO,key:string,jobId:string,session=epoch){return reconcile(()=>api.retryStep(run,key,jobId),applyRun,()=>fetchRun(run.id,session),session)}
async function controlBatch(batch:BatchDTO,state:string,session=epoch){return reconcile(()=>api.controlBatch(batch,state),applyBatch,()=>fetchBatch(batch.id,session),session)}
async function refresh(){const session=epoch;return guarded(async()=>{
const [d,r,b]=await Promise.all([api.workflows({page_size:100}),api.runs({page_size:100}),api.batches({page_size:100})]);if(session!==epoch)return
d.items.forEach(applyDraft);await Promise.all([...r.items.map(run=>fetchRun(run.id,session)),...b.items.map(batch=>fetchBatch(batch.id,session))])
},undefined,session)}
function reset(){epoch++;drafts.value={};runs.value={};batches.value={}}
return {drafts,runs,batches,sessionId,applyDraft,applyRun,applyBatch,refresh,fetchRun,listRuns,fetchDraft,saveDraft,startRun,listBatches,createBatch,controlRun,retryStep,controlBatch,reset}
})

View File

@ -16,3 +16,8 @@
@media(max-width:900px){.sidebar{width:66px}.side-nav{padding-left:8px;padding-right:8px}.side-nav a{height:54px;font-size:10px}.side-nav a.selected:before{left:-8px}.app-header{padding:0 22px;height:58px}.local-label,.header-divider{display:none}.creative-heading h1{font-size:26px}.creative-heading{padding-top:28px;padding-bottom:24px}.inspiration-grid{grid-template-columns:1fr 1fr}.inspiration-card{height:250px}.inspiration-card:nth-child(4){height:250px}.results-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.composer-parameters{gap:5px}.model-chip{max-width:150px}.composer-controls{align-items:center;flex-wrap:wrap}.generate-button{margin-left:auto}.composer-footnote>span:last-child{display:none}.tool-columns{grid-template-columns:1fr}.tool-result-panel{min-height:250px}.tool-empty{min-height:200px}.page-heading h1{font-size:25px}.compose-layout{grid-template-columns:1fr}.compose-settings{display:block}.compose-preview{max-height:380px}.split-heading{align-items:flex-start}.task-row-actions{flex-direction:column}.preview-layout{grid-template-columns:1fr}.preview-meta{display:grid;grid-template-columns:1fr 1fr;gap:10px 20px}.preview-meta>.eyebrow,.preview-meta>.el-form,.metadata-list{grid-column:1/-1}.metadata-list{grid-template-columns:60px 1fr 50px 1fr;gap:9px}.preview-stage{max-height:50vh;min-height:200px}.preview-stage>img,.preview-stage>video{max-height:50vh}.login-art{width:45%}.login-brand{left:25px}.login-art-copy h1{font-size:29px}.login-art-copy{left:25px;bottom:55px}.login-art-copy p{font-size:11px}.login-form-section{padding:30px}}
@media(max-width:640px){.sidebar{width:58px}.brand{height:80px}.brand-glyph{width:29px;height:29px;font-size:20px}.brand-caption{font-size:7px}.side-nav{padding:3px 6px;gap:5px}.side-nav a{height:51px;font-size:9px;gap:5px}.side-nav .el-icon{font-size:19px}.side-nav a.selected:before{left:-6px}.sidebar-bottom{gap:18px;padding:20px 0}.app-header{padding:0 15px}.header-breadcrumb{gap:8px;font-size:10px}.header-breadcrumb>span:first-child{font-size:11px}.connection-status{font-size:9px}.header-actions{gap:5px}.workspace-scroll{padding-left:16px;padding-right:16px}.workspace-topline{padding-top:12px}.mode-switch a,.mode-switch button{padding:8px 11px;font-size:10px}.creative-heading{padding-top:25px}.creative-heading h1{font-size:23px;letter-spacing:-1px}.creative-heading p{font-size:10px}.creative-heading .eyebrow{font-size:7px}.section-heading{gap:10px}.section-heading h2{font-size:12px}.section-heading p{font-size:9px}.outline-label{font-size:6px;letter-spacing:1px}.inspiration-grid{grid-template-columns:1fr;gap:14px}.inspiration-card,.inspiration-card:nth-child(4){height:260px}.inspiration-card:nth-child(2){height:210px}.inspiration-gradient h3{font-size:17px}.sample-label{font-size:8px}.inspiration-actions button{font-size:11px}.composer-wrap{padding:8px 12px 12px}.prompt-composer{padding:11px;border-radius:11px}.prompt-composer>textarea{height:64px;font-size:11px}.composer-parameters{gap:5px}.model-chip{max-width:150px;font-size:9px}.parameter-chip{padding:6px;font-size:9px}.composer-controls{row-gap:10px}.generate-button.el-button{height:32px;font-size:10px;padding:0 12px}.composer-footnote{font-size:8px;margin-top:7px}.count-select{width:60px;min-width:60px}.results-grid{grid-template-columns:1fr}.page-heading h1{font-size:23px}.page-heading p{font-size:10px}.page-heading .eyebrow{font-size:7px}.tool-page,.library-page,.tasks-page,.compose-page{padding:0 16px 75px}.split-heading{flex-direction:column;gap:14px}.tool-input-panel,.tool-result-panel{padding:18px}.panel-heading{gap:6px}.panel-heading h2{font-size:12px}.tiny-model{max-width:160px;font-size:8px}.tool-history>button{gap:9px;padding:13px 3px}.tool-history>button>small{display:none}.asset-library-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.library-caption{padding:10px}.library-caption>button{font-size:10px}.library-caption>div{font-size:8px}.filter-tabs{gap:14px;flex-wrap:wrap}.filter-tabs button{font-size:10px}.library-search{gap:5px}.library-search>.el-input{min-width:0}.library-search>.el-input:first-child{width:75px}.picker-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.picker-toolbar{flex-wrap:wrap}.picker-toolbar>.el-input{flex-basis:100%}.preview-meta{display:block}.preview-meta>.el-button{margin:6px 0}.metadata-list{grid-template-columns:50px 1fr}.task-policy-note{font-size:9px;padding:10px;line-height:1.8;align-items:flex-start}.task-policy-note .live-dot{margin-top:5px;flex-shrink:0}.task-thumb{width:46px;height:57px;border-radius:6px}.task-row{gap:9px;padding:17px 0}.task-title{font-size:11px}.task-title-line{gap:6px;flex-wrap:wrap}.task-main>p{font-size:9px;line-height:1.6}.task-row-actions .el-button{font-size:10px;padding:6px}.task-title-line small{display:none}.task-filter-selects{width:100%}.task-filter-selects .el-select{width:50%;min-width:0}.task-type{font-size:8px}.status-pill{font-size:8px;padding:3px 5px}.task-main>small{font-size:8px}.global-queue-bar{padding:9px 13px;font-size:9px;gap:8px;max-width:calc(100% - 24px)}.global-queue-bar strong{font-size:10px}.global-queue-bar>span:not(.queue-spinner){max-width:125px}.global-queue-bar small{display:none}.compose-preview{min-height:200px;aspect-ratio:auto}.timeline-heading h2>span{display:block;margin:6px 0 0}.compose-job{gap:8px;font-size:10px}.connection-banner{padding:8px 14px;font-size:9px;line-height:1.7}.login-art{display:none}.login-form-section{padding:28px}.login-form-box{max-width:360px}.login-form-box h2{font-size:29px}.login-form-box>.eyebrow{font-size:8px}.login-form-section:before{content:'CMVR VISUAL';position:absolute;top:35px;left:28px;font-size:12px;letter-spacing:2px;color:#95c8b7}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
.v2-page{max-width:1500px;margin:0 auto}.v2-panel{padding:24px;margin-bottom:22px}.v2-panel>h2{margin-bottom:18px}.v2-panel>h3{margin-top:25px}.v2-panel label{display:flex;flex-direction:column;gap:10px;margin:16px 0;color:#9fb8b2;font-size:12px}.v2-panel .el-textarea{margin-bottom:14px}.v2-toolbar,.v2-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.v2-toolbar{margin-bottom:20px}.v2-toolbar>.el-input{flex:1;min-width:180px;max-width:360px}.v2-toolbar>.el-select{width:240px}.v2-toolbar h2{margin:0}.v2-columns{display:grid;grid-template-columns:1fr 1fr;gap:20px}.v2-shots{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.v2-shots h2{margin-top:16px}.v2-shots small{display:block;margin-top:14px;overflow-wrap:anywhere}.v2-steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin:20px 0}.v2-step{border:1px solid var(--line);border-radius:10px;padding:14px;display:flex;gap:10px;flex-direction:column}.v2-step small,.v2-token small{color:var(--muted)}.v2-token{display:flex;gap:12px;flex-direction:column;border-top:1px solid var(--line);padding:16px 0;overflow-wrap:anywhere}.v2-page li{line-height:2;overflow-wrap:anywhere}.v2-panel>.el-select{max-width:350px;width:100%;margin-bottom:12px}.v2-page .json-output{max-height:360px;overflow:auto}.side-nav{overflow-y:auto;min-height:0}.sidebar-bottom{flex-shrink:0}.sidebar{overflow-y:auto}.v2-panel code{font-size:12px;color:var(--accent)}
@media(max-width:1100px){.v2-shots{grid-template-columns:1fr}.v2-columns{grid-template-columns:1fr}.v2-toolbar>.el-input{max-width:100%}}
.v2-page{height:100%;width:100%;overflow:auto;box-sizing:border-box;padding:0 38px 80px}
@media(max-width:1100px){.v2-page{padding-left:26px;padding-right:26px}}
@media(max-width:700px){.v2-page{padding:0 16px 75px}}

View File

@ -1,8 +1,8 @@
export type TaskType = 'image.generate' | 'video.generate' | 'defect.generate' | 'audio.transcribe' | 'audio.speech' | 'math.solve' | 'media.structure' | 'video.compose'
export type AssetKind = 'image' | 'video' | 'audio' | 'text' | 'json'
export type JobState = 'scheduled' | 'submitting' | 'queued' | 'running' | 'collecting' | 'cancelling' | 'succeeded' | 'failed' | 'cancelled' | 'timed_out'
export interface User { id: string; username: string; display_name: string; role: string }
export interface AuthResponse { user: User; csrf_token: string }
export type JobState = 'needs_attention' | 'paused' | 'waiting_window' | 'scheduled' | 'submitting' | 'queued' | 'running' | 'collecting' | 'cancelling' | 'succeeded' | 'failed' | 'cancelled' | 'timed_out'
export interface User { id: string; username: string; display_name: string; role: string; must_change_password?: boolean; disabled?: boolean }
export interface AuthResponse { user: User; csrf_token: string; public_access?: boolean }
export interface Asset {
id: string; name: string; kind: AssetKind; mime_type: string; size_bytes: number
width: number | null; height: number | null; duration_seconds: number | null
@ -20,6 +20,7 @@ export interface Scheduler {
updated_at: string | null
}
export interface Job {
run_id?: string | null; step_key?: string | null; batch_id?: string | null; execution_mode?: string; hold_reasons?: string[]; desired_state?: string;
id: string; task_type: TaskType; state: JobState; phase: string; version: number; prompt: string
parameters: Record<string, any>; input_asset_ids: string[]; result_assets: Asset[]; result: Record<string, any> | null
progress: number | null; queue_position: number | null; upstream_id: string | null
@ -28,7 +29,7 @@ export interface Job {
created_at: string; scheduled_at: string | null; started_at: string | null; finished_at: string | null
}
export interface JobRequest {
task_type: TaskType; input: Record<string, any>; parameters: Record<string, any>; count?: number; scheduled_at?: string | null
task_type: TaskType; input: Record<string, any>; parameters: Record<string, any>; count?: number; execution_mode?: 'interactive' | 'batch'; scheduled_at?: string | null
}
export interface Page<T> { items: T[]; total: number; page: number; page_size: number }
export interface JobsPage extends Page<Job> { cursor: number }

Some files were not shown because too many files have changed in this diff Show More