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
+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)