File size: 10,669 Bytes
ddebc3e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | """Hot-path account selector — pluggable strategies.
Two fully independent strategies:
* ``_quota_select`` — scores candidates by health / quota / inflight / fails.
Used when ``account.refresh.enabled=true``. Behaviour is the historical one,
kept unchanged.
* ``_random_select`` — uniform random choice among non-cooling candidates.
Used when ``account.refresh.enabled=false``. Ignores quota and health entirely.
Strategy selection is process-global, registered once by the lifespan via
:func:`set_strategy`. Callers (``AccountDirectory``) invoke :func:`select` /
:func:`select_any` and are unaware of which strategy is active.
"""
import array # noqa: F401 — used in forward-referenced type annotations
import random
from typing import Literal
from app.platform.config.snapshot import get_config
from .table import AccountRuntimeTable
# Scoring weights used by the quota strategy.
_W_HEALTH = 100.0
_W_QUOTA = 25.0
_W_RECENT = 15.0 # penalty for recently used accounts
_W_INFLIGHT = 20.0
_W_FAIL = 4.0
_RECENT_WINDOW_S = 60 # seconds — 覆盖 grok-4-3 思考时长(典型 30-60s),强制账号轮换
_QUOTA_MAX_INFLIGHT = 12 # quota 策略下单账号最多 12 个并发请求,防止单账号堆积引发上游风控
_RANDOM_MAX_FAILS = 5 # random 策略下,累计失败 >= 5 次的账号暂时不选(D2 修复)
# ---------------------------------------------------------------------------
# Strategy registry
# ---------------------------------------------------------------------------
_StrategyName = Literal["quota", "random"]
_STRATEGY_NAME: _StrategyName = "random"
def set_strategy(name: _StrategyName) -> None:
"""Register the process-global selection strategy.
Called once by the lifespan after reading ``account.refresh.enabled``.
"""
global _STRATEGY_NAME
if name not in ("quota", "random"):
raise ValueError(f"unknown selection strategy: {name!r}")
_STRATEGY_NAME = name
def current_strategy() -> _StrategyName:
return _STRATEGY_NAME
# ---------------------------------------------------------------------------
# Public entry points — delegate to the active strategy
# ---------------------------------------------------------------------------
def select(
table: AccountRuntimeTable,
pool_id: int,
mode_id: int,
*,
exclude_idxs: frozenset[int] | None = None,
prefer_tag_idxs: set[int] | None = None,
now_s: int,
) -> int | None:
"""Select an account slot for ``(pool_id, mode_id)``.
Returns the slot index or ``None`` when no candidate is available.
Does not mutate the table — callers increment inflight separately.
"""
if _STRATEGY_NAME == "random":
return _random_select(
table, pool_id,
exclude_idxs=exclude_idxs,
prefer_tag_idxs=prefer_tag_idxs,
now_s=now_s,
)
return _quota_select(
table, pool_id, mode_id,
exclude_idxs=exclude_idxs,
prefer_tag_idxs=prefer_tag_idxs,
now_s=now_s,
)
def select_any(
table: AccountRuntimeTable,
pool_id: int,
*,
exclude_idxs: frozenset[int] | None = None,
prefer_tag_idxs: set[int] | None = None,
now_s: int,
) -> int | None:
"""Select any active account in ``pool_id`` irrespective of per-mode quota.
Used by WebSocket-based products that manage their own rate limiting.
"""
if _STRATEGY_NAME == "random":
return _random_select(
table, pool_id,
exclude_idxs=exclude_idxs,
prefer_tag_idxs=prefer_tag_idxs,
now_s=now_s,
)
return _quota_select_any(
table, pool_id,
exclude_idxs=exclude_idxs,
prefer_tag_idxs=prefer_tag_idxs,
now_s=now_s,
)
# ---------------------------------------------------------------------------
# Strategy: quota — score-based selection (unchanged behaviour)
# ---------------------------------------------------------------------------
def _quota_select(
table: AccountRuntimeTable,
pool_id: int,
mode_id: int,
*,
exclude_idxs: frozenset[int] | None,
prefer_tag_idxs: set[int] | None,
now_s: int,
) -> int | None:
candidates: set[int] | None = table.mode_available.get((pool_id, mode_id))
if not candidates:
return None
reset_col = table._reset_col(mode_id)
quota_col = table._quota_col(mode_id)
total_col = table._total_col(mode_id)
window_col = table._window_col(mode_id)
inflight_col = table.inflight_by_idx
_maybe_reset_windows(
table, candidates, mode_id,
reset_col, quota_col, total_col, window_col,
pool_id, now_s,
)
working: set[int] = candidates.copy()
if exclude_idxs:
working -= exclude_idxs
# B3: inflight 硬上限过滤,避免单账号堆积导致上游风控
working = {
idx for idx in working
if int(quota_col[idx]) > 0
and int(inflight_col[idx]) < _QUOTA_MAX_INFLIGHT
}
if not working:
return None
if prefer_tag_idxs:
preferred = working & prefer_tag_idxs
working = preferred if preferred else working
return _best(table, working, quota_col, now_s)
def _quota_select_any(
table: AccountRuntimeTable,
pool_id: int,
*,
exclude_idxs: frozenset[int] | None,
prefer_tag_idxs: set[int] | None,
now_s: int,
) -> int | None:
candidates: set[int] = _pool_union(table, pool_id)
if not candidates:
return None
working = candidates.copy()
if exclude_idxs:
working -= exclude_idxs
if not working:
return None
if prefer_tag_idxs:
preferred = working & prefer_tag_idxs
working = preferred if preferred else working
return _best_no_quota(table, working, now_s)
def _maybe_reset_windows(
table: AccountRuntimeTable,
candidates: set[int],
mode_id: int,
reset_col: "array.array",
quota_col: "array.array",
total_col: "array.array",
window_col: "array.array",
pool_id: int,
now_s: int,
) -> None:
"""Reset expired windows inline for any pool (no API call needed).
L7 修复:原仅对 basic 池生效;扩展到 super/heavy 后,在 refresh scheduler
卡死或上游不可达时也能本地兜底重置,避免账号"卡死"在过期窗口。
"""
for idx in list(candidates):
r = reset_col[idx]
if r == 0 or now_s < r:
continue
if int(table.pool_by_idx[idx]) != pool_id:
continue
new_total = int(total_col[idx])
window_s = int(window_col[idx])
if new_total <= 0 or window_s <= 0:
continue
quota_col[idx] = new_total
reset_col[idx] = now_s + window_s
def _best(
table: AccountRuntimeTable,
working: set[int],
quota_col: "array.array",
now_s: int,
) -> int | None:
best_idx = -1
best_score = -1e18
health_col = table.health_by_idx
inflight_col = table.inflight_by_idx
fail_col = table.fail_count_by_idx
last_use_col = table.last_use_at_by_idx
for idx in working:
quota = int(quota_col[idx])
if quota <= 0:
continue
health = float(health_col[idx])
inflight = int(inflight_col[idx])
fails = min(int(fail_col[idx]), 10)
last_use = int(last_use_col[idx])
score = (
health * _W_HEALTH
+ quota * _W_QUOTA
- inflight * _W_INFLIGHT
- fails * _W_FAIL
)
if last_use > 0:
age_s = now_s - last_use
if age_s < _RECENT_WINDOW_S:
score -= (1.0 - age_s / _RECENT_WINDOW_S) * _W_RECENT
if score > best_score:
best_score = score
best_idx = idx
return best_idx if best_idx >= 0 else None
def _best_no_quota(
table: AccountRuntimeTable,
working: set[int],
now_s: int,
) -> int | None:
best_idx = -1
best_score = -1e18
health_col = table.health_by_idx
inflight_col = table.inflight_by_idx
fail_col = table.fail_count_by_idx
last_use_col = table.last_use_at_by_idx
for idx in working:
health = float(health_col[idx])
inflight = int(inflight_col[idx])
fails = min(int(fail_col[idx]), 10)
last_use = int(last_use_col[idx])
score = health * _W_HEALTH - inflight * _W_INFLIGHT - fails * _W_FAIL
if last_use > 0:
age_s = now_s - last_use
if age_s < _RECENT_WINDOW_S:
score -= (1.0 - age_s / _RECENT_WINDOW_S) * _W_RECENT
if score > best_score:
best_score = score
best_idx = idx
return best_idx if best_idx >= 0 else None
# ---------------------------------------------------------------------------
# Strategy: random — uniform choice with cooling + inflight filter
# ---------------------------------------------------------------------------
def _random_select(
table: AccountRuntimeTable,
pool_id: int,
*,
exclude_idxs: frozenset[int] | None,
prefer_tag_idxs: set[int] | None,
now_s: int,
) -> int | None:
candidates: set[int] = _pool_union(table, pool_id)
if not candidates:
return None
max_inflight = int(get_config("account.selection.max_inflight", 8))
cooling_col = table.cooling_until_s_by_idx
inflight_col = table.inflight_by_idx
fail_col = table.fail_count_by_idx
working = candidates.copy()
if exclude_idxs:
working -= exclude_idxs
# D2 修复:累计失败 >= _RANDOM_MAX_FAILS 的账号暂时排除,避免重复打到刚失败的账号
working = {
idx for idx in working
if int(cooling_col[idx]) <= now_s
and int(inflight_col[idx]) < max_inflight
and int(fail_col[idx]) < _RANDOM_MAX_FAILS
}
if not working:
return None
if prefer_tag_idxs:
preferred = working & prefer_tag_idxs
working = preferred if preferred else working
return random.choice(tuple(working))
# ---------------------------------------------------------------------------
# Shared helper
# ---------------------------------------------------------------------------
def _pool_union(table: AccountRuntimeTable, pool_id: int) -> set[int]:
"""Union of all ``mode_available`` buckets for ``pool_id``."""
out: set[int] = set()
for (pid, _mid), accounts in table.mode_available.items():
if pid == pool_id:
out |= accounts
return out
__all__ = ["select", "select_any", "set_strategy", "current_strategy"]
|