from app.services.orchestration.batch_holds import member_holds from app.services.snapshots import snapshot_batch from fastapi import HTTPException from sqlalchemy import select from app.core.security import Actor from app.core.errors import fail from app.services.events import emit_asset, emit_job from app.schemas.jobs import Submit from app.services.jobs import create_jobs from app.domain.tasks import TERMINAL from app.models import Job, utcnow from app.services.submissions import accept_submission, request_payload from app.models import Batch, BatchItem, WorkflowDraft, WorkflowRun, Execution from app.services.snapshots import owned, page_rows from app.services.workflows import ( create_run, control_run, wake, RUN_TERMINAL, check_batch_capability, emit_run, ) from app.schemas.batches import BatchCreate, BatchControl "Persistent mixed workflow/job batches with independently eligible members." 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"} ] 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: 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 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: if b.spec_snapshot.get("kind") == "story_candidates": continue 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, False)) 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, False) if item.target_kind == "run": holds -= {"quota", "storage"} holds |= set(target.hold_reasons or []) - {"quota", "storage"} 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) async def post_batch( body: BatchCreate, runtime, idempotency_key: str | None = None, actor: Actor = None ): from app.core.maintenance import require_writable require_writable(runtime.settings) capability_error = None try: await check_batch_capability( runtime, [i.task_type if i.kind == "job" else "video.generate" for i in body.items] ) except HTTPException as exc: capability_error = exc async with runtime.db.session() as s: sub = await accept_submission( s, actor.id, "batch.create", idempotency_key, 2, request_payload(body) ) if sub.resource_json: b = await owned(s, Batch, sub.resource_json["batch_id"], actor.id) else: if capability_error: raise capability_error from app.services.quotas import reserve_budget, check_parent_capacity await reserve_budget(s, actor.id, "batch.create", units=0, settings=runtime.settings) await check_parent_capacity(s, runtime.settings, actor.id, "batch") b = Batch(owner_id=actor.id, name=body.name, spec_snapshot=request_payload(body)) 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=runtime.settings, output_folder_id=item.output_folder_id if "output_folder_id" in item.model_fields_set else ..., ) 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", **{ field: getattr(item, field) for field in ("folder_id", "output_folder_id") if field in item.model_fields_set }, ), actor, runtime.settings, key=f"batch:{b.id}:{idx}", internal=True, ) for j in jobs: j.batch_id = b.id j.batch_item_index = idx 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=request_payload(item), ) ) 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(runtime) return snap async def list_batches(runtime, page: int = 1, page_size: int = 24, actor: Actor = None): async with runtime.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]} async def get_batch(id: str, runtime, actor: Actor = None): async with runtime.db.session() as s: return await snapshot_batch(s, actor.id, id) async def delete_batch(id: str, runtime, if_match: str | None = None, actor: Actor = None): from app.services.deletions import archive_records async with runtime.db.session() as s: b = await s.scalar(select(Batch).where(Batch.id == id, Batch.owner_id == actor.id)) is_story = b and b.spec_snapshot.get("kind") == "story_candidates" if is_story: from app.services.stories.deletion import delete_candidate_batch return await delete_candidate_batch(runtime, actor, id, if_match) async with runtime.db.session() as s: result = await archive_records(s, Batch, id, actor.id, if_match) await s.commit() return result async def batch_control( id: str, body: BatchControl, runtime, idempotency_key: str | None = None, actor: Actor = None ): async with runtime.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, runtime.settings) if b.spec_snapshot.get("kind") == "story_candidates": from app.services.stories.candidates import advance_candidate_batches await advance_candidate_batches(s, runtime.settings) await emit_batch(s, b) sub.resource_json = {"batch_id": id} await s.commit() snap = await snapshot_batch(s, actor.id, id) wake(runtime) return snap