"""Bounded admission and model health for existing async request factories. This module never retries, spawns a worker, or changes a factory's result/error. Use one controller on one event loop; factories must cooperate with cancellation. Model names must be trusted, nonsecret identifiers. External reports inside an owned lease are coalesced into that run's outcome, including returned partials. Priority 3 is highest. Waiting requests gain one priority level per aging period; FIFO breaks ties. A queued request survives a subsequently opened circuit without holding a permit. New requests fail fast while the circuit is open/probing. """ from __future__ import annotations import asyncio import math import time from collections import OrderedDict, deque from contextvars import ContextVar from dataclasses import dataclass, field from typing import Awaitable, Callable, TypeVar __all__ = ( "StabilityError", "QueueFull", "DeadlineExceeded", "CircuitOpen", "StabilityController", ) T = TypeVar("T") _MAX_MODELS = 128 _MAX_QUEUE = 64 _MAX_USER_QUEUE = 2 _MAX_MODEL_LENGTH = 128 _RECENT_LIMIT = 128 _RECOVERY_SUCCESSES = 8 _FAILURE_STATUSES = frozenset((429, 500, 502, 503, 504)) _OUTCOMES = ("success", "partial", "error", "dependency_failure", "deadline_exceeded", "cancelled") _REJECTS = ("queue_full", "circuit_open") class StabilityError(RuntimeError): """A terminal admission/deadline error, safe to display without its cause.""" terminal = True stability_code = "stability_error" public_message = "Не удалось выполнить запрос. Попробуйте позже." def __init__(self) -> None: super().__init__(self.public_message) class QueueFull(StabilityError): stability_code = "queue_full" public_message = "Сейчас слишком много запросов. Попробуйте позже." class DeadlineExceeded(StabilityError): stability_code = "deadline_exceeded" public_message = "Время ожидания запроса истекло. Попробуйте позже." class CircuitOpen(StabilityError): stability_code = "circuit_open" public_message = "Модель временно недоступна. Попробуйте позже." def _counts(keys: tuple[str, ...]) -> dict[str, int]: return dict.fromkeys(keys, 0) def _positive_int(name: str, value: int, maximum: int | None = None) -> int: if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ValueError(f"{name} must be a positive integer") if maximum is not None and value > maximum: raise ValueError(f"{name} must not exceed {maximum}") return value def _positive_seconds(name: str, value: float) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{name} must be finite and positive") try: result = float(value) except (OverflowError, ValueError) as exc: raise ValueError(f"{name} must be finite and positive") from exc if not math.isfinite(result) or result <= 0: raise ValueError(f"{name} must be finite and positive") return result def _model_name(model: str) -> str: if (not isinstance(model, str) or not model or len(model) > _MAX_MODEL_LENGTH or model.isspace() or any(ord(char) < 32 for char in model)): raise ValueError("model must be a nonempty identifier of at most 128 characters") return model def _dependency_failure(error: BaseException) -> bool: """Only explicit upstream evidence, never a local or delivery timeout.""" if isinstance(error, StabilityError): return False try: status = getattr(error, "upstream_status", None) if status is not None: # A definite auth/input/billing/identity status wins over a marker. return (not isinstance(status, bool) and isinstance(status, int) and status in _FAILURE_STATUSES) return getattr(error, "stability_dependency_failure", False) is True except Exception: # A broken exception attribute must never replace the original error. return False @dataclass(slots=True) class _Sample: queue_seconds: float latency_seconds: float | None @dataclass(slots=True) class _Model: name: str limit: int active: int = 0 queued: int = 0 circuit_until: float | None = None probe_active: bool = False epoch: int = 0 success_streak: int = 0 outcomes: dict[str, int] = field(default_factory=lambda: _counts(_OUTCOMES)) rejects: dict[str, int] = field(default_factory=lambda: _counts(_REJECTS)) recent: deque[_Sample] = field(default_factory=lambda: deque(maxlen=_RECENT_LIMIT)) @dataclass(slots=True) class _Lease: controller: StabilityController state: _Model owner: asyncio.Task user_id: int deadline: float loop_deadline: float epoch: int probe: bool started_at: float | None = None released: bool = False deadline_failure: bool = False reported_outcome: str | None = None timeout_scope: asyncio.Timeout | None = None @dataclass(slots=True, eq=False) class _Request: state: _Model owner: asyncio.Task user_id: int priority: int sequence: int enqueued_at: float deadline: float loop_deadline: float future: asyncio.Future[_Lease] queued: bool = False lease: _Lease | None = None finished: bool = False # Context is inherited by child tasks, but every lookup ALSO checks task identity. _LEASES: ContextVar[tuple[_Lease, ...]] = ContextVar("request_stability_leases", default=()) def _timings(samples: deque[_Sample]) -> dict[str, float | int | None]: queues = sorted(sample.queue_seconds for sample in samples) latencies = sorted(sample.latency_seconds for sample in samples if sample.latency_seconds is not None) def percentile(values: list[float], fraction: float) -> float | None: # Nearest-rank percentiles; no synthetic observations when empty. return values[max(0, math.ceil(len(values) * fraction) - 1)] if values else None return { "recent_samples": len(samples), "latency_p50_seconds": percentile(latencies, 0.50), "latency_p95_seconds": percentile(latencies, 0.95), "queue_p50_seconds": percentile(queues, 0.50), "queue_p95_seconds": percentile(queues, 0.95), } class StabilityController: """Single-event-loop scheduler; all state transitions are synchronous. There is deliberately no admission lock held over an await. Background user 0 is exempt from both user caps, but not global/model capacity or global queue. Nested calls in the same task/model reuse one lease and can shorten, never extend, its deadline. Different-model nesting needs a separate permit. """ def __init__(self, global_limit: int = 24, model_limit: int = 4, user_limit: int = 1, queue_limit: int = 64, aging_seconds: float = 15.0, circuit_seconds: float = 20.0, clock: Callable[[], float] = time.monotonic) -> None: self.global_limit = _positive_int("global_limit", global_limit) self.model_limit = _positive_int("model_limit", model_limit) self.user_limit = _positive_int("user_limit", user_limit) self.queue_limit = _positive_int("queue_limit", queue_limit, _MAX_QUEUE) self.aging_seconds = _positive_seconds("aging_seconds", aging_seconds) self.circuit_seconds = _positive_seconds("circuit_seconds", circuit_seconds) if not callable(clock): raise ValueError("clock must be callable") self._clock = clock self._now() # Reject an invalid clock before any admission is possible. self._loop: asyncio.AbstractEventLoop | None = None self._wakeup: asyncio.TimerHandle | None = None self._models: OrderedDict[str, _Model] = OrderedDict() self._waiting: list[_Request] = [] self._active = 0 self._users_active: dict[int, int] = {} self._users_queued: dict[int, int] = {} self._sequence = 0 self._outcomes = _counts(_OUTCOMES) self._rejects = _counts(_REJECTS) # Report paths run inside exception handlers; they must never raise. self._dropped_reports = 0 self._recent: deque[_Sample] = deque(maxlen=_RECENT_LIMIT) def _now(self) -> float: value = self._clock() if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError("clock must return a finite monotonic number") try: value = float(value) except (OverflowError, ValueError) as exc: raise ValueError("clock must return a finite monotonic number") from exc if not math.isfinite(value): raise ValueError("clock must return a finite monotonic number") return value def _check_loop(self) -> None: if self._loop is not None: try: loop = asyncio.get_running_loop() except RuntimeError as exc: raise RuntimeError("controller must be used on its owning event loop") from exc if loop is not self._loop: raise RuntimeError("controller cannot be shared across event loops") def _bind_loop(self) -> asyncio.AbstractEventLoop: self._check_loop() loop = asyncio.get_running_loop() if self._loop is None: self._loop = loop return loop def _reject(self, code: str, state: _Model | None = None) -> None: self._rejects[code] += 1 if state is not None: state.rejects[code] += 1 raise QueueFull() if code == "queue_full" else CircuitOpen() def _state(self, model: str, now: float) -> _Model: state = self._models.get(model) if state is not None: self._models.move_to_end(model) return state if len(self._models) >= _MAX_MODELS: # In-flight/queued states and unexpired protection cannot be evicted. victim = next((name for name, item in self._models.items() if item.active == 0 and item.queued == 0 and (item.circuit_until is None or item.circuit_until <= now)), None) if victim is None: self._reject("queue_full") del self._models[victim] state = _Model(model, self.model_limit) self._models[model] = state return state def _report_state(self, model: str, now: float) -> _Model | None: """Reports are called from exception handlers; a full table drops the sample.""" try: return self._state(model, now) except QueueFull: self._dropped_reports += 1 return None def _expired(self, deadline: float, loop_deadline: float, now: float) -> bool: return now >= deadline or self._loop.time() >= loop_deadline def _ready(self, state: _Model, user_id: int, now: float) -> bool: if self._active >= self.global_limit or state.active >= state.limit: return False if user_id != 0 and self._users_active.get(user_id, 0) >= self.user_limit: return False if state.circuit_until is not None: return (now >= state.circuit_until and not state.probe_active and state.active == 0) return True def _unqueue(self, request: _Request) -> None: if not request.queued: return request.queued = False self._waiting.remove(request) request.state.queued -= 1 count = self._users_queued[request.user_id] - 1 if count: self._users_queued[request.user_id] = count else: del self._users_queued[request.user_id] def _grant(self, request: _Request) -> None: state = request.state self._unqueue(request) probe = state.circuit_until is not None if probe: state.probe_active = True lease = _Lease(self, state, request.owner, request.user_id, request.deadline, request.loop_deadline, state.epoch, probe) request.lease = lease self._active += 1 state.active += 1 if request.user_id != 0: self._users_active[request.user_id] = self._users_active.get(request.user_id, 0) + 1 request.future.set_result(lease) def _rank(self, request: _Request, now: float) -> tuple[int, int]: elapsed = max(0.0, now - request.enqueued_at) # Saturate before division, including for tiny valid aging periods. age = 3 if elapsed >= 3 * self.aging_seconds else int(elapsed / self.aging_seconds) return -min(3, request.priority + age), request.sequence def _dispatch(self, now: float) -> None: # Removing every expired waiter first prevents it consuming a released slot. for request in tuple(self._waiting): if request.future.done(): self._unqueue(request) elif self._expired(request.deadline, request.loop_deadline, now): self._unqueue(request) request.future.set_exception(DeadlineExceeded()) while self._active < self.global_limit: ready = (request for request in self._waiting if self._ready(request.state, request.user_id, now)) request = min(ready, key=lambda item: self._rank(item, now), default=None) if request is None: break self._grant(request) self._schedule_wakeup(now) def _schedule_wakeup(self, now: float) -> None: if self._wakeup is not None: self._wakeup.cancel() self._wakeup = None if self._loop is None or not self._waiting: return times = [request.state.circuit_until for request in self._waiting if request.state.circuit_until is not None and request.state.circuit_until > now] if times: # A timer is needed only for existing cooldown waiters, never while idle. self._wakeup = self._loop.call_later(min(times) - now, self._on_wakeup) def _on_wakeup(self) -> None: self._wakeup = None self._dispatch(self._now()) def _submit(self, model: str, owner: asyncio.Task, user_id: int, priority: int, deadline: float, loop_deadline: float, now: float) -> _Request: self._dispatch(now) state = self._state(model, now) if state.circuit_until is not None and (now < state.circuit_until or state.probe_active): self._reject("circuit_open", state) self._sequence += 1 request = _Request(state, owner, user_id, priority, self._sequence, now, deadline, loop_deadline, self._loop.create_future()) if self._expired(deadline, loop_deadline, now): request.future.set_exception(DeadlineExceeded()) elif self._ready(state, user_id, now): self._grant(request) else: if (len(self._waiting) >= self.queue_limit or (user_id != 0 and self._users_queued.get(user_id, 0) >= _MAX_USER_QUEUE)): self._reject("queue_full", state) request.queued = True self._waiting.append(request) state.queued += 1 self._users_queued[user_id] = self._users_queued.get(user_id, 0) + 1 self._schedule_wakeup(now) return request def _owned_lease(self, model: str) -> _Lease | None: try: owner = asyncio.current_task() except RuntimeError: return None return next((lease for lease in reversed(_LEASES.get()) if lease.controller is self and lease.owner is owner and lease.state.name == model and not lease.released), None) def _health_failure(self, state: _Model, now: float) -> None: state.epoch += 1 state.circuit_until = now + self.circuit_seconds state.probe_active = False state.success_streak = 0 state.limit = max(1, state.limit // 2) def _health_success(self, state: _Model, lease: _Lease | None = None) -> None: if lease is not None: # An older in-flight success cannot undo a newer confirmed failure. if lease.epoch != state.epoch: return if state.circuit_until is not None and not lease.probe: return state.circuit_until = None state.probe_active = False if state.limit < self.model_limit: state.success_streak += 1 if state.success_streak >= _RECOVERY_SUCCESSES: state.limit += 1 state.success_streak = 0 else: state.success_streak = 0 def _finish(self, request: _Request, outcome: str, dependency_failure: bool) -> None: if request.finished: return request.finished = True now = self._now() self._unqueue(request) if not request.future.done(): request.future.cancel() elif not request.future.cancelled(): request.future.exception() lease = request.lease state = request.state if lease is not None and lease.reported_outcome == "dependency_failure": # The explicit report already opened/reduced health exactly once. dependency_failure = False if outcome in ("success", "error", "dependency_failure"): outcome = "dependency_failure" elif lease is not None and lease.reported_outcome == "partial" and outcome in ("success", "error"): outcome = "partial" elif lease is not None and lease.reported_outcome == "error" and outcome == "success": outcome = "error" if lease is not None and not lease.released: lease.released = True self._active -= 1 state.active -= 1 if lease.user_id != 0: count = self._users_active[lease.user_id] - 1 if count: self._users_active[lease.user_id] = count else: del self._users_active[lease.user_id] if lease.probe and lease.epoch == state.epoch: state.probe_active = False if dependency_failure: self._health_failure(state, now) elif outcome == "success": self._health_success(state, lease) elif outcome in ("error", "partial"): state.success_streak = 0 self._outcomes[outcome] += 1 state.outcomes[outcome] += 1 started = lease.started_at if lease is not None else None sample = _Sample(max(0.0, (started if started is not None else now) - request.enqueued_at), max(0.0, now - started) if started is not None else None) state.recent.append(sample) self._recent.append(sample) self._dispatch(now) async def _nested(self, lease: _Lease, factory: Callable[[], Awaitable[T]], deadline: float, loop_deadline: float) -> T: # A shorter nested budget constrains the whole lease, not just its wrapper. lease.deadline = min(lease.deadline, deadline) lease.loop_deadline = min(lease.loop_deadline, loop_deadline) if (lease.timeout_scope.expired() or self._expired(lease.deadline, lease.loop_deadline, self._now())): lease.deadline_failure = True raise DeadlineExceeded() lease.timeout_scope.reschedule(lease.loop_deadline) scope = asyncio.timeout_at(lease.loop_deadline) try: async with scope: if self._expired(lease.deadline, lease.loop_deadline, self._now()): lease.deadline_failure = True raise DeadlineExceeded() result = await factory() if scope.expired() or self._expired(lease.deadline, lease.loop_deadline, self._now()): lease.deadline_failure = True if (getattr(result, "stability_partial", False) is True and lease.reported_outcome in ("partial", "dependency_failure")): return result raise DeadlineExceeded() return result except TimeoutError as exc: if scope.expired(): lease.deadline_failure = True raise DeadlineExceeded() from exc raise async def run(self, model: str, factory: Callable[[], Awaitable[T]], *, user_id: int = 0, priority: int = 0, timeout: float = 180.0) -> T: """Run exactly once within one queue+execution monotonic deadline. Only this method's own deadline becomes DeadlineExceeded. Factory-raised exceptions retain their identity; upstream_status and the explicit stability_dependency_failure marker control health classification. """ model = _model_name(model) timeout = _positive_seconds("timeout", timeout) if not callable(factory): raise ValueError("factory must be callable") if isinstance(user_id, bool) or not isinstance(user_id, int): raise ValueError("user_id must be an integer") if isinstance(priority, bool) or not isinstance(priority, int): raise ValueError("priority must be an integer") priority = min(3, max(0, priority)) loop = self._bind_loop() owner = asyncio.current_task() now = self._now() deadline, loop_deadline = now + timeout, loop.time() + timeout if not math.isfinite(deadline) or not math.isfinite(loop_deadline): raise ValueError("timeout produces a nonfinite deadline") owned = tuple(lease for lease in _LEASES.get() if lease.controller is self and lease.owner is owner and not lease.released) for lease in owned: deadline = min(deadline, lease.deadline) loop_deadline = min(loop_deadline, lease.loop_deadline) same = next((lease for lease in reversed(owned) if lease.state.name == model), None) if same is not None: return await self._nested(same, factory, deadline, loop_deadline) if (user_id != 0 and sum(lease.user_id == user_id for lease in owned) >= self.user_limit): # Waiting on our own user slot can never make progress. self._reject("queue_full", self._models.get(model)) request: _Request | None = None outcome = "error" dependency_failure = False scope = asyncio.timeout_at(loop_deadline) try: async with scope: request = self._submit(model, owner, user_id, priority, deadline, loop_deadline, now) lease = await asyncio.shield(request.future) if owner.cancelling(): raise asyncio.CancelledError() if self._expired(lease.deadline, lease.loop_deadline, self._now()): raise DeadlineExceeded() lease.started_at = self._now() lease.timeout_scope = scope # Do not accumulate inherited parent-task leases in descendants. current = tuple(item for item in _LEASES.get() if item.owner is owner and not item.released) token = _LEASES.set(current + (lease,)) try: result = await factory() if scope.expired() or self._expired(lease.deadline, lease.loop_deadline, self._now()): lease.deadline_failure = True if (getattr(result, "stability_partial", False) is True and lease.reported_outcome in ("partial", "dependency_failure")): outcome = "success" return result raise DeadlineExceeded() outcome = "success" return result finally: _LEASES.reset(token) except TimeoutError as exc: if scope.expired(): outcome = "deadline_exceeded" dependency_failure = False raise DeadlineExceeded() from exc dependency_failure = _dependency_failure(exc) outcome = "dependency_failure" if dependency_failure else "error" raise except DeadlineExceeded: outcome = "deadline_exceeded" dependency_failure = False raise except asyncio.CancelledError: outcome = "cancelled" raise except BaseException as exc: dependency_failure = _dependency_failure(exc) outcome = "dependency_failure" if dependency_failure else "error" raise finally: if request is not None: self._finish(request, outcome, dependency_failure) def report_partial(self, model: str) -> None: """Record incomplete delivery without inventing an upstream health failure.""" self._check_loop() model = _model_name(model) state = self._report_state(model, self._now()) if state is None: return lease = self._owned_lease(model) if lease is not None: if lease.reported_outcome != "dependency_failure": lease.reported_outcome = "partial" else: state.outcomes["partial"] += 1 self._outcomes["partial"] += 1 state.success_streak = 0 def report_failure(self, model: str, status: int | None = None) -> None: """Record a confirmed observation; None means dependency/transport failure. An owner-task/model report is coalesced into the lease's final outcome; confirmed failures affect health immediately, without counting twice. Outside a lease, reports add an outcome but no invented latency sample. Nonfailure HTTP statuses never open a circuit. """ self._check_loop() model = _model_name(model) if status is not None and (isinstance(status, bool) or not isinstance(status, int) or not 100 <= status <= 599): raise ValueError("status must be an HTTP status integer or None") now = self._now() state = self._report_state(model, now) if state is None: return confirmed = status is None or status in _FAILURE_STATUSES outcome = "dependency_failure" if confirmed else "error" lease = self._owned_lease(model) if lease is not None: if confirmed and lease.reported_outcome != "dependency_failure": lease.reported_outcome = "dependency_failure" self._health_failure(state, now) elif not confirmed and lease.reported_outcome is None: lease.reported_outcome = "error" state.success_streak = 0 self._dispatch(now) return state.outcomes[outcome] += 1 self._outcomes[outcome] += 1 if confirmed: self._health_failure(state, now) else: state.success_streak = 0 self._dispatch(now) def report_success(self, model: str) -> None: """Record external success; owner-lease success is accounted on completion.""" self._check_loop() model = _model_name(model) if self._owned_lease(model) is not None: # In particular, never undo an explicitly reported partial failure. return now = self._now() state = self._report_state(model, now) if state is None: return state.outcomes["success"] += 1 self._outcomes["success"] += 1 # An unowned report cannot bypass cooldown or the exclusive recovery probe. if state.circuit_until is None: self._health_success(state) self._dispatch(now) def snapshot(self) -> dict: """Return detached, bounded nonsecret aggregates (seconds; no TPS estimate).""" self._check_loop() now = self._now() models = {} for name, state in self._models.items(): circuit = ("closed" if state.circuit_until is None else "open" if now < state.circuit_until else "half_open") models[name] = { "active": state.active, "queued": state.queued, "limit": state.limit, "hard_limit": self.model_limit, "circuit": circuit, "probe_active": state.probe_active, "retry_after_seconds": max(0.0, state.circuit_until - now) if state.circuit_until is not None else 0.0, "outcomes": dict(state.outcomes), "rejects": dict(state.rejects), **_timings(state.recent), } return { "active": self._active, "queued": len(self._waiting), "model_count": len(self._models), "limits": {"global": self.global_limit, "model": self.model_limit, "user": self.user_limit, "queue": self.queue_limit, "user_queue": _MAX_USER_QUEUE, "models": _MAX_MODELS, "recent": _RECENT_LIMIT}, "outcomes": dict(self._outcomes), "rejects": dict(self._rejects), "dropped_reports": self._dropped_reports, **_timings(self._recent), "models": models, }