cmvr-visual/backend/app/services/orchestration/workflow_engine.py

235 lines
9.4 KiB
Python
Raw Normal View History

"""Durable orchestration only: never execute a model or a media process here."""
import logging
from fastapi import HTTPException
from sqlalchemy import select, func
from app.models import Job, utcnow
from app.models import WorkflowRun, WorkflowStep, AssetReference
from app.domain.tasks import TERMINAL, GPU_TYPES
from app.services.workflows import RUN_TERMINAL, create_child, emit_run, selected_output
from app.domain.timeline import ordered_step_keys
log = logging.getLogger(__name__)
AUTOMATIC_HOLDS = {"quota", "storage"}
async def child_capacity(session, r, step, settings):
active = Job.state.not_in(TERMINAL)
own = await session.scalar(
select(func.count()).select_from(Job).where(Job.owner_id == r.owner_id, active)
)
total = await session.scalar(select(func.count()).select_from(Job).where(active))
if own >= settings.max_owner_jobs or total >= settings.max_global_jobs:
return False
if (
settings.max_interactive_gpu_jobs > 0
and r.execution_mode == "interactive"
and (step.kind in GPU_TYPES)
):
gpu = await session.scalar(
select(func.count())
.select_from(Job)
.where(
Job.owner_id == r.owner_id,
active,
Job.execution_mode == "interactive",
Job.task_type.in_(GPU_TYPES),
)
)
if gpu >= settings.max_interactive_gpu_jobs:
return False
return True
async def advance_run(session, run_id, settings):
r = await session.scalar(
select(WorkflowRun)
.where(WorkflowRun.id == run_id, WorkflowRun.deleted_at.is_(None))
.with_for_update()
)
if not r or r.state in RUN_TERMINAL:
return
if r.run_kind in {"story_auto", "workflow_auto"}:
from app.services.orchestration.editor_engine import advance_editor_run
return await advance_editor_run(session, r, settings)
before = (r.state, r.current_output_asset_id, r.error_json, tuple(r.hold_reasons or []))
r.hold_reasons = sorted(set(r.hold_reasons or []) - AUTOMATIC_HOLDS)
if (r.error_json or {}).get("admission_pending"):
r.error_json = None
steps = (
await session.scalars(
select(WorkflowStep).where(WorkflowStep.run_id == r.id).order_by(WorkflowStep.step_key)
)
).all()
bykey = {s.step_key: s for s in steps}
changed = False
selected = []
for step in steps:
if not step.selected_job_id:
continue
job = await session.get(Job, step.selected_job_id)
if job is None or job.owner_id != r.owner_id or job.deleted_at is not None:
continue
selected.append(job)
state = (
"succeeded"
if job.state == "succeeded"
else "blocked"
if job.state in {"failed", "timed_out", "needs_attention"}
else "cancelled"
if job.state == "cancelled"
else "paused"
if job.state == "paused"
else "running"
if job.state in {"running", "collecting"}
else "ready"
)
if state == "succeeded":
output = await selected_output(session, job.id, r.owner_id)
if output is None:
state = "blocked"
else:
ref = await session.scalar(
select(AssetReference.id).where(
AssetReference.asset_id == output.id,
AssetReference.ref_kind == "run",
AssetReference.ref_id == r.id,
)
)
if not ref:
session.add(
AssetReference(
owner_id=r.owner_id, asset_id=output.id, ref_kind="run", ref_id=r.id
)
)
if step.state != state:
step.state = state
step.version += 1
changed = True
if r.desired_state == "cancel":
if all((j.state in TERMINAL for j in selected)):
r.state = "cancelled"
r.finished_at = utcnow()
else:
r.state = "cancelling"
else:
blocked = next((s for s in steps if s.state == "blocked"), None)
if blocked:
r.state = "blocked"
r.error_json = {"code": "step_failed", "step_key": blocked.step_key}
elif bykey["compose"].state == "succeeded":
a = await selected_output(session, bykey["compose"].selected_job_id, r.owner_id)
if a:
r.current_output_asset_id = a.id
r.state = "succeeded"
r.finished_at = utcnow()
else:
r.state = "blocked"
r.error_json = {"code": "dependency_changed"}
elif r.desired_state == "pause" or r.hold_reasons:
r.state = "paused"
else:
r.state = "running"
r.started_at = r.started_at or utcnow()
# 每 tick 最多接纳 8 个新子任务只是有界补队,后续 tick 会继续,不是单用户总量配额。
admitted_this_tick = 0
for key in ordered_step_keys(r.spec_snapshot):
step = bykey[key]
if step.state == "succeeded":
continue
if step.state == "cancelled":
r.state = "blocked"
r.error_json = {"code": "step_cancelled", "step_key": key}
break
if not step.selected_job_id and all(
(bykey[dep].state == "succeeded" for dep in step.dependencies)
):
from app.core.maintenance import maintenance_active
if maintenance_active(settings):
r.state = "queued"
break
if admitted_this_tick >= 8:
break
if not await child_capacity(session, r, step, settings):
r.hold_reasons = sorted(set(r.hold_reasons or []) | {"quota"})
r.error_json = {"code": "quota_exceeded", "admission_pending": True}
break
try:
async with session.begin_nested():
await create_child(session, r, step, settings)
except HTTPException as exc:
code = exc.detail.get("code") if isinstance(exc.detail, dict) else None
if code not in {"quota_exceeded", "storage_insufficient"}:
raise
await session.refresh(step)
await session.refresh(r)
hold = "quota" if code == "quota_exceeded" else "storage"
r.hold_reasons = sorted(set(r.hold_reasons or []) | {hold})
r.error_json = {"code": code, "admission_pending": True}
break
admitted_this_tick += 1
changed = True
if changed or before != (
r.state,
r.current_output_asset_id,
r.error_json,
tuple(r.hold_reasons or []),
):
await emit_run(session, r)
async def advance_workflows(db, settings, provider):
from app.services.batches import advance_batches
from app.services.stories.candidates import feed_candidates
async with db.session() as session:
await feed_candidates(session, settings)
await advance_batches(session, settings)
ids = (
await session.scalars(
select(WorkflowRun.id)
.where(WorkflowRun.deleted_at.is_(None), WorkflowRun.state.not_in(RUN_TERMINAL))
.order_by(WorkflowRun.created_at, WorkflowRun.id)
)
).all()
await session.commit()
for run_id in ids:
try:
async with db.session() as session:
await advance_run(session, run_id, settings)
await session.commit()
except Exception as exc:
if isinstance(exc, HTTPException):
code = (
exc.detail.get("code", "workflow_admission_failed")
if isinstance(exc.detail, dict)
else "workflow_admission_failed"
)
else:
log.exception("Workflow advancement failed for %s", run_id)
code = "workflow_orchestration_failed"
async with db.session() as session:
r = await session.scalar(
select(WorkflowRun)
.where(WorkflowRun.id == run_id, WorkflowRun.deleted_at.is_(None))
.with_for_update()
)
if r is None or r.state in RUN_TERMINAL:
continue
hold = {
"quota_exceeded": "quota",
"storage_insufficient": "storage",
"owner_disabled": "admin_suspend",
}.get(code)
if hold:
r.hold_reasons = sorted(set(r.hold_reasons or []) | {hold})
r.state = "queued" if hold in AUTOMATIC_HOLDS else "blocked"
r.error_json = {"code": code, "admission_pending": hold in AUTOMATIC_HOLDS}
await emit_run(session, r)
await session.commit()
async with db.session() as session:
await advance_batches(session, settings)
await session.commit()