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"]
+57
View File
@@ -65,6 +65,57 @@ POLL_INTERVAL_SECONDS = 20
# Spread tasks sharing an interval so they do not all come due on the same tick.
# Applied to interval mode only -- see the advance step below.
JITTER_SECONDS = 60
# 超时之后再等这么久才动手回收。采集那边到点后还要收尾写库,别和它抢。
REAP_GRACE_SECONDS = 300
async def reap_stale_runs() -> int:
"""把「早就该结束却还挂在 running」的 run 收掉,返回收了几个。
**为什么不能只靠 ``asyncio.wait_for`` 的超时。** 它超时后会去**取消**采集协程,
而取消要等协程真正结束。抖音那条路会卡在 Playwright 的调用上
(``douyin_api._read_browser`` 里 ``playwright.stop()`` 原先没包超时,driver
一卡就永不返回),这种协程不响应取消 —— 于是 ``wait_for`` 自己也永远不返回,
``except asyncio.TimeoutError`` 根本轮不到,run 就永远停在「运行中」。
实测:7 条这样的幽灵,最久的挂了 48 小时,产物目录全空。
``recover()`` 只在进程启动时跑一次,进程不重启就没人来收。所以这里按 tick 扫。
判据用**任务自己配的** ``run_timeout_seconds``(默认 3600),不是写死时长 ——
每个任务允许跑多久本来就不一样。
"""
now = get_current_timestamp()
reaped = 0
async with get_session() as session:
rows = (
await session.execute(
select(MonitorRun, MonitorTask.run_timeout_seconds)
.join(MonitorTask, MonitorTask.id == MonitorRun.task_id)
.where(MonitorRun.status == RUN_RUNNING)
)
).all()
for run, timeout_seconds in rows:
if run.started_at is None:
continue
limit_ms = (
max(1, int(timeout_seconds or 3600)) + REAP_GRACE_SECONDS
) * 1000
if now - run.started_at < limit_ms:
continue
run.status = RUN_INTERRUPTED
run.finished_at = now
run.error_message = (
f"超过 {timeout_seconds} 秒仍未结束,已判定为卡死并回收"
"(采集协程没有响应取消,通常卡在浏览器调用上)"
)
reaped += 1
if reaped:
print(
f"[monitor.scheduler] 回收了 {reaped} 个卡死的 run(超过各自超时仍未结束)",
flush=True,
)
return reaped
class MonitorScheduler:
@@ -100,6 +151,12 @@ class MonitorScheduler:
print(f"[monitor.scheduler] recovery failed: {exc}")
while not self._stopping.is_set():
# 先收尸再调度:卡死的 run 不该继续占着界面的「运行中」,也不该让
# 它的任务看起来还在跑。见 reap_stale_runs 的说明。
try:
await reap_stale_runs()
except Exception as exc: # pragma: no cover - keep the loop alive
print(f"[monitor.scheduler] stale run reap failed: {exc}")
try:
await self.tick()
except Exception as exc: # pragma: no cover - keep the loop alive
+74
View File
@@ -338,3 +338,77 @@ class TestRecovery:
async with monitor_db.get_session() as session:
run = await session.scalar(select(MonitorRun))
assert run.status == RUN_SUCCESS
async def _make_run(
task_id: int, *, started_minutes_ago: int, status: str = RUN_RUNNING
) -> int:
now = get_current_timestamp()
async with monitor_db.get_session() as session:
run = MonitorRun(
task_id=task_id,
trigger="scheduled",
status=status,
phase=MODE_CREATOR,
save_data_path="",
queued_at=now,
not_before=0,
started_at=now - started_minutes_ago * MS_PER_MINUTE,
max_comments_count=50,
)
session.add(run)
await session.flush()
return run.id
async def _get_run(run_id: int) -> MonitorRun:
async with monitor_db.get_session() as session:
return await session.get(MonitorRun, run_id)
class TestReapStaleRuns:
"""卡在「运行中」的 run 必须能被周期性地收掉,而不是只能靠重启。
``runner`` 那边用 ``asyncio.wait_for(collect(...), timeout=...)`` 兜底,但超时后
它会去**取消**采集协程、并且**等取消完成**。抖音那条路卡在 Playwright 调用上时
协程不响应取消,于是 ``except asyncio.TimeoutError`` 根本轮不到 —— 线上真的因此
挂过 7 条幽灵 run,最久的 48 小时,产物目录全空,只有重启才清掉。
"""
@pytest.mark.asyncio
async def test_run_past_its_own_timeout_is_reaped(self, db):
task_id = await _make_task(get_current_timestamp()) # run_timeout_seconds=3600
run_id = await _make_run(task_id, started_minutes_ago=120)
assert await scheduler_module.reap_stale_runs() == 1
run = await _get_run(run_id)
assert run.status == RUN_INTERRUPTED
assert run.finished_at is not None
# 留下来的必须是**说得清**的原因,不能是空字符串
assert "卡死" in (run.error_message or "")
@pytest.mark.asyncio
async def test_run_still_inside_its_timeout_is_untouched(self, db):
task_id = await _make_task(get_current_timestamp())
run_id = await _make_run(task_id, started_minutes_ago=30)
assert await scheduler_module.reap_stale_runs() == 0
assert (await _get_run(run_id)).status == RUN_RUNNING
@pytest.mark.asyncio
async def test_grace_period_leaves_the_runner_time_to_finish(self, db):
"""刚过超时那一小段不动手 —— 采集那边到点后还要收尾写库。"""
task_id = await _make_task(get_current_timestamp())
run_id = await _make_run(task_id, started_minutes_ago=61) # 3600s 刚过
assert await scheduler_module.reap_stale_runs() == 0
assert (await _get_run(run_id)).status == RUN_RUNNING
@pytest.mark.asyncio
async def test_finished_runs_are_left_alone(self, db):
task_id = await _make_task(get_current_timestamp())
run_id = await _make_run(task_id, started_minutes_ago=1000, status=RUN_SUCCESS)
assert await scheduler_module.reap_stale_runs() == 0
assert (await _get_run(run_id)).status == RUN_SUCCESS