Peach: Local-first video metadata scraper and media manager.
feat(scan): 新文件登记时把已消失作品的个人记录接回
longmeidaoc267af833d29
diff --git a/migrations/0041_vanished_record_rehome.sql b/migrations/0041_vanished_record_rehome.sqlnew file mode 100644index 000000000..88713a86e--- /dev/null+++ b/migrations/0041_vanished_record_rehome.sql@@ -0,0 +1,38 @@+-- 盘上消失的文件带着个人记录时标「已消失」,新文件登记时把记录接过去(ADR-0087)。+--+-- `asset_quality_goal.replaced_at`:寻找更好版本的目标随记录搬到新行就算达成,`wanted` 置 0+-- 关闭,这一列记下被替换的时刻,和用户自己取消的目标分得开。+--+-- `record_rehome`:一次搬运一行,就是 ADR-0052 的一个批次(`<source>@<id>`)。`snapshot_json`+-- 存旧行整行、它在各引用表里的全部行和指向它的播放列表指针,`moved_json` 存改指新行的那几条的+-- 键;整批撤回时按快照重建旧行,把搬走的改回旧行。两个 asset id 都不挂外键:旧行搬完就删了,+-- 新行以后也可能被删,批次记录要留着。+ALTER TABLE asset_quality_goal ADD COLUMN replaced_at TEXT;++CREATE TABLE record_rehome(+ id INTEGER PRIMARY KEY,+ source TEXT NOT NULL,+ rule TEXT NOT NULL,+ old_asset_id INTEGER NOT NULL,+ new_asset_id INTEGER NOT NULL,+ snapshot_json TEXT NOT NULL,+ moved_json TEXT NOT NULL,+ created_at TEXT NOT NULL,+ reverted_at TEXT+);++CREATE INDEX idx_record_rehome_source ON record_rehome(source,reverted_at,id);++INSERT INTO ledger_revision(tbl) VALUES ('record_rehome');++CREATE TRIGGER rev_record_rehome_insert AFTER INSERT ON record_rehome BEGIN+ UPDATE ledger_revision SET n=n+1 WHERE tbl='record_rehome';+END;++CREATE TRIGGER rev_record_rehome_update AFTER UPDATE ON record_rehome BEGIN+ UPDATE ledger_revision SET n=n+1 WHERE tbl='record_rehome';+END;++CREATE TRIGGER rev_record_rehome_delete AFTER DELETE ON record_rehome BEGIN+ UPDATE ledger_revision SET n=n+1 WHERE tbl='record_rehome';+END;diff --git a/scripts/revert_auto_landing.py b/scripts/revert_auto_landing.pyindex a6d2a93b2..474c560c6 100644--- a/scripts/revert_auto_landing.py+++ b/scripts/revert_auto_landing.py@@ -21,6 +21,11 @@补别名后继只写账本里还没有的写法,补女优资料后继只写自动来源的那一行,补样张后继只给还没有样张的番号写,写下的就是那一格的全部,删掉就回到它写之前的样子。+已消失作品的个人记录接到新文件(ADR-0087)不是删除能撤的:搬运删了旧行,`record_rehome` 存着+旧行快照与搬动的键,批次号 `<source>@<id>`。撤回按快照重建旧行、把搬走的记录改回去,旧行的+id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接回记 `auto:vanished-reattach`,孤儿记录+列表里由人接回记 `user:reattach`。+revert_auto_landing.py --source auto:performer-aliasrevert_auto_landing.py --source auto:performer-alias --batch auto:performer-alias@812revert_auto_landing.py --source auto:performer-profile@@ -28,6 +33,7 @@revert_auto_landing.py --source auto:seed --batch auto:seed@2026-09-25revert_auto_landing.py --source adr-0079-fc2-descriptive-performerrevert_auto_landing.py --source auto:metadata-tags+ revert_auto_landing.py --source auto:vanished-reattach --batch auto:vanished-reattach@3默认只列计划;`--apply` 必须同时给 `--backup`,删文件在账本行之后、同一次运行里完成。"""@@ -40,7 +46,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))-from peach import sample_images # noqa: E402+from peach import record_rehome, sample_images # noqa: E402from peach.config import GENERATED_DIR # noqa: E402from peach.metadata_auto_apply import UNION_TAGS_SOURCE # noqa: E402from peach.scripting import add_ledger_write_args, open_for_write, verify_after_write # noqa: E402@@ -247,6 +253,7 @@ def main(argv: list[str] | None = None) -> int:samples = sample_images.planned_revert(connection, args.source, args.batch)rejections = planned_rejections(connection, args.source, args.batch)tags = planned_tags(connection, args.source, args.batch)+ rehomes = record_rehome.planned_revert(connection, args.source, args.batch)for link in links:print(f" - 链接 {link['entity'][:20]:<20} {link['url'][:56]} {link['batch']}")for alias in aliases:@@ -267,10 +274,13 @@ def main(argv: list[str] | None = None) -> int:print(f" - 否决 {rejection['category']} {rejection['item_key']}")for tag in tags:print(f" - 标签 {tag['asset_id']:<8} {tag['tag'][:30]:<30} {tag['source']}")+ for rehome in rehomes:+ print(f" - 接回 {rehome['old_asset_id']:<8} → {rehome['new_asset_id']:<8} "+ f"{rehome['name'][:40]} {rehome['batch']}")print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "编号": len(refs),"归属": len(memberships), "片商": len(makers), "标识文件": len(files),"样张": sum(sample["count"] for sample in samples), "否决": len(rejections),- "标签": len(tags)})+ "标签": len(tags), "接回": len(rehomes)})if not args.apply:print("dry-run;确认无误后加 --apply --backup <路径>")return 0@@ -305,6 +315,7 @@ def main(argv: list[str] | None = None) -> int:"DELETE FROM asset_tag WHERE asset_id=? AND tag=? AND source=?",(tag["asset_id"], tag["tag"], tag["source"])).rowcount or 0 for tag in tags)reopened = reopen_extended_decisions(connection, {tag["item_key"] for tag in tags})+ restored = record_rehome.revert(connection, args.source, args.batch)integrity, orphans = verify_after_write(connection)finally:connection.close()@@ -318,7 +329,7 @@ def main(argv: list[str] | None = None) -> int:"删除编号": len(refs), "删除归属": len(memberships), "删除片商": len(makers),"删除样张": removed_samples, "删除否决": len(rejections),"删除标签": len(tags), "删除扁平标签": removed_tag_rows, "重开决定": reopened,- "删除文件": removed,+ "撤回接回": restored, "删除文件": removed,"integrity_check": integrity, "foreign_key_check": orphans})return 0diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 74423a013..dc3781ef6 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -51,7 +51,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_studio_followup.py", "test_sample_images.py","test_jav_code_domain.py","test_taste_history.py", "test_web_ui.py", "test_web_js.py",- "test_web_perf.py", "test_web_resource_sync.py",+ "test_web_perf.py", "test_web_resource_sync.py", "test_record_rehome.py","test_web_review.py", "test_web_settings.py"),# 任务中心的两个文件跟着 `test_jobs.py` 走:`jobs.py` 与 `task_runs.py` 是同一条# 接线的两端,改哪一端都要两边一起验。@@ -98,7 +98,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_agency_entity.py", "test_agency_reject.py", "test_label_maker.py","test_seed_pack.py", "test_seed_followup.py"),"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py",- "test_scan.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",+ "test_scan.py", "test_record_rehome.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py","test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py","test_version_bump.py", "test_changelog.py", "test_release_due.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py",@@ -204,6 +204,9 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {"src/peach/performer_header.py": ("metadata", "catalog", "web"),# 推送发现横跨扫描登记(tooling)与 HTTP 端点(catalog),按名字只推得出一个域。"src/peach/push_discovery.py": ("tooling", "catalog"),+ # 个人记录的判据与搬运(ADR-0087):资源同步与列表在 catalog,扫描登记与撤回脚本在 tooling。+ "src/peach/personal_records.py": ("catalog", "tooling"),+ "src/peach/record_rehome.py": ("catalog", "tooling"),# 入口页共用件的测试住在首启与配置来源那两份 tooling 测试里。"src/peach/web_entry.py": ("catalog", "tooling", "web"),# 这几份文档有测试在读它们的正文:改文档也要跑到那条测试。diff --git a/src/peach/library_processing.py b/src/peach/library_processing.pyindex db88bb5cd..032a295e1 100644--- a/src/peach/library_processing.py+++ b/src/peach/library_processing.py@@ -33,6 +33,7 @@ from .scan import scan_locationfrom .ffmpeg import FFmpegResolverfrom .jobs import DiskGuardfrom .media_probe import probe_unmeasured+from .record_rehome import reattach_inFIELDS = ('item_key', 'code', 'query', 'asset_id', 'asset_path', 'field', 'field_label', 'current_value','candidates_json', 'source_count', 'source_profile', 'policy_version', 'status',@@ -1592,6 +1593,8 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='costate['probed'] += probe_unmeasured(db_path, ffprobe, source, root,report=lambda done, total: update(stage='读取时长与分辨率', checked=done, total=total))+ # 登记那一刻新文件还没有时长;探完再判一轮,多个候选按时长挑、无番号按时长配。+ reattach_in(db_path, result.new_ids)if stage == SCAN_STAGE:# `checked`/`total` 在探时长时借给进度条用过;只扫描这一段没有采集,读数归零。update(status='failed' if state['issue_count'] else 'complete',diff --git a/src/peach/personal_records.py b/src/peach/personal_records.pyindex 0c3a81a42..6518a058f 100644--- a/src/peach/personal_records.py+++ b/src/peach/personal_records.py@@ -18,6 +18,15 @@ PERSONAL_RECORD_TABLES = ("asset_quality_goal", "activity_event", "asset_tag_preference",)+#: 一行 `asset` 被物理删除时要一并清掉的引用表,删除与搬运记录的边界只写在这一处。+#: `asset_search` 不在其中:0004 的 `asset_search_asset_delete` 触发器已经负责 FTS 行,+#: 这里再删一遍只会重复,还会诱使测试库伪造一张同名普通表,把 has_fts() 骗成 True。+ASSET_REFERENCE_TABLES = (+ "asset_tag", "media_binding", "activity_event", "asset_entity",+ "watch_queue", "asset_preference", "asset_tag_preference", "asset_quality_goal",+ "playlist_item", "asset_subtitle",+)+#: 文件已不在盘上、带着个人记录的那一档。VANISHED = "vanished"diff --git a/src/peach/push_discovery.py b/src/peach/push_discovery.pyindex 13a48f723..1796569cd 100644--- a/src/peach/push_discovery.py+++ b/src/peach/push_discovery.py@@ -634,12 +634,15 @@ class PushDiscoveryService:return Nonedef _ingest(self, location: str, path: str) -> bool:+ from .record_rehome import reattach_infrom .scan import ingest_pathresult = ingest_path(self.db_path, location, path,declared_roots=self.declared_roots, mounts=self.mounts)# 附属文件按「处理完了」计:文件在,只是按规则不登记,不是「文件不在」。if result.found and not result.sidecar:self._measure(location, path)+ # 登记时已按番号接回过一轮;探到时长之后,要靠时长分辨的那几条再判一次。+ reattach_in(self.db_path, [result.asset_id] if result.new else [])if result.found and self.after_ingest:self.after_ingest()return result.founddiff --git a/src/peach/record_rehome.py b/src/peach/record_rehome.pynew file mode 100644index 000000000..fda2aa3f4--- /dev/null+++ b/src/peach/record_rehome.py@@ -0,0 +1,280 @@+"""把「已消失」行的个人记录接到新文件上(ADR-0087 决策二)。++文件在盘上消失、行上带着个人记录时,资源同步只标 `disposal='vanished'`。新文件登记之后+按两条判据找它的旧行:++1. 番号:`normalise_code_key` 之后对上的已消失行只有一条,新文件也只有一个就搬;新文件有+ 几个时取时长与旧行最接近的那个,时长缺或并列就不搬,留给人在孤儿记录列表里选。+2. 无番号的创作者视频:旧行的创作者是新文件路径上的一层目录、文件名主干相同、时长差在+ `DURATION_TOLERANCE` 秒之内;候选多个时同样取最接近的。++同一 `(location, path)` 的文件回来了不归这里管:扫描的 upsert 直接清掉那一行的 `disposal`。++搬运把五张表的行改指新行,新行已有同一键的记录时以新行为准;`asset_quality_goal` 搬到新行+后置 `wanted=0` 并记 `replaced_at` 关闭,不当作新行的待找目标。搬完删旧行。每次搬运在+`record_rehome` 记一行,批次号 `<source>@<id>`(ADR-0052),存旧行整行、它在各引用表里的+全部行与改指过的键,`revert` 按快照重建旧行并把搬走的改回去。++调用方负责事务:这里的函数都只在给定连接上写,不提交。+"""+from __future__ import annotations++import json+import sqlite3+import time+from collections import Counter, defaultdict+from collections.abc import Iterable, Sequence+from contextlib import closing+from pathlib import PureWindowsPath++from .catalog_rules import normalise_code_key, release_code_from_filename+from .personal_records import ASSET_REFERENCE_TABLES, VANISHED++#: 登记时自动接回记的来源。+AUTO_SOURCE = "auto:vanished-reattach"+#: 孤儿记录列表里由人接到某个文件记的来源。+MANUAL_SOURCE = "user:reattach"++#: 搬运时改指新行的五张表,各自除 `asset_id` 之外认同一条记录的键。+MOVED_TABLES: dict[str, tuple[str, ...]] = {+ "asset_preference": ("profile_id",),+ "watch_queue": ("profile_id",),+ "playlist_item": ("playlist_id",),+ "activity_event": ("id",),+ "asset_tag_preference": ("profile_id", "normalized_tag"),+}+#: 寻找更好版本的目标:搬到新行后关闭。+GOAL_TABLE, GOAL_KEYS = "asset_quality_goal", ("profile_id",)++#: 无番号的创作者视频:时长差在这几秒之内算同一部。+DURATION_TOLERANCE = 2.0++_COLUMNS = "id,location,path,name,code,creator,duration"+++def _rows(connection, sql: str, params: Sequence = ()) -> list[dict]:+ """查询结果按列名转成字典,不依赖调用方连接上的 `row_factory`。"""+ cursor = connection.execute(sql, tuple(params))+ names = [column[0] for column in cursor.description]+ return [dict(zip(names, row)) for row in cursor.fetchall()]+++def code_key(row: dict) -> str:+ """一行的番号键:有 `code` 用它,新登记的行还没有,就从文件名里解析。"""+ return normalise_code_key(row.get("code") or release_code_from_filename(row.get("name")))+++def _stem(name: str | None) -> str:+ return PureWindowsPath(name or "").stem.casefold()+++def _creator(connection, row: dict) -> str:+ """旧行的创作者:先看 `asset.creator`,没有再看挂着的创作者实体。"""+ name = str(row.get("creator") or "").strip()+ if name:+ return name+ found = connection.execute(+ "SELECT e.canonical_name FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "+ "WHERE ae.asset_id=? AND e.kind='creator' ORDER BY e.id LIMIT 1", (row["id"],)).fetchone()+ return str(found[0]) if found else ""+++def _under(path: str, creator: str) -> bool:+ """新文件路径上有一层目录就叫这个创作者名。"""+ folded = creator.casefold()+ return any(part.casefold() == folded for part in PureWindowsPath(path).parent.parts)+++def _closest(old: dict, candidates: list[dict]) -> dict | None:+ """只有一个候选就是它;多个时取时长与旧行最接近的,时长缺或并列返回 None。"""+ if len(candidates) == 1:+ return candidates[0]+ duration = old.get("duration")+ if not candidates or not duration or any(not item.get("duration") for item in candidates):+ return None+ gaps = sorted((abs(float(item["duration"]) - float(duration)), item["id"]) for item in candidates)+ if gaps[0][0] == gaps[1][0]:+ return None+ return next(item for item in candidates if item["id"] == gaps[0][1])+++def _creator_candidates(connection, old: dict, fresh: list[dict]) -> list[dict]:+ creator, duration = _creator(connection, old), old.get("duration")+ if not creator or not duration:+ return []+ return [item for item in fresh+ if not code_key(item) and _stem(item["name"]) == _stem(old["name"])+ and _under(item["path"], creator) and item.get("duration")+ and abs(float(item["duration"]) - float(duration)) <= DURATION_TOLERANCE]+++def plan(connection, new_ids: Iterable[int]) -> list[tuple[dict, dict, str]]:+ """这几行新文件各自该接哪一条已消失行:`(旧行, 新行, 判据)`,一对一。"""+ wanted = sorted({int(item) for item in new_ids})+ if not wanted:+ return []+ vanished = _rows(connection, f"SELECT {_COLUMNS} FROM asset WHERE disposal=? AND medium='video'",+ (VANISHED,))+ if not vanished:+ return []+ fresh = []+ for offset in range(0, len(wanted), 400):+ batch = wanted[offset:offset + 400]+ fresh += _rows(connection, f"SELECT {_COLUMNS} FROM asset WHERE id IN ({','.join('?' * len(batch))}) "+ "AND disposal IS NULL AND medium='video'", batch)+ olds_by_code: dict[str, list[dict]] = defaultdict(list)+ news_by_code: dict[str, list[dict]] = defaultdict(list)+ for row in vanished:+ if key := code_key(row):+ olds_by_code[key].append(row)+ for row in fresh:+ if key := code_key(row):+ news_by_code[key].append(row)+ pairs = []+ for key, olds in olds_by_code.items():+ # 同番号消失了几条(分卷、两个版本都没了)就分不出哪条记录归哪个文件,留给人。+ chosen = _closest(olds[0], news_by_code.get(key, [])) if len(olds) == 1 else None+ if chosen:+ pairs.append((olds[0], chosen, "code"))+ for old in vanished:+ if not code_key(old):+ chosen = _closest(old, _creator_candidates(connection, old, fresh))+ if chosen:+ pairs.append((old, chosen, "creator-stem-duration"))+ # 两条旧行争同一个新文件:分不出,都留给人。+ claimed = Counter(new["id"] for _old, new, _rule in pairs)+ return [pair for pair in pairs if claimed[pair[1]["id"]] == 1]+++def _move_rows(connection, table: str, keys: tuple[str, ...], old_id: int, new_id: int) -> list[dict]:+ """把旧行在这张表里的记录改指新行,新行已有同键记录的那条不搬;返回搬了的键。"""+ moved = []+ match = " AND ".join(f"{key}=?" for key in keys)+ for row in _rows(connection, f"SELECT {','.join(keys)} FROM {table} WHERE asset_id=?", (old_id,)):+ values = [row[key] for key in keys]+ if connection.execute(f"SELECT 1 FROM {table} WHERE asset_id=? AND {match}",+ (new_id, *values)).fetchone():+ continue+ connection.execute(f"UPDATE {table} SET asset_id=? WHERE asset_id=? AND {match}",+ (new_id, old_id, *values))+ moved.append(row)+ return moved+++def _snapshot(connection, old_id: int) -> dict:+ return {+ "asset": _rows(connection, "SELECT * FROM asset WHERE id=?", (old_id,))[0],+ "tables": {table: _rows(connection, f"SELECT * FROM {table} WHERE asset_id=?", (old_id,))+ for table in ASSET_REFERENCE_TABLES},+ "playlists": _rows(connection, "SELECT id,current_asset_id,source_seed_asset_id FROM playlist "+ "WHERE current_asset_id=? OR source_seed_asset_id=?", (old_id, old_id)),+ }+++def move(connection, old_id: int, new_id: int, *, source: str, rule: str,+ now: str | None = None) -> int:+ """把一条已消失行的个人记录搬到新行,删掉旧行;返回这一批的 `record_rehome.id`。"""+ stamp = now or time.strftime("%Y-%m-%d %H:%M:%S")+ old = connection.execute("SELECT disposal FROM asset WHERE id=?", (old_id,)).fetchone()+ target = connection.execute("SELECT disposal FROM asset WHERE id=?", (new_id,)).fetchone()+ if old is None or old[0] != VANISHED:+ raise ValueError("只能接回已消失的行")+ if target is None or target[0] is not None or old_id == new_id:+ raise ValueError("只能接到在库的另一行")+ snapshot = _snapshot(connection, old_id)+ moved = {table: _move_rows(connection, table, keys, old_id, new_id)+ for table, keys in MOVED_TABLES.items()}+ moved[GOAL_TABLE] = _move_rows(connection, GOAL_TABLE, GOAL_KEYS, old_id, new_id)+ connection.executemany(+ f"UPDATE {GOAL_TABLE} SET wanted=0,replaced_at=? WHERE asset_id=? AND profile_id=?",+ [(stamp, new_id, row["profile_id"]) for row in moved[GOAL_TABLE]])+ for column in ("current_asset_id", "source_seed_asset_id"):+ connection.execute(f"UPDATE playlist SET {column}=? WHERE {column}=?", (new_id, old_id))+ for table in ASSET_REFERENCE_TABLES:+ connection.execute(f"DELETE FROM {table} WHERE asset_id=?", (old_id,))+ connection.execute("DELETE FROM asset WHERE id=?", (old_id,))+ cursor = connection.execute(+ "INSERT INTO record_rehome(source,rule,old_asset_id,new_asset_id,snapshot_json,moved_json,"+ "created_at) VALUES(?,?,?,?,?,?,?)",+ (source, rule, old_id, new_id, json.dumps(snapshot, ensure_ascii=False),+ json.dumps(moved, ensure_ascii=False), stamp))+ return int(cursor.lastrowid)+++def reattach(connection, new_ids: Iterable[int], *, now: str | None = None) -> list[int]:+ """登记完一批新文件后接回记录;返回这一轮记下的批次 id。调用方提交。"""+ return [move(connection, old["id"], new["id"], source=AUTO_SOURCE, rule=rule, now=now)+ for old, new, rule in plan(connection, new_ids)]+++def reattach_in(db_path, new_ids: Sequence[int]) -> int:+ """探完时长之后再判一遍:登记那一刻新文件还没有时长,多个候选与无番号的那条判据要等它。"""+ if not new_ids:+ return 0+ with closing(sqlite3.connect(db_path, timeout=30)) as connection:+ batches = reattach(connection, new_ids)+ connection.commit()+ return len(batches)+++def _batch_clause(source: str, batch: str) -> tuple[str, tuple]:+ """批次号是 `<source>@<id>`;前半段要与 `--source` 一致,别的来源的批次号一条都不认。"""+ if batch:+ head, _, tail = batch.rpartition("@")+ return "source=? AND source=? AND id=?", (source, head, int(tail) if tail.isdigit() else -1)+ return "source=?", (source,)+++def planned_revert(connection, source: str, batch: str = "") -> list[dict]:+ """这个来源(或其中一批)还没撤回的搬运,新的在前。"""+ clause, values = _batch_clause(source, batch)+ return [{"id": row["id"], "batch": f"{row['source']}@{row['id']}", "rule": row["rule"],+ "old_asset_id": row["old_asset_id"], "new_asset_id": row["new_asset_id"],+ "name": json.loads(row["snapshot_json"])["asset"].get("name") or ""}+ for row in _rows(connection, "SELECT id,source,rule,old_asset_id,new_asset_id,snapshot_json "+ f"FROM record_rehome WHERE reverted_at IS NULL AND {clause} ORDER BY id DESC",+ values)]+++def _insert(connection, table: str, row: dict) -> None:+ present = {item[1] for item in connection.execute(f"PRAGMA table_info({table})")}+ columns = [column for column in row if column in present]+ connection.execute(+ f"INSERT OR IGNORE INTO {table}({','.join(columns)}) VALUES({','.join('?' * len(columns))})",+ [row[column] for column in columns])+++def revert_one(connection, rehome_id: int, *, now: str | None = None) -> None:+ """按快照重建旧行,把搬到新行的记录改回旧行。旧行的 id 或路径已被占用时拒绝。"""+ row = _rows(connection, "SELECT * FROM record_rehome WHERE id=? AND reverted_at IS NULL", (rehome_id,))+ if not row:+ raise ValueError(f"没有可撤回的批次 {rehome_id}")+ snapshot, moved, new_id = (json.loads(row[0]["snapshot_json"]), json.loads(row[0]["moved_json"]),+ int(row[0]["new_asset_id"]))+ old = snapshot["asset"]+ if connection.execute("SELECT 1 FROM asset WHERE id=? OR (location=? AND path=?)",+ (old["id"], old["location"], old["path"])).fetchone():+ raise ValueError(f"旧行 {old['id']} 的 id 或路径已被占用,不能撤回")+ _insert(connection, "asset", old)+ for table, keys in (*MOVED_TABLES.items(), (GOAL_TABLE, GOAL_KEYS)):+ match = " AND ".join(f"{key}=?" for key in keys)+ connection.executemany(f"DELETE FROM {table} WHERE asset_id=? AND {match}",+ [(new_id, *[item[key] for key in keys]) for item in moved.get(table, [])])+ for table, rows in snapshot["tables"].items():+ for item in rows:+ _insert(connection, table, item)+ for playlist in snapshot["playlists"]:+ for column in ("current_asset_id", "source_seed_asset_id"):+ if playlist[column] == old["id"]:+ connection.execute(f"UPDATE playlist SET {column}=? WHERE id=? AND {column}=?",+ (old["id"], playlist["id"], new_id))+ connection.execute("UPDATE record_rehome SET reverted_at=? WHERE id=?",+ (now or time.strftime("%Y-%m-%d %H:%M:%S"), rehome_id))+++def revert(connection, source: str, batch: str = "") -> int:+ """撤回这个来源(或其中一批)的搬运,新的先撤;返回撤了几批。调用方负责事务与备份。"""+ planned = planned_revert(connection, source, batch)+ for item in planned:+ revert_one(connection, item["id"])+ return len(planned)diff --git a/src/peach/scan.py b/src/peach/scan.pyindex 462206543..658c3b0a5 100644--- a/src/peach/scan.py+++ b/src/peach/scan.py@@ -1,7 +1,11 @@"""扫描一个来源的目录,把文件元数据写进账本。这是摄取入口,不是复核写入:它新增行、刷新 `size`/`mtime`/`last_seen`,不改任何-真相字段,也不删行——本次没扫到的文件只会在 `last_seen` 上落后,由资源同步对账决定去留。+真相字段——本次没扫到的文件只会在 `last_seen` 上落后,由资源同步对账决定去留。++文件消失、带着个人记录的行由资源同步标 `disposal='vanished'`(ADR-0087)。登记时把它们接回:+同一路径的文件回来了,upsert 清掉那一行的 `disposal`;新登记的行由 `record_rehome.reattach`+按番号或「创作者 + 文件名主干 + 时长」找它的旧行,把记录搬过来、删掉旧行,记一个可撤回的批次。两条不变量都在这里守:@@ -33,7 +37,7 @@ from collections.abc import Callable, Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Path, PureWindowsPath-from . import subtitles+from . import record_rehome, subtitlesfrom .platform import is_windows_path, resolve_location, resolve_rootVIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg",@@ -60,10 +64,13 @@ _DERIVED_THUMB = re.compile(+ r")_thumbs?|\.(?:" + "|".join(sorted(ext[1:] for ext in IMAGE)) + r")\.thumb)$",re.IGNORECASE)+# 同一路径上的文件回来了,标「已消失」的那一行就是它:清掉 `disposal`,不另起一行。+# 回收站里的行是用户丢的,文件在不在都不改。_UPSERT = """INSERT INTO asset(location,path,name,medium,size,mtime,first_seen,last_seen)VALUES(?,?,?,?,?,?,?,?)ON CONFLICT(location,path) DO UPDATE SET- size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen"""+ size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen,+ disposal=CASE WHEN asset.disposal='vanished' THEN NULL ELSE asset.disposal END"""class ScanTargetError(ValueError):@@ -188,6 +195,11 @@ class IngestResult:subtitles: int = 0#: 文件在,但认作附属文件(`is_sidecar`),什么也没写。sidecar: bool = False+ #: 登记的那一行;`new` 表示这一次才新建。+ asset_id: int | None = None+ new: bool = False+ #: 新行接回了几条已消失作品的个人记录(`record_rehome`)。+ reattached: int = 0def _directory_stats(directory: Path) -> dict[str, tuple[int, str]]:@@ -270,10 +282,16 @@ def ingest_path(tracks = subtitles.record(connection, location, subtitles.directory_sidecars(ledger_dir, here,[entry for entry in here if medium_of(entry) == "video"]), now)[0]+ asset_id, first_seen = connection.execute(+ "SELECT id,first_seen FROM asset WHERE location=? AND path=?",+ (location, str(ledger_path))).fetchone()+ new = first_seen == now+ reattached = len(record_rehome.reattach(connection, [asset_id] if new else [], now=now))connection.commit()finally:connection.close()- return IngestResult(location, str(ledger_path), True, stat.st_size, tracks)+ return IngestResult(location, str(ledger_path), True, stat.st_size, tracks,+ asset_id=asset_id, new=new, reattached=reattached)@dataclass(frozen=True)@@ -290,6 +308,10 @@ class ScanResult:orphan_subtitles: int = 0#: 认作附属文件、没有登记的条数(`is_sidecar`)。sidecars: int = 0+ #: 本次新建的行;探完时长之后 `record_rehome.reattach_in` 拿它们再判一轮。+ new_ids: tuple[int, ...] = ()+ #: 本次接回了几条已消失作品的个人记录。+ reattached: int = 0def summary(self) -> str:return (f"✓ {self.location}: {self.files:,} 文件 / "@@ -399,12 +421,17 @@ def scan_location(connection.commit()tracks, orphans = subtitles.record(connection, location, sidecars, now)connection.commit()+ # 只有 INSERT 那一支写 `first_seen`,等于本次时刻的就是这一轮新建的行。+ new_ids = tuple(row[0] for row in connection.execute(+ "SELECT id FROM asset WHERE location=? AND first_seen=? ORDER BY id", (location, now)))+ reattached = len(record_rehome.reattach(connection, new_ids, now=now))+ connection.commit()gone = connection.execute("SELECT COUNT(*) FROM asset WHERE location=? AND last_seen<?",(location, now)).fetchone()[0]finally:connection.close()result = ScanResult(location, root, files, total, time.time() - started, gone,- tracks, orphans, skipped)+ tracks, orphans, skipped, new_ids, reattached)report(result.summary())return resultdiff --git a/src/peach/web_batch.py b/src/peach/web_batch.pyindex f141d48c0..1b8914430 100644--- a/src/peach/web_batch.py+++ b/src/peach/web_batch.py@@ -5,7 +5,7 @@判定与执行分家的话,「命中推广词」和「可以删」之间那道界线就没人守了——剥掉推广词后还剩内容的文件不是广告,这条只有把判据和删除放在一起看才成立。-物理删除的边界只写在 `ASSET_REFERENCE_TABLES` 一处;同目录隔离加数据库失败回滚+物理删除要清的引用表只写在 `personal_records.ASSET_REFERENCE_TABLES` 一处;同目录隔离加数据库失败回滚(`_restore_staged_media`)是这个模块最不能出错的部分:删错的文件找不回来。"""from __future__ import annotations@@ -21,7 +21,7 @@ from typing import Sequencefrom .catalog_rules import duration_clusters, is_jav_code, normalise_code_keyfrom .config import LOCATION_ROOT_DECLARATIONSfrom .field_owners import USER_MANUAL, write_owned_fields-from .personal_records import VANISHED+from .personal_records import ASSET_REFERENCE_TABLES, VANISHEDfrom .platform import is_unmapped, root_online, translate_ledger_path, within_rootfrom .regions import normalize_regionfrom .task_runs import TaskRunHandle@@ -39,15 +39,6 @@ BATCH_LABELS = {}-# 清空回收站时要一并清掉的资产引用表,物理删除的边界只写在这一处。-# `asset_search` 不在其中:0004 的 `asset_search_asset_delete` 触发器已经负责 FTS 行,-# 这里再删一遍只会重复,还会诱使测试库伪造一张同名普通表,把 has_fts() 骗成 True。-ASSET_REFERENCE_TABLES = (- "asset_tag", "media_binding", "activity_event", "asset_entity",- "watch_queue", "asset_preference", "asset_tag_preference", "asset_quality_goal",- "playlist_item", "asset_subtitle",-)-# 只认联系方式与站点形态的推广套话。「微信」「成人游戏」这类词单独出现不算:# 实测正片标题里就有(「还要微信跟老公汇报战果」是剧情,不是联系方式)。PROMO_PHRASE = re.compile(diff --git a/tests/test_complexity_ratchet.py b/tests/test_complexity_ratchet.pyindex ec2f6b340..1078410f0 100644--- a/tests/test_complexity_ratchet.py+++ b/tests/test_complexity_ratchet.py@@ -76,6 +76,9 @@ ACCEPTED: dict[str, tuple[int, str]] = {65, "顺序流水线:扫描、探时长、读本地资料、联网采集、写候选、收尾共用一份进度状态""与问题记录;能独立命名的段已经拆出(`_RemoteSession`、`_merge_candidates`、""`_record_issue`),剩下的是编排本身"),+ "scripts/revert_auto_landing.py:main": (+ 30, "撤回入口:每类自动落库各列一遍计划、在同一个事务里各撤一遍、最后汇总报数,"+ "每类一个循环;拆开只是把同一个连接和十来份计划在几个只调一次的函数之间来回传"),"src/peach/jav_cover_fetch.py:run": (50, "批处理的主循环:每个番号依次量本机尺寸、择优、比较、落盘、记日志,统计、日志行""和出错后换新的连接池在整轮里共用,逐段拆开只是把这几样来回传"),diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex bcb280572..567342aa9 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -25,7 +25,7 @@ class MigrationTests(unittest.TestCase):backup = self.root / "before.db"done = upgrade(self.db, MIGRATIONS, backup)self.assertEqual([m.version for m in done],- ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040"])+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040", "0041"])self.assertTrue(backup.exists())con = sqlite3.connect(self.db)tables = {row[0] for row in con.execute(@@ -43,7 +43,7 @@ class MigrationTests(unittest.TestCase):"asset_tag_preference", "asset_search", "follow_playback","genre_decision", "asset_subtitle", "task_run", "performer_profile", "code_sample_image","schema_migration"} <= tables)- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040"])+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039", "0040", "0041"])self.assertEqual(upgrade(self.db, MIGRATIONS), [])self.assertEqual(plan(self.db, MIGRATIONS)[1], [])@@ -324,9 +324,10 @@ class MigrationTests(unittest.TestCase):base_migrations.mkdir()for path in sorted(MIGRATIONS.glob("*.sql")):# 0024 重建 follow_playback,必须与建表的 0022 一起排除;0038 给每张表挂- # 版本号触发器、0039 清 follow_playback 的孤儿行、0040 给墓碑表登记版本号,被排除的迁移建的表这时还- # 不存在,它们也要等到后面一起应用。- if not path.name.startswith(("0020_", "0021_", "0022_", "0024_", "0038_", "0039_", "0040_")):+ # 版本号触发器、0039 清 follow_playback 的孤儿行、0040 给墓碑表登记版本号、0041 给新表挂+ # 版本号触发器,被排除的迁移建的表这时还不存在,它们也要等到后面一起应用。+ if not path.name.startswith(("0020_", "0021_", "0022_", "0024_", "0038_", "0039_", "0040_",+ "0041_")):shutil.copyfile(path, base_migrations / path.name)sqlite3.connect(self.db).close()upgrade(self.db, base_migrations)diff --git a/tests/test_record_rehome.py b/tests/test_record_rehome.pynew file mode 100644index 000000000..3eeacfd1c--- /dev/null+++ b/tests/test_record_rehome.py@@ -0,0 +1,237 @@+"""已消失行的个人记录接到新文件(ADR-0087 决策二)。++登记那一侧走真的 `scan.scan_location` 与 `scan.ingest_path`:全量扫描与推送发现是两条+登记路径,接回要在两条上都发生。声明根写成 `R:\\media`、挂载表指向临时目录,哪台机器上都跑。+"""+from __future__ import annotations++import importlib.util+import io+import json+import sqlite3+import tempfile+import unittest+from contextlib import closing, redirect_stdout+from pathlib import Path++from peach import record_rehome, scan+from peach.migrations import upgrade++ROOT = Path(__file__).resolve().parents[1]+DECLARED = {"local": ("R:\\media",)}+++class RecordRehomeTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name).resolve()+ self.db = self.root / "ledger.db"+ upgrade(self.db, ROOT / "migrations")+ self.media = self.root / "media"+ self.media.mkdir()+ self.mounts = {"local": (str(self.media),)}+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("INSERT INTO playlist(id,profile_id,name,current_asset_id,created_at,updated_at) "+ "VALUES(1,'default','收藏',NULL,'2026-01-01','2026-01-01')")+ connection.commit()++ def add_vanished(self, asset_id, path, *, code=None, creator=None, duration=None, records=True):+ """一条已消失的旧行;`records` 时带上六张表里的记录,各一条。"""+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute(+ "INSERT INTO asset(id,location,path,name,medium,size,code,creator,duration,rating,disposal) "+ "VALUES(?,'local',?,?,'video',10,?,?,?,4,'vanished')",+ (asset_id, path, path.rsplit("\\", 1)[-1], code, creator, duration))+ connection.execute("INSERT INTO asset_tag(asset_id,tag,source) VALUES(?,'旧标签','name')", (asset_id,))+ if records:+ self.add_records(connection, asset_id)+ connection.commit()++ @staticmethod+ def add_records(connection, asset_id, *, liked=1):+ connection.execute("INSERT INTO asset_preference(profile_id,asset_id,liked,reason,updated_at) "+ "VALUES('default',?,?,'旧的','2026-01-01')", (asset_id, liked))+ connection.execute("INSERT INTO watch_queue(profile_id,asset_id,added_at) VALUES('default',?,'2026-01-01')",+ (asset_id,))+ connection.execute("INSERT INTO playlist_item(playlist_id,asset_id,position,added_at) "+ "VALUES(1,?,?,'2026-01-01')", (asset_id, asset_id))+ connection.execute("UPDATE playlist SET current_asset_id=? WHERE id=1", (asset_id,))+ connection.execute("INSERT INTO asset_quality_goal(profile_id,asset_id,wanted,reason,updated_at) "+ "VALUES('default',?,1,'要高清','2026-01-01')", (asset_id,))+ connection.execute("INSERT INTO activity_event(asset_id,profile_id,kind,occurred_at,position_seconds,source) "+ "VALUES(?,'default','climax','2026-01-01',61.5,'web')", (asset_id,))+ connection.execute("INSERT INTO asset_tag_preference(profile_id,asset_id,normalized_tag,hidden,updated_at) "+ "VALUES('default',?,'旧标签',1,'2026-01-01')", (asset_id,))++ def put(self, relative: str) -> str:+ path = self.media.joinpath(*relative.split("/"))+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"0" * 10)+ return "R:\\media\\" + relative.replace("/", "\\")++ def scan_all(self):+ with redirect_stdout(io.StringIO()):+ return scan.scan_location(self.db, "local", "R:\\media", declared_roots=DECLARED,+ mounts=self.mounts, windows=False)++ def ingest(self, path):+ return scan.ingest_path(self.db, "local", path, declared_roots=DECLARED, mounts=self.mounts,+ windows=False)++ def query(self, sql, params=()):+ with closing(sqlite3.connect(self.db)) as connection:+ return connection.execute(sql, params).fetchall()++ def owner(self, table):+ return sorted({row[0] for row in self.query(f"SELECT asset_id FROM {table}")})++ def id_of(self, path):+ return self.query("SELECT id FROM asset WHERE path=?", (path,))[0][0]++ def test_a_file_back_at_its_path_clears_vanished_on_the_same_row(self):+ path = self.put("ABC-123.mp4")+ self.add_vanished(7, path, code="ABC-123")+ result = self.scan_all()+ self.assertEqual(self.query("SELECT id,disposal FROM asset"), [(7, None)])+ self.assertEqual(result.new_ids, ())+ self.assertEqual(self.query("SELECT count(*) FROM record_rehome"), [(0,)])++ def test_a_full_scan_moves_all_records_to_the_one_new_file_with_the_same_code(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123.mp4", code="ABC-123", duration=3600)+ new_path = self.put("hd/ABC-123.mkv")+ result = self.scan_all()+ new_id = self.id_of(new_path)+ self.assertEqual(result.reattached, 1)+ self.assertEqual(self.query("SELECT id FROM asset"), [(new_id,)], "旧行搬完就删")+ for table in ("asset_preference", "watch_queue", "playlist_item", "asset_quality_goal",+ "activity_event", "asset_tag_preference"):+ self.assertEqual(self.owner(table), [new_id], table)+ self.assertEqual(self.query("SELECT current_asset_id FROM playlist"), [(new_id,)])+ self.assertEqual(self.query("SELECT position_seconds FROM activity_event"), [(61.5,)])+ goal = self.query("SELECT wanted,replaced_at IS NOT NULL FROM asset_quality_goal")+ self.assertEqual(goal, [(0, 1)], "寻找更好版本随记录搬过去后关闭,标已替换")+ self.assertEqual(self.owner("asset_tag"), [], "资料不在搬运范围内,留在快照里")+ batch = self.query("SELECT source,rule,old_asset_id,new_asset_id FROM record_rehome")+ self.assertEqual(batch, [(record_rehome.AUTO_SOURCE, "code", 7, new_id)])++ def test_push_discovery_ingest_moves_records_too(self):+ self.add_vanished(7, "R:\\media\\old\\SSIS-950.mp4", code="SSIS-950")+ new_path = self.put("SSIS-950.mkv")+ result = self.ingest(new_path)+ self.assertTrue(result.new)+ self.assertEqual(result.reattached, 1)+ self.assertEqual(self.owner("asset_preference"), [result.asset_id])+ self.assertEqual(self.query("SELECT count(*) FROM asset WHERE id=7"), [(0,)])++ def test_new_row_records_win_over_the_moved_ones(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123.mp4", code="ABC-123")+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("INSERT INTO asset(id,location,path,name,medium,size) "+ "VALUES(9,'local','R:\\media\\ABC-123.mkv','ABC-123.mkv','video',10)")+ connection.execute("INSERT INTO asset_preference(profile_id,asset_id,liked,reason,updated_at) "+ "VALUES('default',9,0,'新的','2026-02-01')")+ record_rehome.move(connection, 7, 9, source=record_rehome.MANUAL_SOURCE, rule="manual")+ connection.commit()+ self.assertEqual(self.query("SELECT asset_id,reason FROM asset_preference"), [(9, "新的")])+ self.assertEqual(self.owner("watch_queue"), [9])++ def test_several_new_files_pick_the_closest_duration_or_wait_for_a_person(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123.mp4", code="ABC-123", duration=3600)+ near, far = self.put("a/ABC-123.mp4"), self.put("b/ABC-123.mp4")+ result = self.scan_all()+ self.assertEqual(result.reattached, 0, "登记那一刻新文件还没有时长,分不出")+ self.assertEqual(self.owner("asset_preference"), [7])+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("UPDATE asset SET duration=3598 WHERE path=?", (near,))+ connection.execute("UPDATE asset SET duration=1800 WHERE path=?", (far,))+ connection.commit()+ self.assertEqual(record_rehome.reattach_in(self.db, list(result.new_ids)), 1)+ self.assertEqual(self.owner("asset_preference"), [self.id_of(near)])++ def test_two_vanished_rows_with_one_code_are_left_for_a_person(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123-1.mp4", code="ABC-123")+ self.add_vanished(8, "R:\\media\\old\\ABC-123-2.mp4", code="ABC-123")+ self.put("ABC-123.mp4")+ self.assertEqual(self.scan_all().reattached, 0)+ self.assertEqual(self.owner("asset_preference"), [7, 8])++ def test_a_creator_video_without_code_matches_creator_stem_and_duration(self):+ self.add_vanished(7, "R:\\media\\桃子\\old\\海边.mp4", creator="桃子", duration=600)+ path = self.put("桃子/2026/海边.mp4")+ result = self.scan_all()+ self.assertEqual(result.reattached, 0, "登记时还没有时长")+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("UPDATE asset SET duration=601 WHERE path=?", (path,))+ connection.commit()+ self.assertEqual(record_rehome.reattach_in(self.db, list(result.new_ids)), 1)+ self.assertEqual(self.owner("watch_queue"), [self.id_of(path)])++ def test_a_creator_video_under_another_creator_is_not_matched(self):+ self.add_vanished(7, "R:\\media\\桃子\\海边.mp4", creator="桃子", duration=600)+ path = self.put("别人/海边.mp4")+ result = self.scan_all()+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("UPDATE asset SET duration=600 WHERE path=?", (path,))+ connection.commit()+ self.assertEqual(record_rehome.reattach_in(self.db, list(result.new_ids)), 0)++ def test_revert_rebuilds_the_old_row_and_points_records_back(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123.mp4", code="ABC-123", duration=3600)+ new_path = self.put("ABC-123.mp4")+ self.scan_all()+ new_id = self.id_of(new_path)+ with closing(sqlite3.connect(self.db)) as connection:+ planned = record_rehome.planned_revert(connection, record_rehome.AUTO_SOURCE)+ self.assertEqual([item["old_asset_id"] for item in planned], [7])+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(record_rehome.planned_revert(+ connection, record_rehome.MANUAL_SOURCE, planned[0]["batch"]), [],+ "别的来源的批次号一条都不认")+ spec = importlib.util.spec_from_file_location(+ "revert_auto_landing_under_test", ROOT / "scripts" / "revert_auto_landing.py")+ script = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(script)+ with redirect_stdout(io.StringIO()) as printed:+ self.assertEqual(script.main([+ "--db", str(self.db), "--logo-root", str(self.root / "logos"),+ "--source", record_rehome.AUTO_SOURCE, "--batch", planned[0]["batch"],+ "--apply", "--backup", str(self.root / "backup.db")]), 0)+ self.assertIn("'撤回接回': 1", printed.getvalue())+ self.assertEqual(self.query("SELECT id,disposal,rating FROM asset ORDER BY id"),+ [(7, "vanished", 4), (new_id, None, None)])+ for table in ("asset_preference", "watch_queue", "playlist_item", "asset_quality_goal",+ "activity_event", "asset_tag_preference", "asset_tag"):+ self.assertEqual(self.owner(table), [7], table)+ self.assertEqual(self.query("SELECT wanted,replaced_at FROM asset_quality_goal"), [(1, None)])+ self.assertEqual(self.query("SELECT current_asset_id FROM playlist"), [(7,)])+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(record_rehome.planned_revert(connection, record_rehome.AUTO_SOURCE), [])++ def test_revert_refuses_when_the_old_id_is_taken(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123.mp4", code="ABC-123")+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("INSERT INTO asset(id,location,path,name,medium,size) "+ "VALUES(9,'local','R:\\media\\ABC-123.mkv','ABC-123.mkv','video',10)")+ batch = record_rehome.move(connection, 7, 9, source=record_rehome.MANUAL_SOURCE, rule="manual")+ connection.execute("INSERT INTO asset(id,location,path,name,medium,size) "+ "VALUES(7,'local','R:\\media\\other.mp4','other.mp4','video',10)")+ with self.assertRaisesRegex(ValueError, "已被占用"):+ record_rehome.revert_one(connection, batch)+ snapshot = json.loads(connection.execute(+ "SELECT snapshot_json FROM record_rehome WHERE id=?", (batch,)).fetchone()[0])+ self.assertEqual(snapshot["asset"]["rating"], 4, "行上的打分留在快照里")++ def test_move_only_takes_a_vanished_row_onto_an_in_library_row(self):+ self.add_vanished(7, "R:\\media\\old\\ABC-123.mp4", code="ABC-123")+ with closing(sqlite3.connect(self.db)) as connection:+ connection.execute("INSERT INTO asset(id,location,path,name,medium,size,disposal) "+ "VALUES(9,'local','R:\\media\\x.mp4','x.mp4','video',10,'trash')")+ with self.assertRaisesRegex(ValueError, "在库"):+ record_rehome.move(connection, 7, 9, source=record_rehome.MANUAL_SOURCE, rule="manual")+ with self.assertRaisesRegex(ValueError, "已消失"):+ record_rehome.move(connection, 9, 7, source=record_rehome.MANUAL_SOURCE, rule="manual")+++if __name__ == "__main__":+ unittest.main()