Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(catalog): 扫描留下待处理项也派补图后继,存量缺图的每轮补一截

longmeidaobb9260c6dc97
diff --git a/docs/adr/0053-followups-dispatch-when-a-run-settles.md b/docs/adr/0053-followups-dispatch-when-a-run-settles.md
new file mode 100644
index 000000000..9e2c25393
--- /dev/null
+++ b/docs/adr/0053-followups-dispatch-when-a-run-settles.md
@@ -0,0 +1,42 @@
+# ADR-0053:结算到底就派后继,存量缺图的每轮补派一截
+
+- 状态:Accepted
+- 日期:2026-09-24
+- 修订:ADR-0040 第四条、第七条
+
+## 背景
+
+补头像后继(ADR-0040)与补厂牌后继(ADR-0052)上线之后,`task_run` 里 `entity-avatar`
+一行都没有。上线后的六轮处理任务,三轮 `failed`、三轮 `interrupted`,成功零轮;那三轮
+`failed` 的原因只是「256 项需要处理,其中 27 项是来源限流」这类留给人的待处理项。
+`process_library` 结算时写 `status='failed' if issue_count else 'complete'`,而 ADR-0040
+第四条规定父任务失败一条后继都不派,于是两条后继从来没有跑过。
+
+第二个缺口在派单范围:后继只派给「这一轮新登记的实体」和「这一轮换了封面的作品上的
+女优」。全库没头像的 211 位女优里,175 位是在后继上线之前登记的,就算以后每一轮都成功,
+也永远轮不到她们。其中 76 位的单人作品封面上就截得出脸。
+
+## 决策
+
+**一、声明了后继就派,与父任务的状态无关。** 处理任务只在结算到底的那一刻声明后继;
+途中抛异常的轮次走不到那一步,`BackgroundJob` 在异常路径上还会把途中的声明清空。所以
+「有没有声明」本身就是「这一轮有没有跑完」的判据。留下待处理项的那一轮照旧记成
+`failed`,活动页上那一行的结论不变,后继照派。ADR-0040 第四条的另一半不变:后继失败
+不改判父任务。
+
+**二、名额先给新实体,余下的给存量。** 每轮至多 `MAX_FOLLOWUPS`(64)条:新登记的先排,
+再按作品数从多到少补上库里至今缺图的女优(没有头像,或装着的是封面截图与整张封面),
+最后是盘上没有标识的厂牌。存量每轮往前推一截,不需要另跑一次性的批处理。
+
+**三、试过又没变的不再派。** 存量里找不到图的实体每轮都还缺图,只看「缺不缺」会让同一批
+每轮都把名额占满。后继跑完记下实体当时的指纹:女优是作品数,厂牌是作品数与官网、目录
+链接数。指纹没变就不再派,多一部作品或多一条链接就再试一次。记号落在
+`generated/provider-cache/followup-attempts/`,一件事一个文件;任务记录每类只留 20 行,
+存不住这份记号。
+
+## 后果
+
+- 下一轮处理任务结算时,新实体加存量共 64 条后继开始跑:先是作品多的缺图女优,再是厂牌。
+- 封面截脸、图库唯一命中这两档判据一个字没变;图库同名多张、别名没统一的那些仍装不上,
+ 需要各自的判据(别名导入、人脸比对),不在本 ADR 内。
+- 删掉 `followup-attempts/` 下的文件,就等于让那些实体在下一轮重新排队。
diff --git a/src/peach/avatar_followup.py b/src/peach/avatar_followup.py
index b5213a3ea..5ce8b1273 100644
--- a/src/peach/avatar_followup.py
+++ b/src/peach/avatar_followup.py
@@ -22,7 +22,7 @@ import sqlite3
from . import avatar_cover_face, avatar_picker
from .avatar_provider import MIN_LONG_SIDE, MIN_SHORT_SIDE, acceptable_avatar
-from .followups import Followup, FollowupType, register
+from .followups import Attempts, Followup, FollowupType, attempts_root, register
#: 这类后继在任务中心的身份,也是活动页上那一行的名字来源。
TASK_KEY = "entity-avatar"
@@ -83,8 +83,7 @@ def plan(connection: sqlite3.Connection, avatar_root, *,
found = []
for row in rows:
entity_id, kind = int(row["id"]), str(row["kind"])
- if (avatar_picker.installed_digest(avatar_root, kind, entity_id)
- and avatar_cover_face.installed_face_px(avatar_root, kind, entity_id) is None):
+ if not _needs_avatar(avatar_root, kind, entity_id):
continue
found.append((int(row["assets"] or 0), entity_id, kind,
str(row["canonical_name"] or "")))
@@ -94,7 +93,58 @@ def plan(connection: sqlite3.Connection, avatar_root, *,
for _assets, entity_id, kind, name in found]
+def _needs_avatar(avatar_root, kind: str, entity_id: int) -> bool:
+ """没有头像,或者装着的是封面截的那一档(还可能换到更清楚的)。"""
+ return (not avatar_picker.installed_digest(avatar_root, kind, entity_id)
+ or avatar_cover_face.installed_face_px(avatar_root, kind, entity_id) is not None)
+
+
+def fingerprint(connection: sqlite3.Connection, entity_id: int) -> str:
+ """会让这条后继结论变的量:她名下的作品数。多一部就多一批封面可截。"""
+ return str(connection.execute(
+ "SELECT count(DISTINCT asset_id) FROM asset_entity WHERE entity_id=?",
+ (int(entity_id),)).fetchone()[0])
+
+
+def stock(connection: sqlite3.Connection, avatar_root, attempts, *, limit: int,
+ skip=()) -> list[Followup]:
+ """库里早就登记、至今缺头像的女优,作品多的在前,最多 `limit` 条(ADR-0053)。
+
+ 跑过一次、作品数也没变的不再派(`attempts`):图库和封面都没变,结论也不会变。
+ """
+ if limit <= 0:
+ return []
+ skip = set(skip)
+ found = []
+ for row in connection.execute(
+ "SELECT e.id,e.kind,e.canonical_name,count(DISTINCT ae.asset_id) AS assets"
+ " FROM entity e JOIN asset_entity ae ON ae.entity_id=e.id"
+ " WHERE e.kind='performer' GROUP BY e.id ORDER BY assets DESC, e.id"):
+ entity_id, kind = int(row["id"]), str(row["kind"])
+ key = followup_key(kind, entity_id)
+ if (key in skip or not _needs_avatar(avatar_root, kind, entity_id)
+ or attempts.settled(key, str(row["assets"]))):
+ continue
+ name = str(row["canonical_name"] or "")
+ found.append(Followup(key=key, task_key=TASK_KEY,
+ label=f"{TASK_LABEL}:{name}" if name else TASK_LABEL))
+ if len(found) >= limit:
+ break
+ return found
+
+
def run(contract, key: str, handle) -> dict:
+ """跑一条补头像后继,再把实体当时的指纹记进 `Attempts`,存量补派按它判。"""
+ summary = _run(contract, key, handle)
+ _kind, entity_id = parse_key(key)
+ with contract.database.read_connection() as connection:
+ current = fingerprint(connection, entity_id)
+ Attempts(attempts_root(contract.candidate_root)).record(
+ key, current, str(summary.get("outcome", "")))
+ return summary
+
+
+def _run(contract, key: str, handle) -> dict:
"""跑一条补头像后继。返回的摘要就是活动页上那一行。
实体身份不进摘要——它已经在这条后继的 key 里,写两遍只是让那一行更难读。
diff --git a/src/peach/followups.py b/src/peach/followups.py
index 1824eb4db..ec37a778d 100644
--- a/src/peach/followups.py
+++ b/src/peach/followups.py
@@ -17,9 +17,12 @@
"""
from __future__ import annotations
+import json
import logging
import threading
+import time
from dataclasses import dataclass
+from pathlib import Path
from typing import Callable
from .task_runs import TaskRunHandle, TaskRunStore
@@ -46,6 +49,42 @@ class Followup:
return (self.key, self.task_key, self.label)
+class Attempts:
+ """存量补派时的记性:一条后继跑过之后,它的实体当时是什么样子(ADR-0053)。
+
+ 存量里缺图的实体每轮都还缺图,光看「缺不缺」会让同一批找不到图的实体每轮都把
+ 名额占满。跑完就记下实体的指纹(作品数、链接数这类会让结论变的量),指纹没变就
+ 不再派;多了一部作品、多了一条链接,指纹变了,自然再试一次。
+
+ 任务记录每类只留最近 20 行,存不住这份记性,所以落在候选缓存里,一件事一个文件。
+ """
+
+ def __init__(self, root):
+ self.root = Path(root)
+
+ def _path(self, key: str):
+ return self.root / f"{str(key).replace(':', '-')}.json"
+
+ def settled(self, key: str, fingerprint: str) -> bool:
+ try:
+ record = json.loads(self._path(key).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return False
+ return isinstance(record, dict) and record.get("fingerprint") == fingerprint
+
+ def record(self, key: str, fingerprint: str, outcome: str) -> None:
+ self.root.mkdir(parents=True, exist_ok=True)
+ self._path(key).write_text(json.dumps(
+ {"key": key, "fingerprint": fingerprint, "outcome": outcome,
+ "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())},
+ ensure_ascii=False), encoding="utf-8")
+
+
+def attempts_root(generated_root):
+ """`Attempts` 落在哪:数据目录 `generated/provider-cache/followup-attempts`。"""
+ return Path(generated_root) / "provider-cache" / "followup-attempts"
+
+
@dataclass(frozen=True)
class FollowupType:
"""一种后继怎么跑。
diff --git a/src/peach/jobs.py b/src/peach/jobs.py
index 5ce21aedb..487f27aa6 100644
--- a/src/peach/jobs.py
+++ b/src/peach/jobs.py
@@ -469,9 +469,10 @@ class BackgroundJob:
try:
fn(job_id)
except Exception as error: # 后台失败必须变成可轮询的状态,不能只留在日志里
+ # 抛出来就是没跑完:途中声明过的后继作废,结算时一条都不派。
self.update(job_id, status="failed",
error=f"{type(error).__name__}: {error}",
- completed_at=time.time())
+ followups=[], completed_at=time.time())
finally:
self._settle(job_id)
@@ -498,8 +499,11 @@ class BackgroundJob:
"""
status = state.get("status")
if status == "failed":
+ # 声明了后继就是结算到了底,只是留下了要人处理的项(ADR-0053):后继照派。
+ # 中途抛异常的那一轮走不到声明那一步,一条都不派。
self._close_run(job_id, "failed", error=str(state.get("error") or "任务失败"),
- summary=self._summary(state))
+ summary={**self._summary(state),
+ **self._dispatch_followups(job_id, state)})
return
if superseded and status == "running":
# 还在跑就被顶掉:它的结果没人要了,记成取消而不是成功。
@@ -514,7 +518,8 @@ class BackgroundJob:
def _dispatch_followups(self, job_id: str, state: dict) -> dict:
"""把这一轮声明的后继交给任务中心,返回要并进摘要的那几个数。
- 只有成功收尾的那条路走到这里:父任务失败一条后继都不派(ADR-0040 第四条)。
+ 成功收尾、以及结算到底但留下待处理项的那一轮都走到这里(ADR-0053);派不派
+ 看这一轮有没有声明,中途中断的轮次声明不到。
没入队的三种情况各占摘要里的一行——静默丢弃和没有上限一样,事后都查不出来。
"""
declared = state.get("followups")
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index 93c529acc..e94445e83 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -1161,13 +1161,19 @@ def _entity_followups(database, config, watermark, covered=()):
女优也算进来(`avatar_followup.plan`)。厂牌盘上没有图的派补厂牌后继
(`studio_followup.plan`),官网与标识在那一条里一起补。
+ 这一轮的名额(`MAX_FOLLOWUPS`)先给新登记的,余下的给库里早就登记、至今缺图的存量
+ (ADR-0053):女优在前,厂牌补满。存量每轮往前推一截,跑过又没变的不再派。
+
只声明,不执行:派发在调用方结算这一轮时发生,真正去跑的是 `followups` 那一层。
这里出任何问题都只让这一轮不派后继,不影响刮削本身的结论。
"""
if database is None or watermark is None:
return []
from . import avatar_followup, studio_followup
+ from .followups import Attempts, attempts_root
+ from .task_runs import MAX_FOLLOWUPS
generated = config.directory('generated')
+ attempts = Attempts(attempts_root(generated))
try:
with database.read_connection() as connection:
found = avatar_followup.plan(
@@ -1175,6 +1181,11 @@ def _entity_followups(database, config, watermark, covered=()):
covered_asset_ids=[asset_id for asset_id, count in covered if count])
found += studio_followup.plan(connection, generated / 'logos',
since_entity_id=watermark)
+ taken = {item.key for item in found}
+ found += avatar_followup.stock(connection, generated / 'avatars', attempts,
+ limit=MAX_FOLLOWUPS - len(found), skip=taken)
+ found += studio_followup.stock(connection, generated / 'logos', attempts,
+ limit=MAX_FOLLOWUPS - len(found), skip=taken)
except sqlite3.Error:
return []
return [{'key': item.key, 'task_key': item.task_key, 'label': item.label}
diff --git a/src/peach/studio_followup.py b/src/peach/studio_followup.py
index 0216494c2..fd0a7161d 100644
--- a/src/peach/studio_followup.py
+++ b/src/peach/studio_followup.py
@@ -27,7 +27,7 @@ from datetime import datetime, timezone
from urllib.parse import urlsplit
from . import studio_icons, studio_sites
-from .followups import Followup, FollowupType, register
+from .followups import Attempts, Followup, FollowupType, attempts_root, register
#: 这类后继在任务中心的身份,也是活动页上那一行的名字来源。
TASK_KEY = "studio-mark"
@@ -82,7 +82,55 @@ def plan(connection: sqlite3.Connection, logo_root, *, since_entity_id: int) ->
for _assets, entity_id, name in found]
+def fingerprint(connection: sqlite3.Connection, entity_id: int) -> str:
+ """会让这条后继结论变的量:作品数与官网、目录链接数。人补上一条链接就该再试。"""
+ assets = connection.execute(
+ "SELECT count(DISTINCT asset_id) FROM asset_entity WHERE entity_id=?",
+ (int(entity_id),)).fetchone()[0]
+ links = connection.execute(
+ "SELECT count(*) FROM entity_link WHERE entity_id=? AND link_kind IN (?,?)",
+ (int(entity_id), *studio_icons.ICON_LINK_KINDS)).fetchone()[0]
+ return f"{assets}/{links}"
+
+
+def stock(connection: sqlite3.Connection, logo_root, attempts, *, limit: int,
+ skip=()) -> list[Followup]:
+ """库里早就登记、盘上至今没有图的厂牌,作品多的在前,最多 `limit` 条(ADR-0053)。
+
+ 跑过一次、作品数与链接数都没变的不再派(`attempts`)。
+ """
+ if limit <= 0:
+ return []
+ skip = set(skip)
+ found = []
+ for row in connection.execute(
+ "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) AS assets"
+ " FROM entity e JOIN asset_entity ae ON ae.entity_id=e.id"
+ " WHERE e.kind='studio' GROUP BY e.id ORDER BY assets DESC, e.id"):
+ entity_id, name = int(row[0]), str(row[1] or "")
+ key = followup_key(entity_id)
+ if key in skip or has_mark(logo_root, name):
+ continue
+ if attempts.settled(key, fingerprint(connection, entity_id)):
+ continue
+ found.append(Followup(key=key, task_key=TASK_KEY,
+ label=f"{TASK_LABEL}:{name}" if name else TASK_LABEL))
+ if len(found) >= limit:
+ break
+ return found
+
+
def run(contract, key: str, handle) -> dict:
+ """跑一条补厂牌后继,再把厂牌当时的指纹记进 `Attempts`,存量补派按它判。"""
+ summary = _run(contract, key, handle)
+ with contract.database.read_connection() as connection:
+ current = fingerprint(connection, parse_key(key))
+ Attempts(attempts_root(contract.candidate_root)).record(
+ key, current, str(summary.get("outcome", "")))
+ return summary
+
+
+def _run(contract, key: str, handle) -> dict:
"""跑一条补厂牌后继。返回的摘要就是活动页上那一行。"""
entity_id = parse_key(key)
logo_root = contract.logo_root
diff --git a/tests/test_followups.py b/tests/test_followups.py
index 20fb20705..68026329d 100644
--- a/tests/test_followups.py
+++ b/tests/test_followups.py
@@ -277,6 +277,16 @@ class BackgroundJobDispatchTests(LedgerTestCase):
self.assertEqual(run.status, "failed")
self.assertEqual(self.store.children(run.id), [])
+ def test_a_run_that_settles_with_open_issues_still_dispatches(self):
+ job = self.job()
+ job.start(lambda job_id: job.update(
+ job_id, status="failed", error="3 项需要处理", followups=self.declared()))
+ job.thread.join(5)
+ run = self.store.query(task_key="library-processing", limit=1)[0]
+ self.assertEqual(run.status, "failed")
+ self.assertEqual(run.result_summary["followups"], 1)
+ self.assertEqual(len(self.store.children(run.id)), 1)
+
def test_the_runner_is_woken_once_the_followups_are_queued(self):
runner = mock.Mock()
job = self.job(runner)
@@ -441,6 +451,27 @@ class CoverFaceFollowupTests(LedgerTestCase):
self.assertEqual(sorted((one["provider"], one["external_id"]) for one in kept),
[("cover-face", "FC2-PPV-2"), ("cover-face", "FC2-PPV-3")])
+ def test_stock_skips_her_once_tried_until_her_works_change(self):
+ from peach.avatar_followup import stock
+ from peach.followups import Attempts, attempts_root
+
+ self.work(1, "FC2-PPV-1", (1800, 1000))
+ chosen = self.entity("performer", "人挑过")
+ self.work(6, "FC2-PPV-6", (600, 400), performers=(chosen,))
+ (self.avatars / f"performer-{chosen}.img").write_bytes(b"jpeg")
+ attempts = Attempts(attempts_root(self.root / "generated"))
+
+ def planned():
+ with self.database.read_connection() as connection:
+ return [item.key for item in stock(connection, self.avatars, attempts,
+ limit=10)]
+
+ self.assertEqual(planned(), [followup_key("performer", self.person)])
+ self.run_followup()
+ self.assertEqual(planned(), [])
+ self.work(2, "FC2-PPV-2", (276, 154))
+ self.assertEqual(planned(), [followup_key("performer", self.person)])
+
def test_a_thumbnail_is_the_floor_not_nothing(self):
self.work(1, "FC2-PPV-1", (1800, 1000))
self.work(2, "FC2-PPV-2", (276, 154))
diff --git a/tests/test_studio_followup.py b/tests/test_studio_followup.py
index 5c9844281..40d8d4bb2 100644
--- a/tests/test_studio_followup.py
+++ b/tests/test_studio_followup.py
@@ -122,6 +122,35 @@ class PlanTests(StudioFollowupCase):
self.assertEqual(found[0].task_key, studio_followup.TASK_KEY)
self.assertTrue(found[0].label.endswith("NEWLABEL"))
+ def test_stock_skips_a_studio_once_tried_until_it_gains_a_link(self):
+ from peach.followups import Attempts, attempts_root
+
+ studio = self.entity("studio", "OLDLABEL")
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute("INSERT INTO asset(id,location,path,name,medium,code,size)"
+ " VALUES(1,'R:','R:\\media\\a.mp4','a.mp4','video','OLD-1',1)")
+ connection.execute("INSERT INTO asset_entity(asset_id,entity_id,role,source)"
+ " VALUES(1,?,'studio','test')", (studio,))
+ attempts = Attempts(attempts_root(self.contract.candidate_root))
+
+ def planned():
+ with self.database.read_connection() as connection:
+ return [item.key for item in
+ studio_followup.stock(connection, self.logos, attempts, limit=10)]
+
+ key = studio_followup.followup_key(studio)
+ self.assertEqual(planned(), [key])
+ with mock.patch.object(studio_followup.studio_sites, "discover",
+ return_value=(site_row("weak"), 0.0)):
+ self.run_followup(studio)
+ self.assertEqual(planned(), [])
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute(
+ "INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,is_sensitive,"
+ "metadata_json,created_at,updated_at) VALUES(?,?,?,?,?,0,'{}',?,?)",
+ (studio, "official", "官方网站", "https://old.jp/", "old.jp", STAMP, STAMP))
+ self.assertEqual(planned(), [key])
+
class SiteTests(StudioFollowupCase):
def test_an_ok_site_is_linked_with_its_source_and_batch(self):