fix: 翻译失败/降级文本不再写 cache(避免 30 天污染)

之前 service.translate 写 cache 无条件,导致:
- 第一次翻译失败时,'[翻译失败: ...]' 占位符被写进 cache
- 30 天内相同文本的请求(新文章 title 与老文章 title 相同时)全部返回占位符
- 触发 200+ 文章 title_zh 字段被永久污染

修法:仅在 engine ∈ {tencent, nllb, cache} 且文本不含错误标记时,才写 cache。
This commit is contained in:
Mavis
2026-06-08 00:48:36 +08:00
parent 9862a92423
commit 639562593e
7 changed files with 251 additions and 5 deletions

View File

@@ -123,11 +123,14 @@ class TranslationService:
# 主 + fallback 都失败:抛异常,让上层标记 status=failed
raise RuntimeError(f"translation failed for {chars} chars (engine={engine.name})")
# 4) 写缓存(无论引擎)
try:
await r.set(ck, res.text, ex=60 * 60 * 24 * 30) # 30 天
except Exception:
pass
# 4) 写缓存 — 只缓存真实翻译结果;失败/降级文本不缓存(避免污染 30 天)
if res.engine in ("tencent", "nllb", "cache") and not res.cached:
# 二次保险:如果文本里仍含错误标记,也不缓存
if "[翻译失败" not in res.text and "[本条未翻译" not in res.text:
try:
await r.set(ck, res.text, ex=60 * 60 * 24 * 30) # 30 天
except Exception:
pass
# 5) 计数(只在 tencent 上计)
if res.engine == "tencent":