"""Advisory login-budget sizing from current inventory and recent outcomes.""" from __future__ import annotations import math from datetime import UTC, datetime, timedelta from typing import Any from sqlalchemy import func from sqlalchemy.orm import Session from ..models import Account, LoginAttempt, LoginQuotaSetting from .account_lifecycle import MANUAL_KINDS, MANUAL_STATES from .account_protection_service import load_protection_snapshot from .account_value import is_high_value_expr CK_AVERAGE_LIFETIME_DAYS = 7.38 RELOGIN_RECOVERY_DAYS = 3 ONBOARDING_RAMP_DAYS = 7 RECENT_WINDOW_DAYS = 7 MIN_RECENT_SAMPLE = 20 DEFAULT_SUCCESS_RATE = 70.0 MIN_EFFECTIVE_SUCCESS_RATE = 35.0 MIN_DAILY_ATTEMPTS = 50 MAX_DAILY_ATTEMPTS = 5000 ASSUMED_ACTIVE_HOURS = 12 def _fit_priority_budgets(limits: list[int], available: int) -> list[int]: """把 P0-P3 预算压进全局可用名额,按优先级从低到高削减。""" fitted = list(limits) excess = max(0, sum(fitted) - max(0, int(available))) for index in range(len(fitted) - 1, -1, -1): if excess <= 0: break cut = min(fitted[index], excess) fitted[index] -= cut excess -= cut return fitted def _automatable_accounts(db: Session): return db.query(Account).filter( Account.auto_managed.is_(True), Account.status.notin_(MANUAL_STATES), ) def _count_high_value(db: Session, query) -> int: return int(query.filter(is_high_value_expr()).count() or 0) def _recent_login_outcomes( db: Session, *, now: datetime, ) -> tuple[int, float]: start_day = now.date() - timedelta(days=RECENT_WINDOW_DAYS - 1) rows = ( db.query( LoginAttempt.status, LoginAttempt.failure_kind, func.count(LoginAttempt.id), ) .filter( LoginAttempt.quota_day >= start_day, LoginAttempt.category.in_( ( "onboarding", "relogin_high_value", "relogin_ordinary", "relogin_protected", "lease_refresh", ) ), ) .group_by(LoginAttempt.status, LoginAttempt.failure_kind) .all() ) success = 0 failed = 0 for status, failure_kind, count in rows: count_value = int(count or 0) if status == "success": success += count_value elif status in {"failed", "error", "stopped"} and failure_kind != "email_quota": failed += count_value sample = success + failed rate = success * 100 / sample if sample else DEFAULT_SUCCESS_RATE return sample, round(rate, 1) def _current_quota(db: Session) -> dict[str, int]: row = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first() if row is None: return { "daily_attempt_limit": 1500, "hourly_attempt_limit": 100, "per_account_daily_limit": 2, "onboarding_daily_limit": 150, "relogin_protected_daily_limit": 500, "lease_refresh_daily_limit": 300, "relogin_high_value_daily_limit": 300, "relogin_ordinary_daily_limit": 500, "manual_daily_limit": 300, "login_concurrency": 3, "failure_pause_ratio": 40, "enabled": True, } return { "daily_attempt_limit": int(row.daily_attempt_limit), "hourly_attempt_limit": int(row.hourly_attempt_limit), "per_account_daily_limit": int(row.per_account_daily_limit), "onboarding_daily_limit": int(row.onboarding_daily_limit), "relogin_protected_daily_limit": int( getattr(row, "relogin_protected_daily_limit", 500) ), "lease_refresh_daily_limit": int( getattr(row, "lease_refresh_daily_limit", 300) ), "relogin_high_value_daily_limit": int( row.relogin_high_value_daily_limit ), "relogin_ordinary_daily_limit": int(row.relogin_ordinary_daily_limit), "manual_daily_limit": int(row.manual_daily_limit), "login_concurrency": int(row.login_concurrency), "failure_pause_ratio": int(row.failure_pause_ratio), "enabled": bool(row.enabled), } def recommend_login_budget( db: Session, *, now: datetime | None = None, ) -> dict[str, Any]: """Return a conservative quota recommendation; never mutate current settings.""" moment = now or datetime.now(UTC) manual_kinds = tuple(sorted(MANUAL_KINDS)) valid_query = _automatable_accounts(db).filter( Account.cookie.isnot(None), Account.cookie != "", Account.ck_check_status == "valid", ) valid_total = int(valid_query.count() or 0) valid_high = _count_high_value(db, valid_query) valid_ordinary = max(0, valid_total - valid_high) invalid_query = _automatable_accounts(db).filter( Account.cookie.isnot(None), Account.cookie != "", Account.ck_check_status == "invalid", Account.relogin_attempts < 2, func.coalesce(Account.relogin_failure_kind, "").notin_(manual_kinds), ) invalid_total = int(invalid_query.count() or 0) invalid_high = _count_high_value(db, invalid_query) invalid_ordinary = max(0, invalid_total - invalid_high) protection = load_protection_snapshot(db) protected_ids = protection.relogin_ids if protected_ids: protected_valid = int( valid_query.filter(Account.id.in_(protected_ids)).count() or 0 ) protected_invalid = int( invalid_query.filter(Account.id.in_(protected_ids)).count() or 0 ) nonprotected_valid_high = int( _count_high_value( db, valid_query.filter(~Account.id.in_(protected_ids)), ) or 0 ) nonprotected_invalid_high = int( _count_high_value( db, invalid_query.filter(~Account.id.in_(protected_ids)), ) or 0 ) else: protected_valid = 0 protected_invalid = 0 nonprotected_valid_high = valid_high nonprotected_invalid_high = invalid_high nonprotected_valid = max(0, valid_total - protected_valid) nonprotected_invalid = max(0, invalid_total - protected_invalid) imported_total = int( _automatable_accounts(db).filter(Account.status == "imported").count() or 0 ) sample, recent_success_rate = _recent_login_outcomes(db, now=moment) effective_rate = ( recent_success_rate if sample >= MIN_RECENT_SAMPLE else DEFAULT_SUCCESS_RATE ) effective_rate = max(effective_rate, MIN_EFFECTIVE_SUCCESS_RATE) / 100 expected_daily_invalid = valid_total / CK_AVERAGE_LIFETIME_DAYS recovery_pressure = invalid_total / RELOGIN_RECOVERY_DAYS onboarding_pressure = imported_total / ONBOARDING_RAMP_DAYS required_success = math.ceil( expected_daily_invalid + recovery_pressure + onboarding_pressure ) core_attempts = math.ceil(required_success / effective_rate) manual_reserve = max(30, math.ceil(core_attempts * 0.1)) onboarding_attempts = math.ceil(onboarding_pressure / effective_rate) nonprotected_relogin_pressure_high = ( nonprotected_valid_high / CK_AVERAGE_LIFETIME_DAYS + nonprotected_invalid_high / RELOGIN_RECOVERY_DAYS ) nonprotected_relogin_pressure_total = ( nonprotected_valid / CK_AVERAGE_LIFETIME_DAYS + nonprotected_invalid / RELOGIN_RECOVERY_DAYS ) high_share = ( nonprotected_relogin_pressure_high / nonprotected_relogin_pressure_total if nonprotected_relogin_pressure_total > 0 else 0.5 ) nonprotected_relogin_attempts = math.ceil( nonprotected_relogin_pressure_total / effective_rate ) relogin_high_limit = max( 0, math.ceil(nonprotected_relogin_attempts * high_share), ) relogin_ordinary_limit = max( 0, nonprotected_relogin_attempts - relogin_high_limit, ) relogin_protected_limit = max( 50, math.ceil( (protected_invalid / RELOGIN_RECOVERY_DAYS) / effective_rate ), ) lease_refresh_limit = max( 50, math.ceil( (protected_valid / CK_AVERAGE_LIFETIME_DAYS) / effective_rate ), ) raw_relogin_limits = [ relogin_protected_limit, lease_refresh_limit, relogin_high_limit, relogin_ordinary_limit, ] planned_attempts = ( sum(raw_relogin_limits) + onboarding_attempts + manual_reserve ) daily_attempts = min( MAX_DAILY_ATTEMPTS, max( MIN_DAILY_ATTEMPTS, core_attempts + manual_reserve, planned_attempts, ), ) available_relogin_attempts = max( 0, daily_attempts - onboarding_attempts - manual_reserve, ) ( relogin_protected_limit, lease_refresh_limit, relogin_high_limit, relogin_ordinary_limit, ) = _fit_priority_budgets( raw_relogin_limits, available_relogin_attempts, ) hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS)) if sample < MIN_RECENT_SAMPLE or recent_success_rate < 70: concurrency = 3 elif recent_success_rate >= 90 and invalid_total >= 50: concurrency = 6 else: concurrency = 4 recommended = { "daily_attempt_limit": daily_attempts, "hourly_attempt_limit": hourly_attempts, "per_account_daily_limit": 2, "onboarding_daily_limit": onboarding_attempts, "relogin_protected_daily_limit": relogin_protected_limit, "lease_refresh_daily_limit": lease_refresh_limit, "relogin_high_value_daily_limit": relogin_high_limit, "relogin_ordinary_daily_limit": relogin_ordinary_limit, "manual_daily_limit": manual_reserve, "login_concurrency": concurrency, } current = _current_quota(db) return { "generated_at": moment, "window_days": RECENT_WINDOW_DAYS, "basis": { "valid_accounts": valid_total, "valid_high_value": valid_high, "valid_ordinary": valid_ordinary, "invalid_backlog": invalid_total, "invalid_high_value": invalid_high, "invalid_ordinary": invalid_ordinary, "protected_valid_accounts": protected_valid, "protected_invalid_backlog": protected_invalid, "imported_backlog": imported_total, "recent_sample": sample, "recent_success_rate": recent_success_rate, "effective_success_rate": round(effective_rate * 100, 1), "expected_daily_invalid": round(expected_daily_invalid, 2), "required_daily_success": required_success, "manual_reserve": manual_reserve, }, "current": current, "recommended": recommended, "delta": { key: recommended[key] - current[key] for key in recommended }, } __all__ = ["recommend_login_budget"]