"""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): if b.deleted_at is not None:return 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 target.deleted_at is None 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 or b.deleted_at is not 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.deleted_at.is_(None),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.delete('/{id}') async def delete_batch(id:str,request:Request,if_match:str|None=Header(None),actor:Actor=Depends(csrf_actor)): from .deletions import archive_records async with request.app.state.db.session() as s: result=await archive_records(s,Batch,id,actor.id,if_match) await s.commit() return result @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