2026-11-10 23:56:50 +08:00
|
|
|
"""Durable orchestration only: never execute a model or a media process here."""
|
|
|
|
|
import logging
|
|
|
|
|
from fastapi import HTTPException
|
2026-11-11 10:59:33 +08:00
|
|
|
from sqlalchemy import select, func
|
2026-11-10 23:56:50 +08:00
|
|
|
from .models import Job, utcnow
|
|
|
|
|
from .v2_models import WorkflowRun, WorkflowStep, AssetReference
|
2026-11-11 10:59:33 +08:00
|
|
|
from .jobs import TERMINAL, GPU_TYPES
|
2026-11-10 23:56:50 +08:00
|
|
|
from .workflows import RUN_TERMINAL, create_child, emit_run, selected_output
|
2026-11-11 00:36:30 +08:00
|
|
|
from .timeline import ordered_step_keys
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
log=logging.getLogger(__name__)
|
|
|
|
|
AUTOMATIC_HOLDS={'quota','storage'}
|
|
|
|
|
|
2026-11-11 10:59:33 +08:00
|
|
|
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
|
2026-11-11 11:44:50 +08:00
|
|
|
if settings.max_interactive_gpu_jobs>0 and r.execution_mode=='interactive' and step.kind in GPU_TYPES:
|
2026-11-11 10:59:33 +08:00
|
|
|
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
|
|
|
|
|
|
2026-11-10 23:56:50 +08:00
|
|
|
async def advance_run(session,run_id,settings):
|
2026-11-11 10:29:01 +08:00
|
|
|
r=await session.scalar(select(WorkflowRun).where(WorkflowRun.id==run_id,WorkflowRun.deleted_at.is_(None)).with_for_update())
|
2026-11-10 23:56:50 +08:00
|
|
|
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)
|
2026-11-11 10:29:01 +08:00
|
|
|
if job is None or job.owner_id!=r.owner_id or job.deleted_at is not None:continue
|
2026-11-10 23:56:50 +08:00
|
|
|
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()
|
2026-11-11 11:44:50 +08:00
|
|
|
# Bound each tick's replenishment work, regardless of how many
|
|
|
|
|
# unfinished jobs this owner already has. Later ticks keep feeding.
|
|
|
|
|
admitted_this_tick=0
|
2026-11-11 00:36:30 +08:00
|
|
|
for key in ordered_step_keys(r.spec_snapshot):
|
2026-11-10 23:56:50 +08:00
|
|
|
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
|
2026-11-11 11:44:50 +08:00
|
|
|
if admitted_this_tick>=8:break
|
2026-11-11 10:59:33 +08:00
|
|
|
if not await child_capacity(session,r,step,settings):
|
|
|
|
|
r.hold_reasons=sorted(set(r.hold_reasons or [])|{'quota'})
|
|
|
|
|
r.error_json={'code':'quota_exceeded','admission_pending':True}
|
|
|
|
|
break
|
|
|
|
|
try:
|
|
|
|
|
# An individual rejected leaf cannot roll back siblings
|
|
|
|
|
# already accepted in this run's transaction.
|
|
|
|
|
async with session.begin_nested():
|
|
|
|
|
await create_child(session,r,step,settings)
|
|
|
|
|
except HTTPException as exc:
|
|
|
|
|
code=exc.detail.get('code') if isinstance(exc.detail,dict) else None
|
|
|
|
|
if code not in {'quota_exceeded','storage_insufficient'}:raise
|
|
|
|
|
await session.refresh(step)
|
|
|
|
|
await session.refresh(r)
|
|
|
|
|
hold='quota' if code=='quota_exceeded' else 'storage'
|
|
|
|
|
r.hold_reasons=sorted(set(r.hold_reasons or [])|{hold})
|
|
|
|
|
r.error_json={'code':code,'admission_pending':True}
|
|
|
|
|
break
|
2026-11-11 11:44:50 +08:00
|
|
|
admitted_this_tick+=1;changed=True
|
2026-11-10 23:56:50 +08:00
|
|
|
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)
|
2026-11-11 10:29:01 +08:00
|
|
|
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()
|
2026-11-10 23:56:50 +08:00
|
|
|
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:
|
2026-11-11 10:29:01 +08:00
|
|
|
r=await session.scalar(select(WorkflowRun).where(WorkflowRun.id==run_id,WorkflowRun.deleted_at.is_(None)).with_for_update())
|
2026-11-10 23:56:50 +08:00
|
|
|
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()
|