变化记录的 affects 先占住那一行再读改写(复核 L5):口径试算记没试算的那几版(ledger/recall._probe_skipped)和探查刷新影响面(data/source_changes.record)以前都是先读再整份写,交错时互相盖掉。现在两处都先发一句按条件的 UPDATE(record 顺手记又见到一次,SQLite 上拿到写锁、PostgreSQL 上锁住这一行),再读出来改。补并发测试(六版口径同时记、探查同时刷新,一条不丢)

This commit is contained in:
ThearchyHelios
2026-10-19 11:48:43 +08:00
parent 4548e8bd25
commit 4ffd9ad431
3 changed files with 54 additions and 6 deletions
+9 -4
View File
@@ -29,7 +29,7 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Any
from sqlalchemy import func, or_, select
from sqlalchemy import func, or_, select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
@@ -150,11 +150,16 @@ async def record(session: AsyncSession, source: Any, change: NewChange, detected
raise ValueError(f"不认识的严重程度:{change.severity}")
fp = fingerprint(change.kind, change.table, change.column, change.key)
now = utcnow()
# 已经有了的:先按条件 UPDATE 记下又见到一次(同时占住那一行:SQLite 上拿到写锁、PostgreSQL 上锁住这一行),再读出来改
# 影响面——口径试算同时往 affects 里记没试算的那几版(ledger/recall._probe_skipped,同样先占住再读改写),谁也不盖掉谁
seen = await session.execute(update(SourceChange).where(
SourceChange.source_id == source.id, SourceChange.fingerprint == fp)
.values(last_seen_at=now, seen_count=func.coalesce(SourceChange.seen_count, 0) + 1)
.execution_options(synchronize_session=False))
found = (await session.execute(select(SourceChange).where(
SourceChange.source_id == source.id, SourceChange.fingerprint == fp))).scalar_one_or_none()
SourceChange.source_id == source.id, SourceChange.fingerprint == fp)
.execution_options(populate_existing=True))).scalar_one_or_none() if seen.rowcount else None
if found is not None:
found.last_seen_at = now
found.seen_count = int(found.seen_count or 0) + 1
if found.status == "open":
# 影响按这一次刷新;表结构变了之后口径试算的情况(ledger/recall 记的 probes)不是探查算的,留着
probes = (found.affects or {}).get("probes") if isinstance(found.affects, dict) else None