perf(platform): 按优先级分层查询账号候选池

This commit is contained in:
yml
2026-11-21 15:30:54 +08:00
parent e1d979a296
commit 3b0c48534d
5 changed files with 130 additions and 20 deletions
@@ -201,26 +201,69 @@ def live_candidate_accounts(
query = query.filter(~exchanged)
if empty_only:
query = query.filter(Account.role_bind_status == "unbound")
order_by = [
case((Account.ck_check_status == "valid", 0), else_=1),
case((Account.status == "active", 0), else_=1),
case((Account.elite_opened.is_(True), 0), else_=1),
case(
(Account.points >= max(0, int(required_points)), 0),
else_=1,
),
Account.ck_checked_at.is_(None).desc(),
Account.ck_checked_at.asc(),
Account.points.asc(),
Account.id.asc(),
]
if prefer_unbound:
order_by.insert(0, case((Account.role_bind_status == "unbound", 0), else_=1))
return (
query.order_by(*order_by)
.limit(max(1, min(int(limit), 100)))
.all()
effective_limit = max(1, min(int(limit), 100))
required = max(0, int(required_points))
# Keep the old priority order, but turn it into disjoint indexed queries.
# A single ORDER BY CASE forced MySQL to sort the whole account pool; each
# tier below can stop as soon as it has enough rows.
tiers = (
(True, "active", True, True),
(True, "active", True, False),
(True, "active", False, True),
(True, "active", False, False),
(True, "not_active", True, True),
(True, "not_active", True, False),
(True, "not_active", False, True),
(True, "not_active", False, False),
(False, "active", True, True),
(False, "active", True, False),
(False, "active", False, True),
(False, "active", False, False),
(False, "not_active", True, True),
(False, "not_active", True, False),
(False, "not_active", False, True),
(False, "not_active", False, False),
)
rows: list[Account] = []
for ck_valid, status_active, elite_opened, points_enough in tiers:
if ck_valid:
tier_query = query.filter(Account.ck_check_status == "valid")
else:
tier_query = query.filter(Account.ck_check_status != "valid")
if status_active == "active":
tier_query = tier_query.filter(Account.status == "active")
else:
tier_query = tier_query.filter(Account.status != "active")
tier_query = tier_query.filter(
Account.elite_opened.is_(True)
if elite_opened
else Account.elite_opened.is_not(True)
)
tier_query = tier_query.filter(
Account.points >= required
if points_enough
else or_(Account.points.is_(None), Account.points < required)
)
order_by = [
Account.ck_checked_at.is_(None).desc(),
Account.ck_checked_at.asc(),
Account.points.asc(),
Account.id.asc(),
]
if prefer_unbound:
order_by.insert(
0,
case((Account.role_bind_status == "unbound", 0), else_=1),
)
rows.extend(
tier_query.order_by(*order_by)
.limit(effective_limit - len(rows))
.all()
)
if len(rows) >= effective_limit:
break
return rows
def capability_candidate_accounts(