fix(monitor): 卡死的 run 会永远停在「运行中」—— 加周期回收,并让 Playwright 卡住时能放手
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

线上现象:抖音任务 7 有 7 条 run 卡在 running,最久的 48 小时,`notes_fetched=0`、
无退出码、无错误,产物目录全空(说明在开始抓之前就挂住了),界面上就是「好多在运行中」。

根因两段,缺一不可:

1. `douyin_api._read_browser` 的 finally 里是裸的 `await playwright.stop()`,**没有
   超时**。Playwright 的 driver 一卡住(容器里能查到两个跑了两天的 run-driver 进程),
   `stop()` 永不返回 → `_read_browser` 永不返回 → `collect` 永不返回。
2. `runner` 用 `asyncio.wait_for(collect(...), timeout=3600)` 兜底,但 **wait_for 超时
   后会先取消、再等取消完成**;协程卡在不响应取消的调用上时,它自己也永远不返回,
   `except asyncio.TimeoutError` 根本轮不到。

于是 run 永远停在 running。而 `recover()` 只在进程启动时跑一次,不重启就没人收。

改动:

* `douyin_api`:`playwright.stop()` 改用新的 `_abandon_after()` —— 它用
  `asyncio.wait`(到点就返回)而不是 `wait_for`(会等取消完成),到点就走;
  `async_playwright().start()` 同样加 20 秒上限,起不来就回退到库里的 cookie。
* `scheduler`:新增 `reap_stale_runs()`,每个 tick(20 秒)扫一遍,把 running 超过
  **该任务自己配的** `run_timeout_seconds` + 300 秒余量的 run 标成 interrupted,
  并写上原因。不再依赖重启。

测试:`TestReapStaleRuns` 四条 —— 超过超时被回收且原因可读、未超时不动、
刚过超时仍在余量内不动、已结束的不碰。
This commit is contained in:
butubb
2026-10-18 16:48:28 +08:00
parent 4cb6c8b9cf
commit 24b7a221f3
3 changed files with 180 additions and 7 deletions
+49 -7
View File
@@ -179,18 +179,57 @@ async def _identity_from_pages(context: Any) -> Tuple[str, Dict[str, str]]:
pass
# 起 Playwright 客户端最多等这么久。起不来就当浏览器不可用,回退到库里的 cookie ——
# 比把整轮采集钉死在这里强。
_START_TIMEOUT_SECONDS = 20.0
async def _abandon_after(coro, timeout: float) -> bool:
"""跑一个收尾动作,最多等 ``timeout`` 秒;到点就放手。返回是否正常结束。
**不能用 ``asyncio.wait_for``。** 它的超时会先取消、再**等取消完成** —— 而这里
要收拾的恰恰是「不响应取消」的那种卡死,用它等于什么都没做,依旧会永远等下去。
``asyncio.wait`` 到点就返回,不管那个协程还在不在跑。
"""
task = asyncio.ensure_future(coro)
done, _pending = await asyncio.wait({task}, timeout=timeout)
if task in done:
try:
task.result()
except Exception: # noqa: BLE001 - 收尾失败无所谓
pass
return True
task.cancel()
return False
async def _start_playwright(timeout: float = _START_TIMEOUT_SECONDS):
"""起一个 Playwright 客户端;起不来或起得太慢就返回 None。"""
from playwright.async_api import async_playwright
task = asyncio.ensure_future(async_playwright().start())
done, _pending = await asyncio.wait({task}, timeout=timeout)
if task not in done:
task.cancel()
return None
try:
return task.result()
except Exception: # noqa: BLE001
return None
async def _read_browser() -> Optional[BrowserIdentity]:
"""连上 CDP 浏览器,一次取齐 cookie、UA、client hints。
读不到返回 None(浏览器没开/没登录),由调用方决定怎么报 —— 不抛异常。
"""
from playwright.async_api import async_playwright
from media_platform.douyin.help import client_hint_headers
playwright = None
try:
playwright = await async_playwright().start()
playwright = await _start_playwright()
if playwright is None:
return None
browser = await playwright.chromium.connect_over_cdp(_cdp_url(), timeout=15000)
if not browser.contexts:
return None
@@ -209,10 +248,13 @@ async def _read_browser() -> Optional[BrowserIdentity]:
if playwright is not None:
# 只断开连接。**绝不能 browser.close()** —— 对这个 CDP 连接而言那会关掉
# 操作者自己的浏览器。
try:
await playwright.stop()
except Exception:
pass
#
# **而且必须能放手。** 这里原先只是 `await playwright.stop()`,没有超时:
# driver 一旦卡住,`stop()` 永不返回,于是 `_read_browser` 永不返回、
# `collect` 永不返回,外面 `asyncio.wait_for` 的超时取消也等不到它结束 ——
# 整轮采集永远停在「运行中」,产物目录全空。实测库里挂了 7 条这样的幽灵,
# 最久 48 小时。用 _abandon_after 到点就走。
await _abandon_after(playwright.stop(), EVALUATE_TIMEOUT_SECONDS)
douyin_cookies = {
cookie["name"]: cookie["value"]