diff --git a/app/api/endpoints/history.py b/app/api/endpoints/history.py index 2d479ac6b..5c4004c7c 100644 --- a/app/api/endpoints/history.py +++ b/app/api/endpoints/history.py @@ -507,6 +507,34 @@ def replan_transfer_history( return _SchemaResponse(success=result.accepted, message=result.message) +async def _grant_manual_identity_authorization( + history: Any, + execution_repository: TransferExecutionRepository, +) -> None: + """ + 在启动智能助手分析时覆盖任务上唯一的待消费身份修正授权。 + + :param history: 本次点击对应的整理历史视图 + :param execution_repository: 拥有短事务的执行仓储 + """ + task_id = getattr(history, "transfer_task_id", None) + settlement_revision = getattr(history, "transfer_settlement_revision", None) + if not task_id or not settlement_revision: + return + try: + granted = await asyncio.to_thread( + TransferExecutionCommand(execution_repository).grant_manual_identity_authorization, + history_id=history.id, + task_id=task_id, + settlement_revision=settlement_revision, + ) + except Exception as error: + logger.warning(f"整理历史 {history.id} 的人工身份授权登记失败:{error}") + return + if not granted: + logger.warning(f"整理历史 {history.id} 的任务或结算版本已变化,未登记人工身份授权") + + @router.post( "/transfer/{history_id}/ai-redo", summary="智能助手重新整理", @@ -537,6 +565,8 @@ async def ai_redo_transfer_history( if rejection: return _SchemaResponse(success=False, message=rejection) + await _grant_manual_identity_authorization(history, execution_repository) + prompt = build_manual_redo_prompt(history) progress_key = f"ai_redo_transfer_{history_id}_{int(time.time() * 1000)}" _start_ai_redo_task( @@ -588,6 +618,9 @@ async def batch_ai_redo_transfer_history( if rejection: return _SchemaResponse(success=False, message=f"第 {history.id} 条:{rejection}") + for history in histories: + await _grant_manual_identity_authorization(history, execution_repository) + return _submit_batch_ai_redo( histories=histories, all_history_ids=[history.id for history in histories], diff --git a/app/application/transfer/execution.py b/app/application/transfer/execution.py index 7e5f47b8c..b890c9d7d 100644 --- a/app/application/transfer/execution.py +++ b/app/application/transfer/execution.py @@ -981,6 +981,18 @@ class TransferExecutionRepository(Protocol): :return: 是否接纳重新规划及持久调度状态 """ + def grant_manual_identity_authorization( + self, *, history_id: int, task_id: str, settlement_revision: int, + ) -> bool: + """ + 为失败历史登记一份短期身份修正授权,后续由重新规划事务一次性消费。 + + :param history_id: 当前失败终态关联的历史标识 + :param task_id: 当前失败任务标识 + :param settlement_revision: 当前失败回执的结算版本 + :return: 授权已登记时为 True;历史或任务已变化时为 False + """ + def discard_corrupt_task( self, *, @@ -1349,6 +1361,25 @@ class TransferExecutionCommand: media_type=normalized_type.value, season=season, episode=episode, requested_by=requested_by, ) + def grant_manual_identity_authorization( + self, *, history_id: int, task_id: str, settlement_revision: int, + ) -> bool: + """ + 为一次人工身份修正保存单个可覆盖授权,不创建授权历史。 + + :param history_id: 当前失败终态关联的历史标识 + :param task_id: 当前失败任务标识 + :param settlement_revision: 当前失败回执的结算版本 + :return: 授权已登记时为 True;历史或任务已变化时为 False + :raises ValueError: 缺少历史、任务或结算版本 + """ + normalized_task_id = task_id.strip() + if history_id <= 0 or settlement_revision <= 0 or not normalized_task_id: + raise ValueError("人工授权缺少历史、结算版本或任务") + return self._repository.grant_manual_identity_authorization( + history_id=history_id, task_id=normalized_task_id, settlement_revision=settlement_revision, + ) + def resolve_manual_review( self, *, diff --git a/app/db/adapters/transfer/execution.py b/app/db/adapters/transfer/execution.py index a923091b1..f168ea970 100644 --- a/app/db/adapters/transfer/execution.py +++ b/app/db/adapters/transfer/execution.py @@ -7,7 +7,7 @@ from __future__ import annotations from collections.abc import Callable from contextlib import AbstractAsyncContextManager from dataclasses import asdict, replace -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Optional from uuid import uuid4 @@ -70,6 +70,7 @@ _UNHANDLED_REVIEW_STEP_KIND = "unhandled_execution_review" _REVIEW_STEP_KINDS = {_LEGACY_REVIEW_STEP_KIND, _UNHANDLED_REVIEW_STEP_KIND} # 与迁移保留的最大序号相邻,复核凭据不占用从零连续递增的真实执行序号。 _UNHANDLED_REVIEW_STEP_ORDINAL = 2_147_483_646 +_MANUAL_IDENTITY_AUTHORIZATION_TTL_SECONDS = 30 * 60 def _local_now() -> datetime: @@ -1538,7 +1539,10 @@ class TransactionalTransferExecutionRepository: raise TransferExecutionConflictError("整理任务正在处理中,暂时无法重新规划") checkpoint, fingerprint = self._plan_identity(pending) steps = TransferExecutionStepOper(session).list_by_task_id(task_id=pending.task_id) - self._validate_recognition_replan(pending, history, checkpoint, steps) + manual_identity = self._validate_recognition_replan( + pending, history, checkpoint, steps, + now_utc=now_utc, + ) self._validate_plan_steps(task_id=pending.task_id, checkpoint=checkpoint, checkpoint_fingerprint=fingerprint, steps=steps) snapshot = self._project_snapshot(pending, steps) @@ -1568,8 +1572,13 @@ class TransactionalTransferExecutionRepository: pending.retry_generation += 1 pending.retry_count += 1 pending.retry_due_at = now_utc - pending.retry_requested_by = requested_by - pending.retry_reason = "智能助手核实媒体身份及季集后重新规划" + pending.retry_requested_by = ( + f"{requested_by}+manual_identity" if manual_identity else requested_by + ) + pending.retry_reason = ( + "管理用户确认媒体身份后由智能助手重新规划" if manual_identity + else "智能助手核实媒体身份及季集后重新规划" + ) pending.updated_at = updated_at transaction.commit() return TransferRetryRequestResult(True, TransferExecutionState.RETRY_WAIT, @@ -1578,11 +1587,10 @@ class TransactionalTransferExecutionRepository: transaction.rollback() raise - @staticmethod def _validate_recognition_replan( - pending: TransferPending, history: TransferHistory, checkpoint: TransferPlanCheckpoint, - steps: list[TransferExecutionStepModel], - ) -> None: + self, pending: TransferPending, history: TransferHistory, checkpoint: TransferPlanCheckpoint, + steps: list[TransferExecutionStepModel], *, now_utc: str, + ) -> bool: """ 拒绝复核、过期回执、预算耗尽或任何可能含文件副作用的重新规划。 @@ -1590,14 +1598,25 @@ class TransactionalTransferExecutionRepository: :param history: 当前读取的失败历史 :param checkpoint: 原始冻结计划 :param steps: 原始持久执行步骤 + :param now_utc: 当前固定宽度 UTC 时间 + :return: 本次放行是否消费了人工身份修正授权 """ if pending.execution_state != TransferExecutionState.FAILED.value: raise TransferExecutionConflictError("任务需要人工确认或正在处理,不能自动重新规划") if (history.status or pending.terminal_history_id != history.id or pending.settlement_revision != history.transfer_settlement_revision): raise TransferExecutionConflictError("整理历史与任务结算版本已变化,请刷新后重试") + authorization = pending.manual_identity_authorization + manual_identity = ( + isinstance(authorization, dict) + and authorization.get("history_id") == history.id + and authorization.get("settlement_revision") == pending.settlement_revision + and isinstance(authorization.get("expires_at"), str) + and authorization["expires_at"] > now_utc + ) if history.auto_paused or max(history.retry_count or 0, pending.retry_count) >= max_failed_retries(): - raise TransferExecutionConflictError("整理任务自动重试次数已耗尽,请人工处理") + if not manual_identity: + raise TransferExecutionConflictError("整理任务自动重试次数已耗尽,请人工处理") stage = history.failure_stage or classify_transfer_failure(checkpoint.rejection_error).stage if stage not in {TransferFailureStage.RECOGNITION, TransferFailureStage.PLANNING}: raise TransferExecutionConflictError("当前失败需要先修复文件或存储配置,不能自动修正识别") @@ -1611,6 +1630,50 @@ class TransactionalTransferExecutionRepository: step = steps[0] if step.phase != "planning" or step.kind != "reject" or step.state != TransferStepState.SUCCEEDED.value: raise TransferExecutionConflictError("存在文件操作或不确定执行证据,不能自动重新规划") + pending.manual_identity_authorization = None + return manual_identity + + def grant_manual_identity_authorization( + self, *, history_id: int, task_id: str, settlement_revision: int, + ) -> bool: + """ + 覆盖任务当前的人工身份授权槽,并拒绝已变化的失败历史。 + + 授权绑定失败历史和结算版本,有效期为 30 分钟;不保存重复点击或消费历史。 + + :param history_id: 触发点击的整理历史标识 + :param task_id: 该历史当前绑定的持久任务标识 + :param settlement_revision: 签发时的结算版本 + :return: 授权已登记时为 True;历史、任务状态或结算版本已变化时为 False + """ + now = self._lease_clock().astimezone(timezone.utc) + now_utc = self._format_utc(now) + expires_at = self._format_utc(now + timedelta(seconds=_MANUAL_IDENTITY_AUTHORIZATION_TTL_SECONDS)) + with self._session_factory() as session: + transaction = SqlAlchemyUnitOfWork(session) + try: + history = TransferHistoryOper(session).get(history_id) + pending = TransferPendingOper(session).get_by_task_id(task_id=task_id) + if (history is None or pending is None or history.transfer_task_id != task_id + or history.transfer_settlement_revision != settlement_revision + or pending.execution_state != TransferExecutionState.FAILED.value + or pending.terminal_history_id != history_id + or pending.settlement_revision != settlement_revision): + transaction.rollback() + return False + if not self._clear_inactive_claim(session, pending=pending, now_utc=now_utc): + transaction.rollback() + return False + pending.manual_identity_authorization = { + "history_id": history_id, + "settlement_revision": settlement_revision, + "expires_at": expires_at, + } + transaction.commit() + return True + except Exception: + self._rollback(transaction) + raise def _replan_music_rejection( self, session: Session, *, pending: TransferPending, updated_at: str, diff --git a/app/db/models/transferpending.py b/app/db/models/transferpending.py index 34c4bfdfa..53339ed0c 100644 --- a/app/db/models/transferpending.py +++ b/app/db/models/transferpending.py @@ -122,6 +122,8 @@ class TransferPending(Base): retry_requested_by: Mapped[Optional[str]] = mapped_column(String(128)) # 最近一次终态失败重试请求原因 retry_reason: Mapped[Optional[str]] = mapped_column(Text) + # 当前待消费的人工身份修正授权;每个任务最多保存一份 + manual_identity_authorization: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON) # 已完成终态结算的单调版本 settlement_revision: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # 失败终态保留的整理历史标识 @@ -771,6 +773,7 @@ class TransferPending(Base): execution_state="failed", settlement_revision=cls.settlement_revision + 1, terminal_history_id=history_id, + manual_identity_authorization=None, lease_owner=None, lease_token=None, lease_expires_at=None, diff --git a/database/versions/b7c1e3d5f9a2_transfer_manual_grant.py b/database/versions/b7c1e3d5f9a2_transfer_manual_grant.py new file mode 100644 index 000000000..b275be86c --- /dev/null +++ b/database/versions/b7c1e3d5f9a2_transfer_manual_grant.py @@ -0,0 +1,40 @@ +"""为持久整理任务增加单份待消费的人工身份修正授权。""" + +from alembic import op +import sqlalchemy as sa + +revision = "b7c1e3d5f9a2" +down_revision = "a7383c1d9e20" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """ + 在旧整理任务表增加授权状态槽,并兼容 ORM 已创建最新结构的启动流程。 + """ + inspector = sa.inspect(op.get_bind()) + if "transferpending" not in inspector.get_table_names(): + return + if "manual_identity_authorization" in { + column["name"] for column in inspector.get_columns("transferpending") + }: + return + op.add_column( + "transferpending", + sa.Column("manual_identity_authorization", sa.JSON(), nullable=True), + ) + + +def downgrade() -> None: + """ + 移除待消费授权槽,不触碰任务或历史记录。 + """ + inspector = sa.inspect(op.get_bind()) + if "transferpending" not in inspector.get_table_names(): + return + if "manual_identity_authorization" not in { + column["name"] for column in inspector.get_columns("transferpending") + }: + return + op.drop_column("transferpending", "manual_identity_authorization") diff --git a/scripts/generate_agent_skill_docs.py b/scripts/generate_agent_skill_docs.py index 5949740bd..121398773 100644 --- a/scripts/generate_agent_skill_docs.py +++ b/scripts/generate_agent_skill_docs.py @@ -19,7 +19,7 @@ if str(PROJECT_ROOT) not in sys.path: # 与对应 SKILL.md 同步维护,重新生成不能回退用户同步所需的版本。 MOVIEPILOT_API_SKILL_VERSION = "74" -DATABASE_OPERATION_SKILL_VERSION = "18" +DATABASE_OPERATION_SKILL_VERSION = "19" DATABASE_TABLE_GUIDES: dict[str, tuple[str, str, str]] = { @@ -189,7 +189,8 @@ DATABASE_TABLE_GUIDES: dict[str, tuple[str, str, str]] = { "identity and actor_name is a bounded display snapshot. Old rows have unknown origin.", ), "transferpending": ( - "Durably stores pending transfer input, plans, checkpoints, leases, retries, and manual review state.", + "Durably stores pending transfer input, plans, checkpoints, leases, retries, manual review state, " + "and one short-lived pending manual identity authorization.", "Diagnosing restart recovery, expired leases, retry_wait, terminal failures, or manual review.", "Core durable state machine advanced only by planning, execution, retry, and review services.", ), diff --git a/skills/database-operation/SKILL.md b/skills/database-operation/SKILL.md index 6c57ef92a..dd9c1fea0 100644 --- a/skills/database-operation/SKILL.md +++ b/skills/database-operation/SKILL.md @@ -1,6 +1,6 @@ --- name: database-operation -version: 18 +version: 19 description: >- Use this skill when you need to inspect, query, maintain, or carefully modify the MoviePilot database. This skill uses the bundled scripts/mp-db.py helper, @@ -344,10 +344,10 @@ and pass the flag only for an explicitly authorized repair. - Columns: `id`, `transfer_task_id`, `transfer_settlement_revision`, `origin`, `registration`, `src`, `src_storage`, `src_fileitem`, `dest`, `dest_storage`, `dest_fileitem`, `mode`, `type`, `media_category_id`, `category`, `classification_rule_id`, `classification_policy_revision`, `classification_source`, `title`, `year`, `media_source`, `media_id`, `music_type`, `total_tracks`, `audio_format`, `audio_lossless`, `bit_depth`, `sample_rate`, `bitrate`, `seasons`, `episodes`, `image`, `downloader`, `download_hash`, `status`, `errmsg`, `retry_count`, `auto_paused`, `failure_stage`, `recovery_action`, `cleanup_status`, `cleanup_error`, `date`, `files`, `episode_group` ### `transferpending` -- Purpose: Durably stores pending transfer input, plans, checkpoints, leases, retries, and manual review state. +- Purpose: Durably stores pending transfer input, plans, checkpoints, leases, retries, manual review state, and one short-lived pending manual identity authorization. - Useful queries: Diagnosing restart recovery, expired leases, retry_wait, terminal failures, or manual review. - Write boundary: Core durable state machine advanced only by planning, execution, retry, and review services. -- Columns: `id`, `task_id`, `storage`, `src_path`, `created_at`, `state`, `updated_at`, `last_error`, `input_version`, `planning_input`, `input_fingerprint`, `checkpoint_version`, `checkpoint_payload`, `planned_at`, `lease_owner`, `lease_token`, `lease_expires_at`, `heartbeat_at`, `attempt_count`, `execution_state`, `execution_version`, `execution_payload`, `execution_fingerprint`, `retry_generation`, `retry_count`, `retry_due_at`, `retry_requested_by`, `retry_reason`, `settlement_revision`, `terminal_history_id`, `manual_review_revision`, `reviewed_at`, `reviewed_by`, `review_reason`, `review_decision` +- Columns: `id`, `task_id`, `storage`, `src_path`, `created_at`, `state`, `updated_at`, `last_error`, `input_version`, `planning_input`, `input_fingerprint`, `checkpoint_version`, `checkpoint_payload`, `planned_at`, `lease_owner`, `lease_token`, `lease_expires_at`, `heartbeat_at`, `attempt_count`, `execution_state`, `execution_version`, `execution_payload`, `execution_fingerprint`, `retry_generation`, `retry_count`, `retry_due_at`, `retry_requested_by`, `retry_reason`, `manual_identity_authorization`, `settlement_revision`, `terminal_history_id`, `manual_review_revision`, `reviewed_at`, `reviewed_by`, `review_reason`, `review_decision` ### `transfersettlementreceipt` - Purpose: Stores immutable terminal settlement receipts with contiguous revisions per transfer task. diff --git a/tests/fixtures/architecture/concurrency-baseline.json b/tests/fixtures/architecture/concurrency-baseline.json index b342581ec..69df04059 100644 --- a/tests/fixtures/architecture/concurrency-baseline.json +++ b/tests/fixtures/architecture/concurrency-baseline.json @@ -238,7 +238,8 @@ "app/api/endpoints/history.py:asyncio.to_thread": { "owners": { "ai_redo_transfer_history": 1, - "batch_ai_redo_transfer_history": 1 + "batch_ai_redo_transfer_history": 1, + "_grant_manual_identity_authorization": 1 }, "target": "asyncio.to_thread" }, diff --git a/tests/test_builtin_skill_boundaries.py b/tests/test_builtin_skill_boundaries.py index dd0877079..335a04c27 100644 --- a/tests/test_builtin_skill_boundaries.py +++ b/tests/test_builtin_skill_boundaries.py @@ -127,7 +127,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None: expected_versions = { "browser-use": "4", "command-dispatch": "2", - "database-operation": "18", + "database-operation": "19", "feedback-issue": "12", "anysearch": "3", "moviepilot-api": "74", diff --git a/tests/test_history_ai_retry_gate.py b/tests/test_history_ai_retry_gate.py index c13e5cb29..6cb30f358 100644 --- a/tests/test_history_ai_retry_gate.py +++ b/tests/test_history_ai_retry_gate.py @@ -6,7 +6,7 @@ from __future__ import annotations import asyncio from types import SimpleNamespace -from unittest.mock import Mock +from unittest.mock import Mock, call import pytest @@ -94,7 +94,9 @@ def test_single_ai_redo_starts_agent_without_retrying_frozen_plan(monkeypatch): started = Mock() monkeypatch.setattr(history_endpoint, "_start_ai_redo_task", started) response = asyncio.run(history_endpoint.ai_redo_transfer_history( - 11, query=_HistoryQuery([TransferHistory(id=11, transfer_task_id="task-11")]), + 11, query=_HistoryQuery([TransferHistory( + id=11, transfer_task_id="task-11", transfer_settlement_revision=1, + )]), runtime_config=_runtime(), task_registry=object(), execution_repository=repository, _=None, )) assert response.success @@ -104,6 +106,9 @@ def test_single_ai_redo_starts_agent_without_retrying_frozen_plan(monkeypatch): assert "task-11" in prompt and "transfer.history.replan" in prompt repository.request_retry.assert_not_called() repository.request_replan.assert_not_called() + repository.grant_manual_identity_authorization.assert_called_once_with( + history_id=11, task_id="task-11", settlement_revision=1, + ) @pytest.mark.parametrize("batch", [False, True]) @@ -156,8 +161,12 @@ def test_batch_ai_redo_sends_all_eligible_records_to_agent(monkeypatch, mixed): monkeypatch.setattr(history_endpoint, "_start_batch_ai_redo_task", started) response = asyncio.run(history_endpoint.batch_ai_redo_transfer_history( BatchTransferHistoryRedoRequest(history_ids=[18, 19, 18]), - query=_HistoryQuery([TransferHistory(id=18, transfer_task_id="task-18"), - TransferHistory(id=19, transfer_task_id=None if mixed else "task-19")]), + query=_HistoryQuery([TransferHistory( + id=18, transfer_task_id="task-18", transfer_settlement_revision=1, + ), TransferHistory( + id=19, transfer_task_id=None if mixed else "task-19", + transfer_settlement_revision=None if mixed else 1, + )]), runtime_config=_runtime(), task_registry=object(), execution_repository=repository, _=None, )) assert response.success @@ -166,6 +175,10 @@ def test_batch_ai_redo_sends_all_eligible_records_to_agent(monkeypatch, mixed): assert started.call_args.kwargs["history_ids"] == [18, 19] assert "task-18" in started.call_args.kwargs["prompt"] repository.request_retry.assert_not_called() + expected_grants = [call(history_id=18, task_id="task-18", settlement_revision=1)] + if not mixed: + expected_grants.append(call(history_id=19, task_id="task-19", settlement_revision=1)) + assert repository.grant_manual_identity_authorization.call_args_list == expected_grants def test_batch_rejection_has_no_partial_retry_side_effects(monkeypatch): diff --git a/tests/test_subscription_identity_review_migration.py b/tests/test_subscription_identity_review_migration.py index 5de132251..6a1a01c85 100644 --- a/tests/test_subscription_identity_review_migration.py +++ b/tests/test_subscription_identity_review_migration.py @@ -87,7 +87,8 @@ def test_identity_upgrade_chain_preserves_plugin_installation_snapshot(monkeypat config = Config() config.set_main_option("script_location", "database") script = ScriptDirectory.from_config(config) - assert script.get_heads() == ["a7383c1d9e20"] + assert script.get_heads() == ["b7c1e3d5f9a2"] + assert script.get_revision("b7c1e3d5f9a2").down_revision == "a7383c1d9e20" assert script.get_revision("a7383c1d9e20").down_revision == "b849e613a72f" assert script.get_revision("b849e613a72f").down_revision == "97ad7239c1e0" assert script.get_revision("97ad7239c1e0").down_revision == "4f62a73e81c9" diff --git a/tests/test_transfer_ai_replan.py b/tests/test_transfer_ai_replan.py index 503ce9fca..e71cd2ca0 100644 --- a/tests/test_transfer_ai_replan.py +++ b/tests/test_transfer_ai_replan.py @@ -14,6 +14,7 @@ from sqlalchemy.orm import sessionmaker from app.api.endpoints import history as history_endpoint from app.application.chain.events import TransferResultSettlement from app.application.history import TransferHistoryWrite +from app.application.history.retry import max_failed_retries from app.application.transfer.execution import ( TransferExecutionCommand, TransferExecutionConflictError, @@ -113,21 +114,52 @@ def _failed_recognition(store, tmp_path): return claimed, planning, receipt -def _correct(executions, history_id, task_id): +def _correct(executions, history_id, task_id, settlement_revision=1): """ 模拟 Agent 经媒体查询核实后提交本 Issue 的 S02E03 修正。 :param executions: 执行仓储端口 :param history_id: 精确失败历史标识 :param task_id: 原始失败回执关联的持久任务 + :param settlement_revision: 当前失败回执的结算版本 :return: 持久调度受理结果 """ return TransferExecutionCommand(executions).request_replan( - history_id=history_id, task_id=task_id, settlement_revision=1, media_source='themoviedb', media_id='117061', media_type='tv', + history_id=history_id, task_id=task_id, settlement_revision=settlement_revision, + media_source='themoviedb', media_id='117061', media_type='tv', season=2, episode=3, requested_by='test-agent', ) +def _grant_manual_identity_authorization(executions, history_id, task_id): + """ + 为当前失败结算覆盖任务上的单份人工身份修正授权。 + + :param executions: 执行仓储端口 + :param history_id: 失败历史标识 + :param task_id: 失败任务标识 + :return: 授权是否登记成功 + """ + return TransferExecutionCommand(executions).grant_manual_identity_authorization( + history_id=history_id, task_id=task_id, settlement_revision=1, + ) + + +def _exhaust_replan_budget(factory, history_id): + """ + 将测试任务推进到真实预算门拒绝的状态。 + + :param factory: 隔离数据库的会话工厂 + :param history_id: 失败历史标识 + """ + with factory() as session: + pending = session.scalars(select(TransferPending)).one() + history = session.get(TransferHistory, history_id) + pending.retry_count = history.retry_count = max_failed_retries() + history.auto_paused = True + session.commit() + + def test_replan_preserves_identity_evidence_budget_and_replays_correct_season(replan_store, tmp_path, monkeypatch): """ 修正重启后仍使用同一任务与预算,并从 accepted 输入恢复正确身份和 S02E03。 @@ -209,6 +241,85 @@ def test_repeated_replan_is_rejected_without_extra_generation(replan_store, tmp_ assert len(session.scalars(select(TransferSettlementReceipt)).all()) == 1 +def test_manual_identity_authorization_is_one_slot_and_consumed_with_replan(replan_store, tmp_path): + """ + 预算耗尽时仅接受任务上的单份授权,并与重规划在同一事务中清除。 + """ + _admissions, executions, factory, _writer = replan_store + claimed, _planning, receipt = _failed_recognition(replan_store, tmp_path) + _exhaust_replan_budget(factory, receipt.history_id) + with pytest.raises(TransferExecutionConflictError, match="自动重试次数已耗尽"): + _correct(executions, receipt.history_id, claimed.task_id) + + assert _grant_manual_identity_authorization(executions, receipt.history_id, claimed.task_id) + assert _grant_manual_identity_authorization(executions, receipt.history_id, claimed.task_id) + with factory() as session: + pending = session.scalars(select(TransferPending)).one() + assert pending.manual_identity_authorization["history_id"] == receipt.history_id + assert pending.manual_identity_authorization["settlement_revision"] == receipt.settlement_revision + + before = executions.get_snapshot(task_id=claimed.task_id) + result = _correct(executions, receipt.history_id, claimed.task_id) + assert result.accepted and result.state is TransferExecutionState.RETRY_WAIT + with factory() as session: + pending = session.scalars(select(TransferPending)).one() + assert pending.manual_identity_authorization is None + assert pending.retry_count == before.retry_count + 1 + assert pending.retry_requested_by.endswith("+manual_identity") + assert "管理用户确认" in pending.retry_reason + with pytest.raises(TransferExecutionConflictError): + _correct(executions, receipt.history_id, claimed.task_id) + + +@pytest.mark.parametrize("authorization", [ + {"history_id": 999, "settlement_revision": 1, "expires_at": "2999-01-01 00:00:00.000000"}, + {"history_id": 1, "settlement_revision": 99, "expires_at": "2999-01-01 00:00:00.000000"}, + {"history_id": 1, "settlement_revision": 1, "expires_at": "2000-01-01 00:00:00.000000"}, +]) +def test_stale_manual_identity_authorization_does_not_bypass_budget( + replan_store, tmp_path, authorization, +): + """ + 错历史、错结算版本或过期授权均保持预算拒绝,且不改写授权槽。 + """ + _admissions, executions, factory, _writer = replan_store + claimed, _planning, receipt = _failed_recognition(replan_store, tmp_path) + _exhaust_replan_budget(factory, receipt.history_id) + authorization = dict(authorization) + if authorization["history_id"] == 1: + authorization["history_id"] = receipt.history_id + with factory() as session: + pending = session.scalars(select(TransferPending)).one() + pending.manual_identity_authorization = authorization + session.commit() + + with pytest.raises(TransferExecutionConflictError, match="自动重试次数已耗尽"): + _correct(executions, receipt.history_id, claimed.task_id) + with factory() as session: + pending = session.scalars(select(TransferPending)).one() + assert pending.manual_identity_authorization == authorization + + +def test_manual_authorization_rolls_back_when_file_side_effect_guard_rejects(replan_store, tmp_path): + """ + 文件副作用检查拒绝后回滚授权清除,保留单份授权供后续安全处理。 + """ + _admissions, executions, factory, _writer = replan_store + claimed, _planning, receipt = _failed_recognition(replan_store, tmp_path) + _exhaust_replan_budget(factory, receipt.history_id) + assert _grant_manual_identity_authorization(executions, receipt.history_id, claimed.task_id) + with factory() as session: + step = session.scalars(select(TransferExecutionStep)).one() + step.phase, step.kind = "transfer", "materialize_target" + session.commit() + + with pytest.raises(TransferExecutionConflictError, match="文件操作"): + _correct(executions, receipt.history_id, claimed.task_id) + with factory() as session: + pending = session.scalars(select(TransferPending)).one() + assert pending.manual_identity_authorization is not None + + @pytest.mark.parametrize('blocker', ['manual_review', 'running', 'active_lease', 'history_revision', 'receipt_revision', 'paused', 'history_budget', 'task_budget', 'file_step', 'storage', 'corrupt_input']) def test_replan_rejects_unsafe_or_stale_tasks_atomically(replan_store, tmp_path, blocker): diff --git a/tests/test_transfer_execution_migration.py b/tests/test_transfer_execution_migration.py index e4a2d5213..c177f35a3 100644 --- a/tests/test_transfer_execution_migration.py +++ b/tests/test_transfer_execution_migration.py @@ -28,6 +28,7 @@ from app.db.adapters.transfer.execution import ( from app.db.models.transferpending import TransferPending MIGRATION = "database.versions.e5c7a9b1d3f6_3_0_16" +MANUAL_GRANT_MIGRATION = "database.versions.b7c1e3d5f9a2_transfer_manual_grant" LEGACY_DIAGNOSTIC = "升级检测到既有执行迹象,需人工确认后再处理" @@ -781,6 +782,13 @@ def test_migrated_legacy_reviews_are_discoverable_resolvable_and_retryable( _insert_legacy_rows(connection, pending) migration = _bind_migration(monkeypatch, connection) migration.upgrade() + current_migration = importlib.import_module(MANUAL_GRANT_MIGRATION) + monkeypatch.setattr( + current_migration, + "op", + Operations(MigrationContext.configure(connection)), + ) + current_migration.upgrade() factory = sessionmaker(bind=engine, expire_on_commit=False) repository = TransactionalTransferExecutionRepository( diff --git a/tests/test_transfer_lease_migration.py b/tests/test_transfer_lease_migration.py index dd124ddeb..fb8a26f91 100644 --- a/tests/test_transfer_lease_migration.py +++ b/tests/test_transfer_lease_migration.py @@ -35,6 +35,7 @@ TRANSFER_EXECUTION_COLUMNS = { "reviewed_by", "review_reason", "review_decision", + "manual_identity_authorization", } diff --git a/tests/test_transfer_manual_grant_migration.py b/tests/test_transfer_manual_grant_migration.py new file mode 100644 index 000000000..0464f2d75 --- /dev/null +++ b/tests/test_transfer_manual_grant_migration.py @@ -0,0 +1,38 @@ +"""验证任务授权状态槽迁移不影响已有整理任务。""" + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_manual_grant_migration_preserves_existing_pending_rows(monkeypatch): + """ + 升级增加空授权槽,降级只移除该列并保留原任务数据。 + """ + migration = importlib.import_module("database.versions.b7c1e3d5f9a2_transfer_manual_grant") + engine = sa.create_engine("sqlite://") + with engine.begin() as connection: + connection.execute(sa.text( + "CREATE TABLE transferpending (id INTEGER PRIMARY KEY, task_id TEXT NOT NULL)" + )) + connection.execute(sa.text("INSERT INTO transferpending (id, task_id) VALUES (1, 'task-1')")) + monkeypatch.setattr(migration, "op", Operations(MigrationContext.configure(connection))) + + migration.upgrade() + columns = {column["name"]: column for column in sa.inspect(connection).get_columns("transferpending")} + assert columns["manual_identity_authorization"]["nullable"] is True + assert connection.execute(sa.text( + "SELECT task_id, manual_identity_authorization FROM transferpending" + )).all() == [("task-1", None)] + migration.upgrade() + assert len(sa.inspect(connection).get_columns("transferpending")) == len(columns) + + migration.downgrade() + migration.downgrade() + assert "manual_identity_authorization" not in { + column["name"] for column in sa.inspect(connection).get_columns("transferpending") + } + assert connection.execute(sa.text("SELECT task_id FROM transferpending")).all() == [("task-1",)] + engine.dispose() diff --git a/tests/test_transfer_planning_migration.py b/tests/test_transfer_planning_migration.py index ffc10e5bb..5ba565cb8 100644 --- a/tests/test_transfer_planning_migration.py +++ b/tests/test_transfer_planning_migration.py @@ -45,6 +45,7 @@ POST_LEASE_EXECUTION_COLUMNS = { "reviewed_by", "review_reason", "review_decision", + "manual_identity_authorization", } diff --git a/tests/test_transfer_reconciliation_migration.py b/tests/test_transfer_reconciliation_migration.py index b6df980d8..2e452da07 100644 --- a/tests/test_transfer_reconciliation_migration.py +++ b/tests/test_transfer_reconciliation_migration.py @@ -53,6 +53,7 @@ PLANNING_MIGRATION = "database.versions.c2f8a4d6e1b3_3_0_14" LEASE_MIGRATION = "database.versions.d3a9e5f7b2c4_3_0_15" EXECUTION_MIGRATION = "database.versions.e5c7a9b1d3f6_3_0_16" RECONCILIATION_MIGRATION = "database.versions.f6d8b0c2e4a7_3_0_17" +MANUAL_GRANT_MIGRATION = "database.versions.b7c1e3d5f9a2_transfer_manual_grant" def _bind_migration(monkeypatch, connection, module_name: str): @@ -391,6 +392,12 @@ def test_upgrade_reconciles_invalid_execution_combinations(monkeypatch) -> None: ) reconciliation.upgrade() reconciliation.upgrade() + manual_grant = _bind_migration( + monkeypatch, + connection, + MANUAL_GRANT_MIGRATION, + ) + manual_grant.upgrade() rows = { row["task_id"]: dict(row) @@ -622,7 +629,7 @@ def _create_history_table(connection) -> None: def _run_upgrade_chain(monkeypatch, connection) -> list[object]: """ - 从 3.0.13 顺序升级到 3.0.17 并返回迁移模块。 + 从 3.0.13 顺序升级到当前迁移 head 并返回迁移模块。 """ migrations = [ _bind_migration(monkeypatch, connection, module_name) @@ -632,6 +639,7 @@ def _run_upgrade_chain(monkeypatch, connection) -> list[object]: LEASE_MIGRATION, EXECUTION_MIGRATION, RECONCILIATION_MIGRATION, + MANUAL_GRANT_MIGRATION, ) ] for migration in migrations: @@ -677,6 +685,11 @@ def test_full_legacy_chain_projects_after_downgrade_and_reupgrade( connection, RECONCILIATION_MIGRATION, ) + manual_grant = _bind_migration( + monkeypatch, + connection, + MANUAL_GRANT_MIGRATION, + ) admission.upgrade() planning.upgrade() lease.upgrade() @@ -717,6 +730,7 @@ def test_full_legacy_chain_projects_after_downgrade_and_reupgrade( )) execution.upgrade() reconciliation.upgrade() + manual_grant.upgrade() normalized = dict(connection.execute(sa.text( "SELECT src_path, state FROM transferpending ORDER BY id" )).all()) @@ -776,6 +790,7 @@ def test_full_legacy_chain_projects_after_downgrade_and_reupgrade( with engine.begin() as connection: for migration in ( + manual_grant, reconciliation, execution, lease,