fix(monitor): 卡死的一轮不再堵住调度循环;矩阵补总获赞和首条视频日期
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

「抓不到最新的」有两个叠加的原因:

1. 采集卡死时 `_run_due_task` 是内联 await,execute_task 里的 wait_for 又在等
   一个不响应取消的协程 —— 整个调度循环(连同自动追加、每日推送、其他任务)
   一起停 65 分钟。现在采集丢到后台任务里跑,循环照常 tick,reap_stale_runs
   也能按时回收。实测任务 25 最近 8 次运行有 4 次这样。
2. 超级编导自动追加在 10-25 因密码错误被停到 11-24(防锁号),新作品进不来。
   已把 25 号的调度钟拨回现在,补进了 10-31 那条。

标签矩阵:博主名字左边在粉丝数之后加「主页总获赞」和「第一条视频发布日期」
(查全库最早的作品时间,不受 7/14/30 天窗口限制)。
This commit is contained in:
2026-11-02 10:24:36 +08:00
parent cd2a276630
commit c06848ae98
5 changed files with 215 additions and 17 deletions
+42 -3
View File
@@ -144,6 +144,9 @@ class MonitorScheduler:
self._warned_no_cookie: set = set()
# 超级编导自动追加是网络操作,单独一个后台任务,不占调度循环。
self._superdir_task: Optional[asyncio.Task] = None
# 正在跑的采集(task_id -> asyncio.Task)。**必须留强引用**,否则任务可能被
# GC 回收;顺带让测试和停机可以等它们结束。
self._running_tasks: dict[int, asyncio.Task] = {}
async def start(self) -> None:
if self._loop_task is not None and not self._loop_task.done():
@@ -469,11 +472,47 @@ class MonitorScheduler:
task_id = task.id
try:
await execute_task(task_id, trigger="scheduled")
except Exception as exc:
self._start_execution(task_id)
def _start_execution(self, task_id: int) -> asyncio.Task:
"""把采集丢到后台跑,**不让它堵住调度循环**。
``execute_task`` 里的超时用的是 ``asyncio.wait_for``,它到点会取消采集协程、
然后**等取消完成**。抖音那条路偶尔卡在不响应取消的浏览器调用上 —— 内联
``await`` 会把整个循环一起钉死 65 分钟:其他任务不触发、自动追加不跑、每日
推送也错过。实测任务 25 的 8 次运行里有 4 次就是这样。
放到后台之后,``reap_stale_runs`` 仍会把卡死的 run 标记回收,循环照常 tick。
"""
running = self._running_tasks.get(task_id)
if running is not None and not running.done():
# 同一个任务已经有采集在跑(比如手动触发的还没结束),不要再起一个。
return running
task = asyncio.create_task(execute_task(task_id, trigger="scheduled"))
self._running_tasks[task_id] = task
task.add_done_callback(lambda done: self._execution_done(task_id, done))
return task
def _execution_done(self, task_id: int, task: asyncio.Task) -> None:
if self._running_tasks.get(task_id) is task:
self._running_tasks.pop(task_id, None)
if task.cancelled():
return
exc = task.exception()
if exc is not None:
print(f"[monitor.scheduler] task {task_id} failed: {exc}")
async def drain(self) -> None:
"""等后台采集结束。测试与优雅停机用。"""
while True:
pending = [
task for task in self._running_tasks.values() if not task.done()
]
if not pending:
return
await asyncio.gather(*pending, return_exceptions=True)
# Global singleton, mirroring the crawler_manager pattern.
monitor_scheduler = MonitorScheduler()
+32 -1
View File
@@ -1578,7 +1578,9 @@ async def daily_tag_matrix(
返回**长表结构**,转置由前端做:
{"dates": ["2026-10-21", ...], # 新到旧
"creators": [{"hash": ..., "name": ...}], # 按昵称排序
"creators": [{"hash": ..., "name": ..., "fans": 1200,
"total_favorited": 83000,
"first_published_at": 1780000000000}], # 按昵称排序
"cells": {"2026-10-21": {"<hash>": {
"count": 2, "tags": ["大字报", "养号"],
"likes": 120, "comments": 8, "collected": 30, "shares": 4,
@@ -1701,6 +1703,7 @@ async def daily_tag_matrix(
MonitorCreatorStat.nickname,
MonitorCreatorStat.captured_at,
MonitorCreatorStat.fans,
MonitorCreatorStat.total_favorited,
).where(
MonitorCreatorStat.task_id.in_(task_ids),
MonitorCreatorStat.creator_hash != "",
@@ -1711,11 +1714,20 @@ async def daily_tag_matrix(
# 粉丝数是给博主列显示用的「最近一次已知值」。某一轮没解析出来(None)不让它把
# 之前的好数字盖掉 —— 一个号有几千粉丝,不会因为这一轮没读到就变成不知道。
latest_fans: Dict[str, tuple] = {}
# 主页上的「获赞总数」,和粉丝数一样取最近一次读到的值。
latest_likes: Dict[str, tuple] = {}
for stat in stat_rows:
if stat.fans is not None:
current_fans = latest_fans.get(stat.creator_hash)
if current_fans is None or stat.captured_at > current_fans[1]:
latest_fans[stat.creator_hash] = (stat.fans, stat.captured_at)
if stat.total_favorited is not None:
current_likes = latest_likes.get(stat.creator_hash)
if current_likes is None or stat.captured_at > current_likes[1]:
latest_likes[stat.creator_hash] = (
stat.total_favorited,
stat.captured_at,
)
# **空昵称不算名字。** 资料接口偶尔会回一个空对象(昵称、sec_uid、粉丝、
# 作品数全空),如果把这一轮当最新快照,就会用一个空字符串把之前的好名字
# 盖掉,界面上变成「未知(hash)」。实测线上有两个号就是这么丢的名字。
@@ -1802,6 +1814,23 @@ async def daily_tag_matrix(
# 作品是按发布时间倒序取回来的,明细按时间正序更好读(1、2、3…)。
bucket["details"].reverse()
# 博主的**第一条视频**发布时间。查全库,不受上面 days 窗口的限制 —— 一个号最早的
# 作品很可能在窗口之外,而「这个号做了多久」看的就是它。
first_rows = (
await session.execute(
select(MonitorNote.creator_hash, func.min(MonitorNote.published_at))
.where(
MonitorNote.task_id.in_(task_ids),
MonitorNote.published_at.is_not(None),
MonitorNote.creator_hash != "",
)
.group_by(MonitorNote.creator_hash)
)
).all()
first_published: Dict[str, int] = {
creator_hash: first_at for creator_hash, first_at in first_rows if first_at
}
creators = [
{
"hash": hash_,
@@ -1809,6 +1838,8 @@ async def daily_tag_matrix(
# 没有账号快照的博主(作品模式刚导入、还没跑过一轮)就是 None,
# 前端据此不画那个数字,而不是显示 0。
"fans": latest_fans.get(hash_, (None, 0))[0],
"total_favorited": latest_likes.get(hash_, (None, 0))[0],
"first_published_at": first_published.get(hash_),
}
for hash_, name in known.items()
]
+47 -6
View File
@@ -163,19 +163,27 @@
.untagged { color: var(--muted); font-size: 11px; }
.empty { color: #2a3646; }
/* 博主名字左边的粉丝数。压暗一点:它是参照信息,不该和名字抢视线。 */
.fans {
/* 博主名字左边的参照信息:粉丝 / 总获赞 / 第一条视频日期。
都压暗、贴边,不该和名字抢视线。 */
.fans, .likes, .first {
display: inline-block;
min-width: 36px;
margin-right: 6px;
padding: 0 4px;
border-radius: 4px;
background: rgba(34, 211, 238, 0.08);
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
text-align: right;
}
.fans { background: rgba(34, 211, 238, 0.08); }
.likes { background: rgba(244, 114, 182, 0.08); }
.first {
min-width: 70px;
background: rgba(123, 139, 163, 0.10);
text-align: center;
font-size: 10px;
}
/* 条件格式命中的格子。用 inset 描边而不是 box-shadow 扩散:不改变布局,
也不会触发整行重排。 */
@@ -300,7 +308,7 @@
<div class="wrap" id="wrap"></div>
<div id="tip"></div>
<div class="legend">
<span><b>名字左边</b> = 粉丝数</span>
<span><b>名字左边</b> = 粉丝数 / 主页总获赞 / 第一条视频发布日期</span>
<span><b>赞 / 评</b> = 当天这些作品的点赞 / 评论</span>
<span><b>左下角数字</b> = 当天作品条数</span>
<span><b>悬停后点标题</b> = 在抖音打开这条作品</span>
@@ -349,6 +357,15 @@
return number.toLocaleString('zh-CN');
}
function dateParts(ms) {
const date = new Date(ms);
const pad = (value) => String(value).padStart(2, '0');
return {
date: date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()),
time: pad(date.getHours()) + ':' + pad(date.getMinutes()),
};
}
function metricNode(label, kind, value) {
const span = document.createElement('span');
span.className = kind;
@@ -593,17 +610,41 @@
// 粉丝数放在**名字左边**,一眼能看出这个号多大。没有快照的博主
// (作品模式刚导入还没跑过一轮)就不画 —— 不写 0,那会被读成「没有粉丝」。
const fansKnown = creator.fans !== null && creator.fans !== undefined;
const likesKnown =
creator.total_favorited !== null && creator.total_favorited !== undefined;
const firstAt = creator.first_published_at;
const titleParts = [];
if (fansKnown) {
const fans = document.createElement('span');
fans.className = 'fans';
fans.textContent = fmt(creator.fans);
fans.textContent = compact(creator.fans);
fans.title = '粉丝数';
th.appendChild(fans);
titleParts.push(fmt(creator.fans) + ' 粉丝');
}
if (likesKnown) {
// 主页上显示的那个「获赞总数」。
const likes = document.createElement('span');
likes.className = 'likes';
likes.textContent = compact(creator.total_favorited);
likes.title = '主页总获赞';
th.appendChild(likes);
titleParts.push(fmt(creator.total_favorited) + ' 总获赞');
}
if (firstAt) {
const parts = dateParts(firstAt);
const first = document.createElement('span');
first.className = 'first';
first.textContent = parts.date;
first.title = '第一条视频发布于 ' + parts.date + ' ' + parts.time;
th.appendChild(first);
titleParts.push('第一条视频 ' + parts.date);
}
const nameSpan = document.createElement('span');
nameSpan.textContent = label;
th.appendChild(nameSpan);
th.title = (fansKnown ? fmt(creator.fans) + ' 粉丝 · ' : '') + label;
titleParts.push(label);
th.title = titleParts.join(' · ');
tr.appendChild(th);
for (const day of data.dates) {
const rowCells = data.cells[day] || {};
+48
View File
@@ -262,6 +262,7 @@ async def _stat(
captured_at: int | None = None,
run_id: int = 1,
fans: int | None = None,
total_favorited: int | None = None,
) -> None:
async with monitor_db.get_session() as session:
session.add(
@@ -273,6 +274,7 @@ async def _stat(
creator_id="",
works_count=0,
fans=fans,
total_favorited=total_favorited,
captured_at=captured_at or get_current_timestamp(),
)
)
@@ -317,6 +319,52 @@ async def test_the_creator_row_carries_the_latest_fan_count(db):
assert data["creators"][0]["fans"] == 1200
@pytest.mark.asyncio
async def test_the_creator_row_carries_the_total_likes_from_the_profile(db):
"""名字左边还要显示主页上的「获赞总数」,同样取最近一次读到的值。"""
task_id = await _task()
now = get_current_timestamp()
await _stat(
task_id, "hash-a", "博主A",
captured_at=now - 60_000, total_favorited=80000, run_id=1,
)
await _stat(
task_id, "hash-a", "博主A",
captured_at=now, total_favorited=83000, run_id=2,
)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["creators"][0]["total_favorited"] == 83000
@pytest.mark.asyncio
async def test_the_first_video_date_comes_from_the_whole_table(db):
"""第一条视频可能远在日期窗口之外 —— 要查全库,不能只看这 7 天。"""
task_id = await _task()
now = get_current_timestamp() - 1000
first = now - 400 * DAY_MS
await _note(task_id, "old", "博主A", first)
await _note(task_id, "new", "博主A", now)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["creators"][0]["first_published_at"] == first
@pytest.mark.asyncio
async def test_a_creator_without_works_has_no_first_video_date(db):
task_id = await _task()
await _stat(task_id, "hash-a", "博主A", fans=10)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["creators"][0]["first_published_at"] is None
@pytest.mark.asyncio
async def test_a_creator_without_a_snapshot_has_no_fan_count(db):
"""作品模式刚导入、还没跑过一轮:粉丝数留 None,界面不画那个数字(不是 0)。"""
+46 -7
View File
@@ -18,6 +18,8 @@
"""Tests for the monitor scheduler's firing, deferral and recovery rules."""
import asyncio
import pytest
import pytest_asyncio
from sqlalchemy import select
@@ -73,6 +75,16 @@ async def executed(monkeypatch):
return calls
async def _tick(scheduler: MonitorScheduler) -> None:
"""tick + 等后台采集结束。
采集现在跑在后台任务里(卡死的一轮不能堵住整个调度循环),断言调用记录之前
得先把它等回来。
"""
await scheduler.tick()
await scheduler.drain()
async def _make_task(
next_run_at, enabled: bool = True, interval: int = 60, platform: str = "xhs"
) -> int:
@@ -123,7 +135,7 @@ class TestFiring:
past = get_current_timestamp() - MS_PER_MINUTE
task_id = await _make_task(past)
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == [(task_id, "scheduled")]
task = await _get_task(task_id)
@@ -135,7 +147,7 @@ class TestFiring:
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
await _make_task(get_current_timestamp() + 10 * MS_PER_MINUTE)
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == []
@@ -144,7 +156,7 @@ class TestFiring:
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
await _make_task(get_current_timestamp() - MS_PER_MINUTE, enabled=False)
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == []
@@ -163,7 +175,7 @@ class TestFiring:
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == [(task_id, "scheduled")]
@@ -182,7 +194,7 @@ class TestFiring:
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == [(task_id, "scheduled")]
@@ -195,11 +207,36 @@ class TestFiring:
scheduler = MonitorScheduler()
await scheduler.tick()
await scheduler.drain()
await scheduler.tick()
await scheduler.drain()
assert len(executed) == 1
class TestNonBlocking:
@pytest.mark.asyncio
async def test_a_hanging_run_does_not_block_the_scheduler(self, monkeypatch, db):
"""卡死的一轮不能钉住整个循环 —— 其他任务和自动追加都靠这个 tick。
实测:抖音采集协程偶尔不响应取消,内联 await 会让循环停 65 分钟。
"""
async def never(task_id, trigger="scheduled"):
await asyncio.Event().wait()
monkeypatch.setattr(scheduler_module, "execute_task", never)
await _make_task(get_current_timestamp() - MS_PER_MINUTE)
scheduler = MonitorScheduler()
# 必须在很短时间内返回,而不是等采集结束。
await asyncio.wait_for(scheduler.tick(), timeout=2)
assert len(scheduler._running_tasks) == 1
for task in list(scheduler._running_tasks.values()):
task.cancel()
class TestDeferral:
@pytest.mark.asyncio
async def test_busy_crawler_defers_without_advancing(self, monkeypatch, db, executed):
@@ -208,7 +245,7 @@ class TestDeferral:
due_at = get_current_timestamp() - MS_PER_MINUTE
task_id = await _make_task(due_at)
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == []
task = await _get_task(task_id)
@@ -223,10 +260,12 @@ class TestDeferral:
scheduler = MonitorScheduler()
await scheduler.tick()
await scheduler.drain()
assert executed == []
fake.busy = False
await scheduler.tick()
await scheduler.drain()
assert executed == [(task_id, "scheduled")]
@@ -243,7 +282,7 @@ class TestCookieGuard:
due_at = get_current_timestamp() - MS_PER_MINUTE
task_id = await _make_task(due_at)
await MonitorScheduler().tick()
await _tick(MonitorScheduler())
assert executed == []
task = await _get_task(task_id)