fix(monitor): 一轮产物里重复的作品会让指标快照撞唯一键,整个 run 崩掉
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

跑真任务时踩到的:

    sqlalchemy.exc.IntegrityError: (1062, "Duplicate entry
    '7-7690458980574358513-45' for key 'uq_note_metric'")

根因是我上一版写错了一处作用域:退化路径里那个「遍历已知作品」的循环写在了**目标循环内部**,
所以任务有多个目标时,同一批已知作品会被拉两遍 → 同一件作品在一轮里出现两条记录 →
ingest 给同一件作品写两份本轮快照 → 撞 (task_id, note_id, run_id) 唯一键。

两处都修,各挡一层:

* douyin_fetch:去重集合挪到 collect 的最外层,**跨目标**只算一次;退化时也先查一遍
  已知作品是否已刷过。
* ingest:`_ingest_notes` 对「一轮里重复出现的 note_id」免疫。一层在源头、一层在入口,
  因为产物里重复并不罕见(多个目标指向同一个人、上游重跑、退化路径),不该靠上游自觉。

测试 +2:多目标时已知作品只刷一次;同一轮里重复的作品只落一份快照(这条会崩在
唯一键上,所以它测的正是运行时的那个崩法)。
This commit is contained in:
2026-10-10 17:24:08 +08:00
parent 3b6a437e6c
commit 95b1be2c2e
4 changed files with 67 additions and 1 deletions
+22
View File
@@ -725,6 +725,28 @@ class TestDouyinIngest:
assert len(await _events(db, EVENT_METRIC_DELTA)) == 1
class TestDuplicateRecordsInOneRun:
"""一轮产物里重复出现的作品只该算一次。
指标快照的唯一键是 ``(task_id, note_id, run_id)``:同一条作品在一轮里进来两次,
第二次插入会撞键并让整个 run 崩掉 —— 产物里重复并不罕见(多个目标指向同一个人、
或退化路径重复刷新)。
"""
@pytest.mark.asyncio
async def test_a_duplicated_note_is_processed_once(self, db, tmp_path):
task = await _make_task(db)
_write_run_dir(tmp_path, [_note("n1"), _note("n1")])
run = await _make_run(db, task, started_at=1)
result = await ingest_run(db, run, task, tmp_path)
assert result.new_notes == 1
assert len(list((await db.scalars(select(MonitorNote))).all())) == 1
# 崩就崩在这一句上:一条作品只能有一份本轮快照。
assert len(list((await db.scalars(select(MonitorNoteMetric))).all())) == 1
class TestNicknameRefresh:
"""已入库的评论,昵称要跟着重新采集的值走。