From 100654adb8a3fa2cf4d09ff6c85fc006806d9844 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 20 Apr 2026 17:45:22 +0800 Subject: [PATCH] feat: Introduce random selection strategy and cooldown configuration for account management --- app/dataplane/account/__init__.py | 44 ++++- app/dataplane/account/feedback.py | 96 ++++++--- app/dataplane/account/selector.py | 301 ++++++++++++++++++++--------- app/dataplane/account/table.py | 6 + app/dataplane/shared/enums.py | 3 + app/main.py | 25 ++- app/products/_account_selection.py | 25 ++- app/products/anthropic/messages.py | 4 +- app/products/openai/chat.py | 4 +- app/products/openai/responses.py | 4 +- app/products/web/admin/__init__.py | 2 + app/statics/admin/account.html | 34 +++- app/statics/admin/config.html | 167 ++++++++++++++++ app/statics/i18n/de.json | 17 +- app/statics/i18n/en.json | 23 +++ app/statics/i18n/es.json | 17 +- app/statics/i18n/fr.json | 17 +- app/statics/i18n/ja.json | 17 +- app/statics/i18n/zh.json | 23 +++ config.defaults.toml | 14 ++ 20 files changed, 688 insertions(+), 155 deletions(-) diff --git a/app/dataplane/account/__init__.py b/app/dataplane/account/__init__.py index b753edcb..20937f36 100644 --- a/app/dataplane/account/__init__.py +++ b/app/dataplane/account/__init__.py @@ -8,16 +8,17 @@ changesets without holding the selection lock. import asyncio from typing import TYPE_CHECKING +from app.platform.config.snapshot import get_config from app.platform.logging.logger import logger from app.platform.runtime.clock import now_s from app.control.account.repository import AccountRepository from app.control.account.enums import FeedbackKind from .table import AccountRuntimeTable from .lease import AccountLease, new_lease -from .selector import select, select_any +from .selector import current_strategy, select, select_any from .sync import bootstrap as _bootstrap, apply_changes from . import feedback as fb -from ..shared.enums import StatusId +from ..shared.enums import POOL_ID_TO_STR, StatusId if TYPE_CHECKING: pass @@ -250,12 +251,22 @@ class AccountDirectory: ts = now_s_val if now_s_val is not None else now_s() + strategy = current_strategy() + async with self._lock: if kind == FeedbackKind.SUCCESS: - fb.apply_success(table, idx, mode_id) + if strategy == "random": + fb.apply_success_random(table, idx) + else: + fb.apply_success_quota(table, idx, mode_id) elif kind == FeedbackKind.RATE_LIMITED: - fb.apply_rate_limited(table, idx, mode_id) + if strategy == "random": + pool_id = int(table.pool_by_idx[idx]) + cooling_sec = _pool_cooling_sec(pool_id) + fb.apply_rate_limited_random(table, idx, cooling_sec=cooling_sec) + else: + fb.apply_rate_limited_quota(table, idx, mode_id) fb.update_last_fail(table, idx, ts) elif kind == FeedbackKind.UNAUTHORIZED: @@ -271,8 +282,9 @@ class AccountDirectory: fb.apply_server_error(table, idx) fb.update_last_fail(table, idx, ts) - # Apply authoritative quota data from upstream response headers. - if remaining is not None and reset_at_ms is not None: + # Quota strategy may receive authoritative quota data from upstream + # response headers; the random strategy ignores this entirely. + if strategy == "quota" and remaining is not None and reset_at_ms is not None: reset_s = int(reset_at_ms // 1000) fb.apply_quota_update(table, idx, mode_id, remaining, reset_s) @@ -289,6 +301,26 @@ class AccountDirectory: return self._table.revision if self._table else 0 +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +_DEFAULT_COOLING_HOURS: dict[str, int] = { + "basic": 20, + "super": 2, + "heavy": 2, +} + + +def _pool_cooling_sec(pool_id: int) -> int: + """Cooling seconds for a 429 on a given pool (random strategy only).""" + pool_str = POOL_ID_TO_STR.get(pool_id, "basic") + default_hours = _DEFAULT_COOLING_HOURS.get(pool_str, 2) + hours = int(get_config(f"account.random.cooling_{pool_str}_hours", default_hours)) + return max(0, hours) * 3600 + + # --------------------------------------------------------------------------- # Module-level singleton # --------------------------------------------------------------------------- diff --git a/app/dataplane/account/feedback.py b/app/dataplane/account/feedback.py index b77942c1..3372b56e 100644 --- a/app/dataplane/account/feedback.py +++ b/app/dataplane/account/feedback.py @@ -1,39 +1,78 @@ """Apply feedback to the runtime table columns (in-place, lock-free inner ops). -The caller (AccountDirectory) is responsible for holding the state lock -before calling these functions. +The caller (AccountDirectory) is responsible for holding the state lock before +calling these functions. + +Strategy-split functions +------------------------ +``apply_success`` / ``apply_rate_limited`` are split into ``*_quota`` and +``*_random`` variants. The caller picks exactly one based on the active +selector strategy. No runtime ``if`` inside the apply helpers themselves. """ +from app.platform.runtime.clock import now_s from ..shared.enums import ALL_MODE_IDS, StatusId from .table import AccountRuntimeTable # Health adjustment constants. -_SUCCESS_STEP = 0.12 -_AUTH_FACTOR = 0.55 -_FORBIDDEN_FACTOR = 0.25 -_RATE_LIMIT_FACTOR = 0.45 +_SUCCESS_STEP = 0.12 +_AUTH_FACTOR = 0.55 +_FORBIDDEN_FACTOR = 0.25 +_RATE_LIMIT_FACTOR = 0.45 _SERVER_ERROR_FACTOR = 0.75 _MIN_HEALTH = 0.05 _MAX_HEALTH = 1.0 -def apply_success(table: AccountRuntimeTable, idx: int, mode_id: int) -> None: - """Record a successful call: decrement quota, improve health.""" +# --------------------------------------------------------------------------- +# apply_success — two independent implementations +# --------------------------------------------------------------------------- + + +def apply_success_quota(table: AccountRuntimeTable, idx: int, mode_id: int) -> None: + """Quota strategy: decrement per-mode quota and improve health.""" quota_col = table._quota_col(mode_id) - new_q = max(0, int(quota_col[idx]) - 1) - quota_col[idx] = new_q - - # Recover health. - h = min(_MAX_HEALTH, float(table.health_by_idx[idx]) + _SUCCESS_STEP) - table.health_by_idx[idx] = h + quota_col[idx] = max(0, int(quota_col[idx]) - 1) + _bump_health(table, idx) -def apply_rate_limited(table: AccountRuntimeTable, idx: int, mode_id: int) -> None: - """Zero the mode quota and reduce health.""" +def apply_success_random(table: AccountRuntimeTable, idx: int) -> None: + """Random strategy: only improve health; quota columns are ignored.""" + _bump_health(table, idx) + + +# --------------------------------------------------------------------------- +# apply_rate_limited — two independent implementations +# --------------------------------------------------------------------------- + + +def apply_rate_limited_quota( + table: AccountRuntimeTable, idx: int, mode_id: int +) -> None: + """Quota strategy: zero the mode quota and reduce health.""" table._quota_col(mode_id)[idx] = 0 _adjust_health(table, idx, _RATE_LIMIT_FACTOR) +def apply_rate_limited_random( + table: AccountRuntimeTable, idx: int, *, cooling_sec: int +) -> None: + """Random strategy: set per-account cooldown timestamp; do not touch quota. + + The account stays in ``mode_available``; ``_random_select`` filters it out + until ``cooling_until_s_by_idx`` has elapsed. + """ + ts = now_s() + max(0, cooling_sec) + cooling_col = table.cooling_until_s_by_idx + cooling_col[idx] = max(int(cooling_col[idx]), ts) + _adjust_health(table, idx, _RATE_LIMIT_FACTOR) + + +# --------------------------------------------------------------------------- +# Strategy-agnostic feedback helpers (shared) +# --------------------------------------------------------------------------- + + def apply_auth_failure(table: AccountRuntimeTable, idx: int) -> None: """Reduce health on 401; caller may mark account expired.""" _adjust_health(table, idx, _AUTH_FACTOR) @@ -62,13 +101,11 @@ def apply_status_change( table.status_by_idx[idx] = new_status_id if new_status_id != int(StatusId.ACTIVE): - # Remove from all mode availability buckets. for mode_id in ALL_MODE_IDS: bucket = table.mode_available.get((pool_id, mode_id)) if bucket: bucket.discard(idx) else: - # Re-add to mode buckets where quota > 0. for mode_id in ALL_MODE_IDS: if int(table._quota_col(mode_id)[idx]) > 0: table.mode_available.setdefault((pool_id, mode_id), set()).add(idx) @@ -81,7 +118,11 @@ def apply_quota_update( remaining: int, reset_s: int, ) -> None: - """Update quota and reset timestamp from upstream API data.""" + """Update quota and reset timestamp from upstream API data. + + Used exclusively by the quota strategy (refresh service). The random + strategy never calls this. + """ quota_col = table._quota_col(mode_id) reset_col = table._reset_col(mode_id) quota_col[idx] = max(0, min(remaining, 32767)) @@ -116,14 +157,23 @@ def update_last_fail(table: AccountRuntimeTable, idx: int, now_s: int) -> None: # --------------------------------------------------------------------------- +def _bump_health(table: AccountRuntimeTable, idx: int) -> None: + table.health_by_idx[idx] = min( + _MAX_HEALTH, float(table.health_by_idx[idx]) + _SUCCESS_STEP + ) + + def _adjust_health(table: AccountRuntimeTable, idx: int, factor: float) -> None: - h = max(_MIN_HEALTH, float(table.health_by_idx[idx]) * factor) - table.health_by_idx[idx] = h + table.health_by_idx[idx] = max( + _MIN_HEALTH, float(table.health_by_idx[idx]) * factor + ) __all__ = [ - "apply_success", - "apply_rate_limited", + "apply_success_quota", + "apply_success_random", + "apply_rate_limited_quota", + "apply_rate_limited_random", "apply_auth_failure", "apply_forbidden", "apply_server_error", diff --git a/app/dataplane/account/selector.py b/app/dataplane/account/selector.py index 81425904..c7d048cb 100644 --- a/app/dataplane/account/selector.py +++ b/app/dataplane/account/selector.py @@ -1,22 +1,63 @@ -"""Hot-path account selector — pure function, no object allocation. +"""Hot-path account selector — pluggable strategies. -All scoring operates on typed ``array.array`` columns; no attribute lookup -overhead. The caller provides the frozen set of excluded indices and -pre-resolved tag index set. +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 ..shared.enums import PoolId from .table import AccountRuntimeTable -# Scoring weights — tuned for throughput/fairness balance. -_W_HEALTH = 100.0 -_W_QUOTA = 25.0 -_W_RECENT = 15.0 # penalty for recently used accounts +# 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 +_W_FAIL = 4.0 _RECENT_WINDOW_S = 15 # seconds +# --------------------------------------------------------------------------- +# 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, @@ -26,30 +67,79 @@ def select( prefer_tag_idxs: set[int] | None = None, now_s: int, ) -> int | None: - """Select the best available account slot index. + """Select an account slot for ``(pool_id, mode_id)``. - Returns the slot index on success, ``None`` if no account is available. - Does **not** mutate any table state — callers must increment inflight. + 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 - # Apply window-expiry resets for basic accounts inline. - reset_col = table._reset_col(mode_id) - quota_col = table._quota_col(mode_id) - total_col = table._total_col(mode_id) + 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) _maybe_reset_windows( - table, - candidates, - mode_id, - reset_col, - quota_col, - total_col, - window_col, - pool_id, - now_s, + table, candidates, mode_id, + reset_col, quota_col, total_col, window_col, + pool_id, now_s, ) working: set[int] = candidates.copy() @@ -59,30 +149,50 @@ def select( if not working: return None - # Prefer tagged subset; fall back to full set if empty. if prefer_tag_idxs: preferred = working & prefer_tag_idxs working = preferred if preferred else working - return _best(table, working, mode_id, quota_col, now_s) + 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, + table: AccountRuntimeTable, candidates: set[int], - mode_id: 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, + pool_id: int, + now_s: int, ) -> None: - """Reset expired windows for basic-pool accounts (no API call required). - - Only applies to the basic pool — super/heavy quotas are managed exclusively - by the periodic refresh service and must not be reset inline. - """ + """Reset expired windows for basic-pool accounts inline (no API call needed).""" if pool_id != int(PoolId.BASIC): return @@ -93,22 +203,19 @@ def _maybe_reset_windows( if int(table.pool_by_idx[idx]) != pool_id: continue new_total = int(total_col[idx]) - window_s = int(window_col[idx]) + window_s = int(window_col[idx]) if new_total <= 0 or window_s <= 0: continue - # Window expired — restore the last known total for this account/mode. quota_col[idx] = new_total reset_col[idx] = now_s + window_s def _best( - table: AccountRuntimeTable, - working: set[int], - mode_id: int, + table: AccountRuntimeTable, + working: set[int], quota_col: "array.array", - now_s: int, -) -> int: - """Return the index of the highest-scoring candidate.""" + now_s: int, +) -> int | None: best_idx = -1 best_score = -1e18 @@ -118,7 +225,7 @@ def _best( last_use_col = table.last_use_at_by_idx for idx in working: - quota = int(quota_col[idx]) + quota = int(quota_col[idx]) if quota <= 0: continue health = float(health_col[idx]) @@ -144,60 +251,23 @@ def _best( return best_idx if best_idx >= 0 else None -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 from *pool_id* without mode-specific quota checking. - - Used for WebSocket-based operations that manage their own upstream rate limiting - and do not consume tracked quota buckets. Candidates are the union of all - mode_available sets for the pool so that accounts are reachable even when one - particular mode bucket (e.g. AUTO) is exhausted. - """ - candidates: set[int] = set() - for (pid, _mid), accounts in table.mode_available.items(): - if pid == pool_id: - candidates |= accounts - - 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 _best_no_quota( table: AccountRuntimeTable, working: set[int], now_s: int, ) -> int | None: - """Score candidates by health and inflight only — no quota weighting.""" - best_idx = -1 + best_idx = -1 best_score = -1e18 - health_col = table.health_by_idx + health_col = table.health_by_idx inflight_col = table.inflight_by_idx - fail_col = table.fail_count_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]) + health = float(health_col[idx]) inflight = int(inflight_col[idx]) - fails = min(int(fail_col[idx]), 10) + fails = min(int(fail_col[idx]), 10) last_use = int(last_use_col[idx]) score = health * _W_HEALTH - inflight * _W_INFLIGHT - fails * _W_FAIL @@ -208,9 +278,62 @@ def _best_no_quota( if score > best_score: best_score = score - best_idx = idx + best_idx = idx return best_idx if best_idx >= 0 else None -__all__ = ["select", "select_any"] +# --------------------------------------------------------------------------- +# 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 + + working = candidates.copy() + if exclude_idxs: + working -= exclude_idxs + working = { + idx for idx in working + if int(cooling_col[idx]) <= now_s + and int(inflight_col[idx]) < max_inflight + } + 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"] diff --git a/app/dataplane/account/table.py b/app/dataplane/account/table.py index 69ab143a..16a5719e 100644 --- a/app/dataplane/account/table.py +++ b/app/dataplane/account/table.py @@ -151,6 +151,11 @@ class AccountRuntimeTable: default_factory=lambda: array.array("L") ) + # --- Per-account cooldown (random strategy only; uint32 epoch-seconds; 0 = not cooling) --- + cooling_until_s_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + # --- Pre-computed selection indexes --- # (pool_id, mode_id) → set of idx with a supported quota window and status == ACTIVE mode_available: dict[tuple[int, int], set[int]] = field(default_factory=dict) @@ -300,6 +305,7 @@ class AccountRuntimeTable: self.health_by_idx.append(health) self.last_use_at_by_idx.append(last_use_s) self.last_fail_at_by_idx.append(last_fail_s) + self.cooling_until_s_by_idx.append(0) self.size += 1 self._add_to_indexes(idx) self._add_to_tag_idx(idx, tags) diff --git a/app/dataplane/shared/enums.py b/app/dataplane/shared/enums.py index bdbe4a9e..88b9ed66 100644 --- a/app/dataplane/shared/enums.py +++ b/app/dataplane/shared/enums.py @@ -36,6 +36,8 @@ POOL_STR_TO_ID: dict[str, int] = { "heavy": int(PoolId.HEAVY), } +POOL_ID_TO_STR: dict[int, str] = {v: k for k, v in POOL_STR_TO_ID.items()} + STATUS_STR_TO_ID: dict[str, int] = { "active": int(StatusId.ACTIVE), "cooling": int(StatusId.COOLING), @@ -56,6 +58,7 @@ __all__ = [ "PoolId", "StatusId", "POOL_STR_TO_ID", + "POOL_ID_TO_STR", "STATUS_STR_TO_ID", "ALL_MODE_IDS", ] diff --git a/app/main.py b/app/main.py index 9a517492..60bb560a 100644 --- a/app/main.py +++ b/app/main.py @@ -182,7 +182,16 @@ async def lifespan(app: FastAPI): # 4. Account refresh scheduler — only the leader worker. # Uses an advisory file lock so exactly one process runs the heavy # upstream quota-fetch loop regardless of worker count. + # + # ``account.refresh.enabled`` selects between two independent runtime + # strategies: + # - true → "quota" selector + scheduler running (default). + # - false → "random" selector + scheduler idle (no upstream probing). from app.control.account.refresh import AccountRefreshService + from app.dataplane.account.selector import set_strategy as _set_selection_strategy + + refresh_enabled = _config.get_bool("account.refresh.enabled", False) + _set_selection_strategy("quota" if refresh_enabled else "random") refresh_svc = AccountRefreshService(repo) set_refresh_service(refresh_svc) @@ -190,18 +199,28 @@ async def lifespan(app: FastAPI): is_leader = _try_acquire_scheduler_lock() scheduler = get_account_refresh_scheduler(refresh_svc) - if is_leader: + strategy_name = "quota" if refresh_enabled else "random" + if is_leader and refresh_enabled: scheduler.start() logger.info( - "scheduler leader: pid={} active_sync_s={} idle_sync_s={}", + "scheduler leader: pid={} strategy=quota active_sync_s={} idle_sync_s={}", + os.getpid(), + _SYNC_ACTIVE_INTERVAL, + _SYNC_IDLE_INTERVAL, + ) + elif is_leader: + logger.info( + "scheduler leader: pid={} strategy=random (scheduler idle) " + "active_sync_s={} idle_sync_s={}", os.getpid(), _SYNC_ACTIVE_INTERVAL, _SYNC_IDLE_INTERVAL, ) else: logger.info( - "scheduler follower: pid={} active_sync_s={} idle_sync_s={}", + "scheduler follower: pid={} strategy={} active_sync_s={} idle_sync_s={}", os.getpid(), + strategy_name, _SYNC_ACTIVE_INTERVAL, _SYNC_IDLE_INTERVAL, ) diff --git a/app/products/_account_selection.py b/app/products/_account_selection.py index 056583e6..a2f9423d 100644 --- a/app/products/_account_selection.py +++ b/app/products/_account_selection.py @@ -3,8 +3,26 @@ from app.control.model.enums import ModeId from app.control.model.spec import ModelSpec from app.control.account.runtime import get_refresh_service +from app.dataplane.account.selector import current_strategy from app.platform.config.snapshot import get_config +# Random strategy has no config key for retry count; it is pinned here so that +# every retry-driven call site (chat / images / video / anthropic) sees the same +# value without introducing scattered magic numbers. +_RANDOM_MAX_RETRIES = 5 + + +def selection_max_retries() -> int: + """Retry count for account-swap loops, aware of the active selection strategy. + + - ``random`` strategy: fixed at :data:`_RANDOM_MAX_RETRIES` (=5). + - ``quota`` strategy: reads ``retry.max_retries`` (default 1), preserving + the historical behaviour. + """ + if current_strategy() == "random": + return _RANDOM_MAX_RETRIES + return int(get_config("retry.max_retries", 1)) + def mode_candidates(spec: ModelSpec) -> tuple[int, ...]: """Return mode IDs to try for *spec* in priority order. @@ -32,7 +50,9 @@ async def reserve_account( ): """Reserve an account and return ``(lease, selected_mode_id)``. - Returns ``(None, original_mode_id)`` when no account is available. + Returns ``(None, original_mode_id)`` when no account is available. Under the + random strategy no on-demand refresh fallback is attempted — upstream quota + data is never probed. """ original_mode_id = int(spec.mode_id) @@ -52,6 +72,9 @@ async def reserve_account( if lease is not None: return lease, selected_mode_id + if current_strategy() == "random": + return None, original_mode_id + refresh_svc = get_refresh_service() if refresh_svc is not None: await refresh_svc.refresh_on_demand() diff --git a/app/products/anthropic/messages.py b/app/products/anthropic/messages.py index 31ef2f90..42ba98a1 100644 --- a/app/products/anthropic/messages.py +++ b/app/products/anthropic/messages.py @@ -33,7 +33,7 @@ from app.products.openai.chat import ( _quota_sync, _fail_sync, _parse_retry_codes, _feedback_kind, _log_task_exception, _configured_retry_codes, _should_retry_upstream, ) -from app.products._account_selection import reserve_account +from app.products._account_selection import reserve_account, selection_max_retries from app.products.openai._tool_sieve import ToolSieve @@ -310,7 +310,7 @@ async def create( raise RateLimitError("Account directory not initialised") directory = _acct_dir - max_retries = cfg.get_int("retry.max_retries", 1) + max_retries = selection_max_retries() retry_codes = _configured_retry_codes(cfg) timeout_s = cfg.get_float("chat.timeout", 120.0) msg_id = _make_msg_id() diff --git a/app/products/openai/chat.py b/app/products/openai/chat.py index 4eeab694..facdd4f5 100644 --- a/app/products/openai/chat.py +++ b/app/products/openai/chat.py @@ -54,7 +54,7 @@ from ._format import ( build_usage, ) from ._tool_sieve import ToolSieve -from app.products._account_selection import reserve_account +from app.products._account_selection import reserve_account, selection_max_retries def _to_chat_annotations(anns: list[dict]) -> list[dict]: @@ -470,7 +470,7 @@ async def completions( raise RateLimitError("Account directory not initialised") directory = _acct_dir - max_retries = cfg.get_int("retry.max_retries", 1) + max_retries = selection_max_retries() retry_codes = _configured_retry_codes(cfg) response_id = make_response_id() timeout_s = cfg.get_float("chat.timeout", 120.0) diff --git a/app/products/openai/responses.py b/app/products/openai/responses.py index 95fdc3e7..d816c7a9 100644 --- a/app/products/openai/responses.py +++ b/app/products/openai/responses.py @@ -18,7 +18,7 @@ from app.control.model.enums import ModeId from app.control.model.registry import resolve as resolve_model from app.control.account.enums import FeedbackKind from app.dataplane.reverse.protocol.xai_chat import classify_line, StreamAdapter -from app.products._account_selection import reserve_account +from app.products._account_selection import reserve_account, selection_max_retries from .chat import _stream_chat, _extract_message, _resolve_image, _quota_sync, _fail_sync, _parse_retry_codes, _feedback_kind, _log_task_exception, _upstream_body_excerpt from .chat import _configured_retry_codes, _should_retry_upstream @@ -247,7 +247,7 @@ async def create( raise RateLimitError("Account directory not initialised") directory = _acct_dir - max_retries = cfg.get_int("retry.max_retries", 1) + max_retries = selection_max_retries() retry_codes = _configured_retry_codes(cfg) response_id = make_resp_id("resp") reasoning_id = make_resp_id("rs") diff --git a/app/products/web/admin/__init__.py b/app/products/web/admin/__init__.py index 529452a4..61494f8d 100644 --- a/app/products/web/admin/__init__.py +++ b/app/products/web/admin/__init__.py @@ -206,6 +206,7 @@ async def get_storage_mode(): @router.get("/status", tags=[_TAG_ADMIN_SYSTEM]) async def runtime_status(): from app.dataplane.account import _directory + from app.dataplane.account.selector import current_strategy if _directory is None: raise AppError( @@ -220,6 +221,7 @@ async def runtime_status(): "status": "ok", "size": _directory.size, "revision": _directory.revision, + "selection_strategy": current_strategy(), } ), media_type="application/json", diff --git a/app/statics/admin/account.html b/app/statics/admin/account.html index f8983e3f..9107c5de 100644 --- a/app/statics/admin/account.html +++ b/app/statics/admin/account.html @@ -782,7 +782,7 @@
0
-
+
Auto 余额
@@ -791,7 +791,7 @@
0
-
+
Fast 余额
@@ -800,7 +800,7 @@
0
-
+
Expert 余额
@@ -809,7 +809,7 @@
0
-
+
Heavy 余额
@@ -934,7 +934,7 @@ Token 类型 状态 - + 额度 A @@ -1134,25 +1134,45 @@ async function _api(method, path, body) { return r.json(); } +// Selection strategy reported by /status — "quota" | "random". +// Controls whether quota columns / stats are rendered (hidden in random mode). +let selectionStrategy = 'quota'; + // ── Load ─────────────────────────────────────────────────────────────────── async function load() { try { - const data = await _api('GET', '/tokens'); + const [data, status] = await Promise.all([ + _api('GET', '/tokens'), + _api('GET', '/status').catch(() => null), + ]); + if (status && typeof status.selection_strategy === 'string') { + selectionStrategy = status.selection_strategy; + } allTokens = Array.isArray(data.tokens) ? data.tokens : Object.entries(data.tokens || {}).flatMap(([pool, items]) => Array.isArray(items) ? items.map(t => ({ ...t, pool: t.pool || pool })) : []); + applyStrategyUI(); invalidateTokenView(); render(); } catch (e) { showToast(`${tr('account.loadFailed', null, '加载失败')}: ${e.message}`, 'error'); } } +function applyStrategyUI() { + // Random strategy: hide quota-related stat cells and the table column. + const isRandom = selectionStrategy === 'random'; + document.querySelectorAll('[data-quota-only]').forEach(el => { + el.style.display = isRandom ? 'none' : ''; + }); +} + // ── Render ───────────────────────────────────────────────────────────────── function render() { const view = getTokenView(); renderStats(view); renderFilters(view); renderTable(view); + applyStrategyUI(); } function getTokenView() { @@ -1409,7 +1429,7 @@ function rowHtml(t) {
${xe(poolLabel(t.pool || 'basic'))} ${statusBadge(t.status)} -
${qpills(q)}
+
${qpills(q)}
${success} ${fail} ${fmtRate(success, fail)} diff --git a/app/statics/admin/config.html b/app/statics/admin/config.html index eb8fd63b..a6802007 100644 --- a/app/statics/admin/config.html +++ b/app/statics/admin/config.html @@ -111,6 +111,67 @@ line-height:1.35; } .cfg-desc { max-width:520px; font-size:11px; color:#9a9a9a; line-height:1.45 } + .cfg-help { + position:relative; + width:16px; + height:16px; + display:inline-flex; + align-items:center; + justify-content:center; + padding:0; + border-radius:50%; + border:1px solid #e6e6e6; + background:#fafafa; + color:#8d8d8d; + font-size:11px; + line-height:1; + font-weight:700; + cursor:help; + flex-shrink:0; + } + .cfg-help:hover, + .cfg-help:focus-visible { + color:#222; + border-color:#d6d6d6; + background:#fff; + outline:none; + } + .cfg-help-tip { + position:fixed; + box-sizing:border-box; + max-width:min(320px, calc(100vw - 24px)); + padding:9px 10px; + border-radius:8px; + background:#171717; + color:#fff; + font-size:12px; + font-weight:500; + line-height:1.5; + text-align:left; + white-space:pre-line; + overflow-wrap:anywhere; + box-shadow:0 8px 24px rgba(0,0,0,.16); + opacity:0; + pointer-events:none; + transform:translateY(3px); + transition:opacity .15s, transform .15s; + z-index:1000; + } + .cfg-help-tip.visible { + opacity:1; + transform:translateY(0); + } + .cfg-help-tip::before { + content:''; + position:absolute; + left:var(--arrow-left, 50%); + width:8px; + height:8px; + background:#171717; + transform:translateX(-50%) rotate(45deg); + } + .cfg-help-tip[data-placement="top"]::before { bottom:-4px } + .cfg-help-tip[data-placement="bottom"]::before { top:-4px } .cfg-input-col { min-width:0; display:flex; align-items:center; justify-content:flex-start; gap:8px } .cfg-input-col.is-bool { justify-content:flex-end } .cfg-inline-action { @@ -434,6 +495,7 @@ const SCHEMA_DEF = [ title: '配额刷新调度', titleKey: 'config.schema.groups.refreshSchedule', section: 'account.refresh', fields: [ + { key: 'enabled', label: '启用配额刷新', labelKey: 'config.schema.fields.refreshEnabled.label', type: 'bool', desc: '开启配额探测和评分选号;万级以上账号建议关闭。', descKey: 'config.schema.fields.refreshEnabled.desc', help: '开启:配额刷新模式,scheduler 周期同步真实配额,选号按评分。\n关闭:自动重试模式,不主动探测 upstream,选号随机,出错自动换号重试最多 5 次。\n建议:万级以上账号关闭,避免主动探测触发 upstream 429。', helpKey: 'config.schema.fields.refreshEnabled.help' }, { key: 'basic_interval_sec', label: 'Basic 刷新周期(秒)', labelKey: 'config.schema.fields.basicInterval.label', type: 'number', desc: 'basic 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 36000 s / 10 h)。', descKey: 'config.schema.fields.basicInterval.desc' }, { key: 'super_interval_sec', label: 'Super 刷新周期(秒)', labelKey: 'config.schema.fields.superInterval.label', type: 'number', desc: 'super 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 7200 s / 2 h)。', descKey: 'config.schema.fields.superInterval.desc' }, { key: 'heavy_interval_sec', label: 'Heavy 刷新周期(秒)', labelKey: 'config.schema.fields.heavyInterval.label', type: 'number', desc: 'heavy 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 7200 s / 2 h)。', descKey: 'config.schema.fields.heavyInterval.desc' }, @@ -441,6 +503,22 @@ const SCHEMA_DEF = [ { key: 'usage_concurrency', label: '刷新并发数', labelKey: 'config.schema.fields.usageConcurrency.label', type: 'number', desc: '并发调用 usage 接口刷新额度时允许的最大并行数。', descKey: 'config.schema.fields.usageConcurrency.desc' }, ] }, + { + title: '自动重试冷却', titleKey: 'config.schema.groups.randomCooling', + section: 'account.random', + fields: [ + { key: 'cooling_basic_hours', label: 'Basic 冷却(小时)', labelKey: 'config.schema.fields.coolingBasicHours.label', type: 'number', desc: 'basic 号收到 429 后的冷却时长,默认 20 h(对齐 upstream 20 h 限流窗口)。仅在自动重试模式下生效。', descKey: 'config.schema.fields.coolingBasicHours.desc' }, + { key: 'cooling_super_hours', label: 'Super 冷却(小时)', labelKey: 'config.schema.fields.coolingSuperHours.label', type: 'number', desc: 'super 号收到 429 后的冷却时长,默认 2 h(对齐 upstream 2 h 限流窗口)。仅在自动重试模式下生效。', descKey: 'config.schema.fields.coolingSuperHours.desc' }, + { key: 'cooling_heavy_hours', label: 'Heavy 冷却(小时)', labelKey: 'config.schema.fields.coolingHeavyHours.label', type: 'number', desc: 'heavy 号收到 429 后的冷却时长,默认 2 h(对齐 upstream 2 h 限流窗口)。仅在自动重试模式下生效。', descKey: 'config.schema.fields.coolingHeavyHours.desc' }, + ] + }, + { + title: '选号并发限制', titleKey: 'config.schema.groups.selection', + section: 'account.selection', + fields: [ + { key: 'max_inflight', label: '单号并发上限', labelKey: 'config.schema.fields.maxInflight.label', type: 'number', desc: '单个账号同时在执行的请求上限,超过则选号路径跳过该号(两种模式共用)。', descKey: 'config.schema.fields.maxInflight.desc' }, + ] + }, { title: '批量操作并发', titleKey: 'config.schema.groups.batchConcurrency', section: 'batch', @@ -722,6 +800,7 @@ function _localizeField(field) { ...field, label: field.labelKey ? tr(field.labelKey, null, field.label ?? field.key) : (field.label ?? field.key), desc: field.descKey ? tr(field.descKey, null, field.desc ?? '') : (field.desc ?? ''), + help: field.helpKey ? tr(field.helpKey, null, field.help ?? '') : (field.help ?? ''), options: field.options ? field.options.map(_localizeOption) : field.options, }; } @@ -824,6 +903,76 @@ function _el(tag, attrs, ...children) { return el; } +let _helpTipEl = null; +let _activeHelpButton = null; + +function _hideHelpTip() { + if (_activeHelpButton) _activeHelpButton.removeAttribute('aria-describedby'); + if (_helpTipEl) _helpTipEl.remove(); + _helpTipEl = null; + _activeHelpButton = null; +} + +function _positionHelpTip(button, tip) { + const margin = 12; + const rect = button.getBoundingClientRect(); + const viewportWidth = window.innerWidth || document.documentElement.clientWidth; + const viewportHeight = window.innerHeight || document.documentElement.clientHeight; + const maxWidth = Math.max(120, viewportWidth - margin * 2); + + tip.style.maxWidth = `${Math.min(320, maxWidth)}px`; + tip.style.left = '0px'; + tip.style.top = '0px'; + + const tipRect = tip.getBoundingClientRect(); + let left = rect.left + rect.width / 2 - tipRect.width / 2; + left = Math.max(margin, Math.min(left, viewportWidth - tipRect.width - margin)); + + let placement = 'top'; + let top = rect.top - tipRect.height - 8; + if (top < margin) { + placement = 'bottom'; + top = rect.bottom + 8; + } + if (top + tipRect.height > viewportHeight - margin) { + top = Math.max(margin, viewportHeight - tipRect.height - margin); + } + + const arrowLeft = Math.max(12, Math.min(rect.left + rect.width / 2 - left, tipRect.width - 12)); + tip.dataset.placement = placement; + tip.style.setProperty('--arrow-left', `${arrowLeft}px`); + tip.style.left = `${left}px`; + tip.style.top = `${top}px`; +} + +function _showHelpTip(button) { + const text = button.getAttribute('data-tip'); + if (!text) return; + _hideHelpTip(); + + const tip = _el('div', { + class: 'cfg-help-tip', + id: 'cfg-help-tip', + role: 'tooltip', + }, text); + document.body.appendChild(tip); + button.setAttribute('aria-describedby', 'cfg-help-tip'); + + _helpTipEl = tip; + _activeHelpButton = button; + _positionHelpTip(button, tip); + requestAnimationFrame(() => tip.classList.add('visible')); +} + +window.addEventListener('resize', _hideHelpTip); +window.addEventListener('scroll', _hideHelpTip, true); +document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') _hideHelpTip(); +}); +document.addEventListener('click', (event) => { + if (!event.target.closest?.('.cfg-help')) _hideHelpTip(); +}); + function renderInput(field, section, value) { const fp = _fullPath(section, field.key); @@ -941,6 +1090,24 @@ function renderRow(field, section, tabId) { labelChildren.push(btn); } + if (field.help) { + labelChildren.push(_el('button', { + class: 'cfg-help', + type: 'button', + 'aria-label': field.help, + 'data-tip': field.help, + onmouseenter: (event) => _showHelpTip(event.currentTarget), + onmouseleave: _hideHelpTip, + onfocus: (event) => _showHelpTip(event.currentTarget), + onblur: _hideHelpTip, + onclick: (event) => { + event.preventDefault(); + event.stopPropagation(); + _showHelpTip(event.currentTarget); + }, + }, '?')); + } + labelChildren.push(dot); const labelCol = _el('div', { class: 'cfg-label-col' }, diff --git a/app/statics/i18n/de.json b/app/statics/i18n/de.json index c9d974d9..c75508a8 100644 --- a/app/statics/i18n/de.json +++ b/app/statics/i18n/de.json @@ -330,6 +330,8 @@ "features": "Kernfunktionen", "mediaFormat": "Medienausgabe", "refreshSchedule": "Quotenaktualisierung", + "randomCooling": "Auto-Retry-Abkühlung", + "selection": "Auswahl-Nebenläufigkeit", "batchConcurrency": "Batch-Konkurrenz", "egressProxy": "Ausgehender Proxy", "clearance": "Cloudflare Clearance", @@ -381,11 +383,16 @@ "customInstruction": { "label": "Globale Zusatzanweisung" }, "imageFormat": { "label": "Bildausgabeformat" }, "videoFormat": { "label": "Videoausgabeformat" }, - "basicInterval": { "label": "Basic-Aktualisierungsintervall (s)" }, - "superInterval": { "label": "Super-Aktualisierungsintervall (s)" }, - "heavyInterval": { "label": "Heavy-Aktualisierungsintervall (s)" }, - "usageConcurrency": { "label": "Aktualisierungs-Konkurrenz" }, - "onDemandMinInterval": { "label": "Minimales On-Demand-Intervall (s)" }, + "refreshEnabled": { "label": "Quotenaktualisierung aktivieren", "desc": "Aktiviert Quotenabfrage und bewertete Auswahl; bei mehr als 10.000 Konten empfohlen aus.", "help": "Ein: Quotenaktualisierung. Der Scheduler synchronisiert regelmäßig echte Quoten, die Auswahl erfolgt nach Bewertung.\nAus: Auto-Retry-Modus. Keine aktive upstream-Abfrage, zufällige Auswahl und automatischer Kontowechsel bei Fehlern mit bis zu 5 Wiederholungen.\nEmpfehlung: Bei mehr als 10.000 Konten ausschalten, um upstream 429 durch aktive Abfragen zu vermeiden." }, + "coolingBasicHours": { "label": "Basic-Abkühlung (Stunden)", "desc": "Abkühldauer nach 429 für Basic-Konten, Standard 20 h (entspricht dem upstream-20-h-Fenster). Nur im Auto-Retry-Modus wirksam." }, + "coolingSuperHours": { "label": "Super-Abkühlung (Stunden)", "desc": "Abkühldauer nach 429 für Super-Konten, Standard 2 h (entspricht dem upstream-2-h-Fenster). Nur im Auto-Retry-Modus wirksam." }, + "coolingHeavyHours": { "label": "Heavy-Abkühlung (Stunden)", "desc": "Abkühldauer nach 429 für Heavy-Konten, Standard 2 h (entspricht dem upstream-2-h-Fenster). Nur im Auto-Retry-Modus wirksam." }, + "maxInflight": { "label": "Max. laufende Anfragen pro Konto", "desc": "Maximale Anzahl gleichzeitig laufender Anfragen pro Konto. Konten am Limit werden von der Auswahl übersprungen (für beide Modi gemeinsam)." }, + "basicInterval": { "label": "Basic-Aktualisierungsintervall (s)", "desc": "Geplantes Aktualisierungsintervall für den Basic-Pool. Möglichst am Quotenfenster ausrichten (Standard 36000 s / 10 h)." }, + "superInterval": { "label": "Super-Aktualisierungsintervall (s)", "desc": "Geplantes Aktualisierungsintervall für den Super-Pool. Möglichst am Quotenfenster ausrichten (Standard 7200 s / 2 h)." }, + "heavyInterval": { "label": "Heavy-Aktualisierungsintervall (s)", "desc": "Geplantes Aktualisierungsintervall für den Heavy-Pool. Möglichst am Quotenfenster ausrichten (Standard 7200 s / 2 h)." }, + "usageConcurrency": { "label": "Aktualisierungs-Konkurrenz", "desc": "Maximale Anzahl paralleler usage-Aufrufe während der Quotenaktualisierung." }, + "onDemandMinInterval": { "label": "Minimales On-Demand-Intervall (s)", "desc": "Drosselungsfenster für durch Requests ausgelöste Aktualisierungen, z. B. nach 429. Wiederholte Auslöser innerhalb des Intervalls werden zu einer Aktualisierung zusammengefasst." }, "nsfwConcurrency": { "label": "Konkurrenz für NSFW-Aktivierung" }, "refreshConcurrency": { "label": "Usage-Aktualisierungskonkurrenz" }, "assetUploadConcurrency": { "label": "Asset-Upload-Konkurrenz" }, diff --git a/app/statics/i18n/en.json b/app/statics/i18n/en.json index 0b8dd3f1..2d529e25 100644 --- a/app/statics/i18n/en.json +++ b/app/statics/i18n/en.json @@ -331,6 +331,8 @@ "features": "Core Features", "mediaFormat": "Media Output", "refreshSchedule": "Quota Refresh", + "randomCooling": "Auto-Retry Cooldown", + "selection": "Selection Concurrency", "batchConcurrency": "Batch Concurrency", "egressProxy": "Egress Proxy", "clearance": "Cloudflare Clearance", @@ -433,6 +435,27 @@ "label": "Video Output Format", "desc": "local_* modes download video assets to the server and deliver them through the local proxy. Configure the APP Base URL first and account for outbound bandwidth usage." }, + "refreshEnabled": { + "label": "Enable Quota Refresh", + "desc": "Enables quota probing and scored selection. Recommended off for >10k accounts.", + "help": "On: quota refresh mode. The scheduler periodically syncs real quota, and selection uses scoring.\nOff: auto-retry mode. No upstream probing, uniform random selection, and auto-swap on errors for up to 5 retries.\nRecommendation: turn this off for >10k accounts to avoid self-triggering upstream 429s." + }, + "coolingBasicHours": { + "label": "Basic Cooldown (hours)", + "desc": "Cooldown duration after a 429 on basic-pool accounts, default 20h (matches upstream 20h window). Only effective in auto-retry mode." + }, + "coolingSuperHours": { + "label": "Super Cooldown (hours)", + "desc": "Cooldown duration after a 429 on super-pool accounts, default 2h (matches upstream 2h window). Only effective in auto-retry mode." + }, + "coolingHeavyHours": { + "label": "Heavy Cooldown (hours)", + "desc": "Cooldown duration after a 429 on heavy-pool accounts, default 2h (matches upstream 2h window). Only effective in auto-retry mode." + }, + "maxInflight": { + "label": "Max Inflight per Account", + "desc": "Maximum concurrent in-flight requests per account. Accounts at this limit are skipped by the selector (shared by both modes)." + }, "basicInterval": { "label": "Basic Refresh Interval (s)", "desc": "Scheduled quota refresh interval for the basic pool. Align this with the quota window when possible (default 36000 s / 10 h)." diff --git a/app/statics/i18n/es.json b/app/statics/i18n/es.json index 3ec90709..04f3c74b 100644 --- a/app/statics/i18n/es.json +++ b/app/statics/i18n/es.json @@ -330,6 +330,8 @@ "features": "Funciones principales", "mediaFormat": "Salida multimedia", "refreshSchedule": "Actualización de cuota", + "randomCooling": "Enfriamiento de reintento automático", + "selection": "Concurrencia de selección", "batchConcurrency": "Concurrencia por lotes", "egressProxy": "Proxy de salida", "clearance": "Cloudflare Clearance", @@ -381,11 +383,16 @@ "customInstruction": { "label": "Instrucción suplementaria global" }, "imageFormat": { "label": "Formato de salida de imagen" }, "videoFormat": { "label": "Formato de salida de video" }, - "basicInterval": { "label": "Intervalo de refresco Basic (s)" }, - "superInterval": { "label": "Intervalo de refresco Super (s)" }, - "heavyInterval": { "label": "Intervalo de refresco Heavy (s)" }, - "usageConcurrency": { "label": "Concurrencia de actualización" }, - "onDemandMinInterval": { "label": "Intervalo mínimo bajo demanda (s)" }, + "refreshEnabled": { "label": "Activar actualización de cuota", "desc": "Activa la comprobación de cuotas y la selección por puntuación; se recomienda desactivarlo con más de 10.000 cuentas.", "help": "Activado: modo de actualización de cuota. El scheduler sincroniza periódicamente la cuota real y la selección usa puntuación.\nDesactivado: modo de reintento automático. No comprueba upstream activamente, usa selección aleatoria y cambia de cuenta al fallar hasta 5 reintentos.\nRecomendación: desactívalo con más de 10.000 cuentas para evitar provocar 429 de upstream con comprobaciones activas." }, + "coolingBasicHours": { "label": "Enfriamiento Basic (horas)", "desc": "Duración del enfriamiento tras un 429 en cuentas Basic, por defecto 20 h (coincide con la ventana upstream de 20 h). Solo efectivo en modo de reintento automático." }, + "coolingSuperHours": { "label": "Enfriamiento Super (horas)", "desc": "Duración del enfriamiento tras un 429 en cuentas Super, por defecto 2 h (coincide con la ventana upstream de 2 h). Solo efectivo en modo de reintento automático." }, + "coolingHeavyHours": { "label": "Enfriamiento Heavy (horas)", "desc": "Duración del enfriamiento tras un 429 en cuentas Heavy, por defecto 2 h (coincide con la ventana upstream de 2 h). Solo efectivo en modo de reintento automático." }, + "maxInflight": { "label": "Máximo en curso por cuenta", "desc": "Máximo de solicitudes simultáneas en curso por cuenta. Las cuentas en ese límite se omiten en la selección (compartido por ambos modos)." }, + "basicInterval": { "label": "Intervalo de refresco Basic (s)", "desc": "Intervalo programado de actualización para el pool Basic. Alinéalo con la ventana de cuota cuando sea posible (por defecto 36000 s / 10 h)." }, + "superInterval": { "label": "Intervalo de refresco Super (s)", "desc": "Intervalo programado de actualización para el pool Super. Alinéalo con la ventana de cuota cuando sea posible (por defecto 7200 s / 2 h)." }, + "heavyInterval": { "label": "Intervalo de refresco Heavy (s)", "desc": "Intervalo programado de actualización para el pool Heavy. Alinéalo con la ventana de cuota cuando sea posible (por defecto 7200 s / 2 h)." }, + "usageConcurrency": { "label": "Concurrencia de actualización", "desc": "Número máximo de llamadas usage paralelas permitidas durante la actualización de cuota." }, + "onDemandMinInterval": { "label": "Intervalo mínimo bajo demanda (s)", "desc": "Ventana de limitación para actualizaciones activadas por solicitudes, como el manejo de 429. Los disparos repetidos dentro del intervalo se agrupan en una sola actualización." }, "nsfwConcurrency": { "label": "Concurrencia de activación NSFW" }, "refreshConcurrency": { "label": "Concurrencia de refresco de Usage" }, "assetUploadConcurrency": { "label": "Concurrencia de carga de Asset" }, diff --git a/app/statics/i18n/fr.json b/app/statics/i18n/fr.json index f947d753..71c87c50 100644 --- a/app/statics/i18n/fr.json +++ b/app/statics/i18n/fr.json @@ -330,6 +330,8 @@ "features": "Fonctionnalités principales", "mediaFormat": "Sortie multimédia", "refreshSchedule": "Actualisation du quota", + "randomCooling": "Refroidissement de relance automatique", + "selection": "Concurrence de sélection", "batchConcurrency": "Concurrence par lot", "egressProxy": "Proxy sortant", "clearance": "Cloudflare Clearance", @@ -381,11 +383,16 @@ "customInstruction": { "label": "Instruction globale supplémentaire" }, "imageFormat": { "label": "Format de sortie image" }, "videoFormat": { "label": "Format de sortie vidéo" }, - "basicInterval": { "label": "Intervalle d’actualisation Basic (s)" }, - "superInterval": { "label": "Intervalle d’actualisation Super (s)" }, - "heavyInterval": { "label": "Intervalle d’actualisation Heavy (s)" }, - "usageConcurrency": { "label": "Concurrence d’actualisation" }, - "onDemandMinInterval": { "label": "Intervalle minimal à la demande (s)" }, + "refreshEnabled": { "label": "Activer l’actualisation du quota", "desc": "Active la sonde de quota et la sélection par score ; recommandé désactivé au-delà de 10 000 comptes.", "help": "Activé : mode d’actualisation du quota. Le scheduler synchronise périodiquement le quota réel et la sélection utilise un score.\nDésactivé : mode de relance automatique. Aucune sonde upstream active, sélection aléatoire et changement automatique de compte en cas d’erreur jusqu’à 5 relances.\nRecommandation : désactivez-le au-delà de 10 000 comptes pour éviter de déclencher des 429 upstream par les sondes actives." }, + "coolingBasicHours": { "label": "Refroidissement Basic (heures)", "desc": "Durée de refroidissement après un 429 sur les comptes Basic, par défaut 20 h (alignée sur la fenêtre upstream de 20 h). Effectif uniquement en mode de relance automatique." }, + "coolingSuperHours": { "label": "Refroidissement Super (heures)", "desc": "Durée de refroidissement après un 429 sur les comptes Super, par défaut 2 h (alignée sur la fenêtre upstream de 2 h). Effectif uniquement en mode de relance automatique." }, + "coolingHeavyHours": { "label": "Refroidissement Heavy (heures)", "desc": "Durée de refroidissement après un 429 sur les comptes Heavy, par défaut 2 h (alignée sur la fenêtre upstream de 2 h). Effectif uniquement en mode de relance automatique." }, + "maxInflight": { "label": "Maximum en cours par compte", "desc": "Nombre maximal de requêtes simultanées par compte. Les comptes à cette limite sont ignorés par la sélection (partagé par les deux modes)." }, + "basicInterval": { "label": "Intervalle d’actualisation Basic (s)", "desc": "Intervalle d’actualisation planifiée du pool Basic. À aligner avec la fenêtre de quota si possible (par défaut 36000 s / 10 h)." }, + "superInterval": { "label": "Intervalle d’actualisation Super (s)", "desc": "Intervalle d’actualisation planifiée du pool Super. À aligner avec la fenêtre de quota si possible (par défaut 7200 s / 2 h)." }, + "heavyInterval": { "label": "Intervalle d’actualisation Heavy (s)", "desc": "Intervalle d’actualisation planifiée du pool Heavy. À aligner avec la fenêtre de quota si possible (par défaut 7200 s / 2 h)." }, + "usageConcurrency": { "label": "Concurrence d’actualisation", "desc": "Nombre maximal d’appels usage parallèles autorisés pendant l’actualisation du quota." }, + "onDemandMinInterval": { "label": "Intervalle minimal à la demande (s)", "desc": "Fenêtre de limitation pour les actualisations déclenchées par les requêtes, par exemple après un 429. Les déclenchements répétés dans l’intervalle sont regroupés en une seule actualisation." }, "nsfwConcurrency": { "label": "Concurrence d’activation NSFW" }, "refreshConcurrency": { "label": "Concurrence d’actualisation Usage" }, "assetUploadConcurrency": { "label": "Concurrence d’envoi Asset" }, diff --git a/app/statics/i18n/ja.json b/app/statics/i18n/ja.json index b5fb9ae2..227deb34 100644 --- a/app/statics/i18n/ja.json +++ b/app/statics/i18n/ja.json @@ -330,6 +330,8 @@ "features": "基本機能", "mediaFormat": "メディア出力", "refreshSchedule": "クォータ更新", + "randomCooling": "自動再試行クールダウン", + "selection": "選択同時実行数", "batchConcurrency": "一括処理の並列数", "egressProxy": "送信プロキシ", "clearance": "Cloudflare Clearance", @@ -381,11 +383,16 @@ "customInstruction": { "label": "グローバル補助指示" }, "imageFormat": { "label": "画像出力形式" }, "videoFormat": { "label": "動画出力形式" }, - "basicInterval": { "label": "Basic 更新間隔(秒)" }, - "superInterval": { "label": "Super 更新間隔(秒)" }, - "heavyInterval": { "label": "Heavy 更新間隔(秒)" }, - "usageConcurrency": { "label": "更新並列数" }, - "onDemandMinInterval": { "label": "最小オンデマンド更新間隔(秒)" }, + "refreshEnabled": { "label": "クォータ更新を有効化", "desc": "クォータ確認とスコア選択を有効にします。1 万件以上のアカウントでは無効化を推奨します。", "help": "オン:クォータ更新モード。scheduler が実クォータを定期同期し、スコアでアカウントを選択します。\nオフ:自動再試行モード。upstream を能動的に確認せず、ランダム選択し、エラー時は最大 5 回まで別アカウントへ自動切替します。\n推奨:1 万件以上のアカウントではオフにして、能動確認による upstream 429 を避けてください。" }, + "coolingBasicHours": { "label": "Basic クールダウン(時間)", "desc": "Basic アカウントで 429 を受けた後のクールダウン時間。既定は 20 h(upstream の 20 h ウィンドウに対応)。自動再試行モードでのみ有効です。" }, + "coolingSuperHours": { "label": "Super クールダウン(時間)", "desc": "Super アカウントで 429 を受けた後のクールダウン時間。既定は 2 h(upstream の 2 h ウィンドウに対応)。自動再試行モードでのみ有効です。" }, + "coolingHeavyHours": { "label": "Heavy クールダウン(時間)", "desc": "Heavy アカウントで 429 を受けた後のクールダウン時間。既定は 2 h(upstream の 2 h ウィンドウに対応)。自動再試行モードでのみ有効です。" }, + "maxInflight": { "label": "アカウントごとの同時実行上限", "desc": "1 アカウントで同時に処理中にできるリクエスト数の上限です。上限に達したアカウントは選択時にスキップされます(両モード共通)。" }, + "basicInterval": { "label": "Basic 更新間隔(秒)", "desc": "Basic プールの定期クォータ更新間隔です。可能ならクォータウィンドウに合わせてください(既定 36000 s / 10 h)。" }, + "superInterval": { "label": "Super 更新間隔(秒)", "desc": "Super プールの定期クォータ更新間隔です。可能ならクォータウィンドウに合わせてください(既定 7200 s / 2 h)。" }, + "heavyInterval": { "label": "Heavy 更新間隔(秒)", "desc": "Heavy プールの定期クォータ更新間隔です。可能ならクォータウィンドウに合わせてください(既定 7200 s / 2 h)。" }, + "usageConcurrency": { "label": "更新並列数", "desc": "クォータ更新中に許可する usage 呼び出しの最大並列数です。" }, + "onDemandMinInterval": { "label": "最小オンデマンド更新間隔(秒)", "desc": "429 処理など、リクエスト経路から発生する更新のスロットル間隔です。この間隔内の重複トリガーは 1 回の更新にまとめられます。" }, "nsfwConcurrency": { "label": "NSFW 有効化の並列数" }, "refreshConcurrency": { "label": "Usage 更新の並列数" }, "assetUploadConcurrency": { "label": "Asset アップロード並列数" }, diff --git a/app/statics/i18n/zh.json b/app/statics/i18n/zh.json index 6f88402b..1f21050b 100644 --- a/app/statics/i18n/zh.json +++ b/app/statics/i18n/zh.json @@ -331,6 +331,8 @@ "features": "基本功能设置", "mediaFormat": "媒体返回格式", "refreshSchedule": "配额刷新调度", + "randomCooling": "自动重试冷却", + "selection": "选号并发限制", "batchConcurrency": "批量操作并发", "egressProxy": "出站代理设置", "clearance": "Cloudflare Clearance", @@ -433,6 +435,27 @@ "label": "视频返回格式", "desc": "local_* 模式会先将视频下载至服务端,再通过本地 URL 代理分发;请确保已配置 APP 访问地址,并评估出站带宽消耗。" }, + "refreshEnabled": { + "label": "启用配额刷新", + "desc": "开启配额探测和评分选号;万级以上账号建议关闭。", + "help": "开启:配额刷新模式,scheduler 周期同步真实配额,选号按评分。\n关闭:自动重试模式,不主动探测 upstream,选号随机,出错自动换号重试最多 5 次。\n建议:万级以上账号关闭,避免主动探测触发 upstream 429。" + }, + "coolingBasicHours": { + "label": "Basic 冷却(小时)", + "desc": "basic 号收到 429 后的冷却时长,默认 20 h(对齐 upstream 20 h 限流窗口)。仅在自动重试模式下生效。" + }, + "coolingSuperHours": { + "label": "Super 冷却(小时)", + "desc": "super 号收到 429 后的冷却时长,默认 2 h(对齐 upstream 2 h 限流窗口)。仅在自动重试模式下生效。" + }, + "coolingHeavyHours": { + "label": "Heavy 冷却(小时)", + "desc": "heavy 号收到 429 后的冷却时长,默认 2 h(对齐 upstream 2 h 限流窗口)。仅在自动重试模式下生效。" + }, + "maxInflight": { + "label": "单号并发上限", + "desc": "单个账号同时在执行的请求上限,超过则选号路径跳过该号(两种模式共用)。" + }, "basicInterval": { "label": "Basic 刷新周期(秒)", "desc": "basic 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 36000 s / 10 h)。" diff --git a/config.defaults.toml b/config.defaults.toml index 4a716fef..2e64cd87 100644 --- a/config.defaults.toml +++ b/config.defaults.toml @@ -103,6 +103,8 @@ on_codes = "429,401,503" [account.refresh] +# 总开关:true=配额刷新模式(主动探测,选号评分);false=自动重试模式(随机选号,零探测) +enabled = true basic_interval_sec = 36000 # basic 号池刷新周期(秒),默认 10 h super_interval_sec = 7200 # super 号池刷新周期(秒),默认 2 h heavy_interval_sec = 7200 # heavy 号池刷新周期(秒),默认 2 h @@ -110,6 +112,18 @@ usage_concurrency = 50 on_demand_min_interval_sec = 300 +[account.random] +# 仅 account.refresh.enabled=false 时生效 +# 429 后按 pool 冷却的小时数(对齐 upstream 限流窗口) +cooling_basic_hours = 20 +cooling_heavy_hours = 2 + + +[account.selection] +# 单号并发上限(两模式共用) +max_inflight = 8 + + # ==================== 对话配置 ==================== [chat] timeout = 60