Peach: Local-first video metadata scraper and media manager.
fix(scan): 隔离规范路径冲突并恢复其余文件入库
longmeidao512d27d57b25
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 52061dc43..c11271d6a 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -291,6 +291,8 @@ Peach 配置页地址是 `/configuration`。从管理菜单或设置弹窗的「扫描与采集逐项保留结果。文件抽帧失败、资料请求超时等单项问题记入清单,继续处理其余文件与后续阶段;所有阶段结束后,有问题的任务显示「处理已结束,部分项目需处理」,可查看全部内容或仅重试未完成项。状态保存、数据库等公共环节异常导致的中断单独显示。未取得发行资料的视频仍可在「全部内容」浏览;JAV 分类按番号和发行资料筛选。需要选择处理范围时,使用「更多同步方式」中的仅扫描、仅补资料或仅补预览图。+同一 Windows 规范路径存在多条历史记录时,扫描在问题清单中列出路径和记录编号,其他文件继续入库。冲突记录的身份、资料、个人记录和处置状态分别保留;枚举确认文件仍在时只刷新这些记录的观测时间。自动发现可登记同目录的其他文件,直接登记冲突文件则报告具体冲突。重复记录需复核,重新扫描不会自动合并或删除它们。+媒体目录、NFO 与配套图片的单次读取限时 20 秒,超时会结束读取子进程并记录问题;本趟任务不反复读取已失败的目录。单个视频的九宫格共用 120 秒处理时限,失败后继续下一部影片与外部资料采集。用户暂停、磁盘空间不足、账本或结果保存失败会中断任务并保留检查点。未登记成功的目录需要重新扫描;已登记影片的问题可按清单重试。文件在磁盘上被移除后,可到数据管理页下方的「资源同步」检查账本记录。该分区要求至少一个可扫描来源配置了根目录;清理前核对检查结果并确认。带个人记录的失联作品保留为已消失,其余清理规则见资源同步的确认说明。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex d764f525d..996f49ba4 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -1,5 +1,11 @@# 复用清单+## 扫描路径冲突隔离++路径归组复用 Python 3.14 标准库的 [`PureWindowsPath`](https://docs.python.org/3.14/library/pathlib.html#general-properties) 与现有大小写口径,入库复用 SQLite 的 [UPSERT](https://www.sqlite.org/lang_upsert.html)、扫描检查点和单路径摄取入口,未新增依赖。两者均由现有运行时携带,许可与版本沿用运行时声明。路径相等不决定个人记录归属,Peach 负责将歧义组交给现有任务问题清单,保留每条身份及处置,只更新实际观察到的文件时间;不另建路径解析器或自动合并器。++隔离回归使用临时账本与目录,覆盖大小写和斜杠变体、个人记录保留、缺失文件、多根目录、断点配对和自动发现。真实 ledger 未用于修复演练,部署与报告者验收分别记录。+## 升级自动处理与更新提示本地补修复用 `catalog_rules` 的用户识别规则、`field_owners.write_owned_fields`、r18 文字修复与复合别名拆分判据。两个维护脚本调用同一领域模块。结构迁移、SQLite 备份、文件锁和原子回执继续使用项目现有入口;后台复用 `TaskRunStore`、`FollowupRunner`、`Attempts`、来源冷却和影片处理检查点,未新增运行依赖。diff --git a/src/peach/scan.py b/src/peach/scan.pyindex 3af982619..bd77eb550 100644--- a/src/peach/scan.py+++ b/src/peach/scan.py@@ -85,25 +85,41 @@ class ScanTargetError(ValueError):"""来源与扫描根对不上,或者来源在本机没有落点。消息可以直接给人看。"""+class ScanPathConflict(ScanTargetError):+ """同一规范路径的既有记录须由用户复核,摄取不选择或合并身份。"""++ def __init__(self, entries):+ self.asset_ids = tuple(entry[0] for entry in entries)+ self.paths = tuple(entry[1] for entry in entries)+ ids = '、'.join(str(value) for value in self.asset_ids)+ super().__init__(f'同一规范路径有多条文件记录(记录 {ids}):{self.paths[0]};'+ '已保留全部记录,请复核;其他文件继续处理')++def _registered_paths(connection, location, root):- """保留既有文件路径写法;有歧义时拒绝自动合并个人记录。"""+ """既有路径按 Windows 语义分组,歧义记录单列供复核。"""declared = PureWindowsPath(root)- result = {}- for (path,) in connection.execute("SELECT path FROM asset WHERE location=? AND path IS NOT NULL", (location,)):+ groups = {}+ for asset_id, path in connection.execute(+ "SELECT id,path FROM asset WHERE location=? AND path IS NOT NULL ORDER BY id", (location,)):target = PureWindowsPath(path)if not target.is_relative_to(declared):continuekey = str(target).casefold()- if key in result and result[key] != path:- raise ScanTargetError("同一规范路径有多条文件记录,请先复核重复记录")- result[key] = path- return result+ groups.setdefault(key, []).append((asset_id, path))+ return ({key: entries[0][1] for key, entries in groups.items() if len(entries) == 1},+ {key: ScanPathConflict(entries) for key, entries in groups.items() if len(entries) > 1})-def _upsert_records(connection, batch, registered):+def _upsert_records(connection, batch, registered, conflicts):rows = []for location, path, *values in batch:key = str(PureWindowsPath(path)).casefold()+ if key in conflicts:+ # 枚举确认文件仍在,只刷新观测时间;身份、处置与个人资料保持各自原值。+ connection.executemany('UPDATE asset SET last_seen=? WHERE id=?',+ [(values[-1], asset_id) for asset_id in conflicts[key].asset_ids])+ continuestored = registered.setdefault(key, path)rows.append((location, stored, *values))connection.executemany(_UPSERT, rows)@@ -335,21 +351,21 @@ def ingest_path(tracks = 0# 列目录在开连接之前做完:写事务从 upsert 开始一直持有写锁,网盘挂载卡住的那几十秒# 不能落在锁里,否则同一账本的其他写入者全部跟着超时。- pairing = None+ here = Noneif medium == "video" or subtitles.subtitle_format(name):here = _directory_stats(directory)- pairing = subtitles.directory_sidecars(- ledger_dir, here, [entry for entry in here if medium_of(entry) == "video"])# 忙等时长与 `LedgerDatabase.connect` 一致。connection = sqlite3.connect(db_path, timeout=30)try:connection.execute("PRAGMA journal_mode=WAL")- registered = _registered_paths(connection, location, str(ledger_dir))+ registered, conflicts = _registered_paths(connection, location, str(ledger_dir))+ if str(ledger_path).casefold() in conflicts:+ raise conflicts[str(ledger_path).casefold()]_upsert_records(connection, [(location, str(ledger_path), name, medium,- stat.st_size, mtime, now, now)], registered)+ stat.st_size, mtime, now, now)], registered, conflicts)stored_path = registered[str(ledger_path).casefold()]- if pairing is not None:- tracks = subtitles.record(connection, location, pairing, now)[0]+ if here is not None:+ tracks = _record_directory_subtitles(connection, location, ledger_dir, here, conflicts, now)[0]asset_id, first_seen = connection.execute("SELECT id,first_seen FROM asset WHERE location=? AND path=?",(location, stored_path)).fetchone()@@ -387,13 +403,15 @@ class ScanResult:acquired: int = 0junk_isolated: int = 0junk_review: int = 0+ path_conflicts: int = 0def summary(self) -> str:return (f"✓ {self.location}: {self.files:,} 文件 / "f"{self.total_bytes / 1024 ** 4:.2f} TB / 耗时 {self.seconds:.0f}s;"f"附属文件未登记 {self.sidecars:,} 个;清单中已消失 {self.gone:,} 个;"f"字幕 {self.subtitles:,} 条(孤立 {self.orphan_subtitles:,} 条);"- f"垃圾移入回收站 {self.junk_isolated:,} 个,待复核 {self.junk_review:,} 个")+ f"垃圾移入回收站 {self.junk_isolated:,} 个,待复核 {self.junk_review:,} 个;"+ f"路径重复待复核 {self.path_conflicts:,} 组")def _walk(top: Path, pending: list[str] | None = None, *, onerror=lambda error: None, read_directory=None):@@ -532,6 +550,15 @@ def _scan_resume_state(walk_root, resume_state):return mapping, previous, completed+def _record_directory_subtitles(connection, location, directory, here, conflicts, now):+ """只给身份唯一的文件配对字幕,断点中的目录资料遵守相同判据。"""+ sidecars = subtitles.directory_sidecars(+ directory, here, [name for name in here if medium_of(name) == 'video'])+ unambiguous = [sidecar for sidecar in sidecars if sidecar.path.casefold() not in conflicts+ and (not sidecar.video or sidecar.video.casefold() not in conflicts)]+ return subtitles.record(connection, location, unambiguous, now)++def _scan_location(db_path: str | os.PathLike[str], location: str, root: str, *,declared_roots: Mapping[str, str], mounts: Mapping[str, str | Path] | None = None,@@ -582,7 +609,10 @@ def _scan_location(connection = sqlite3.connect(db_path, timeout=30)try:connection.execute("PRAGMA journal_mode=WAL")- registered = _registered_paths(connection, location, root)+ registered, conflicts = _registered_paths(connection, location, root)+ for conflict in conflicts.values():+ onerror(conflict)+ report(str(conflict))for directory, entries in _walk(walk_root, pending, read_directory=read_directory, onerror=onerror):checkpoint('scan')relative = _relative_directory(directory, walk_root)@@ -618,25 +648,23 @@ def _scan_location(total += stat.st_sizeprogress(files, total)if len(batch) >= BATCH_SIZE:- _upsert_records(connection, batch, registered)+ _upsert_records(connection, batch, registered, conflicts)connection.commit()batch.clear()save_directory(directory, name, here)report(f" {time.time() - started:5.0f}s {files:,} 文件 "f"{total / 1024 ** 4:.2f} TB")- sidecars = subtitles.directory_sidecars(- ledger_root.joinpath(*relative), here,- [name for name in here if medium_of(name) == "video"])if batch:- _upsert_records(connection, batch, registered)+ _upsert_records(connection, batch, registered, conflicts)batch.clear()- directory_tracks, directory_orphans = subtitles.record(connection, location, sidecars, now)+ directory_tracks, directory_orphans = _record_directory_subtitles(+ connection, location, ledger_root.joinpath(*relative), here, conflicts, now)connection.commit()tracks += directory_tracksorphans += directory_orphanssave_directory()if batch:- _upsert_records(connection, batch, registered)+ _upsert_records(connection, batch, registered, conflicts)connection.commit()# 只有 INSERT 那一支写 `first_seen`,等于本次时刻的就是这一轮新建的行。from .media_folders import path_predicate@@ -655,7 +683,7 @@ def _scan_location(checked = junk.isolate(db_path, roots=[(location, root)])result = ScanResult(location, root, files, total, time.time() - started, gone,tracks, orphans, skipped, new_ids, reattached, acquired,- checked['isolated'], checked['review'])+ checked['isolated'], checked['review'], len(conflicts))save_checkpoint({'mapping': mapping, 'result': asdict(result)})progress(files, total, force=True)report(result.summary())diff --git a/tests/test_processing_control.py b/tests/test_processing_control.pyindex 7c348ae6f..74cc17821 100644--- a/tests/test_processing_control.py+++ b/tests/test_processing_control.py@@ -565,3 +565,34 @@ class ProcessingControlTests(unittest.TestCase):self.assertTrue(all(row['total'] == 0 for row in discovering))self.assertEqual((result.scanned, result.scanned_bytes), (4, 60))self.assertEqual(result.junk_isolated, 2)++ def test_library_scan_reports_conflicting_records_and_processes_both_roots(self):+ import sqlite3+ from peach.library_processing import _scan_sources+ first, second = self.root / 'first', self.root / 'second'+ first.mkdir()+ second.mkdir()+ (first / 'copy.mp4').write_bytes(b'copy')+ (first / 'new.mp4').write_bytes(b'new')+ (second / 'other.mp4').write_bytes(b'other')+ config = PeachConfig(self.root, self.root / 'config.toml', present=True,+ locations={'local': ('R:\\Media', 'S:\\Other')},+ mounts={'local': (str(first), str(second))})+ with closing(sqlite3.connect(self.db)) as connection, connection:+ for path in ('R:\\Media\\copy.mp4', 'r:\\MEDIA\\COPY.MP4'):+ connection.execute("INSERT INTO asset(location,path,name,medium) "+ "VALUES('local',?,'copy.mp4','video')", (path,))+ issues = []+ with patch('peach.library_processing._online_source_root', return_value=first), \+ patch('peach.library_processing._ffprobe_path', return_value=None), \+ patch('peach.library_processing.probe_unmeasured', return_value=0):+ result = _scan_sources(config, self.db, locations=config.locations, asset_ids=None,+ stage='scan', guard=Mock(), update=lambda **values: None,+ issue=lambda row, message, **values: issues.append((message, values)))+ self.assertEqual((result.scanned, result.scanned_bytes), (3, 12))+ self.assertEqual(len(issues), 1)+ self.assertIn('记录 1、2', issues[0][0])+ self.assertEqual(issues[0][1]['action'], 'scanning_files')+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(connection.execute('SELECT count(*) FROM asset').fetchone()[0], 4)+ self.assertIsNotNone(connection.execute("SELECT id FROM asset WHERE path='S:\\Other\\other.mp4'").fetchone())diff --git a/tests/test_push_discovery.py b/tests/test_push_discovery.pyindex f11958900..a999c362c 100644--- a/tests/test_push_discovery.py+++ b/tests/test_push_discovery.py@@ -16,6 +16,7 @@ import threadingimport timeimport tomllibimport unittest+from contextlib import closingfrom dataclasses import replacefrom pathlib import Path, PureWindowsPathfrom types import SimpleNamespace@@ -368,6 +369,28 @@ class IngestPathTests(_ServiceCase):scan.ingest_path(self.db, "local", path, **kwargs)self.assertEqual(self.rows(), {path: ("video", 9)})+ def test_a_conflict_in_the_directory_does_not_block_a_different_new_file(self):+ (self.media / 'copy.mp4').write_bytes(b'copy')+ (self.media / 'copy.srt').write_text('subtitle', encoding='utf-8')+ (self.media / 'new.mp4').write_bytes(b'new')+ path = self.ledger('local', 'copy.mp4')+ with closing(sqlite3.connect(self.db)) as connection, connection:+ for value in (path, path.upper()):+ connection.execute("INSERT INTO asset(location,path,name,medium,rating,play_count) "+ "VALUES('local',?,'copy.mp4','video',4,7)", (value,))+ result = scan.ingest_path(self.db, 'local', self.ledger('local', 'new.mp4'),+ declared_roots=self.declared, mounts=self.mounts)+ self.assertTrue(result.new)+ self.assertEqual(len(self.rows()), 3)+ with self.assertRaises(scan.ScanPathConflict) as caught:+ scan.ingest_path(self.db, 'local', path,+ declared_roots=self.declared, mounts=self.mounts)+ self.assertEqual(caught.exception.asset_ids, (1, 2))+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(list(connection.execute(+ 'SELECT rating,play_count FROM asset WHERE id<=2 ORDER BY id')), [(4, 7), (4, 7)])+ self.assertEqual(connection.execute('SELECT count(*) FROM asset_subtitle').fetchone()[0], 0)+def test_a_subtitle_next_to_its_video_is_paired_in_the_same_pass(self):(self.media / "a.mp4").write_bytes(b"0" * 4)(self.media / "a.zh.srt").write_bytes(b"1" * 4)diff --git a/tests/test_scan.py b/tests/test_scan.pyindex 4dd73f223..58ee24a4a 100644--- a/tests/test_scan.py+++ b/tests/test_scan.py@@ -138,6 +138,70 @@ class PosixShapeTests(_ScanCase):with closing(sqlite3.connect(self.db)) as connection, connection:self.assertEqual(list(connection.execute("SELECT id,path,rating,play_count FROM asset ORDER BY id")), before)+ def test_conflicting_paths_preserve_each_record_and_allow_other_files_to_register(self):+ paths = ('R:\\media\\copy.mp4', 'r:/MEDIA/COPY.MP4')+ (self.media / 'copy.mp4').write_bytes(b'present')+ with closing(sqlite3.connect(self.db)) as connection, connection:+ for path, rating, plays, disposal in zip(paths, (2, 5), (3, 9), ('vanished', 'trash')):+ connection.execute(+ 'INSERT INTO asset(location,path,name,medium,size,first_seen,last_seen,rating,play_count,disposal) '+ "VALUES('local',?,'copy.mp4','video',99,'2000-01-01','2000-01-01',?,?,?)",+ (path, rating, plays, disposal))+ before = list(connection.execute('SELECT id,path,size,rating,play_count,disposal FROM asset ORDER BY id'))+ issues = []+ with patch.object(scan, 'BATCH_SIZE', 1):+ result, output = self._scan('R:\\media', declared_roots={'local': ('R:\\media',)},+ mounts={'local': (self.media,)}, windows=False, onerror=issues.append)+ self.assertEqual((result.files, result.path_conflicts, result.gone), (3, 1, 0))+ self.assertEqual(len(result.new_ids), 2)+ self.assertEqual(len(issues), 1)+ self.assertIsInstance(issues[0], scan.ScanPathConflict)+ self.assertEqual(issues[0].paths, paths)+ self.assertEqual(issues[0].asset_ids, (1, 2))+ self.assertIn('路径重复待复核 1 组', output)+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(list(connection.execute(+ 'SELECT id,path,size,rating,play_count,disposal FROM asset WHERE id<=2 ORDER BY id')), before)+ self.assertEqual(connection.execute('SELECT count(*) FROM asset').fetchone()[0], 4)+ self.assertTrue(all(row[0] > '2000-01-01' for row in connection.execute(+ 'SELECT last_seen FROM asset WHERE id<=2')))++ def test_missing_conflict_records_remain_unobserved_and_do_not_block_another_root(self):+ (self.root / 'other').mkdir()+ (self.root / 'other' / 'new.mp4').write_bytes(b'new')+ with closing(sqlite3.connect(self.db)) as connection, connection:+ for path in ('R:\\media\\missing.mp4', 'r:\\MEDIA\\MISSING.mp4'):+ connection.execute("INSERT INTO asset(location,path,name,medium,last_seen) "+ "VALUES('local',?,'missing.mp4','video','2000-01-01')", (path,))+ options = dict(declared_roots={'local': ('R:\\media', 'S:\\other')},+ mounts={'local': (self.media, self.root / 'other')}, windows=False)+ first, _ = self._scan('R:\\media', **options)+ second, _ = self._scan('S:\\other', **options)+ self.assertEqual((first.path_conflicts, first.gone), (1, 2))+ self.assertEqual((second.path_conflicts, second.files, second.gone), (0, 1, 0))+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(list(connection.execute('SELECT last_seen FROM asset WHERE id<=2')),+ [('2000-01-01',), ('2000-01-01',)])++ def test_subtitles_do_not_choose_between_conflicting_video_records(self):+ (self.media / 'copy.mp4').write_bytes(b'present')+ (self.media / 'copy.srt').write_text('subtitle', encoding='utf-8')+ options = dict(declared_roots={'local': ('R:\\media',)}, mounts={'local': (self.media,)}, windows=False)+ self._scan('R:\\media', **options)+ with closing(sqlite3.connect(self.db)) as connection, connection:+ before = list(connection.execute('SELECT id,asset_id,path,pairing FROM asset_subtitle'))+ self.assertEqual(len(before), 1)+ connection.execute("INSERT INTO asset(location,path,name,medium) "+ "VALUES('local','r:\\MEDIA\\COPY.mp4','copy.mp4','video')")+ (self.media / 'copy.en.srt').write_text('another subtitle', encoding='utf-8')+ result, _ = self._scan('R:\\media', **options)+ self.assertEqual(result.path_conflicts, 1)+ self._scan('R:\\media', **options, resume_state={'mapping': str(self.media), 'pending': [],+ 'current_directory': str(self.media), 'cursor': 'copy.srt',+ 'here': {'copy.mp4': (7, '2000-01-01'), 'copy.srt': (8, '2000-01-01')}})+ with closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(list(connection.execute('SELECT id,asset_id,path,pairing FROM asset_subtitle')), before)+def test_relocated_mount_restarts_traversal_and_preserves_file_id(self):saved = []options = dict(declared_roots={'local': ('R:\\media',)}, mounts={'local': (self.media,)}, windows=False)