Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

feat: pluggable QuotaTracker ABC + QuotaTrackerRegistry

JerrettDavisc03b9cca05fa
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index fae3e9883..d80b759fd 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -127,12 +127,12 @@ from headroom.proxy.prometheus_metrics import PrometheusMetrics # noqa: F401
from headroom.proxy.rate_limiter import TokenBucketRateLimiter # noqa: F401
from headroom.proxy.request_logger import RequestLogger # noqa: F401
from headroom.proxy.semantic_cache import SemanticCache # noqa: F401
+from headroom.subscription.base import get_quota_registry
from headroom.subscription.codex_rate_limits import get_codex_rate_limit_state
-from headroom.subscription.copilot_quota import discover_github_token, get_copilot_quota_tracker
+from headroom.subscription.copilot_quota import get_copilot_quota_tracker
from headroom.subscription.tracker import (
configure_subscription_tracker,
get_subscription_tracker,
- shutdown_subscription_tracker,
)
from headroom.telemetry import get_telemetry_collector
from headroom.telemetry.beacon import is_telemetry_enabled
@@ -156,19 +156,6 @@ _build_session_summary = build_session_summary
_merge_cost_stats = merge_cost_stats
-def _get_codex_rate_limit_stats() -> dict | None:
- """Return the latest Codex rate-limit snapshot for the /stats endpoint."""
- return get_codex_rate_limit_state().get_stats()
-
-
-def _get_copilot_quota_stats() -> dict | None:
- """Return the latest GitHub Copilot quota snapshot for the /stats endpoint."""
- state = get_copilot_quota_tracker().state
- if state.get("latest") is None and state.get("last_error") is None:
- return None
- return state
-
-
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
@@ -683,13 +670,19 @@ class HeadroomProxy(
logger.info("CCR: DISABLED")
logger.info(f"Savings history: {self.metrics.savings_tracker.storage_path}")
- # Subscription window tracker (Anthropic OAuth accounts)
+ # Register all quota trackers and start them via the registry
+ registry = get_quota_registry()
+ tracker = configure_subscription_tracker(
+ poll_interval_s=self.config.subscription_poll_interval_s,
+ active_window_s=self.config.subscription_active_window_s,
+ enabled=self.config.subscription_tracking_enabled,
+ )
+ registry.register(tracker)
+ registry.register(get_codex_rate_limit_state())
+ registry.register(get_copilot_quota_tracker())
+ await registry.start_all()
+
if self.config.subscription_tracking_enabled:
- tracker = configure_subscription_tracker(
- poll_interval_s=self.config.subscription_poll_interval_s,
- active_window_s=self.config.subscription_active_window_s,
- )
- await tracker.start()
logger.info(
"Subscription tracking: ENABLED "
f"(poll_interval={self.config.subscription_poll_interval_s}s, "
@@ -698,10 +691,8 @@ class HeadroomProxy(
else:
logger.info("Subscription tracking: DISABLED")
- # Start GitHub Copilot quota tracking if a GitHub token is available
- if discover_github_token():
- copilot_tracker = get_copilot_quota_tracker()
- await copilot_tracker.start()
+ copilot_tracker = get_copilot_quota_tracker()
+ if copilot_tracker.is_available():
logger.info("GitHub Copilot quota tracking: ENABLED")
else:
logger.info(
@@ -727,11 +718,8 @@ class HeadroomProxy(
if self.memory_handler and hasattr(self.memory_handler, "close"):
await self.memory_handler.close()
- # Stop subscription tracker
- await shutdown_subscription_tracker()
-
- # Stop Copilot quota tracker
- await get_copilot_quota_tracker().stop()
+ # Stop all quota trackers via the registry
+ await get_quota_registry().stop_all()
# Print final stats
self._print_summary()
@@ -1420,11 +1408,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"cache": await proxy.cache.stats() if proxy.cache else None,
"rate_limiter": await proxy.rate_limiter.stats() if proxy.rate_limiter else None,
"recent_requests": proxy.logger.get_recent(10) if proxy.logger else [],
- "subscription_window": get_subscription_tracker().state
- if get_subscription_tracker()
- else None,
- "codex_rate_limits": _get_codex_rate_limit_stats(),
- "copilot_quota": _get_copilot_quota_stats(),
+ **get_quota_registry().get_all_stats(),
}
@app.get("/stats-history")
@@ -1454,6 +1438,11 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
)
return JSONResponse(content=tracker.state)
+ @app.get("/quota")
+ async def quota():
+ """Unified quota/rate-limit stats for all registered providers (Anthropic, Codex, Copilot)."""
+ return JSONResponse(content=get_quota_registry().get_all_stats())
+
@app.get("/metrics")
async def metrics():
"""Prometheus metrics endpoint."""
diff --git a/headroom/subscription/__init__.py b/headroom/subscription/__init__.py
index d40a3aca0..e4760c942 100644
--- a/headroom/subscription/__init__.py
+++ b/headroom/subscription/__init__.py
@@ -1,5 +1,11 @@
"""Subscription window tracking for Anthropic Claude Code accounts and Codex rate limits."""
+from headroom.subscription.base import (
+ QuotaTracker,
+ QuotaTrackerRegistry,
+ get_quota_registry,
+ reset_quota_registry,
+)
from headroom.subscription.client import SubscriptionClient, read_cached_oauth_token
from headroom.subscription.codex_rate_limits import (
CodexCreditsSnapshot,
@@ -43,6 +49,8 @@ __all__ = [
"CopilotQuotaState",
"ExtraUsage",
"HeadroomContribution",
+ "QuotaTracker",
+ "QuotaTrackerRegistry",
"RateLimitWindow",
"SubscriptionClient",
"SubscriptionSnapshot",
@@ -54,9 +62,11 @@ __all__ = [
"discover_github_token",
"get_codex_rate_limit_state",
"get_copilot_quota_tracker",
+ "get_quota_registry",
"get_subscription_tracker",
"parse_codex_rate_limits",
"parse_copilot_quota",
"read_cached_oauth_token",
+ "reset_quota_registry",
"shutdown_subscription_tracker",
]
diff --git a/headroom/subscription/base.py b/headroom/subscription/base.py
new file mode 100644
index 000000000..c6664f5a8
--- /dev/null
+++ b/headroom/subscription/base.py
@@ -0,0 +1,230 @@
+"""Base abstractions for pluggable AI-tool quota / rate-limit trackers.
+
+Every provider tracker (Anthropic, Codex, Copilot, …) inherits from
+:class:`QuotaTracker` and is registered with the process-global
+:class:`QuotaTrackerRegistry`. ``server.py`` only interacts with the
+registry — adding a new provider requires *zero* changes to the server.
+
+Quick-start for a new provider::
+
+ from headroom.subscription.base import QuotaTracker, get_quota_registry
+
+ class GeminiQuotaTracker(QuotaTracker):
+ key = "gemini_quota"
+ label = "Google Gemini"
+
+ def is_available(self) -> bool:
+ return bool(os.environ.get("GOOGLE_API_KEY"))
+
+ async def start(self) -> None: ... # launch background poll
+ async def stop(self) -> None: ... # cancel poll task
+
+ def get_stats(self) -> dict | None:
+ return ... # serialisable dict or None if no data yet
+
+ get_quota_registry().register(GeminiQuotaTracker())
+"""
+
+from __future__ import annotations
+
+import abc
+import logging
+from threading import Lock
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+class QuotaTracker(abc.ABC):
+ """Abstract base for a single AI-tool quota / rate-limit tracker.
+
+ Subclasses must define :attr:`key`, :attr:`label`, and
+ :meth:`get_stats`. All other methods have sensible defaults.
+ """
+
+ # ------------------------------------------------------------------ #
+ # Class-level identity — subclasses should override as class attributes
+ # ------------------------------------------------------------------ #
+
+ @property
+ @abc.abstractmethod
+ def key(self) -> str:
+ """Stats key used in ``/stats`` and the dashboard.
+
+ Must be unique across all registered trackers.
+ Examples: ``"subscription_window"``, ``"codex_rate_limits"``.
+ """
+
+ @property
+ @abc.abstractmethod
+ def label(self) -> str:
+ """Human-readable name for log messages.
+
+ Example: ``"Anthropic Claude Code"``.
+ """
+
+ # ------------------------------------------------------------------ #
+ # Availability gate
+ # ------------------------------------------------------------------ #
+
+ def is_available(self) -> bool:
+ """Return ``True`` if this tracker should be activated.
+
+ Override to gate on environment variables, config flags, etc.
+ The registry calls this before :meth:`start` and skips trackers
+ that return ``False``. Default: always available.
+ """
+ return True
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle — default no-ops (suitable for passive/header-based trackers)
+ # ------------------------------------------------------------------ #
+
+ async def start(self) -> None: # noqa: B027
+ """Start background polling. No-op for passive trackers."""
+
+ async def stop(self) -> None: # noqa: B027
+ """Stop background polling. No-op for passive trackers."""
+
+ # ------------------------------------------------------------------ #
+ # Stats
+ # ------------------------------------------------------------------ #
+
+ @abc.abstractmethod
+ def get_stats(self) -> dict[str, Any] | None:
+ """Return the current snapshot as a serialisable dict, or ``None``.
+
+ ``None`` means "no data yet" and causes the key to be omitted from
+ ``/stats`` rather than appearing as ``null``.
+ """
+
+
+# --------------------------------------------------------------------------- #
+# Registry
+# --------------------------------------------------------------------------- #
+
+
+class QuotaTrackerRegistry:
+ """Process-global registry of all :class:`QuotaTracker` instances.
+
+ Typical usage::
+
+ registry = get_quota_registry()
+ registry.register(SubscriptionTracker(...))
+ registry.register(get_codex_rate_limit_state())
+ registry.register(get_copilot_quota_tracker())
+
+ # server startup
+ await registry.start_all()
+
+ # /stats assembly
+ stats.update(registry.get_all_stats())
+
+ # server shutdown
+ await registry.stop_all()
+ """
+
+ def __init__(self) -> None:
+ self._trackers: list[QuotaTracker] = []
+ self._lock = Lock()
+
+ # ------------------------------------------------------------------ #
+ # Registration
+ # ------------------------------------------------------------------ #
+
+ def register(self, tracker: QuotaTracker) -> None:
+ """Register a tracker. Duplicate keys are rejected."""
+ with self._lock:
+ existing_keys = {t.key for t in self._trackers}
+ if tracker.key in existing_keys:
+ raise ValueError(
+ f"A tracker with key '{tracker.key}' is already registered. "
+ "Each tracker must have a unique key."
+ )
+ self._trackers.append(tracker)
+
+ def get(self, key: str) -> QuotaTracker | None:
+ """Return the registered tracker for *key*, or ``None``."""
+ with self._lock:
+ for t in self._trackers:
+ if t.key == key:
+ return t
+ return None
+
+ @property
+ def trackers(self) -> list[QuotaTracker]:
+ """Read-only snapshot of the registered tracker list."""
+ with self._lock:
+ return list(self._trackers)
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle
+ # ------------------------------------------------------------------ #
+
+ async def start_all(self) -> None:
+ """Start every available tracker and log its status."""
+ for tracker in self.trackers:
+ if tracker.is_available():
+ await tracker.start()
+ logger.info("%s quota tracking: ENABLED", tracker.label)
+ else:
+ logger.info("%s quota tracking: DISABLED (not available)", tracker.label)
+
+ async def stop_all(self) -> None:
+ """Stop all registered trackers (regardless of availability)."""
+ for tracker in self.trackers:
+ try:
+ await tracker.stop()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Error stopping %s tracker: %s", tracker.label, exc)
+
+ # ------------------------------------------------------------------ #
+ # Stats
+ # ------------------------------------------------------------------ #
+
+ def get_all_stats(self) -> dict[str, dict[str, Any] | None]:
+ """Return ``{key: stats_dict}`` for every available tracker.
+
+ Trackers that are unavailable or return ``None`` are excluded.
+ """
+ result: dict[str, dict[str, Any] | None] = {}
+ for tracker in self.trackers:
+ if not tracker.is_available():
+ continue
+ stats = tracker.get_stats()
+ if stats is not None:
+ result[tracker.key] = stats
+ return result
+
+ def get_stats(self, key: str) -> dict[str, Any] | None:
+ """Return stats for a single tracker by key, or ``None``."""
+ tracker = self.get(key)
+ return tracker.get_stats() if tracker is not None else None
+
+
+# --------------------------------------------------------------------------- #
+# Process-global singleton
+# --------------------------------------------------------------------------- #
+
+_registry: QuotaTrackerRegistry | None = None
+_registry_lock = Lock()
+
+
+def get_quota_registry() -> QuotaTrackerRegistry:
+ """Return the process-global :class:`QuotaTrackerRegistry` singleton."""
+ global _registry
+ if _registry is None:
+ with _registry_lock:
+ if _registry is None:
+ _registry = QuotaTrackerRegistry()
+ return _registry
+
+
+def reset_quota_registry() -> None:
+ """Replace the global registry with a fresh empty instance.
+
+ Intended for use in tests only.
+ """
+ global _registry
+ with _registry_lock:
+ _registry = QuotaTrackerRegistry()
diff --git a/headroom/subscription/codex_rate_limits.py b/headroom/subscription/codex_rate_limits.py
index 8a87e29f0..3934ff8b1 100644
--- a/headroom/subscription/codex_rate_limits.py
+++ b/headroom/subscription/codex_rate_limits.py
@@ -26,6 +26,8 @@ import time
from dataclasses import dataclass, field
from threading import Lock
+from headroom.subscription.base import QuotaTracker
+
@dataclass
class CodexRateLimitWindow:
@@ -195,13 +197,20 @@ def parse_codex_rate_limits(headers: dict[str, str]) -> CodexRateLimitSnapshot |
# ---------------------------------------------------------------------------
-class CodexRateLimitState:
+class CodexRateLimitState(QuotaTracker):
"""Thread-safe store for the latest Codex rate-limit snapshot.
- Updated by the OpenAI proxy handler each time a response containing
- ``x-codex-*`` headers passes through headroom.
+ Implements :class:`~headroom.subscription.base.QuotaTracker` so it can
+ be registered with the :class:`~headroom.subscription.base.QuotaTrackerRegistry`.
+ This tracker is *passive* — it is updated by the OpenAI proxy handler
+ each time a response containing ``x-codex-*`` headers passes through
+ headroom, so :meth:`start` and :meth:`stop` are no-ops.
"""
+ # QuotaTracker identity
+ key = "codex_rate_limits"
+ label = "OpenAI Codex"
+
def __init__(self) -> None:
self._lock = Lock()
self._latest: CodexRateLimitSnapshot | None = None
diff --git a/headroom/subscription/copilot_quota.py b/headroom/subscription/copilot_quota.py
index 52aa5c77e..782431f0a 100644
--- a/headroom/subscription/copilot_quota.py
+++ b/headroom/subscription/copilot_quota.py
@@ -41,6 +41,8 @@ from dataclasses import dataclass, field
from threading import Lock
from typing import Any
+from headroom.subscription.base import QuotaTracker
+
logger = logging.getLogger(__name__)
_GITHUB_API_BASE = "https://api.github.com"
@@ -196,8 +198,17 @@ def discover_github_token() -> str | None:
# ---------------------------------------------------------------------------
-class _CopilotQuotaTracker:
- """Singleton background poller for GitHub Copilot quota."""
+class _CopilotQuotaTracker(QuotaTracker):
+ """Singleton background poller for GitHub Copilot quota.
+
+ Implements :class:`~headroom.subscription.base.QuotaTracker` so it can be
+ registered with the :class:`~headroom.subscription.base.QuotaTrackerRegistry`.
+ Availability is gated on a GitHub token being present in the environment.
+ """
+
+ # QuotaTracker identity
+ key = "copilot_quota"
+ label = "GitHub Copilot"
def __init__(self, poll_interval_s: float = 60.0) -> None:
self._poll_interval_s = poll_interval_s
@@ -206,6 +217,21 @@ class _CopilotQuotaTracker:
self._stop_event: asyncio.Event | None = None
self._task: asyncio.Task | None = None # type: ignore[type-arg]
+ # ------------------------------------------------------------------
+ # QuotaTracker interface
+ # ------------------------------------------------------------------
+
+ def is_available(self) -> bool:
+ """Returns ``True`` when a GitHub token is available in the environment."""
+ return discover_github_token() is not None
+
+ def get_stats(self) -> dict[str, Any] | None:
+ """Return the latest quota state dict, or ``None`` if no data yet."""
+ data = self.state
+ if not data.get("latest"):
+ return None
+ return data
+
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
diff --git a/headroom/subscription/tracker.py b/headroom/subscription/tracker.py
index 6b941ec90..33dccab51 100644
--- a/headroom/subscription/tracker.py
+++ b/headroom/subscription/tracker.py
@@ -29,6 +29,7 @@ import threading
from pathlib import Path
from typing import Any
+from headroom.subscription.base import QuotaTracker
from headroom.subscription.client import SubscriptionClient
from headroom.subscription.models import (
HeadroomContribution,
@@ -63,24 +64,36 @@ def _get_persist_path() -> Path:
return Path.home() / _DEFAULT_PERSIST_DIR / _DEFAULT_PERSIST_FILE
-class SubscriptionTracker:
+class SubscriptionTracker(QuotaTracker):
"""Background tracker for Anthropic Claude Code subscription windows.
+ Implements :class:`~headroom.subscription.base.QuotaTracker` so it can
+ be registered with :func:`~headroom.subscription.base.get_quota_registry`
+ alongside the Codex and Copilot trackers.
+
Args:
poll_interval_s: Seconds between polls while active (1–300).
active_window_s: Seconds since last notify_active call that keeps
polling alive (default 60 = 1 minute).
+ enabled: Set to ``False`` to disable tracking (mirrors
+ ``ProxyConfig.subscription_tracking_enabled``).
persist_path: Where to persist state across restarts.
client: Injected client (for testing); defaults to SubscriptionClient().
"""
+ # QuotaTracker identity
+ key = "subscription_window"
+ label = "Anthropic Claude Code"
+
def __init__(
self,
poll_interval_s: int = _DEFAULT_POLL_INTERVAL_S,
active_window_s: float = _DEFAULT_ACTIVE_WINDOW_S,
+ enabled: bool = True,
persist_path: Path | None = None,
client: SubscriptionClient | None = None,
) -> None:
+ self._enabled = enabled
self._poll_interval_s = max(1, min(poll_interval_s, 300))
self._active_window_s = max(5.0, active_window_s)
self._persist_path = persist_path or _get_persist_path()
@@ -96,6 +109,18 @@ class SubscriptionTracker:
self._load_persisted_state()
+ # ------------------------------------------------------------------
+ # QuotaTracker interface
+ # ------------------------------------------------------------------
+
+ def is_available(self) -> bool:
+ """Returns ``True`` when subscription tracking is enabled in config."""
+ return self._enabled
+
+ def get_stats(self) -> dict[str, Any] | None:
+ """Return current tracker state dict for ``/stats``."""
+ return self.state
+
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
@@ -408,6 +433,7 @@ def get_subscription_tracker() -> SubscriptionTracker | None:
def configure_subscription_tracker(
poll_interval_s: int = _DEFAULT_POLL_INTERVAL_S,
active_window_s: float = _DEFAULT_ACTIVE_WINDOW_S,
+ enabled: bool = True,
persist_path: Path | None = None,
client: SubscriptionClient | None = None,
) -> SubscriptionTracker:
@@ -418,6 +444,7 @@ def configure_subscription_tracker(
_tracker_instance = SubscriptionTracker(
poll_interval_s=poll_interval_s,
active_window_s=active_window_s,
+ enabled=enabled,
persist_path=persist_path,
client=client,
)
diff --git a/tests/test_quota_registry.py b/tests/test_quota_registry.py
new file mode 100644
index 000000000..7824c5970
--- /dev/null
+++ b/tests/test_quota_registry.py
@@ -0,0 +1,263 @@
+"""Tests for the pluggable QuotaTracker / QuotaTrackerRegistry abstraction."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from headroom.subscription.base import (
+ QuotaTracker,
+ QuotaTrackerRegistry,
+ get_quota_registry,
+ reset_quota_registry,
+)
+
+# ---------------------------------------------------------------------------
+# Minimal concrete trackers for test use
+# ---------------------------------------------------------------------------
+
+
+class _AlwaysOnTracker(QuotaTracker):
+ key = "always_on"
+ label = "AlwaysOn"
+
+ def __init__(self, stats: dict | None = None) -> None:
+ self._stats = stats or {"value": 1}
+ self.started = False
+ self.stopped = False
+
+ async def start(self) -> None:
+ self.started = True
+
+ async def stop(self) -> None:
+ self.stopped = True
+
+ def get_stats(self) -> dict[str, Any] | None:
+ return self._stats
+
+
+class _UnavailableTracker(QuotaTracker):
+ key = "unavailable"
+ label = "Unavailable"
+
+ def is_available(self) -> bool:
+ return False
+
+ def get_stats(self) -> dict[str, Any] | None:
+ return {"should_not_appear": True}
+
+
+class _NoDataTracker(QuotaTracker):
+ key = "no_data"
+ label = "NoData"
+
+ def get_stats(self) -> dict[str, Any] | None:
+ return None
+
+
+class _PassiveTracker(QuotaTracker):
+ """Uses inherited no-op start/stop."""
+
+ key = "passive"
+ label = "Passive"
+
+ def get_stats(self) -> dict[str, Any] | None:
+ return {"passive": True}
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def fresh_registry():
+ """Reset the global registry before every test."""
+ reset_quota_registry()
+ yield
+ reset_quota_registry()
+
+
+# ---------------------------------------------------------------------------
+# Registration tests
+# ---------------------------------------------------------------------------
+
+
+def test_register_single_tracker():
+ registry = QuotaTrackerRegistry()
+ tracker = _AlwaysOnTracker()
+ registry.register(tracker)
+ assert registry.get("always_on") is tracker
+
+
+def test_register_multiple_trackers():
+ registry = QuotaTrackerRegistry()
+ t1 = _AlwaysOnTracker()
+ t2 = _PassiveTracker()
+ registry.register(t1)
+ registry.register(t2)
+ assert len(registry.trackers) == 2
+
+
+def test_duplicate_key_raises():
+ registry = QuotaTrackerRegistry()
+ registry.register(_AlwaysOnTracker())
+ with pytest.raises(ValueError, match="already registered"):
+ registry.register(_AlwaysOnTracker())
+
+
+def test_get_unknown_key_returns_none():
+ registry = QuotaTrackerRegistry()
+ assert registry.get("nonexistent") is None
+
+
+def test_trackers_property_is_snapshot():
+ registry = QuotaTrackerRegistry()
+ t = _AlwaysOnTracker()
+ registry.register(t)
+ snapshot = registry.trackers
+ # Mutations to the snapshot don't affect the registry
+ snapshot.clear()
+ assert len(registry.trackers) == 1
+
+
+# ---------------------------------------------------------------------------
+# Lifecycle tests
+# ---------------------------------------------------------------------------
+
+
+def test_start_all_calls_available_trackers():
+ registry = QuotaTrackerRegistry()
+ t = _AlwaysOnTracker()
+ registry.register(t)
+ asyncio.run(registry.start_all())
+ assert t.started is True
+
+
+def test_start_all_skips_unavailable_trackers():
+ registry = QuotaTrackerRegistry()
+ unavailable = _UnavailableTracker()
+ registry.register(unavailable)
+
+ # Patch start to detect if it was called
+ called = []
+
+ async def _start() -> None:
+ called.append(True)
+
+ unavailable.start = _start # type: ignore[method-assign]
+ asyncio.run(registry.start_all())
+ assert called == []
+
+
+def test_stop_all_calls_stop_on_all_registered():
+ registry = QuotaTrackerRegistry()
+ t = _AlwaysOnTracker()
+ unavailable = _UnavailableTracker()
+ registry.register(t)
+ registry.register(unavailable)
+ asyncio.run(registry.stop_all())
+ assert t.stopped is True
+
+
+def test_stop_all_continues_on_exception():
+ registry = QuotaTrackerRegistry()
+
+ class _BrokenTracker(QuotaTracker):
+ key = "broken"
+ label = "Broken"
+
+ async def stop(self) -> None:
+ raise RuntimeError("stop failed")
+
+ def get_stats(self) -> dict | None:
+ return None
+
+ registry.register(_BrokenTracker())
+ # Should not raise
+ asyncio.run(registry.stop_all())
+
+
+def test_passive_tracker_start_stop_are_noops():
+ registry = QuotaTrackerRegistry()
+ t = _PassiveTracker()
+ registry.register(t)
+ asyncio.run(registry.start_all())
+ asyncio.run(registry.stop_all())
+ # No assertions needed — we verify no exception is raised
+
+
+# ---------------------------------------------------------------------------
+# Stats tests
+# ---------------------------------------------------------------------------
+
+
+def test_get_all_stats_includes_available_with_data():
+ registry = QuotaTrackerRegistry()
+ registry.register(_AlwaysOnTracker({"x": 1}))
+ stats = registry.get_all_stats()
+ assert "always_on" in stats
+ assert stats["always_on"] == {"x": 1}
+
+
+def test_get_all_stats_excludes_unavailable():
+ registry = QuotaTrackerRegistry()
+ registry.register(_UnavailableTracker())
+ stats = registry.get_all_stats()
+ assert "unavailable" not in stats
+
+
+def test_get_all_stats_excludes_none_data():
+ registry = QuotaTrackerRegistry()
+ registry.register(_NoDataTracker())
+ stats = registry.get_all_stats()
+ assert "no_data" not in stats
+
+
+def test_get_all_stats_mixed():
+ registry = QuotaTrackerRegistry()
+ registry.register(_AlwaysOnTracker({"ok": True}))
+ registry.register(_UnavailableTracker())
+ registry.register(_NoDataTracker())
+ stats = registry.get_all_stats()
+ assert set(stats.keys()) == {"always_on"}
+
+
+def test_get_stats_single_key():
+ registry = QuotaTrackerRegistry()
+ registry.register(_AlwaysOnTracker({"z": 99}))
+ assert registry.get_stats("always_on") == {"z": 99}
+
+
+def test_get_stats_missing_key_returns_none():
+ registry = QuotaTrackerRegistry()
+ assert registry.get_stats("missing") is None
+
+
+# ---------------------------------------------------------------------------
+# Global singleton tests
+# ---------------------------------------------------------------------------
+
+
+def test_get_quota_registry_returns_same_instance():
+ r1 = get_quota_registry()
+ r2 = get_quota_registry()
+ assert r1 is r2
+
+
+def test_reset_quota_registry_gives_fresh_instance():
+ r1 = get_quota_registry()
+ r1.register(_AlwaysOnTracker())
+ reset_quota_registry()
+ r2 = get_quota_registry()
+ assert r1 is not r2
+ assert len(r2.trackers) == 0
+
+
+def test_reset_quota_registry_clears_registrations():
+ registry = get_quota_registry()
+ registry.register(_AlwaysOnTracker())
+ reset_quota_registry()
+ assert len(get_quota_registry().trackers) == 0