修复(执行队列): 登录批次不再把斗鱼履约批次饿死

现象:新建斗鱼任务报「斗鱼任务繁忙:当前有 10 个批次运行中,上限 10 个」。

根因:登录任务页(JOB_LOGIN_BATCH)和 CK 重登页(JOB_RELOGIN_BATCH)走
execution_jobs 的 auth lane,斗鱼履约/绑定批次(JOB_DOUYU_BATCH)走 fulfillment
lane,但两条 lane 共用同一个 ThreadPoolExecutor(EXECUTION_WORKER_MAX_JOBS=2)。
斗鱼邮箱验证码是攒批投递的,等一封验证码最长 25 分钟/账号,登录批次长时间持槽,
履约批次被挤到排队,堆满 DOUYU_MAX_ACTIVE_BATCHES(10) 后新建任务直接被挡。

改动:

- 执行 worker 改为 lane 隔离:每条 lane 独立线程池,总槽位不变,但 auth 最多
  占 total-1、fulfillment 最多占 total,且履约优先领取 —— 登录再慢也饿不死履约
- 单个登录批次最多占槽 LOGIN_BATCH_MAX_SECONDS(默认 1800 秒):每个账号开始
  执行前检查批次时长,超时后本轮剩余账号记「未执行」(不是失败),留待下一轮
- 新增 EXECUTION_WORKER_AUTH_JOBS / EXECUTION_WORKER_FULFILLMENT_JOBS 旋钮

验证:1732 passed / 6 skipped,pyright 生产代码 0 错误
This commit is contained in:
yml
2026-11-25 20:53:29 +08:00
parent da85373884
commit 0943b7a362
6 changed files with 387 additions and 31 deletions
+98 -31
View File
@@ -55,12 +55,51 @@ def _lane_scopes() -> tuple[str, ...]:
return scopes or (LANE_AUTH, LANE_FULFILLMENT)
def _lane_slot_limits() -> dict[str, int]:
"""每条 lane 的槽位上限(总槽位不变,只做隔离)。
登录(auth)批次现在可能长时间持槽 —— 斗鱼邮箱验证码是攒批投递的,等一封
验证码最长 25 分钟。如果 auth 和履约(fulfillment)共用同一个线程池,
登录批次会把履约批次饿死:履约批次排队到 10 个之后,新建斗鱼任务直接
被「斗鱼任务繁忙」挡掉。
所以总槽位不变(``EXECUTION_WORKER_MAX_JOBS``),但给履约预留:auth 最多
占 total-1,fulfillment 最多占 total —— 履约永远至少有 1 个槽可用。
"""
total = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
auth_limit = _env_positive_int(
"EXECUTION_WORKER_AUTH_JOBS",
max(1, total - 1),
)
fulfillment_limit = _env_positive_int(
"EXECUTION_WORKER_FULFILLMENT_JOBS",
total,
)
limits: dict[str, int] = {}
for lane in _lane_scopes():
limits[lane] = auth_limit if lane == LANE_AUTH else fulfillment_limit
return limits
def _lane_claim_order() -> tuple[str, ...]:
"""领取顺序:履约优先,登录用剩余槽位。"""
lanes = _lane_scopes()
return tuple(
sorted(lanes, key=lambda lane: 0 if lane == LANE_FULFILLMENT else 1)
)
class ExecutionJobWorker:
def __init__(self) -> None:
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
self._executor: ThreadPoolExecutor | None = None
# 每条 lane 一个独立线程池:慢的 lane 再慢也吃不掉别的 lane 的槽位。
self._executors: dict[str, ThreadPoolExecutor] = {}
self._inflight: dict[str, int] = {}
self._owner = execution_worker_owner()
def start(self) -> bool:
@@ -68,14 +107,15 @@ class ExecutionJobWorker:
if self._thread is not None and self._thread.is_alive():
return False
self._stop.clear()
max_workers = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
self._executor = ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix="execution-job",
)
lane_limits = _lane_slot_limits()
self._executors = {
lane: ThreadPoolExecutor(
max_workers=limit,
thread_name_prefix=f"execution-job-{lane}",
)
for lane, limit in lane_limits.items()
}
self._inflight = {lane: 0 for lane in lane_limits}
self._thread = threading.Thread(
target=self._run,
name="execution-job-consumer",
@@ -83,9 +123,13 @@ class ExecutionJobWorker:
)
self._thread.start()
logger.info(
"执行任务 worker 已启动 lanes={} max_jobs={}",
"执行任务 worker 已启动 lanes={} max_jobs={} lane_slots={}",
",".join(_lane_scopes()),
max_workers,
_env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
),
lane_limits,
)
return True
@@ -93,44 +137,66 @@ class ExecutionJobWorker:
self._stop.set()
with self._lock:
thread = self._thread
executor = self._executor
executors = list(self._executors.values())
self._thread = None
self._executor = None
self._executors = {}
if thread is not None and thread.is_alive():
thread.join(timeout=5)
if executor is not None:
for executor in executors:
executor.shutdown(wait=True, cancel_futures=True)
def _run(self) -> None:
futures: set[Future] = set()
futures: dict[Future, str] = {}
max_jobs = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
lane_limits = _lane_slot_limits()
poll_seconds = _env_positive_int(
"EXECUTION_WORKER_POLL_SECONDS",
DEFAULT_POLL_SECONDS,
)
while not self._stop.is_set():
futures = {future for future in futures if not future.done()}
executor = self._executor
if executor is None:
break
slots = max_jobs - len(futures)
if slots > 0:
# 回收已完成的 job,同时把 lane 的在途计数减回来。
for future in [item for item in futures if item.done()]:
lane = futures.pop(future)
self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1)
try:
jobs = claim_execution_jobs(
lane_scopes=_lane_scopes(),
owner=self._owner,
limit=slots,
future.result()
except Exception: # noqa: BLE001 - 结果已落库,这里只消费异常
pass
executors = self._executors
if not executors:
break
slots = max_jobs - sum(self._inflight.values())
if slots > 0:
# 履约优先:先把 fulfillment 的槽填满,登录只用剩下的。
# 登录批次等邮箱验证码时可能持槽 25 分钟,绝不能把履约饿死。
for lane in _lane_claim_order():
lane_free = lane_limits.get(lane, 0) - self._inflight.get(
lane, 0
)
except Exception: # noqa: BLE001 - 消费循环必须存活
logger.exception("领取执行任务失败")
jobs = []
for job in jobs:
futures.add(executor.submit(self._run_job, job.id))
take = min(slots, lane_free)
if take <= 0:
continue
try:
jobs = claim_execution_jobs(
lane_scopes=(lane,),
owner=self._owner,
limit=take,
)
except Exception: # noqa: BLE001 - 消费循环必须存活
logger.exception("领取执行任务失败 lane={}", lane)
jobs = []
executor = executors.get(lane)
for job in jobs:
if executor is None:
break
self._inflight[lane] = self._inflight.get(lane, 0) + 1
futures[executor.submit(self._run_job, job.id)] = lane
slots -= len(jobs)
if futures:
wait(futures, timeout=poll_seconds)
wait(list(futures), timeout=poll_seconds)
else:
self._stop.wait(poll_seconds)
@@ -297,6 +363,7 @@ def execution_job_worker_status() -> dict[str, Any]:
return {
"running": bool(thread and thread.is_alive()),
"lanes": list(_lane_scopes()),
"lane_slots": _lane_slot_limits(),
"max_jobs": _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,