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
@@ -557,6 +557,10 @@
"20261128_0139_scale_account_recovery_jobs.py": {
"revision": "20261128_0139",
"sha256": "42d1bb6dc3e22738a2f69054089610d42f9f0e06b280221d2554365c704a610f"
},
"20261129_0140_add_account_elite_capability_projection.py": {
"revision": "20261129_0140",
"sha256": "c19909f65b4826cd292176b71481f45eb4c1fb211b1db7923df7e92e54903c6d"
}
}
}
@@ -0,0 +1,125 @@
"""add account elite capability projection columns and backfill
Revision ID: 20261129_0140
Revises: 20261128_0139
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261129_0140"
down_revision: str | None = "20261128_0139"
branch_labels: str | None = None
depends_on: str | None = None
def _has_column(inspector: sa.Inspector, table: str, column: str) -> bool:
return any(col["name"] == column for col in inspector.get_columns(table))
def _has_index(inspector: sa.Inspector, table: str, index_name: str) -> bool:
return any(idx["name"] == index_name for idx in inspector.get_indexes(table))
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("accounts"):
return
if not _has_column(inspector, "accounts", "elite_covered"):
op.add_column(
"accounts",
sa.Column("elite_covered", sa.Boolean(), nullable=True),
)
if not _has_column(inspector, "accounts", "elite_eligible_until"):
op.add_column(
"accounts",
sa.Column("elite_eligible_until", sa.DateTime(), nullable=True),
)
inspector = sa.inspect(bind)
if not _has_index(inspector, "accounts", "ix_accounts_elite_supply"):
op.create_index(
"ix_accounts_elite_supply",
"accounts",
[
"auto_managed",
"ck_check_status",
"status",
"elite_covered",
"elite_eligible_until",
"value_tier",
"id",
],
)
if inspector.has_table("account_commodity_states"):
if bind.dialect.name == "mysql":
op.execute(
sa.text(
"""
UPDATE accounts a
LEFT JOIN (
SELECT
account_id,
MAX(CASE WHEN observed_at IS NOT NULL THEN 1 ELSE 0 END) AS has_observed,
MAX(
CASE
WHEN account_eligibility = 'eligible'
AND offer_state IN ('active', 'before')
AND valid_until IS NOT NULL
THEN valid_until
ELSE NULL
END
) AS eligible_until
FROM account_commodity_states
WHERE platform = 'douyu' AND scope = 'elite'
GROUP BY account_id
) s ON s.account_id = a.id
SET a.elite_covered = COALESCE(s.has_observed, 0),
a.elite_eligible_until = s.eligible_until
"""
)
)
else:
op.execute(
sa.text(
"""
UPDATE accounts
SET elite_covered = CASE
WHEN EXISTS (
SELECT 1 FROM account_commodity_states s
WHERE s.account_id = accounts.id
AND s.platform = 'douyu'
AND s.scope = 'elite'
AND s.observed_at IS NOT NULL
) THEN 1 ELSE 0 END,
elite_eligible_until = (
SELECT MAX(s.valid_until)
FROM account_commodity_states s
WHERE s.account_id = accounts.id
AND s.platform = 'douyu'
AND s.scope = 'elite'
AND s.account_eligibility = 'eligible'
AND s.offer_state IN ('active', 'before')
AND s.valid_until IS NOT NULL
)
"""
)
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("accounts"):
return
if _has_index(inspector, "accounts", "ix_accounts_elite_supply"):
op.drop_index("ix_accounts_elite_supply", table_name="accounts")
if _has_column(inspector, "accounts", "elite_eligible_until"):
op.drop_column("accounts", "elite_eligible_until")
if _has_column(inspector, "accounts", "elite_covered"):
op.drop_column("accounts", "elite_covered")
+17
View File
@@ -153,6 +153,13 @@ class Account(Base):
# 账号价值 1-5 档的后台投影。为空时查询会回退实时 CASE,便于新账号和
# 灰度期间保持正确;生产行由 account_value_projection 作业周期性刷新。
value_tier: Mapped[int | None] = mapped_column(Integer, nullable=True)
# 精英域商品能力摘要投影(elite_covered=None 表示尚未投影,查询回退子查询)。
# 由 account_capability_service 在写入 account_commodity_states 时同步维护,
# 避免全局库存汇总每次扫描全量 68 万+ 商品明细行。
elite_covered: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
elite_eligible_until: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
# 积分**到期时刻**(斗鱼在积分查询里给 `willExpireTime`,只有送礼后的那次查询才有)。
# 积分到期是账号资产的真实减少,但斗鱼不会「通知」你 —— 所以这里记下到期时刻,
# 由作业在到期后补记一条 `points_expire` 事件(否则这个减少在时间线上是空白)。
@@ -307,6 +314,16 @@ class Account(Base):
# 高价值三态的过期判定和待刷新筛选
Index("ix_accounts_high_value_checked_at", "high_value_checked_at"),
Index("ix_accounts_value_tier", "value_tier", "id"),
Index(
"ix_accounts_elite_supply",
"auto_managed",
"ck_check_status",
"status",
"elite_covered",
"elite_eligible_until",
"value_tier",
"id",
),
# 账号池选号:先按自动管理/生命周期过滤,再按 CK、积分和到期时间排序。
# 这条索引避免每次选号都回表扫描全部账号后再排序。
Index(
@@ -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()