diff --git a/app/application/history/__init__.py b/app/application/history/__init__.py index 0436d6610..4f67c2186 100644 --- a/app/application/history/__init__.py +++ b/app/application/history/__init__.py @@ -322,11 +322,14 @@ class DownloadHistoryQueryPort(Protocol): def get_by_hashes( self, download_hashes: list[str], + *, + downloader: Optional[str] = None, ) -> dict[str, DownloadHistorySnapshot]: """ 批量返回以下载任务 Hash 为键的最新历史快照。 :param download_hashes: 待批量查询的下载任务哈希标识 + :param downloader: 限定为该名称的下载器实例;None 表示跨实例查询 :return: 以任务哈希为键的最新历史映射;未找到的哈希不写入映射 """ ... diff --git a/app/chain/download/pending.py b/app/chain/download/pending.py index e453e28c5..e9ba5f70e 100644 --- a/app/chain/download/pending.py +++ b/app/chain/download/pending.py @@ -667,15 +667,15 @@ class DownloadPendingOwner(_DownloadOwnerBase): if current is None: # 已被并发线程确认结算或释放,无需重复处理。 return "already_gone", None - already_recorded = self._find_settled_history_for_pending(current) - if already_recorded is not None: + settled_hash = self._find_settled_history_for_pending(current) + if settled_hash is not None: self._delete_pending_record(current.pending_key) context = self._build_confirmed_context(current) return "confirmed", ConfirmedPendingDownload( record=current, context=context, - downloader=already_recorded[0], - download_hash=already_recorded[1], + downloader=current.downloader, + download_hash=settled_hash, ) check = self._query_pending_in_downloader(current) if check.status is PendingDownloadCheckStatus.CONFIRMED and check.download_hash: @@ -739,26 +739,27 @@ class DownloadPendingOwner(_DownloadOwnerBase): def _find_settled_history_for_pending( self, record: DownloadPendingSnapshot, - ) -> Optional[tuple[Optional[str], str]]: + ) -> Optional[str]: """ - 检查该待确认提交的哈希是否已写入不早于本次提交时间的下载历史,实现崩溃恢复幂等。 + 仅使用同一下载器实例在提交时或之后写入的历史作为已结算凭据。 + + :param record: 待恢复的提交记录;缺少实例名称时继续向下载器核对 + :return: 符合恢复条件的任务哈希;无匹配时返回 None """ - if not record.hashes: + if not record.downloader or not record.hashes: return None - history_repo = getattr(self, "download_history_repository", None) + history_repo = self.download_history_repository if history_repo is None: return None candidates = sorted({variant for item in record.hashes for variant in (item.lower(), item.upper())}) try: - histories = history_repo.get_by_hashes(candidates) + histories = history_repo.get_by_hashes(candidates, downloader=record.downloader) except Exception as err: logger.debug(f"幂等检查待确认下载历史失败:{err}") return None - for item in (histories or {}).values(): - history_date = str(getattr(item, "date", "") or "") - history_hash = str(getattr(item, "download_hash", "") or "") - if history_hash and history_date >= record.submitted_at: - return getattr(item, "downloader", None), history_hash + for history_hash, item in histories.items(): + if item.date and item.date >= record.submitted_at: + return history_hash return None def _query_pending_in_downloader( diff --git a/app/db/adapters/history/download.py b/app/db/adapters/history/download.py index cdb503efd..cbb3c8817 100644 --- a/app/db/adapters/history/download.py +++ b/app/db/adapters/history/download.py @@ -153,14 +153,20 @@ class TransactionalDownloadHistoryRepository: def get_by_hashes( self, download_hashes: list[str], + *, + downloader: Optional[str] = None, ) -> dict[str, DownloadHistorySnapshot]: """ 批量返回以下载任务 Hash 为键的最新历史快照。 + + :param download_hashes: 待批量查询的下载任务哈希标识 + :param downloader: 限定为该名称的下载器实例;None 表示跨实例查询 + :return: 以任务哈希为键的最新历史映射 """ return self._read( lambda repository: { download_hash: _project_history(record) - for download_hash, record in repository.get_by_hashes(download_hashes).items() + for download_hash, record in repository.get_by_hashes(download_hashes, downloader=downloader).items() } ) diff --git a/app/db/models/downloadhistory.py b/app/db/models/downloadhistory.py index 6dfbda897..3ba1ec1b1 100644 --- a/app/db/models/downloadhistory.py +++ b/app/db/models/downloadhistory.py @@ -107,9 +107,16 @@ class DownloadHistory(Base): return history @classmethod - def get_by_hashes(cls, db: Session, download_hashes: List[str]) -> list["DownloadHistory"]: + def get_by_hashes( + cls, db: Session, download_hashes: List[str], *, downloader: Optional[str] = None, + ) -> list["DownloadHistory"]: """ 批量查询多个下载任务的最新历史记录,避免在上层形成 N+1 查询。 + + :param db: 调用方持有的同步数据库会话 + :param download_hashes: 待批量查询的下载任务哈希标识 + :param downloader: 选取最新记录前限定下载器实例名称;None 表示跨实例查询 + :return: 按请求顺序返回的最新历史列表,每个哈希最多一条 """ normalized_hashes = [] seen_hashes = set() @@ -122,11 +129,12 @@ class DownloadHistory(Base): if not normalized_hashes: return [] + statement = select(DownloadHistory).where(DownloadHistory.download_hash.in_(normalized_hashes)) + if downloader is not None: + statement = statement.where(DownloadHistory.downloader == downloader) histories = db.execute( - select(DownloadHistory) - .where(DownloadHistory.download_hash.in_(normalized_hashes)) # 登记时间只精确到秒,同一秒内的多条记录以主键为准,与 get_by_hash 的"最新"口径一致。 - .order_by(DownloadHistory.download_hash, DownloadHistory.date.desc(), DownloadHistory.id.desc()) + statement.order_by(DownloadHistory.download_hash, DownloadHistory.date.desc(), DownloadHistory.id.desc()) ).scalars().all() latest_histories = {} for history in histories: diff --git a/app/db/oper/downloadhistory.py b/app/db/oper/downloadhistory.py index e74afe769..d88c3b32d 100644 --- a/app/db/oper/downloadhistory.py +++ b/app/db/oper/downloadhistory.py @@ -147,13 +147,19 @@ class DownloadHistoryOper(DbOper): lambda session: DownloadHistory.get_by_hash(session, download_hash) ) - def get_by_hashes(self, download_hashes: List[str]) -> Dict[str, DownloadHistory]: + def get_by_hashes( + self, download_hashes: List[str], *, downloader: Optional[str] = None, + ) -> Dict[str, DownloadHistory]: """ 批量按 Hash 查询下载记录,并返回以 Hash 为键的映射。 + + :param download_hashes: 待批量查询的下载任务哈希标识 + :param downloader: 限定为该名称的下载器实例;None 表示跨实例查询 + :return: 以任务哈希为键的最新历史映射 """ histories = self._execute_sync_query( lambda session: DownloadHistory.get_by_hashes( - session, download_hashes + session, download_hashes, downloader=downloader, ) ) return { diff --git a/tests/test_download_pending_confirmation.py b/tests/test_download_pending_confirmation.py index a2061267a..10b36b107 100644 --- a/tests/test_download_pending_confirmation.py +++ b/tests/test_download_pending_confirmation.py @@ -32,6 +32,7 @@ from app.db.adapters.download import ( TransactionalDownloadFailureRepository, TransactionalDownloadPendingRepository, ) +from app.db.models.downloadhistory import DownloadHistory from app.db.models.downloadpending import DownloadPending from app.db.session import SessionFactory from app.domain.context import Context, MediaInfo, MusicInfo, TorrentInfo @@ -708,12 +709,36 @@ def test_transfer_chain_reconciles_pending_before_scanning_completed_torrents(): assert events == ["reconcile", "list_torrents"] -def test_reconcile_pending_is_idempotent_when_history_was_already_written_after_submission(): +@pytest.mark.parametrize( + ("pending_downloader", "histories", "already_settled"), + [ + pytest.param("qb", [("qb", "22:27:05")], True, id="same-instance"), + pytest.param("qb", [("qb", "22:27:05"), ("qb-other", "22:28:05")], True, id="same-instance-shadowed"), + pytest.param("qb", [("qb-other", "22:28:05")], False, id="other-instance"), + pytest.param("qb", [("qb", "21:42:00"), ("qb-other", "22:28:05")], False, id="old-same-instance"), + pytest.param("", [("", "22:28:05")], False, id="unknown-instance"), + ], +) +def test_reconcile_pending_recovers_only_from_current_instance_history( + db, pending_downloader, histories, already_settled, +): """ - 崩溃恢复幂等:若该哈希已存在不早于提交时间的下载历史,核对时直接清理待确认而不重复写历史。 + 同一下载器在提交后写入的历史可用于幂等恢复。其他实例或归属不明的历史仍须向下载器核对。 """ + db.watermark(DownloadPending) pending_repo = TransactionalDownloadPendingRepository(SessionFactory) target_hash = "c" * 40 + db.add(*[ + DownloadHistory( + path="/downloads/Inception", + type=MediaType.MOVIE.value, + title="Inception", + downloader=history_downloader, + download_hash=target_hash, + date=f"2026-11-22 {history_time}", + ) + for history_downloader, history_time in histories + ]) pending_repo.upsert( DownloadPendingWrite( pending_key="idempotent-pending", @@ -725,7 +750,7 @@ def test_reconcile_pending_is_idempotent_when_history_was_already_written_after_ year="2010", media_source=MediaSource.TMDB, media_id="27205", - downloader="qb", + downloader=pending_downloader, hashes=(target_hash,), torrent_name="Release-A", source='Subscribe|{"id": 42}', @@ -734,27 +759,27 @@ def test_reconcile_pending_is_idempotent_when_history_was_already_written_after_ ) chain = DownloadChain() chain.download_pending_repository = pending_repo - chain.download_history_repository = SimpleNamespace( - get_by_hashes=MagicMock( - return_value={ - target_hash: SimpleNamespace( - downloader="qb", - download_hash=target_hash, - date="2026-11-22 22:27:05", - ) - } + chain.confirm_pending_download = MagicMock( + return_value=PendingDownloadCheckResult( + status=PendingDownloadCheckStatus.NOT_FOUND, + downloader=pending_downloader or None, ) ) - chain.confirm_pending_download = MagicMock() chain._settle_download_success = MagicMock() - result = chain.reconcile_pending_downloads() + result = chain.reconcile_pending_downloads(subscription_id=42) - assert len(result.confirmed) == 1 - assert result.confirmed[0].download_hash == target_hash - assert pending_repo.list_all() == [] - chain.confirm_pending_download.assert_not_called() chain._settle_download_success.assert_not_called() + if already_settled: + assert [(item.downloader, item.download_hash) for item in result.confirmed] == [(pending_downloader, target_hash)] + assert pending_repo.get_by_key("idempotent-pending") is None + chain.confirm_pending_download.assert_not_called() + else: + assert result.confirmed == () + assert [item.pending_key for item in result.still_pending] == ["idempotent-pending"] + assert pending_repo.get_by_key("idempotent-pending") is not None + chain.confirm_pending_download.assert_called_once() + assert chain.confirm_pending_download.call_args.kwargs["downloader"] == (pending_downloader or None) def test_music_batch_blocks_same_music_after_unconfirmed_without_blocking_other_music(monkeypatch):