优化(账号自动化): 履约保护登录配额与重登优先级

This commit is contained in:
yml
2026-11-25 22:13:21 +08:00
parent 0943b7a362
commit 9bdd2f4e1a
25 changed files with 1510 additions and 193 deletions
+3 -3
View File
@@ -233,9 +233,9 @@ def register_default_jobs() -> None:
register_job(
JobSpec(
key=LEASE_CK_REFRESH_KEY,
title="租约 CK 到期前刷新",
# 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK,
# 不参与普通失效重登的批次。
title="履约 CK 到期前刷新",
# 处理仍有效、但预测 24h 内到期的全部履约保护账号(预售 / 协作单 / 生效租约),
# 提前续 CK,不参与普通失效重登的批次。
interval_seconds=600,
run_interval_seconds=600,
batch_size=10,
@@ -45,7 +45,7 @@ from ...account_protection_service import (
load_protection_snapshot,
)
from ...account_query_filters import automation_account_filter
from ...account_value import value_tier_expr
from ...account_value import is_high_value_expr, value_tier_expr
from ...account_work_queue import (
WORK_AGING_SECONDS,
active_account_work_exists,
@@ -74,9 +74,8 @@ RETRYABLE_KINDS = frozenset({"email_code", "interrupted", "network"})
# 退避阶梯(分钟):1h → 3h → 12h → 24h,超出取最后一级。
BACKOFF_MINUTES = (60, 180, 720, 1440)
# 自动重登时给 runner 的总时长上限。必须能覆盖斗鱼验证码邮件的最坏投递延迟
# (实测 8~13 分钟),否则等待会被掐断成失败;一轮跑不完的账号反正有退避。
AUTO_MAX_TOTAL_TIME = 1800
# 自动重登时给 runner 的总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。
AUTO_MAX_TOTAL_TIME = 300
# 邮箱配额打满后退避到次日零点,再叠加随机抖动,避免整点齐发。
QUOTA_JITTER_MINUTES = 30
@@ -226,18 +225,22 @@ def _enqueue_due_relogin_work(
max_attempts: int,
protection: ProtectionSnapshot,
limit: int,
account_ids_filter: frozenset[int] | None = None,
) -> int:
"""把已判定失效但尚未进入队列的账号补成持久工作项。"""
accounts = build_select_query(
query = build_select_query(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
apply_limit=False,
).filter(
~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN)
).limit(max(1, limit)).all()
).filter(~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN))
if account_ids_filter is not None:
if not account_ids_filter:
return 0
query = query.filter(Account.id.in_(account_ids_filter))
accounts = query.limit(max(1, limit)).all()
for account in accounts:
priority = 10 if int(account.id) in protection.relogin_ids else 30
enqueue_account_work(
@@ -314,6 +317,28 @@ def _claim_relogin_work(
limit: int,
) -> list[AccountWorkItem]:
"""从持久队列领取重登任务,而不是每轮重新从账号表直接选执行对象。"""
relogin_ids = protection.relogin_ids
if relogin_ids:
# 先把已在队列但优先级仍为普通档的保护账号同步到 10,
# 防止先失效、后进保护组的账号一直排在后面。
db.query(AccountWorkItem).filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.account_id.in_(relogin_ids),
AccountWorkItem.priority > 10,
).update({AccountWorkItem.priority: 10}, synchronize_session=False)
# 履约关系结束后必须收回上一轮提升过的优先级,否则历史保护账号会
# 一直以 P0 档排在普通库存前面。
demote_query = db.query(AccountWorkItem).filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.priority == 10,
)
if relogin_ids:
demote_query = demote_query.filter(
~AccountWorkItem.account_id.in_(relogin_ids)
)
demote_query.update({AccountWorkItem.priority: 30}, synchronize_session=False)
eligible_ids = build_select_query(
db,
job,
@@ -322,42 +347,58 @@ def _claim_relogin_work(
protection=protection,
apply_limit=False,
).with_entities(Account.id)
ordering: list[Any] = []
if relogin_ids:
# P0 履约保护目标绝对优先:即使普通账号已积压超 30 分钟,
# 也绝不允许通过 aging 插队到保护账号前面。
ordering.append(
case((AccountWorkItem.account_id.in_(relogin_ids), 0), else_=1)
)
# P2 高价值(第 1、2 档)优先于 P3 普通账号,aging 仅在同档内部防饿死。
ordering.extend(
[
case((is_high_value_expr(now=now), 0), else_=1),
case(
(
AccountWorkItem.due_at
<= now - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
]
)
account_ids = [
int(account_id)
for (account_id,) in (
db.query(AccountWorkItem.account_id)
.join(Account, Account.id == AccountWorkItem.account_id)
.filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.due_at <= now,
AccountWorkItem.account_id.in_(eligible_ids),
)
.order_by(
case(
(
AccountWorkItem.due_at
<= now - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
)
.order_by(*ordering)
.limit(max(1, limit))
.all()
)
]
if not account_ids:
return []
return claim_account_work(
claimed = claim_account_work(
db,
work_types=(WORK_LOGIN_RELOGIN,),
account_ids=tuple(account_ids),
limit=limit,
now=now,
)
order_index = {account_id: index for index, account_id in enumerate(account_ids)}
claimed.sort(key=lambda item: order_index.get(int(item.account_id), len(order_index)))
return claimed
def _load_batch_state(
@@ -486,8 +527,10 @@ def evaluate_failure_circuit(
counters: dict[str, int],
config: dict[str, Any],
) -> tuple[bool, int, float]:
"""评估硬失败率;邮箱配额满属于预期供给限制,不计入熔断。"""
"""评估硬失败率;预算跳过和邮箱配额满都不属于真实失败样本。"""
scanned = max(0, int(counters.get("scanned", 0) or 0))
skipped = max(0, int(counters.get("skipped", 0) or 0))
attempted = max(0, scanned - skipped)
invalid = max(0, int(counters.get("invalid", 0) or 0))
email_quota = max(0, int(counters.get("email_quota", 0) or 0))
hard_failures = max(0, invalid - email_quota)
@@ -505,8 +548,8 @@ def evaluate_failure_circuit(
)
threshold = raw_ratio / 100 if raw_ratio > 1 else raw_ratio
threshold = max(0.0, min(threshold, 1.0))
ratio = hard_failures / scanned if scanned else 0.0
return scanned >= minimum and ratio > threshold, hard_failures, ratio
ratio = hard_failures / attempted if attempted else 0.0
return attempted >= minimum and ratio > threshold, hard_failures, ratio
def resolve_failure_circuit_config(
@@ -544,7 +587,7 @@ def _recent_relogin_success(
.filter(
LoginAttempt.quota_day >= start_day,
LoginAttempt.category.in_(
("relogin_high_value", "relogin_ordinary")
("relogin_high_value", "relogin_ordinary", "relogin_protected")
),
)
.group_by(LoginAttempt.status, LoginAttempt.failure_kind)
@@ -701,6 +744,17 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
now=now,
pending=pending,
)
if protection.relogin_ids:
# 先把尚未入队的到期履约保护账号补进队列,避免被既有普通积压挡住。
_enqueue_due_relogin_work(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
limit=adaptive.batch_size,
account_ids_filter=protection.relogin_ids,
)
work_items = _claim_relogin_work(
db,
job,
@@ -773,6 +827,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
concurrency=max(min(int(job.concurrency or 3), 8), 1),
mode="relogin",
trigger_source="automation",
batch_max_seconds=0.0,
)
batch_id = runner.batch_id
try:
@@ -839,6 +894,8 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
parts.append(f"硬失败 {hard_failures}({hard_failure_ratio:.0%})")
if paused:
parts.append("失败率过高,已自动暂停作业")
if counters.get("skipped"):
parts.append(f"预算/预检跳过 {counters['skipped']}")
if adaptive.action != "hold":
parts.append(
f"批量策略 {adaptive.previous_batch_size}->{adaptive.batch_size}"
@@ -850,7 +907,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
"invalid": counters["invalid"],
"relogin_started": counters["scanned"],
"relogin_success": counters["valid"],
"skipped": 0,
"skipped": counters.get("skipped", 0),
"message": ",".join(parts),
"detail": {
"batch_id": batch_id,
@@ -902,6 +959,7 @@ def settle_results(
"manual": 0,
"retry": 0,
"email_quota": 0,
"skipped": 0,
}
for account_id in account_ids:
entry = fresh.get(account_id)
@@ -917,7 +975,7 @@ def settle_results(
due_at=retry_at,
reason="自动重登未产生账号任务,重新排队",
)
counters["retry"] += 1
counters["skipped"] += 1
continue
account, task = entry
if task.attempt_status == "success":
@@ -925,6 +983,24 @@ def settle_results(
# 重登成功:清退避痕迹 + 重算状态(与人工登录成功同一套语义)
on_login_success(db, account, occurred_at=now)
continue
if task.attempt_status == "skipped":
counters["skipped"] += 1
# 被预算/槽位跳过不是失败:绝不加 relogin_attempts、不转人工,
# 只保留在队列中等待下一轮重试。
skip_message = task.attempt_message or "本轮未执行,留待下一轮"
delay = (
timedelta(hours=1)
if "今日登录尝试上限" in skip_message
else timedelta(minutes=5)
)
reschedule_account_work_type(
db,
account_id=int(account.id),
work_type=WORK_LOGIN_RELOGIN,
due_at=now + delay,
reason=skip_message,
)
continue
counters["invalid"] += 1
kind = classify_failure(task.attempt_message)
@@ -1,11 +1,12 @@
"""租约账号 CK 到期前刷新(P1)。
"""履约保护账号 CK 到期前刷新(P1)。
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但租约账号如果等到
失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
24 小时**,对仍持有有效 CK 的生效租约账号做一次主动登录,延长 CK 生命周期。
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但履约保护账号如果
等到失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
24 小时**,对仍持有有效 CK 的履约保护账号做一次主动登录,延长 CK 生命周期。
范围:
- 预售履约任务分配的账号、进行中的斗鱼外部协作单绑定账号;
- `account_leases.status=active` 且 purpose 为 `platform_fulfillment` / `douyu_collab`;
- `ck_check_status=valid`、有 Cookie、可自动管理、没有在途登录;
- 预测到期时间 <= now + 24h(`ck_expected_expires_at` 或 `cookie_updated_at + 7d`);
@@ -23,18 +24,18 @@ from typing import Any
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, User
from ....models import Account, AutomationJob, User
from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
from ...account_protection_service import load_protection_snapshot
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 到期前刷新"
# 单账号总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。
LEASE_MAX_TOTAL_TIME = 300
TITLE = "履约 CK 到期前刷新"
REFRESH_BEFORE = timedelta(hours=24)
@@ -55,15 +56,17 @@ def due_lease_account_query(
db: Session,
now: datetime | None = None,
):
"""到期前 24h 的租约账号查询(执行和测试共用)。"""
"""到期前 24h 的履约保护账号查询(预售 / 协作单 / 生效租约共用)。"""
moment = now or datetime.now(UTC)
cutoff = moment + REFRESH_BEFORE
protection = load_protection_snapshot(db)
relogin_ids = protection.relogin_ids
if not relogin_ids:
return db.query(Account).filter(Account.id == -1)
return (
db.query(Account)
.join(AccountLease, AccountLease.account_id == Account.id)
.filter(
AccountLease.status == "active",
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
Account.id.in_(relogin_ids),
Account.ck_check_status == "valid",
Account.cookie_updated_at.isnot(None),
automation_account_filter(cookie_operable=True),
@@ -79,7 +82,12 @@ def due_lease_account_query(
Account.relogin_next_at <= moment,
),
)
.order_by(Account.cookie_updated_at.asc(), Account.id.asc())
.order_by(
Account.ck_expected_expires_at.is_(None).asc(),
Account.ck_expected_expires_at.asc(),
Account.cookie_updated_at.asc(),
Account.id.asc(),
)
)