"""Transactional archival of owner records; execution and asset audit rows survive.""" from sqlalchemy import delete, or_, select from app.core.errors import fail from app.services.events import emit_asset from app.models import Job, JobAsset, utcnow from app.models import ( AssetReference, Batch, Execution, Submission, WorkflowDraft, WorkflowRun, WorkflowStep, ) JOB_TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"} RUN_TERMINAL = {"succeeded", "failed", "cancelled"} BATCH_TERMINAL = {"succeeded", "cancelled", "completed_with_errors"} MODEL_KEYS = { Job: "job_ids", WorkflowRun: "run_ids", WorkflowDraft: "draft_ids", Batch: "batch_ids", } EVENT_NAMES = { Job: "job.deleted", WorkflowRun: "workflow.deleted", WorkflowDraft: "draft.deleted", Batch: "batch.deleted", } # 历史归档与素材物理删除是两条流程:保留生成素材,只在整棵执行树清理确认后释放引用。 async def archive_records(session, model, record_id, owner_id, if_match=None): """Validate the complete tree before changing anything in the caller's unit.""" root = await session.scalar( select(model).where(model.id == record_id, model.owner_id == owner_id).with_for_update() ) if root is None: fail(404, "resource_not_found", "记录不存在") groups = {Job: [], WorkflowRun: [], WorkflowDraft: [], Batch: []} groups[model] = [root] if model is WorkflowDraft: groups[WorkflowRun] = list( ( await session.scalars( select(WorkflowRun) .where(WorkflowRun.owner_id == owner_id, WorkflowRun.draft_id == root.id) .order_by(WorkflowRun.created_at, WorkflowRun.id) .with_for_update() ) ).all() ) elif model is Batch: groups[WorkflowRun] = list( ( await session.scalars( select(WorkflowRun) .where(WorkflowRun.owner_id == owner_id, WorkflowRun.batch_id == root.id) .order_by(WorkflowRun.created_at, WorkflowRun.id) .with_for_update() ) ).all() ) run_ids = [run.id for run in groups[WorkflowRun]] if model is not Job: child_filter = Job.run_id.in_(run_ids) if model is WorkflowDraft and root.kind == "story_v3": from app.models import ShotCandidate candidate_jobs = select(ShotCandidate.job_id).where( ShotCandidate.draft_id == root.id, ShotCandidate.owner_id == owner_id ) child_filter = or_(child_filter, Job.id.in_(candidate_jobs)) if model is Batch: child_filter = or_(child_filter, Job.batch_id == root.id) groups[Job] = list( ( await session.scalars( select(Job) .where(Job.owner_id == owner_id, child_filter) .order_by(Job.created_at, Job.id) .with_for_update() ) ).all() ) result = { "deleted": {MODEL_KEYS[kind]: [row.id for row in rows] for kind, rows in groups.items()} } if root.deleted_at is not None: return result if if_match is not None and if_match.strip('"') != str(root.version): fail(409, "version_conflict", "记录已更新,请刷新后重试删除") if model is Job and (root.run_id or root.batch_id): fail(409, "parent_control_required", "请在所属工作流或批次中删除此任务") if model is WorkflowRun and root.batch_id: fail(409, "parent_control_required", "请删除所属批次") if model is WorkflowDraft: batch_ids = { run.batch_id for run in groups[WorkflowRun] if run.batch_id and run.deleted_at is None } if batch_ids and await session.scalar( select(Batch.id) .where(Batch.id.in_(batch_ids), Batch.owner_id == owner_id, Batch.deleted_at.is_(None)) .limit(1) ): fail(409, "parent_control_required", "草稿仍有关联批次,请先删除所属批次") for kind, terminal in ( (Job, JOB_TERMINAL), (WorkflowRun, RUN_TERMINAL), (Batch, BATCH_TERMINAL), ): if any((row.deleted_at is None and row.state not in terminal for row in groups[kind])): fail(409, "deletion_requires_terminal", "请先取消活动任务,等待执行结束后再删除") job_ids = [job.id for job in groups[Job]] executions = ( list( ( await session.scalars( select(Execution).where(Execution.job_id.in_(job_ids)).with_for_update() ) ).all() ) if job_ids else [] ) if any((execution.state not in {"exited", "results_ready"} for execution in executions)): fail(409, "cleanup_pending", "执行尚未确认清理,请等待清理完成后再删除") if job_ids: in_use = await session.scalar( select(WorkflowRun.id) .join(WorkflowStep, WorkflowStep.run_id == WorkflowRun.id) .where( WorkflowRun.deleted_at.is_(None), WorkflowRun.id.not_in(run_ids), WorkflowStep.selected_job_id.in_(job_ids), ) .limit(1) ) if in_use: fail(409, "resource_in_use", "任务产物仍被其他工作流运行复用,请先删除该运行") now = utcnow() for kind in (Job, WorkflowRun, WorkflowDraft, Batch): for row in groups[kind]: if row.deleted_at is not None: continue row.deleted_at = now row.version += 1 emit_asset(session, owner_id, EVENT_NAMES[kind], {"id": row.id, "version": row.version}) if run_ids: drafts = ( await session.scalars( select(WorkflowDraft) .where( WorkflowDraft.owner_id == owner_id, WorkflowDraft.current_run_id.in_(run_ids), WorkflowDraft.deleted_at.is_(None), ) .with_for_update() ) ).all() from app.services.snapshots import draft_dto for draft in drafts: draft.current_run_id = None draft.version += 1 draft.updated_at = now emit_asset(session, owner_id, "draft.updated", {"draft": draft_dto(draft)}) for draft in groups[WorkflowDraft]: draft.current_run_id = None draft.updated_at = now if job_ids: await session.execute(delete(JobAsset).where(JobAsset.job_id.in_(job_ids))) refs = [] if run_ids: refs.append((AssetReference.ref_kind == "run") & AssetReference.ref_id.in_(run_ids)) if groups[WorkflowDraft]: refs.append( (AssetReference.ref_kind == "draft") & AssetReference.ref_id.in_([d.id for d in groups[WorkflowDraft]]) ) if executions: refs.append( (AssetReference.ref_kind == "execution") & AssetReference.ref_id.in_([e.id for e in executions]) ) if refs: await session.execute( delete(AssetReference).where(AssetReference.owner_id == owner_id, or_(*refs)) ) archived_ids = {row.id for rows in groups.values() for row in rows} submissions = ( await session.scalars( select(Submission) .where(Submission.owner_id == owner_id, Submission.status != "purged") .with_for_update() ) ).all() for submission in submissions: if references_any(submission.resource_json, archived_ids): submission.status = "purged" await session.flush() return result def references_any(value, ids): if isinstance(value, str): return value in ids if isinstance(value, dict): return any((references_any(item, ids) for item in value.values())) if isinstance(value, list): return any((references_any(item, ids) for item in value)) return False