100 lines
5.7 KiB
Python
100 lines
5.7 KiB
Python
"""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()
|