cmvr-visual/backend/app/jobs.py

291 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime, timezone
import hashlib
import json
from fastapi import APIRouter, Depends, Header, Request
from pydantic import BaseModel, Field, ConfigDict
from typing import Literal
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from .assets import owned_asset
from .auth import Actor, csrf_actor, current_actor
from .dto import job_dto
from .errors import fail
from .events import emit_job
from .models import Event, Job, JobAsset, new_id, utcnow
router = APIRouter(prefix="/jobs", tags=["jobs"])
GPU_TYPES = {"image.generate", "video.generate", "defect.generate", "audio.transcribe"}
CPU_TYPES = {"math.solve", "media.structure", "video.compose", "audio.speech"}
TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"}
class Submit(BaseModel):
model_config = ConfigDict(extra="forbid")
execution_mode: Literal["interactive", "batch"] = "interactive"
task_type: str
input: dict = Field(default_factory=dict)
parameters: dict = Field(default_factory=dict)
count: int = Field(default=1, ge=1, le=4)
scheduled_at: datetime | None = None
async def owned_job(session, job_id, owner_id):
job = await session.scalar(select(Job).where(Job.id == job_id, Job.owner_id == owner_id,
Job.deleted_at.is_(None)).with_for_update())
if job is None:
fail(404, "job_not_found", "任务不存在")
return job
def input_ids(inputs, parameters):
result = []
for field in ("image_asset_id", "audio_asset_id", "asset_id"):
if inputs.get(field):
result.append(inputs[field])
if inputs.get("asset_ids"):
if not isinstance(inputs["asset_ids"], list):
fail(422, "invalid_assets", "asset_ids 必须为素材编号列表")
result.extend(inputs["asset_ids"])
for clip in parameters.get("clips", []):
if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str):
fail(422, "invalid_clip", "每个片段需要素材编号")
result.append(clip["asset_id"])
if parameters.get("audio_asset_id"):
result.append(parameters["audio_asset_id"])
if any(not isinstance(value, str) or len(value) > 64 for value in result):
fail(422, "invalid_assets", "素材编号格式不正确")
return list(dict.fromkeys(result))
async def validate_submission(session, body, owner_id, settings, *, frozen_workflow=False):
if body.task_type not in GPU_TYPES | CPU_TYPES:
fail(422, "unsupported_task", "不支持此任务类型")
allowed = {"prompt", "negative_prompt", "image_asset_id", "audio_asset_id", "asset_id", "asset_ids"}
if set(body.input) - allowed:
fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL")
if body.count > 1 and body.task_type not in {"image.generate", "defect.generate"}:
fail(422, "batch_not_supported", "此任务类型不支持批量生成")
if body.task_type == "audio.speech" and not settings.tts_base_url:
fail(422, "speech_unavailable", "尚未配置真实配音服务")
from .providers import ProviderError, validate_arguments
try:
validate_arguments(body.task_type, body.input, body.parameters, settings)
except ProviderError as exc:
fail(400, exc.code, exc.message)
prompt = body.input.get("prompt", "")
if not isinstance(prompt, str) or len(prompt) > 8000:
fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本")
if body.task_type in {"image.generate", "video.generate", "defect.generate", "math.solve", "audio.speech"} and not prompt.strip():
fail(422, "prompt_required", "请输入提示词或文本")
ids = input_ids(body.input, body.parameters)
assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids}
required = {"defect.generate": "image_asset_id", "audio.transcribe": "audio_asset_id", "media.structure": "asset_id"}
if body.task_type in required:
key = required[body.task_type]
value = body.input.get(key) or (body.input.get("asset_id") if key == "audio_asset_id" else None)
if not value:
fail(422, "asset_required", "此任务需要输入素材")
for key, kinds in (("image_asset_id", {"image"}), ("audio_asset_id", {"audio", "video"})):
if body.input.get(key) and assets[body.input[key]].kind not in kinds:
fail(422, "wrong_asset_kind", "输入素材类型不正确")
if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in {"image", "video"}:
fail(422, "wrong_asset_kind", "素材理解需要图片或视频")
if body.task_type == "audio.transcribe":
source_id = body.input.get("audio_asset_id") or body.input.get("asset_id")
if assets[source_id].kind not in {"audio", "video"}:
fail(422, "wrong_asset_kind", "转写需要音频或视频素材")
if body.task_type == "video.compose" and not ids:
fail(422, "clips_required", "请添加待合成片段")
if body.task_type == "video.compose":
if not frozen_workflow:
from .runtime_policy import read_runtime_policy
policy=read_runtime_policy(settings)
if policy.get('configuration_error'):fail(503,'runtime_policy_unavailable','运行配置无效,请联系管理员')
if len(body.parameters.get('clips',[]))>policy['workflow_max_shots']:
fail(422,'workflow_shot_limit',f"当前配置最多允许{policy['workflow_max_shots']}个视频片段")
if any(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])):
fail(422, "wrong_asset_kind", "编排片段必须为视频素材")
audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id")
if audio_id and assets[audio_id].kind != "audio":
fail(422, "wrong_asset_kind", "成片音轨必须为音频素材")
if body.scheduled_at is not None and body.scheduled_at.tzinfo is None:
fail(422, "timezone_required", "定时任务时间须包含时区")
return ids
async def create_jobs(session, body, actor, settings, key=None, internal=False, *, frozen_workflow=False):
if key is not None and not 1 <= len(key) <= 128:
fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128")
payload = body.model_dump(mode="json")
if body.execution_mode == "interactive":
payload.pop("execution_mode", None)
try:
fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
allow_nan=False).encode()).hexdigest()
except (ValueError, TypeError):
fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON")
if key:
existing = (await session.scalars(select(Job).where(Job.owner_id == actor.id, Job.request_key == key)
.order_by(Job.batch_index))).all()
if existing:
if existing[0].request_hash != fingerprint:
fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数")
if any(job.deleted_at is not None for job in existing):
fail(410, "resource_purged", "此幂等键对应的任务已删除")
from .submissions import accept_submission
saved=await accept_submission(session,actor.id,"jobs.create",key,2,body.model_dump(mode="json"))
saved.resource_json={"job_ids":[job.id for job in existing]}
return existing
from .submissions import accept_submission
record = await accept_submission(session, actor.id, "jobs.create", key, 2, body.model_dump(mode="json")) if key else None
from .quotas import reserve_budget
await reserve_budget(session, actor.id, "workflow.child" if internal else "jobs.create", units=body.count, settings=settings)
from .maintenance import require_writable
require_writable(settings)
if actor.auth_kind == "bearer" and body.execution_mode == "interactive" and "interactive:write" not in actor.scopes:
fail(403,"scope_required","Machine tokens require interactive:write for interactive jobs")
from .quotas import check_storage_budget
await check_storage_budget(session,settings,actor.id,new_jobs=body.count)
if body.execution_mode=="interactive" and body.task_type in GPU_TYPES:
active=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==actor.id,Job.execution_mode=="interactive",Job.task_type.in_(GPU_TYPES),Job.state.notin_(TERMINAL)))
if active+body.count>settings.max_interactive_gpu_jobs:fail(429,"quota_exceeded","Interactive GPU queue limit reached")
# Internal quota accounting also covers newly submitted batch members.
# Only children of an already accepted, frozen workflow bypass a new cap.
ids = await validate_submission(session, body, actor.id, settings, frozen_workflow=frozen_workflow)
scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None
jobs = []
for index in range(body.count):
job_id = new_id()
future = scheduled and scheduled > utcnow()
parameters = dict(body.parameters)
if body.count > 1:
parameters["seed"] = (parameters.get("seed", 42) + index) % (2 ** 32)
job = Job(id=job_id, owner_id=actor.id, task_type=body.task_type,
state="scheduled" if future else "submitting", phase="scheduled" if future else "waiting_dispatch",
execution_mode=body.execution_mode, version=1, input_json=body.input, parameters=parameters, request_key=key,
request_hash=fingerprint, batch_index=index, upstream_key="cmvr-visual:" + job_id,
scheduled_at=scheduled, next_action_at=scheduled if future else utcnow(),
attempt_count=0, work_attempt=0, preemptions=0, cancel_requested=False)
session.add(job)
await session.flush()
session.add_all(JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids)
await emit_job(session, job, increment=False)
jobs.append(job)
if record is not None:
record.resource_json = {"job_ids": [job.id for job in jobs]}
return jobs
def wake(request):
request.app.state.coordinator.wake()
@router.post("", status_code=202)
async def submit(body: Submit, request: Request, idempotency_key: str | None = Header(default=None),
actor: Actor = Depends(csrf_actor)):
recovering=False
if idempotency_key:
async with request.app.state.db.session() as session:
recovering=bool(await session.scalar(select(Job.id).where(Job.owner_id==actor.id,Job.request_key==idempotency_key).limit(1)))
if body.execution_mode=="batch" and body.task_type in GPU_TYPES and not recovering:
provider=request.app.state.provider
capabilities=await provider.upstream_capabilities() if hasattr(provider,"upstream_capabilities") else {}
if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False):
fail(503,"upstream_protocol_incompatible","Batch requires scheduling protocol v2")
async with request.app.state.db.session() as session:
try:
jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key)
await session.commit()
except IntegrityError:
await session.rollback()
jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key)
await session.commit()
result = {"jobs": [await job_dto(session, job) for job in jobs]}
wake(request)
return result
@router.get("")
async def list_jobs(request: Request, page: int = 1, page_size: int = 24, task_type: str = "", state: str = "", root_only: bool = False,
actor: Actor = Depends(current_actor)):
if page < 1 or not 1 <= page_size <= 100:
fail(422, "invalid_page", "分页参数无效")
async with request.app.state.db.session() as session:
query = select(Job).where(Job.owner_id == actor.id, Job.deleted_at.is_(None))
if root_only:
query = query.where(Job.run_id.is_(None))
if task_type:
query = query.where(Job.task_type == task_type)
if state:
query = query.where(Job.state == state)
total = await session.scalar(select(func.count()).select_from(query.subquery()))
jobs = (await session.scalars(query.order_by(Job.created_at.desc(), Job.id.desc())
.offset((page - 1) * page_size).limit(page_size))).all()
cursor = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0
return {"items": [await job_dto(session, job) for job in jobs], "total": total,
"page": page, "page_size": page_size, "cursor": cursor}
@router.get("/{job_id}")
async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)):
async with request.app.state.db.session() as session:
return await job_dto(session, await owned_job(session, job_id, actor.id))
@router.delete("/{job_id}")
async def delete_job(job_id: str, request: Request, if_match: str | None = Header(default=None),
actor: Actor = Depends(csrf_actor)):
from .deletions import archive_records
async with request.app.state.db.session() as session:
result = await archive_records(session, Job, job_id, actor.id, if_match)
await session.commit()
return result
@router.post("/{job_id}/cancel")
async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
async with request.app.state.db.session() as session:
job = await owned_job(session, job_id, actor.id)
if job.state not in TERMINAL and job.state != "collecting":
job.cancel_requested = True
if job.upstream_id is None and job.upstream_payload is None and job.phase not in {"cpu_running", "preparing"}:
job.state, job.phase, job.finished_at = "cancelled", "cancelled", utcnow()
else:
job.state, job.phase = "cancelling", "cancellation_pending"
await emit_job(session, job)
await session.commit()
result = await job_dto(session, job)
wake(request)
return result
@router.post("/{job_id}/retry", status_code=202)
async def retry(job_id: str, request: Request, idempotency_key: str | None = Header(default=None), actor: Actor = Depends(csrf_actor)):
async with request.app.state.db.session() as session:
old = await owned_job(session, job_id, actor.id)
if old.state not in TERMINAL:
fail(409, "job_not_finished", "请先等待或取消当前任务")
if old.run_id:
fail(409, "workflow_child", "Use workflow step retry")
if old.batch_id:
fail(409,"parent_control_required","Batch members require parent control")
from .submissions import accept_submission
record = await accept_submission(session, actor.id, "jobs.retry", idempotency_key, 2, {"job_id":job_id}) if idempotency_key else None
if record and record.resource_json.get("job_ids"):
jobs = list((await session.scalars(select(Job).where(Job.owner_id == actor.id,
Job.id.in_(record.resource_json["job_ids"]), Job.deleted_at.is_(None)))).all())
if len(jobs) != len(record.resource_json["job_ids"]):
fail(410, "resource_purged", "重试任务已删除")
return {"jobs": [await job_dto(session, job) for job in jobs]}
from .v2_models import Execution
unsafe=await session.scalar(select(Execution.id).where(Execution.job_id==old.id,Execution.state.in_(["allocated","running","stopping","unknown"])).limit(1))
if unsafe:fail(409,"cleanup_pending","Previous execution has not confirmed cleanup")
body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters, execution_mode=old.execution_mode)
jobs = await create_jobs(session, body, actor, request.app.state.settings)
if record:
record.resource_json = {"job_ids":[j.id for j in jobs]}
await session.commit()
result = {"jobs": [await job_dto(session, job) for job in jobs]}
wake(request)
return result