修复(账号自动化): 租约 CK 续期不再冒充「首次登录」,补齐等待预算

排查「首次登录都关掉了为什么还在一直登录」时发现:

- 真正在跑登录的是 lease_ck_refresh(租约 CK 续期,每 600 秒一轮),
  account_onboarding 确实已关;两者都显示成「自动化·首次登录」,所以很难分辨
- 根因是分类逻辑:trigger_source=automation 一律落 onboarding。但租约续期的
  账号本来就有 CK,只是租约到期前提前续一次,不是首次登录
- 这批租约账号全部「等待验证码超时」失败,因为生产跑的还是旧镜像(60 秒
  等待窗口),而且 lease_ck_refresh 的单账号总时长硬编码 240 秒,连新的
  900 秒等待窗口都会被掐断

改动:

- 新增 lease_refresh 分类:页面显示「自动化·租约CK续期」,日预算归到普通
  重登(不再占用「首次登录」的 150/天额度)
- lease_ck_refresh 单账号总时长 240 → 1800 秒,覆盖实测 8~13 分钟的投递延迟
- 登录预算建议的成功率样本纳入 lease_refresh

验证:1728 passed / 6 skipped,前端 tsc -b 通过,pyright 生产代码 0 错误
This commit is contained in:
yml
2026-11-25 20:04:59 +08:00
parent 9473645548
commit da85373884
8 changed files with 94 additions and 2 deletions
+50
View File
@@ -37,7 +37,9 @@ from web.backend.services.automation.jobs import ck_health
from web.backend.services.douyu_account_state import DouyuLiveAccountState
from web.backend.services.douyu_read_gateway import StorehomeSnapshot
from web.backend.services.login_quota_service import (
CATEGORY_LEASE_REFRESH,
CATEGORY_MANUAL,
classify_login_category,
finish_login_attempt,
reserve_login_attempt,
)
@@ -354,6 +356,54 @@ def test_missing_storehome_goods_blocks_fulfillment_as_off_shelf():
assert gate[:2] == ("not_available", "commodity_not_offered")
def test_lease_refresh_category_overrides_onboarding(db):
"""租约 CK 续期不能被判成「首次登录」。
这类账号**有 CK**,只是租约到期前提前续一次。以前 trigger_source=automation
一律落 onboarding,页面显示成「自动化·首次登录」,还把租约续期的量算进
「首次登录」的日预算里 —— 排查时极难看出是谁在发起登录。
"""
account = _account("lease-category")
db.add(account)
db.add(
LoginQuotaSetting(
id=1,
daily_attempt_limit=20,
hourly_attempt_limit=10,
per_account_daily_limit=2,
onboarding_daily_limit=1,
relogin_ordinary_daily_limit=10,
manual_daily_limit=10,
)
)
db.commit()
now = datetime.now(UTC).replace(microsecond=0)
assert (
classify_login_category(
account,
mode="login",
trigger_source="automation",
category=CATEGORY_LEASE_REFRESH,
)
== CATEGORY_LEASE_REFRESH
)
decision = reserve_login_attempt(
db,
account=account,
mode="login",
trigger_source="automation",
batch_id="lease-batch",
created_by=None,
now=now,
category=CATEGORY_LEASE_REFRESH,
)
assert decision.allowed
assert decision.attempt is not None
assert decision.attempt.category == CATEGORY_LEASE_REFRESH
def test_login_quota_enforces_per_account_and_hourly_budget(db):
first = _account("quota-first")
second = _account("quota-second")
+4
View File
@@ -126,6 +126,10 @@ def test_run_lease_ck_refresh_calls_login_for_selected_accounts(db, monkeypatch)
assert calls["kwargs"]["account_ids"] == [due.id]
assert calls["kwargs"]["mode"] == "login"
# 租约账号**有 CK**,不能被判成"首次登录",否则页面标签和日预算都错位
assert calls["kwargs"]["category"] == "lease_refresh"
# 单账号总时长要能覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟)
assert calls["kwargs"]["max_total_time"] >= 1800
assert result["scanned"] == 1
assert result["success"] == 1
assert result["batchIds"] == ["lease-batch"]
@@ -27,8 +27,13 @@ from ....models import Account, AccountLease, AutomationJob, User
from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
from ...account_query_filters import automation_account_filter
from ...login_automation import run_login_batch_with_fallback
from ...login_quota_service import CATEGORY_LEASE_REFRESH
JOB_KEY = "lease_ck_refresh"
# 单账号总时长上限:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟),
# 否则等待会被掐断成"等待验证码超时",租约账号一批批地失败。
LEASE_MAX_TOTAL_TIME = 1800
TITLE = "租约 CK 到期前刷新"
REFRESH_BEFORE = timedelta(hours=24)
@@ -115,7 +120,11 @@ def run_lease_ck_refresh(db: Session, job: AutomationJob) -> dict[str, Any]:
mode="login",
created_by=system_user_id,
concurrency=max(1, min(int(job.concurrency or 3), 8)),
max_total_time=240,
max_total_time=LEASE_MAX_TOTAL_TIME,
# 这些账号**有 CK**,是租约到期前提前续期,不是首次登录。
# 不显式指定分类的话会被判成 onboarding,页面显示成"自动化·首次登录",
# 还把租约续期的量算进「首次登录」的日预算里。
category=CATEGORY_LEASE_REFRESH,
)
_settle_outcome(accounts, outcome, now=now)
db.commit()
+5
View File
@@ -107,6 +107,7 @@ def run_login_batch(
concurrency: int = 3,
max_total_time: int | None = None,
max_login_retries: int = DEFAULT_MAX_RETRIES,
category: str = "",
) -> str:
"""同步跑一个登录批次,返回 batch_id;runner 使用独立会话。"""
proxy = db.query(ProxyConfig).first()
@@ -130,6 +131,7 @@ def run_login_batch(
api_strategy=api_strategy,
mode=mode,
trigger_source="automation",
category=category,
)
batch_id = runner.batch_id
runner.run()
@@ -177,6 +179,7 @@ def run_login_batch_with_fallback(
concurrency: int = 3,
max_total_time: int | None = None,
max_login_retries: int = DEFAULT_MAX_RETRIES,
category: str = "",
) -> LoginBatchOutcome:
"""先走 wgapi;仅对 email_code 失败账号切 iframe 重试一次。
@@ -194,6 +197,7 @@ def run_login_batch_with_fallback(
concurrency=concurrency,
max_total_time=max_total_time,
max_login_retries=max_login_retries,
category=category,
)
outcome.batch_ids.append(primary_batch)
primary = collect_batch_results(primary_batch)
@@ -219,6 +223,7 @@ def run_login_batch_with_fallback(
concurrency=concurrency,
max_total_time=max_total_time,
max_login_retries=max_login_retries,
category=category,
)
outcome.fallback_batch_ids.append(fallback_batch)
fallback = collect_batch_results(fallback_batch)
@@ -51,7 +51,12 @@ def _recent_login_outcomes(
.filter(
LoginAttempt.quota_day >= start_day,
LoginAttempt.category.in_(
("onboarding", "relogin_high_value", "relogin_ordinary")
(
"onboarding",
"relogin_high_value",
"relogin_ordinary",
"lease_refresh",
)
),
)
.group_by(LoginAttempt.status, LoginAttempt.failure_kind)
@@ -24,6 +24,10 @@ CATEGORY_ONBOARDING = "onboarding"
CATEGORY_RELOGIN_HIGH = "relogin_high_value"
CATEGORY_RELOGIN_ORDINARY = "relogin_ordinary"
CATEGORY_ACCOUNT_CHECK = "account_check"
#: 租约 CK 续期:账号**已经有 CK**,只是租约到期前提前登录续一次。
#: 必须和「首次登录」分开 —— 两者触发方式都是 automation,但预算归属不同,
#: 页面标签也不同(曾经被显示成"自动化·首次登录",排查时非常误导)。
CATEGORY_LEASE_REFRESH = "lease_refresh"
BUSINESS_TZ = ZoneInfo("Asia/Shanghai")
@@ -48,7 +52,11 @@ def classify_login_category(
mode: str,
trigger_source: str = "manual",
now: datetime | None = None,
category: str = "",
) -> str:
# 调用方显式指定分类时优先用它(例如租约 CK 续期)。
if category:
return category
if mode == "check":
return CATEGORY_ACCOUNT_CHECK
if mode == "relogin":
@@ -160,6 +168,8 @@ def _category_limit(setting: LoginQuotaSetting, category: str) -> int:
CATEGORY_RELOGIN_ORDINARY: int(setting.relogin_ordinary_daily_limit),
CATEGORY_MANUAL: int(setting.manual_daily_limit),
CATEGORY_ACCOUNT_CHECK: int(setting.manual_daily_limit),
# 租约续期本质是「提前重登」,借用普通重登的日预算。
CATEGORY_LEASE_REFRESH: int(setting.relogin_ordinary_daily_limit),
}.get(category, int(setting.daily_attempt_limit))
@@ -172,6 +182,7 @@ def reserve_login_attempt(
batch_id: str,
created_by: int | None,
now: datetime | None = None,
category: str = "",
) -> QuotaDecision:
moment = now or datetime.now(UTC)
quota_day, quota_hour = _bucket(moment)
@@ -182,6 +193,7 @@ def reserve_login_attempt(
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
)
attempt = LoginAttempt(
account_id=int(account.id),
@@ -239,6 +251,7 @@ def reserve_login_attempt(
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
)
if _category_daily_total(db, quota_day, category) >= _category_limit(
setting, category
@@ -328,6 +341,7 @@ def cleanup_orphan_login_attempts(
__all__ = [
"CATEGORY_ACCOUNT_CHECK",
"CATEGORY_LEASE_REFRESH",
"CATEGORY_MANUAL",
"CATEGORY_ONBOARDING",
"CATEGORY_RELOGIN_HIGH",
+4
View File
@@ -513,6 +513,7 @@ class LoginBatchRunner:
api_strategy: str = "wgapi",
mode: str = "login",
trigger_source: str = "manual",
category: str = "",
batch_id: str | None = None,
log_sink: Callable[[dict[str, Any]], None] | None = None,
):
@@ -535,6 +536,8 @@ class LoginBatchRunner:
)
self.api_strategy = create_login_api_strategy(api_strategy)
self.mode = mode if mode in ("login", "check", "relogin") else "login"
# 显式分类覆盖(例如租约 CK 续期):留空时按 mode/trigger 自动判定。
self.category = str(category or "")
self.trigger_source = (
trigger_source
if trigger_source
@@ -1054,6 +1057,7 @@ class LoginBatchRunner:
trigger_source=self.trigger_source,
batch_id=batch_id,
created_by=self.created_by,
category=self.category,
)
if not quota.allowed:
self._push_log(
@@ -54,6 +54,7 @@ const LOGIN_CATEGORY_LABELS: Record<string, string> = {
relogin_ordinary: '普通重登',
manual: '人工登录',
account_check: '账号检测',
lease_refresh: '租约CK续期',
};
function loginSourceLabel(task: LoginTaskItem) {