diff --git a/README.md b/README.md index 5c63cf4..4e284ce 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.21)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.22)。 ## 能做什么 diff --git a/pyproject.toml b/pyproject.toml index 27be495..51598a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.21" +version = "0.4.22" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_account_capability_refresh_job.py b/tests/test_account_capability_refresh_job.py index b776b54..937a0ae 100644 --- a/tests/test_account_capability_refresh_job.py +++ b/tests/test_account_capability_refresh_job.py @@ -671,3 +671,64 @@ def test_multi_commodity_refresh_handles_missing_and_due_states(db): now=NOW, ) assert {row.id for row in selected} == {missing_one.id, due_one.id} + + +def test_capability_refresh_tier0_fast_path_and_fallback_order(db): + from web.backend.services.platform_fulfillment.account_selector import ( + capability_refresh_candidate_accounts, + ) + + user = User( + username="cap-tier-order", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.flush() + + t0_never_queried = _account(db, "cap-t0-null") + t0_never_queried.overview_queried_at = None + t0_older = _account(db, "cap-t0-older") + t0_older.overview_queried_at = NOW - timedelta(days=3) + t1_bound = _account(db, "cap-t1-bound") + t1_bound.role_bind_status = "bound" + t2_leased = _account(db, "cap-t2-leased") + db.flush() + db.add( + AccountLease( + account_id=t2_leased.id, + holder_user_id=user.id, + scope="elite", + purpose="platform_fulfillment", + status="active", + ) + ) + for acc in (t0_never_queried, t0_older, t1_bound, t2_leased): + _state(db, acc, commodity_id="C1", valid_until=NOW - timedelta(minutes=1)) + db.commit() + + # limit=2 时直接由 Tier-0 命中返回,顺序严格为 never_queried -> older + top2 = capability_refresh_candidate_accounts( + db, + commodity_ids=["C1"], + scope="elite", + limit=2, + now=NOW, + ) + assert [row.id for row in top2] == [t0_never_queried.id, t0_older.id] + + # limit=4 时自动回退补齐 bound 与 leased 档,全局顺序不变 + all4 = capability_refresh_candidate_accounts( + db, + commodity_ids=["C1"], + scope="elite", + limit=4, + now=NOW, + ) + assert [row.id for row in all4] == [ + t0_never_queried.id, + t0_older.id, + t1_bound.id, + t2_leased.id, + ] diff --git a/tests/test_account_supply_service.py b/tests/test_account_supply_service.py index 00342d3..43549c5 100644 --- a/tests/test_account_supply_service.py +++ b/tests/test_account_supply_service.py @@ -938,3 +938,80 @@ def test_valid_ck_older_than_24h_is_still_a_sync_candidate(db): result = enqueue_supply_replenishment(db, now=NOW, max_per_target=10) assert result.queued == 1 + + +def test_elite_capability_projection_lifecycle_and_global_totals(db): + from web.backend.services.account_capability_service import ( + invalidate_account_commodity_states, + mark_commodity_exchanged, + record_account_commodity_state, + sync_account_goods_states, + ) + + acc_sync = _account("proj-sync", points=400) + acc_limited = _account("proj-limited", points=0) + db.add_all([acc_sync, acc_limited]) + db.commit() + + sync_account_goods_states( + db, + acc_sync, + [ + {"commodityId": "C1", "status": 0, "storeStatus": 1, "count": 5}, + {"commodityId": "C2", "status": 1, "storeStatus": 1, "count": 5}, + ], + scope="elite", + observed_at=NOW, + ) + record_account_commodity_state( + db, + acc_limited, + commodity_id="C1", + availability="available", + observed_at=NOW, + scope="elite", + ) + db.commit() + db.refresh(acc_sync) + db.refresh(acc_limited) + + assert acc_sync.elite_covered is True + assert acc_sync.elite_eligible_until is not None + assert acc_sync.elite_eligible_until > NOW + assert acc_limited.elite_covered is True + assert acc_limited.elite_eligible_until is not None + + # 兑换唯一可兑换商品后,acc_limited 变为 covered 但不再 eligible + mark_commodity_exchanged( + db, + account_id=acc_limited.id, + commodity_id="C1", + occurred_at=NOW, + scope="elite", + ) + db.commit() + db.refresh(acc_limited) + assert acc_limited.elite_covered is True + assert acc_limited.elite_eligible_until is None + + totals = _global_inventory_totals(db, platform="douyu", scope="elite", now=NOW) + assert totals == { + "high_value": (1, 1, 1), + "ordinary": (1, 0, 0), + } + + # 作废能力后清除可兑换有效期,覆盖仍保留 + invalidate_account_commodity_states( + db, + account_id=acc_sync.id, + reason="ck invalid", + observed_at=NOW, + ) + db.commit() + db.refresh(acc_sync) + assert acc_sync.elite_covered is True + assert acc_sync.elite_eligible_until is None + assert _global_inventory_totals(db, platform="douyu", scope="elite", now=NOW) == { + "high_value": (1, 0, 0), + "ordinary": (1, 0, 0), + } diff --git a/tests/test_migrations.py b/tests/test_migrations.py index db8dbe4..1b55cdb 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261128_0139" +HEAD_REVISION = "20261129_0140" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -68,6 +68,8 @@ _ACCOUNT_PLATFORM_COLUMNS = { "ck_observed_lifetime_seconds": "INTEGER NULL", "ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''", "value_tier": "INTEGER NULL", + "elite_covered": "BOOLEAN NULL", + "elite_eligible_until": "DATETIME NULL", "role_change_official_at": "DATETIME NULL", "last_bind_ok_at": "DATETIME NULL", "role_bind_lock_until": "DATETIME NULL", diff --git a/uv.lock b/uv.lock index 7840e9a..daeba82 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.21" +version = "0.4.22" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index 6d09766..39bc53e 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -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" } } } diff --git a/web/backend/migrations/versions/20261129_0140_add_account_elite_capability_projection.py b/web/backend/migrations/versions/20261129_0140_add_account_elite_capability_projection.py new file mode 100644 index 0000000..71f0551 --- /dev/null +++ b/web/backend/migrations/versions/20261129_0140_add_account_elite_capability_projection.py @@ -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") diff --git a/web/backend/models.py b/web/backend/models.py index 9535023..9686899 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -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( diff --git a/web/backend/services/account_capability_service.py b/web/backend/services/account_capability_service.py index 54eca82..fe115b7 100644 --- a/web/backend/services/account_capability_service.py +++ b/web/backend/services/account_capability_service.py @@ -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", ] diff --git a/web/backend/services/account_supply_service.py b/web/backend/services/account_supply_service.py index e552a65..2820a45 100644 --- a/web/backend/services/account_supply_service.py +++ b/web/backend/services/account_supply_service.py @@ -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) diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index c64975f..d627f30 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -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()