cmvr-visual/backend/app/services/deletions.py

265 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Transactional archival of owner records; execution and asset audit rows survive."""
from sqlalchemy import delete, or_, select
from sqlalchemy.orm import load_only
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 ordered_locked_records(session, model, *conditions):
"""先锁轻量ID,再读取宽行;冻结JSON不能参与MySQL的排序缓冲。"""
ids = list(
(
await session.scalars(
select(model.id)
.where(*conditions)
.order_by(model.created_at, model.id)
.with_for_update()
)
).all()
)
if not ids:
return []
rows = (
await session.scalars(
select(model)
.where(model.id.in_(ids))
.options(load_only(model.version, model.state, model.deleted_at, model.batch_id))
.with_for_update()
.execution_options(populate_existing=True)
)
).all()
# ID查询已持有同一事务的行锁;第二次仍用当前读,避免RR快照或identity map中的旧状态。
# 在应用层恢复原来的事件/响应顺序,不再对含多份JSON的完整行做数据库排序。
by_id = {row.id: row for row in rows}
return [by_id[id] for id in ids]
# 历史归档与素材物理删除是两条流程:保留生成素材,只在整棵执行树清理确认后释放引用。
def story_job_condition(draft_id, owner_id):
"""并入旧候选的独立任务;其他在用工作流仍需读取复用的任务及其输出。"""
from app.models import ShotCandidate
runs = select(WorkflowRun.id).where(
WorkflowRun.draft_id == draft_id, WorkflowRun.owner_id == owner_id
)
candidate_jobs = select(ShotCandidate.job_id).where(
ShotCandidate.draft_id == draft_id, ShotCandidate.owner_id == owner_id
)
# 源故事已执行过级联删除时,由最后一个复用者接手之前保留的生产任务。
deleted_stories = select(Submission.key).where(
Submission.owner_id == owner_id, Submission.operation == "story.delete"
)
deleted_source_runs = select(WorkflowRun.id).where(
WorkflowRun.owner_id == owner_id, WorkflowRun.draft_id.in_(deleted_stories)
)
deleted_source_candidates = select(ShotCandidate.job_id).where(
ShotCandidate.owner_id == owner_id, ShotCandidate.draft_id.in_(deleted_stories)
)
previously_retained = Job.id.in_(
select(WorkflowStep.selected_job_id).where(WorkflowStep.run_id.in_(runs))
) & (Job.run_id.in_(deleted_source_runs) | Job.id.in_(deleted_source_candidates))
shared_jobs = (
select(WorkflowStep.selected_job_id)
.join(WorkflowRun, WorkflowRun.id == WorkflowStep.run_id)
.where(
WorkflowRun.deleted_at.is_(None),
WorkflowRun.draft_id != draft_id,
WorkflowStep.selected_job_id.is_not(None),
)
)
return (
(Job.owner_id == owner_id)
& (Job.run_id.in_(runs) | Job.id.in_(candidate_jobs) | previously_retained)
& Job.id.not_in(shared_jobs)
)
async def archive_records(
session, model, record_id, owner_id, if_match=None, *, finishing_story=False
):
"""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] = await ordered_locked_records(
session, WorkflowRun, WorkflowRun.owner_id == owner_id, WorkflowRun.draft_id == root.id
)
elif model is Batch:
groups[WorkflowRun] = await ordered_locked_records(
session, WorkflowRun, WorkflowRun.owner_id == owner_id, WorkflowRun.batch_id == root.id
)
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":
child_filter = story_job_condition(root.id, owner_id)
if model is Batch:
child_filter = or_(child_filter, Job.batch_id == root.id)
groups[Job] = await ordered_locked_records(
session, Job, Job.owner_id == owner_id, child_filter
)
result = {
"deleted": {MODEL_KEYS[kind]: [row.id for row in rows] for kind, rows in groups.items()}
}
if root.deleted_at is not None and not finishing_story:
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 and not finishing_story:
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)
.options(load_only(Submission.resource_json))
.where(
Submission.owner_id == owner_id,
Submission.status != "purged",
Submission.operation != "story.delete",
)
.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