perf(fulfillment): 优化能力刷新候选查询并新增精英能力投影

This commit is contained in:
yml
2026-11-29 13:06:54 +08:00
parent 2ea105a924
commit be7146a9ef
12 changed files with 548 additions and 54 deletions
@@ -7,6 +7,7 @@
from __future__ import annotations
import os
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -70,6 +71,58 @@ def _apply_commodity_state_values(
return changed
def refresh_account_elite_capability_projection(
db: Session,
*,
account_id: int,
account: Account | None = None,
states: Iterable[AccountCommodityState] | None = None,
) -> None:
"""同步维护账号表上的精英域覆盖与可兑换有效期投影。"""
target = account if account is not None else db.get(Account, int(account_id))
if target is None:
return
if states is not None:
covered = any(row.observed_at is not None for row in states)
eligible_until = max(
(
row.valid_until
for row in states
if row.account_eligibility == ACCOUNT_ELIGIBILITY_ELIGIBLE
and row.offer_state in (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
and row.valid_until is not None
),
default=None,
)
else:
covered = bool(
db.query(AccountCommodityState.id)
.filter(
AccountCommodityState.account_id == int(account_id),
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == "elite",
AccountCommodityState.observed_at.isnot(None),
)
.first()
)
eligible_until = (
db.query(func.max(AccountCommodityState.valid_until))
.filter(
AccountCommodityState.account_id == int(account_id),
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == "elite",
AccountCommodityState.account_eligibility == ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.offer_state.in_(
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
),
AccountCommodityState.valid_until.isnot(None),
)
.scalar()
)
_set_if_changed(target, "elite_covered", covered)
_set_if_changed(target, "elite_eligible_until", eligible_until)
def _env_positive_int(name: str, default: int) -> int:
try:
value = int(os.getenv(name, str(default)))
@@ -606,6 +659,13 @@ def sync_account_goods_states(
state.updated_at = moment
changed += 1
if scope == "elite":
refresh_account_elite_capability_projection(
db,
account_id=int(account.id),
account=account,
states=by_commodity.values(),
)
db.flush()
return changed
@@ -707,6 +767,13 @@ def record_account_commodity_state(
state.next_check_at = state.valid_until
state.updated_at = moment
db.flush()
if scope == "elite" and account.id is not None:
refresh_account_elite_capability_projection(
db,
account_id=int(account.id),
account=account,
)
db.flush()
return state
@@ -758,6 +825,12 @@ def mark_commodity_exchanged(
state.error_code = ""
state.updated_at = moment
db.flush()
if scope == "elite":
refresh_account_elite_capability_projection(
db,
account_id=int(account_id),
)
db.flush()
def invalidate_account_commodity_states(
@@ -789,6 +862,16 @@ def invalidate_account_commodity_states(
synchronize_session=False,
)
)
target = db.get(Account, int(account_id))
if target is not None:
if target.elite_covered is None:
refresh_account_elite_capability_projection(
db,
account_id=int(account_id),
account=target,
)
else:
_set_if_changed(target, "elite_eligible_until", None)
return int(changed or 0)
@@ -911,5 +994,6 @@ __all__ = [
"invalidate_account_commodity_states",
"mark_commodity_exchanged",
"record_account_commodity_state",
"refresh_account_elite_capability_projection",
"sync_account_goods_states",
]
+65 -12
View File
@@ -6,7 +6,7 @@ import os
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from sqlalchemy import and_, case, func, select
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
@@ -202,19 +202,76 @@ def _global_inventory_totals(
) -> dict[str, tuple[int, int, int]]:
"""一次算出某作用域下高价值/普通的覆盖、可兑换和可分配数量。
全局目标不指定 commodity_id,因此不能用
``ix_account_commodity_match`` 的 commodity_id 前缀。固定拆成两条 SQL:
1. accounts + EXISTS:计算 covered;
2. account_commodity_states JOIN accounts:同时计算 available/allocatable。
第二条走 ``ix_account_commodity_global_available``,避免先物化全部商品状态。
精英域优先消费 ``accounts`` 上的 ``elite_covered`` / ``elite_eligible_until``
投影(彻底避开 68 万+ 商品明细全扫描与 ``COUNT(DISTINCT)`` 临时表);
未投影行(``elite_covered IS NULL``)自动回退子查询,兼容灰度与裸测夹具。
"""
value_class = case(
(is_high_value_expr(now=now), VALUE_HIGH),
else_=VALUE_ORDINARY,
)
base_filter = _base_account_filter()
totals = {
VALUE_HIGH: [0, 0, 0],
VALUE_ORDINARY: [0, 0, 0],
}
if platform == "douyu" and scope == "elite":
covered_filter = or_(
Account.elite_covered.is_(True),
and_(
Account.elite_covered.is_(None),
_global_state_exists_for(platform=platform, scope=scope),
),
)
covered_rows = (
db.query(value_class, func.count(Account.id))
.select_from(Account)
.filter(base_filter, covered_filter)
.group_by(value_class)
.all()
)
for class_name, covered in covered_rows:
totals[str(class_name)][0] = int(covered or 0)
has_fresh_eligible = or_(
and_(
Account.elite_covered.isnot(None),
Account.elite_eligible_until.isnot(None),
Account.elite_eligible_until > now,
),
and_(
Account.elite_covered.is_(None),
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == platform,
AccountCommodityState.scope == scope,
_fresh_eligible_filter(now),
)
.exists(),
),
)
allocatable_flag = case((_allocatable_filter(now), 1), else_=0)
available_rows = (
db.query(
value_class,
func.count(Account.id),
func.sum(allocatable_flag),
)
.select_from(Account)
.filter(base_filter, has_fresh_eligible)
.group_by(value_class)
.all()
)
for class_name, available, allocatable in available_rows:
bucket = totals[str(class_name)]
bucket[1] = int(available or 0)
bucket[2] = int(allocatable or 0)
return {
class_name: (values[0], values[1], values[2])
for class_name, values in totals.items()
}
covered_rows = (
db.query(value_class, func.count(Account.id))
@@ -226,10 +283,6 @@ def _global_inventory_totals(
.group_by(value_class)
.all()
)
totals = {
VALUE_HIGH: [0, 0, 0],
VALUE_ORDINARY: [0, 0, 0],
}
for class_name, covered in covered_rows:
totals[str(class_name)][0] = int(covered or 0)
@@ -623,18 +623,103 @@ def capability_candidate_accounts(
]
def _refresh_tiebreaker_order_by() -> tuple[Any, ...]:
return (
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
)
def _refresh_priority_tier0_filter(now: datetime):
return and_(
~active_lease_exists(),
~active_collab_order_exists(),
role_change_ready_filter(now),
Account.role_bind_status == "unbound",
)
def _refresh_candidate_order_by(now: datetime) -> tuple[Any, ...]:
return (
case((active_lease_exists(), 1), else_=0),
case((active_collab_order_exists(), 1), else_=0),
case((role_change_ready_filter(now), 0), else_=1),
case((Account.role_bind_status == "unbound", 0), else_=1),
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
*_refresh_tiebreaker_order_by(),
)
def _pool_refresh_base_query(
db: Session,
*,
excluded_ids: tuple[int, ...] = (),
):
query = db.query(Account).filter(
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
)
active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC)
if active_work_ids is None:
query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC))
elif active_work_ids:
query = query.filter(~Account.id.in_(active_work_ids))
if excluded_ids:
query = query.filter(~Account.id.in_(excluded_ids))
return query
def _select_refresh_candidates_tier0_first(
db: Session,
*,
base_pool,
condition,
moment: datetime,
limit: int,
) -> list[Account]:
"""优先只取最高优先级窗口账号再校验商品明细,避免全池 1.1 万账号逐行扫 45 条商品。"""
effective_limit = max(1, min(int(limit), 100))
window_limit = max(effective_limit * 4, 200)
tier0_ids = [
int(account_id)
for (account_id,) in (
base_pool.with_entities(Account.id)
.filter(_refresh_priority_tier0_filter(moment))
.order_by(*_refresh_tiebreaker_order_by())
.limit(window_limit)
.all()
)
]
if not tier0_ids:
return (
base_pool.filter(condition)
.order_by(*_refresh_candidate_order_by(moment))
.limit(effective_limit)
.all()
)
collected = (
db.query(Account)
.filter(Account.id.in_(tier0_ids), condition)
.order_by(*_refresh_tiebreaker_order_by())
.limit(effective_limit)
.all()
)
if len(collected) >= effective_limit:
return collected[:effective_limit]
remaining = effective_limit - len(collected)
rest = (
base_pool.filter(~Account.id.in_(tier0_ids), condition)
.order_by(*_refresh_candidate_order_by(moment))
.limit(remaining)
.all()
)
return [*collected, *rest]
def capability_refresh_candidate_accounts(
db: Session,
*,
@@ -708,25 +793,17 @@ def capability_refresh_candidate_accounts(
< len(commodities)
)
query = db.query(Account).filter(
or_(
state_due,
and_(~fresh_storehome, missing_state),
),
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
base_pool = _pool_refresh_base_query(db)
needs_refresh = or_(
state_due,
and_(~fresh_storehome, missing_state),
)
active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC)
if active_work_ids is None:
query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC))
elif active_work_ids:
query = query.filter(~Account.id.in_(active_work_ids))
return (
query.order_by(*_refresh_candidate_order_by(moment))
.limit(max(1, min(int(limit), 100)))
.all()
return _select_refresh_candidates_tier0_first(
db,
base_pool=base_pool,
condition=needs_refresh,
moment=moment,
limit=limit,
)
@@ -798,23 +875,17 @@ def storehome_refresh_candidate_accounts(
)
for group in preferred_groups
]
query = db.query(Account).filter(
~fresh_storehome,
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
)
active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC)
if active_work_ids is None:
query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC))
elif active_work_ids:
query = query.filter(~Account.id.in_(active_work_ids))
if excluded_ids:
query = query.filter(~Account.id.in_(excluded_ids))
order_by: list[Any] = []
if preferred_exprs:
order_by.append(case((or_(*preferred_exprs), 0), else_=1))
base_pool = _pool_refresh_base_query(db, excluded_ids=excluded_ids)
if not preferred_exprs:
return _select_refresh_candidates_tier0_first(
db,
base_pool=base_pool,
condition=~fresh_storehome,
moment=moment,
limit=limit,
)
query = base_pool.filter(~fresh_storehome)
order_by: list[Any] = [case((or_(*preferred_exprs), 0), else_=1)]
order_by.extend(_refresh_candidate_order_by(moment))
return query.order_by(*order_by).limit(max(1, min(int(limit), 100))).all()