Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix: backup vlm token usage stat (#2068)
MaojiaShengf45b22a9a862
diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex a425b6777..d7f3ddbdc 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -277,8 +277,7 @@ List directory contents.| output | str | No | `agent` | Output format: `agent` or `original` || abs_limit | int | No | 256 | Abstract length limit for `agent` output || show_all_hidden | bool | No | False | Include hidden files like `-a` |-| node_limit | int | No | 1000 | Maximum number of nodes to return |-| limit | int | No | None | Alias for `node_limit` |+| node_limit | int | No | 1000 | Maximum number of results |**Entry Structure**@@ -362,8 +361,7 @@ Get directory tree structure.| output | str | No | `agent` | Output format: `agent` or `original` || abs_limit | int | No | 256 | Abstract length limit for `agent` output || show_all_hidden | bool | No | False | Include hidden files like `-a` |-| node_limit | int | No | 1000 | Maximum number of nodes to return |-| limit | int | No | None | Alias for `node_limit` |+| node_limit | int | No | 1000 | Maximum number of results || level_limit | int | No | 3 | Maximum directory depth to traverse |**Python SDK (Embedded / HTTP)**@@ -704,7 +702,7 @@ Search content by pattern.| pattern | str | Yes | - | Search pattern (regex) || case_insensitive | bool | No | False | Ignore case || exclude_uri | str | No | None | URI prefix to exclude from search |-| node_limit | int | No | None | Maximum number of nodes to search |+| node_limit | int | No | None | Maximum number of results || level_limit | int | No | 5 | Maximum directory depth to traverse |**Python SDK (Embedded / HTTP)**@@ -776,7 +774,7 @@ Match files by pattern.|-----------|------|----------|---------|-------------|| pattern | str | Yes | - | Glob pattern (e.g., `**/*.md`) || uri | str | No | "viking://" | Starting URI |-| node_limit | int | No | None | Maximum number of matches to return |+| node_limit | int | No | None | Maximum number of results |**Python SDK (Embedded / HTTP)**diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex 7a79b42ab..58c9216b9 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -56,8 +56,7 @@ The `find()` method performs pure vector similarity search for simple query scen|-----------|------|----------|---------|-------------|| query | str | Yes | - | Search query string || target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix |-| limit | int | No | 10 | Maximum number of results |-| node_limit | int | No | None | Optional HTTP alias that overrides `limit` when provided |+| node_limit | int | No | None | Maximum number of results || score_threshold | float | No | None | Minimum relevance score threshold || filter | Dict | No | None | Metadata filter || since | str | No | None | Lower time bound, accepts `2h` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--after` maps to this field |@@ -274,8 +273,7 @@ The `search()` method adds session context understanding and intent analysis cap| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix || session | Session | No | None | Session for context-aware search (SDK) || session_id | str | No | None | Session ID for context-aware search (HTTP) |-| limit | int | No | 10 | Maximum number of results |-| node_limit | int | No | None | Optional HTTP alias that overrides `limit` when provided |+| node_limit | int | No | None | Maximum number of results || score_threshold | float | No | None | Minimum relevance score threshold || filter | Dict | No | None | Metadata filter || since | str | No | None | Lower time bound, accepts `2h` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--after` maps to this field |@@ -453,7 +451,7 @@ The `grep()` method performs regex pattern matching search in the file system, u| pattern | str | Yes | - | Search pattern (regex) || case_insensitive | bool | No | False | Ignore case || exclude_uri | str | No | None | URI prefix to exclude from search |-| node_limit | int | No | None | Maximum number of nodes to search |+| node_limit | int | No | None | Maximum number of results || level_limit | int | No | 5 | Maximum directory depth to traverse |#### 3. Usage Examplesdiff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex c17c90a1a..8d27c2a67 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -363,7 +363,6 @@ openviking ls viking://resources/ [--simple] [--recursive]| abs_limit | int | 否 | 256 | `agent` 输出中的摘要长度限制 || show_all_hidden | bool | 否 | False | 像 `-a` 一样包含隐藏文件 || node_limit | int | 否 | 1000 | 最大返回节点数 |-| limit | int | 否 | None | `node_limit` 的别名 || level_limit | int | 否 | 3 | 最大目录遍历深度 |**Python SDK (Embedded / HTTP)**@@ -704,7 +703,7 @@ openviking mv viking://resources/old-name/ viking://resources/new-name/| pattern | str | 是 | - | 搜索模式(正则表达式) || case_insensitive | bool | 否 | False | 忽略大小写 || exclude_uri | str | 否 | None | 搜索时要排除的 URI 前缀 |-| node_limit | int | 否 | None | 最大搜索节点数 |+| node_limit | int | 否 | None | 最大返回节点数 || level_limit | int | 否 | 5 | 最大目录遍历深度 |**Python SDK (Embedded / HTTP)**diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex ca2806dc9..d703d09d6 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -452,7 +452,7 @@ openviking search "how to implement OAuth" -L 1,2| uri | str | 是 | - | 要搜索的 Viking URI || pattern | str | 是 | - | 搜索模式(正则表达式)|| case_insensitive | bool | 否 | False | 忽略大小写 |-| node_limit | int | 否 | None | 最大搜索节点数 |+| node_limit | int | 否 | None | 最大返回节点数 || exclude_uri | str | 否 | None | 要排除在搜索之外的 URI 前缀 || level_limit | int | 否 | 5 | 最大目录遍历深度 |diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.pyindex 6d962d7af..25443584e 100644--- a/openviking/models/vlm/base.py+++ b/openviking/models/vlm/base.py@@ -4,11 +4,20 @@import loggingimport re+import threading+import timefrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Union+from openviking.utils.model_retry import (+ classify_api_error,+ ERROR_CLASS_QUOTA_EXCEEDED,+ ERROR_CLASS_TRANSIENT,+ ERROR_CLASS_PERMANENT,+ PrimaryBackupSwitcher,+)from openviking.utils.time_utils import format_iso8601from openviking_cli.utils import get_logger@@ -253,20 +262,6 @@ class VLMBase(ABC):"""return self._token_tracker.to_dict()- def get_token_usage_summary(self) -> Dict[str, Any]:- """Get token usage summary-- Returns:- Dict[str, Any]: Token usage summary- """- total_usage = self._token_tracker.get_total_usage()- return {- "total_prompt_tokens": total_usage.prompt_tokens,- "total_completion_tokens": total_usage.completion_tokens,- "total_tokens": total_usage.total_tokens,- "last_updated": format_iso8601(total_usage.last_updated),- }-def reset_token_usage(self) -> None:"""Reset token usage"""self._token_tracker.reset()@@ -337,16 +332,25 @@ class VLMFactory:class FailoverVLM(VLMBase):"""VLM wrapper that provides failover to a backup VLM instance.- When the primary VLM instance fails with retryable errors (like rate limits),+ When the primary VLM instance fails with permanent or quota errors,this wrapper will automatically switch to using the backup VLM instance.+ After 10 minutes or 50 requests, it will attempt to failback to primary."""- def __init__(self, primary: VLMBase, backup: VLMBase):+ def __init__(+ self,+ primary: VLMBase,+ backup: VLMBase,+ failback_timeout_seconds: float = 600.0, # 10 minutes+ failback_request_count: int = 50,+ ):"""Initialize FailoverVLM with primary and backup VLM instances.Args:primary: The primary VLM instance to use firstbackup: The backup VLM instance to use when primary fails+ failback_timeout_seconds: Time after which to attempt failback to primary+ failback_request_count: Number of backup requests after which to attempt failback"""# Use a dummy config since we're wrapping existing instancesconfig = {@@ -358,50 +362,10 @@ class FailoverVLM(VLMBase):self.primary = primaryself.backup = backupself._logger = logging.getLogger(__name__)- self._using_backup = False-- def _should_failover(self, error: Exception) -> bool:- """Determine if an error should trigger failover to backup.-- Args:- error: The exception that occurred-- Returns:- True if failover should be attempted, False otherwise- """- # Check for common retryable/failover error patterns- error_str = str(error).lower()-- # Rate limiting errors- rate_limit_patterns = [- "rate limit",- "ratelimit",- "too many requests",- "429",- "quota",- ]-- # Server errors- server_error_patterns = [- "500",- "502",- "503",- "504",- "server error",- "service unavailable",- "timeout",- ]-- # Connection errors- connection_patterns = [- "connection",- "network",- "unreachable",- ]-- all_patterns = rate_limit_patterns + server_error_patterns + connection_patterns-- return any(pattern in error_str for pattern in all_patterns)+ self._switcher = PrimaryBackupSwitcher(+ failback_timeout_seconds=failback_timeout_seconds,+ failback_request_count=failback_request_count,+ )def _get_completion_with_failover(self,@@ -424,27 +388,25 @@ class FailoverVLM(VLMBase):"""last_error = None- # Try primary first if not already using backup- if not self._using_backup:+ # Try primary if we should+ if self._switcher.should_try_primary():try:method = getattr(self.primary, method_name)result = method(*args, **kwargs)- # If successful and we were in failover mode, consider switching back- # (but we'll stay conservative and keep using backup for this session)+ self._switcher.record_primary_success()return resultexcept Exception as e:last_error = e- if self._should_failover(e):- self._logger.warning(- f"Primary VLM failed with error: {e}, switching to backup"- )- self._using_backup = True+ if self._switcher.record_primary_failure(e):+ # Switched to backup, continue to try backup+ passelse:# Not a failover-worthy error, re-raiseraise# Try backuptry:+ self._switcher.record_backup_request()method = getattr(self.backup, method_name)return method(*args, **kwargs)except Exception as e:@@ -473,24 +435,25 @@ class FailoverVLM(VLMBase):"""last_error = None- # Try primary first if not already using backup- if not self._using_backup:+ # Try primary if we should+ if self._switcher.should_try_primary():try:method = getattr(self.primary, method_name)result = await method(*args, **kwargs)+ self._switcher.record_primary_success()return resultexcept Exception as e:last_error = e- if self._should_failover(e):- self._logger.warning(- f"Primary VLM failed with error: {e}, switching to backup"- )- self._using_backup = True+ if self._switcher.record_primary_failure(e):+ # Switched to backup, continue to try backup+ passelse:+ # Not a failover-worthy error, re-raiseraise# Try backuptry:+ self._switcher.record_backup_request()method = getattr(self.backup, method_name)return await method(*args, **kwargs)except Exception as e:@@ -577,4 +540,40 @@ class FailoverVLM(VLMBase):@propertydef is_using_backup(self) -> bool:"""Check if currently using the backup VLM instance."""- return self._using_backup+ return self._switcher.is_using_backup++ @property+ def _active_vlm(self) -> VLMBase:+ """Get the currently active VLM instance."""+ return self.backup if self._switcher.is_using_backup else self.primary++ def update_token_usage(+ self,+ model_name: str,+ provider: str,+ prompt_tokens: int,+ completion_tokens: int,+ duration_seconds: float = 0.0,+ ) -> None:+ """Update token usage for the currently active instance."""+ self._active_vlm.update_token_usage(+ model_name=model_name,+ provider=provider,+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ duration_seconds=duration_seconds,+ )++ def get_token_usage(self) -> Dict[str, Any]:+ """Get combined token usage from both primary and backup instances."""+ from openviking.models.vlm.token_usage import TokenUsageTracker+ merged_tracker = TokenUsageTracker.merge(+ self.primary._token_tracker,+ self.backup._token_tracker+ )+ return merged_tracker.to_dict()++ def reset_token_usage(self) -> None:+ """Reset token usage for both primary and backup instances."""+ self.primary.reset_token_usage()+ self.backup.reset_token_usage()diff --git a/openviking/models/vlm/token_usage.py b/openviking/models/vlm/token_usage.pyindex 26d736281..44efcc7f1 100644--- a/openviking/models/vlm/token_usage.py+++ b/openviking/models/vlm/token_usage.py@@ -211,3 +211,34 @@ class TokenUsageTracker:)total = self.get_total_usage()return f"TokenUsageTracker(total={total.total_tokens}, models=[{models}])"++ @staticmethod+ def merge(*trackers: "TokenUsageTracker") -> "TokenUsageTracker":+ """Merge multiple TokenUsageTracker instances into one.++ Args:+ *trackers: One or more TokenUsageTracker instances to merge++ Returns:+ New TokenUsageTracker with merged data+ """+ merged = TokenUsageTracker()++ for tracker in trackers:+ for model_name, model_usage in tracker._usage_by_model.items():+ for provider_name, provider_usage in model_usage.usage_by_provider.items():+ merged.update(+ model_name=model_name,+ provider=provider_name,+ prompt_tokens=provider_usage.prompt_tokens,+ completion_tokens=provider_usage.completion_tokens,+ )+ # Update call count (update() only increments by 1)+ if provider_usage.call_count > 1:+ merged_model = merged._usage_by_model[model_name]+ merged_provider = merged_model.usage_by_provider[provider_name]+ merged_provider.call_count = provider_usage.call_count+ # Update last_updated+ merged_provider.last_updated = provider_usage.last_updated++ return mergeddiff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.pyindex dc8457452..7514ff6da 100644--- a/openviking/storage/collection_schemas.py+++ b/openviking/storage/collection_schemas.py@@ -32,6 +32,7 @@ from openviking.utils.circuit_breaker import (CircuitBreakerOpen,classify_api_error,)+from openviking.utils.model_retry import ERROR_CLASS_PERMANENTfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfig@@ -520,7 +521,7 @@ class TextEmbeddingHandler(DequeueHandlerBase):except Exception:pass- if error_class == "permanent":+ if error_class == ERROR_CLASS_PERMANENT:logger.critical(error_msg)self._circuit_breaker.record_failure(embed_err)self._merge_request_stats(embedding_msg.telemetry_id, error_count=1)diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.pyindex a6d117c29..d849c5208 100644--- a/openviking/storage/queuefs/semantic_dag.py+++ b/openviking/storage/queuefs/semantic_dag.py@@ -248,7 +248,7 @@ class SemanticDagExecutor:self._parent[dir_uri] = parent_uritry:- children_dirs, file_paths = await self._list_dir(dir_uri)+ children_dirs, file_paths = await self._list_dir(dir_uri, "_dispatch_dir")file_index = {path: idx for idx, path in enumerate(file_paths)}child_index = {path: idx for idx, path in enumerate(children_dirs)}if self._recursive:@@ -294,12 +294,12 @@ class SemanticDagExecutor:elif self._root_done:self._root_done.set()- async def _list_dir(self, uri: str) -> tuple[list[str], list[str]]:+ async def _list_dir(self, uri: str, from_hint: str) -> tuple[list[str], list[str]]:"""List directory entries and return (child_dirs, file_paths)."""try:entries = await self._viking_fs.ls(uri, ctx=self._ctx)except Exception as e:- logger.warning(f"Failed to list directory {uri}: {e}")+ logger.warning(f"[SemanticDagExecutor] Failed to list directory {uri}: {e} from {from_hint}")return [], []children_dirs: List[str] = []@@ -438,7 +438,7 @@ class SemanticDagExecutor:if not target_path:return Truetry:- target_dirs, target_files = await self._list_dir(target_path)+ target_dirs, target_files = await self._list_dir(target_path, "_check_dir_children_changed")current_file_names = {f.split("/")[-1] for f in current_files}target_file_names = {f.split("/")[-1] for f in target_files}if current_file_names != target_file_names:diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.pyindex e5b7a2227..6057405ab 100644--- a/openviking/storage/queuefs/semantic_processor.py+++ b/openviking/storage/queuefs/semantic_processor.py@@ -41,6 +41,7 @@ from openviking.utils.circuit_breaker import (CircuitBreakerOpen,classify_api_error,)+from openviking.utils.model_retry import ERROR_CLASS_PERMANENTfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import VikingURIfrom openviking_cli.utils.config import get_openviking_config@@ -404,7 +405,7 @@ class SemanticProcessor(DequeueHandlerBase):except Exception as e:error_class = classify_api_error(e)- if error_class == "permanent":+ if error_class == ERROR_CLASS_PERMANENT:logger.critical(f"Permanent API error processing semantic message, dropping: {e}",exc_info=True,diff --git a/openviking/telemetry/execution.py b/openviking/telemetry/execution.pyindex 019946828..688fbacc5 100644--- a/openviking/telemetry/execution.py+++ b/openviking/telemetry/execution.py@@ -53,7 +53,7 @@ def build_telemetry_payload(def _log_telemetry_summary(snapshot: Optional[TelemetrySnapshot]) -> None:if snapshot is None:return- logger.info(+ logger.debug("Telemetry summary (id=%s): %s",snapshot.telemetry_id,snapshot.summary,diff --git a/openviking/utils/circuit_breaker.py b/openviking/utils/circuit_breaker.pyindex a479e780f..c8a67d9aa 100644--- a/openviking/utils/circuit_breaker.py+++ b/openviking/utils/circuit_breaker.py@@ -7,7 +7,11 @@ from __future__ import annotationsimport threadingimport time-from openviking.utils.model_retry import classify_api_error+from openviking.utils.model_retry import (+ ERROR_CLASS_PERMANENT,+ ERROR_CLASS_QUOTA_EXCEEDED,+ classify_api_error,+)from openviking_cli.utils.logger import get_loggerlogger = get_logger(__name__)@@ -105,10 +109,10 @@ class CircuitBreaker:)return- if error_class == "permanent":+ if error_class in (ERROR_CLASS_PERMANENT, ERROR_CLASS_QUOTA_EXCEEDED):self._state = _STATE_OPENself._current_reset_timeout = self._base_reset_timeout- logger.info(f"Circuit breaker tripped immediately on permanent error: {error}")+ logger.info(f"Circuit breaker tripped immediately on {error_class} error: {error}")returnif self._failure_count >= self._failure_threshold:diff --git a/openviking/utils/model_retry.py b/openviking/utils/model_retry.pyindex fe8b9fbd0..49a76567e 100644--- a/openviking/utils/model_retry.py+++ b/openviking/utils/model_retry.py@@ -1,19 +1,36 @@from __future__ import annotationsimport asyncio+import loggingimport random+import threadingimport timefrom typing import Awaitable, Callable, TypeVar+logger = logging.getLogger(__name__)+T = TypeVar("T")+# Error classification categories returned by classify_api_error()+ERROR_CLASS_PERMANENT = "permanent"+ERROR_CLASS_QUOTA_EXCEEDED = "quota_exceeded"+ERROR_CLASS_TRANSIENT = "transient"+ERROR_CLASS_UNKNOWN = "unknown"+PERMANENT_API_ERROR_PATTERNS = ("400","401","403",- "Forbidden",- "Unauthorized",- "AccountOverdue",+ "forbidden",+ "unauthorized",+ "accountoverdue",+)++QUOTA_EXCEEDED_PATTERNS = (+ "quotaexceeded", # also 429+ "quota limit",+ "quota exceed",+ "usage quota",)_PERMANENT_IO_ERRORS = (FileNotFoundError, PermissionError, IsADirectoryError, NotADirectoryError)@@ -24,43 +41,63 @@ TRANSIENT_API_ERROR_PATTERNS = ("502","503","504",- "TooManyRequests",- "RateLimit",- "RequestBurstTooFast",+ "toomanyrequests",+ "ratelimit",+ "requestbursttoofast","timeout",- "Timeout",- "ConnectionError",- "Connection refused",- "Connection reset",+ "connectionerror",+ "connection refused",+ "connection reset",)def classify_api_error(error: Exception) -> str:- """Classify an API error as permanent, transient, or unknown."""+ """Classify an API error as permanent, quota_exceeded, transient, or unknown.++ ``quota_exceeded`` is checked before ``transient`` because quota errors+ typically include "429" / "TooManyRequests" which would otherwise match+ the transient category. Quota errors should not be retried; the caller+ should fail over to a backup model instead.+ """for exc in (error, getattr(error, "__cause__", None)):if exc is not None and isinstance(exc, _PERMANENT_IO_ERRORS):- return "permanent"+ return ERROR_CLASS_PERMANENTtexts = [str(error)]if error.__cause__ is not None:texts.append(str(error.__cause__))for text in texts:+ text_lower = text.lower()for pattern in PERMANENT_API_ERROR_PATTERNS:- if pattern in text:- return "permanent"+ if pattern in text_lower:+ return ERROR_CLASS_PERMANENT++ # Check quota_exceeded *before* transient so that "429 … AccountQuotaExceeded"+ # is classified as quota_exceeded, not transient.+ for text in texts:+ text_lower = text.lower()+ for pattern in QUOTA_EXCEEDED_PATTERNS:+ if pattern in text_lower:+ return ERROR_CLASS_QUOTA_EXCEEDEDfor text in texts:+ text_lower = text.lower()for pattern in TRANSIENT_API_ERROR_PATTERNS:- if pattern in text:- return "transient"+ if pattern in text_lower:+ return ERROR_CLASS_TRANSIENT- return "unknown"+ return ERROR_CLASS_UNKNOWN+++def is_quota_exceeded_api_error(error: Exception) -> bool:+ """Return True if the error indicates an account quota has been exceeded."""+ return classify_api_error(error) == ERROR_CLASS_QUOTA_EXCEEDEDdef is_retryable_api_error(error: Exception) -> bool:"""Return True if the error should be retried."""- return classify_api_error(error) == "transient"+ return classify_api_error(error) == ERROR_CLASS_TRANSIENTdef _compute_delay(@@ -154,3 +191,94 @@ async def retry_async()await asyncio.sleep(delay)attempt += 1+++class PrimaryBackupSwitcher:+ """Thread-safe primary/backup switcher with automatic failback logic.++ When an error of type ERROR_CLASS_PERMANENT or ERROR_CLASS_QUOTA_EXCEEDED occurs,+ switches to backup immediately. Then, after either:+ - 10 minutes have passed, OR+ - 200 requests have been made to backup+ it will attempt to failback to primary. If failback fails, it switches back+ to backup and resets the timer/counter.+ """++ def __init__(+ self,+ failback_timeout_seconds: float = 600.0, # 10 minutes+ failback_request_count: int = 200,+ ):+ self._failback_timeout = failback_timeout_seconds+ self._failback_request_count = failback_request_count+ self._lock = threading.Lock()++ # State+ self._using_backup = False+ self._switch_to_backup_time: float = 0.0+ self._backup_request_count = 0++ def should_try_primary(self) -> bool:+ """Check if we should try primary again.++ Returns True if we're using backup and either the timeout has elapsed+ or we've made enough requests to backup.+ """+ with self._lock:+ if not self._using_backup:+ return True # Already using primary++ elapsed = time.monotonic() - self._switch_to_backup_time+ if elapsed >= self._failback_timeout:+ logger.info(+ f"Failback timeout elapsed ({elapsed:.0f}s), attempting to switch back to primary"+ )+ return True++ if self._backup_request_count >= self._failback_request_count:+ logger.info(+ f"Failback request count reached ({self._backup_request_count}), attempting to switch back to primary"+ )+ return True++ return False++ def record_primary_success(self) -> None:+ """Record a successful primary call - stay on primary."""+ with self._lock:+ if self._using_backup:+ logger.info("Primary succeeded, switching back from backup to primary")+ self._using_backup = False+ self._backup_request_count = 0+ # else already on primary, do nothing++ def record_primary_failure(self, error: Exception) -> bool:+ """Record a primary failure. Returns True if should switch to backup.++ Switches to backup immediately for ERROR_CLASS_PERMANENT or ERROR_CLASS_QUOTA_EXCEEDED.+ """+ error_class = classify_api_error(error)+ if error_class in (ERROR_CLASS_PERMANENT, ERROR_CLASS_QUOTA_EXCEEDED):+ with self._lock:+ if not self._using_backup:+ logger.warning(+ f"Primary failed with {error_class}, switching to backup"+ )+ self._using_backup = True+ # Always reset timer and counter when we fail (whether initial fail or failback fail)+ self._switch_to_backup_time = time.monotonic()+ self._backup_request_count = 0+ return True+ return False++ def record_backup_request(self) -> None:+ """Record a request to backup (for counting towards failback)."""+ with self._lock:+ if self._using_backup:+ self._backup_request_count += 1++ @property+ def is_using_backup(self) -> bool:+ """Check if currently using backup."""+ with self._lock:+ return self._using_backupdiff --git a/tests/unit/test_circuit_breaker.py b/tests/unit/test_circuit_breaker.pyindex 9916f608e..f3bf77ccb 100644--- a/tests/unit/test_circuit_breaker.py+++ b/tests/unit/test_circuit_breaker.py@@ -12,6 +12,12 @@ from openviking.utils.circuit_breaker import (CircuitBreakerOpen,classify_api_error,)+from openviking.utils.model_retry import (+ ERROR_CLASS_PERMANENT,+ ERROR_CLASS_QUOTA_EXCEEDED,+ ERROR_CLASS_TRANSIENT,+ ERROR_CLASS_UNKNOWN,+)class TestClassifyApiError:@@ -20,99 +26,99 @@ class TestClassifyApiError:def test_classify_403_as_permanent(self):"""Test 403 Forbidden is classified as permanent."""error = Exception("403 Forbidden")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTdef test_classify_401_as_permanent(self):"""Test 401 Unauthorized is classified as permanent."""error = Exception("401 Unauthorized")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTdef test_classify_forbidden_as_permanent(self):"""Test 'Forbidden' string is classified as permanent."""error = Exception("Access Forbidden")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTdef test_classify_unauthorized_as_permanent(self):"""Test 'Unauthorized' string is classified as permanent."""error = Exception("Unauthorized access")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTdef test_classify_account_overdue_as_permanent(self):"""Test 'AccountOverdue' string is classified as permanent."""error = Exception("AccountOverdue error")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTdef test_classify_429_as_transient(self):"""Test 429 TooManyRequests is classified as transient."""error = Exception("429 TooManyRequests")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_500_as_transient(self):"""Test 500 Internal Server Error is classified as transient."""error = Exception("500 Internal Server Error")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_502_as_transient(self):"""Test 502 Bad Gateway is classified as transient."""error = Exception("502 Bad Gateway")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_503_as_transient(self):"""Test 503 Service Unavailable is classified as transient."""error = Exception("503 Service Unavailable")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_504_as_transient(self):"""Test 504 Gateway Timeout is classified as transient."""error = Exception("504 Gateway Timeout")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_rate_limit_as_transient(self):"""Test 'RateLimit' string is classified as transient."""error = Exception("RateLimit exceeded")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_timeout_as_transient(self):"""Test 'timeout' string is classified as transient."""error = Exception("Connection timeout")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_connection_error_as_transient(self):"""Test 'ConnectionError' string is classified as transient."""error = Exception("ConnectionError: Connection refused")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_connection_refused_as_transient(self):"""Test 'Connection refused' string is classified as transient."""error = Exception("Connection refused by server")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_connection_reset_as_transient(self):"""Test 'Connection reset' string is classified as transient."""error = Exception("Connection reset by peer")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_classify_unknown_error(self):"""Test unknown error type is classified as unknown."""error = Exception("Some random error")- assert classify_api_error(error) == "unknown"+ assert classify_api_error(error) == ERROR_CLASS_UNKNOWNdef test_classify_error_with_cause(self):"""Test classification checks error cause."""error = Exception("Primary error")error.__cause__ = Exception("403 Forbidden")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTdef test_classify_error_with_transient_cause(self):"""Test classification checks error cause for transient."""error = Exception("Primary error")error.__cause__ = Exception("429 Rate limit")- assert classify_api_error(error) == "transient"+ assert classify_api_error(error) == ERROR_CLASS_TRANSIENTdef test_permanent_takes_precedence_over_transient(self):"""Test permanent error patterns are checked first."""error = Exception("403 Forbidden 429 timeout")- assert classify_api_error(error) == "permanent"+ assert classify_api_error(error) == ERROR_CLASS_PERMANENTclass TestCircuitBreaker:@@ -333,3 +339,21 @@ class TestCircuitBreakerEdgeCases:with pytest.raises(CircuitBreakerOpen):cb.check()++ def test_quota_exceeded_trips_immediately(self):+ """Test breaker trips immediately on quota_exceeded error."""+ cb = CircuitBreaker(failure_threshold=10)++ cb.record_failure(Exception("AccountQuotaExceeded"))++ with pytest.raises(CircuitBreakerOpen):+ cb.check()++ def test_quota_exceeded_trips_even_with_high_threshold(self):+ """Test quota_exceeded bypasses failure threshold."""+ cb = CircuitBreaker(failure_threshold=100)++ cb.record_failure(Exception("usage quota exceeded"))++ with pytest.raises(CircuitBreakerOpen):+ cb.check()diff --git a/tests/unit/test_model_retry.py b/tests/unit/test_model_retry.pyindex 7f0360805..be59be298 100644--- a/tests/unit/test_model_retry.py+++ b/tests/unit/test_model_retry.py@@ -4,11 +4,20 @@import pytest-from openviking.utils.model_retry import classify_api_error, retry_async, retry_sync+from openviking.utils.model_retry import (+ ERROR_CLASS_PERMANENT,+ ERROR_CLASS_QUOTA_EXCEEDED,+ ERROR_CLASS_TRANSIENT,+ ERROR_CLASS_UNKNOWN,+ classify_api_error,+ is_quota_exceeded_api_error,+ retry_async,+ retry_sync,+)def test_classify_api_error_recognizes_request_burst_too_fast():- assert classify_api_error(RuntimeError("RequestBurstTooFast")) == "transient"+ assert classify_api_error(RuntimeError("RequestBurstTooFast")) == ERROR_CLASS_TRANSIENTdef test_retry_sync_retries_transient_error_until_success():@@ -36,3 +45,83 @@ async def test_retry_async_does_not_retry_unknown_error():await retry_async(_call, max_retries=3)assert attempts["count"] == 1+++# --- quota_exceeded classification ---+++def test_classify_account_quota_exceeded():+ """AccountQuotaExceeded is classified as quota_exceeded, not transient."""+ error = RuntimeError(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded",'+ '"message":"You have exceeded the 5-hour usage quota"}}'+ )+ assert classify_api_error(error) == ERROR_CLASS_QUOTA_EXCEEDED+++def test_classify_quota_limit():+ """'quota limit' is classified as quota_exceeded."""+ assert classify_api_error(RuntimeError("quota limit reached")) == ERROR_CLASS_QUOTA_EXCEEDED+++def test_classify_quota_exceed():+ """'quota exceed' is classified as quota_exceeded."""+ assert classify_api_error(RuntimeError("quota exceed")) == ERROR_CLASS_QUOTA_EXCEEDED+++def test_classify_usage_quota():+ """'usage quota' is classified as quota_exceeded."""+ assert classify_api_error(RuntimeError("usage quota exceeded")) == ERROR_CLASS_QUOTA_EXCEEDED+++def test_quota_exceeded_takes_precedence_over_transient():+ """A 429 with AccountQuotaExceeded is quota_exceeded, not transient."""+ error = RuntimeError(+ '429 {"error":{"code":"AccountQuotaExceeded","message":"TooManyRequests"}}'+ )+ assert classify_api_error(error) == ERROR_CLASS_QUOTA_EXCEEDED+++def test_permanent_still_takes_precedence_over_quota():+ """Permanent errors (e.g. 403) still take highest precedence."""+ assert classify_api_error(RuntimeError("403 AccountQuotaExceeded")) == ERROR_CLASS_PERMANENT+++def test_is_quota_exceeded_api_error():+ assert is_quota_exceeded_api_error(RuntimeError("AccountQuotaExceeded")) is True+ assert is_quota_exceeded_api_error(RuntimeError("429 TooManyRequests")) is False+++def test_retry_sync_does_not_retry_quota_exceeded():+ """Quota-exceeded errors should NOT be retried."""+ attempts = {"count": 0}++ def _call():+ attempts["count"] += 1+ raise RuntimeError("AccountQuotaExceeded")++ with pytest.raises(RuntimeError, match="AccountQuotaExceeded"):+ retry_sync(_call, max_retries=5)++ assert attempts["count"] == 1+++async def test_retry_async_does_not_retry_quota_exceeded():+ """Quota-exceeded errors should NOT be retried (async)."""+ attempts = {"count": 0}++ async def _call():+ attempts["count"] += 1+ raise RuntimeError("AccountQuotaExceeded")++ with pytest.raises(RuntimeError, match="AccountQuotaExceeded"):+ await retry_async(_call, max_retries=5)++ assert attempts["count"] == 1+++def test_quota_exceeded_case_insensitive():+ """Quota detection is case-insensitive."""+ assert classify_api_error(RuntimeError("QUOTA LIMIT")) == ERROR_CLASS_QUOTA_EXCEEDED+ assert classify_api_error(RuntimeError("Quota Exceed")) == ERROR_CLASS_QUOTA_EXCEEDEDdiff --git a/tests/unit/test_vlm_failover.py b/tests/unit/test_vlm_failover.pyindex d265d542d..fc662607b 100644--- a/tests/unit/test_vlm_failover.py+++ b/tests/unit/test_vlm_failover.py@@ -2,10 +2,11 @@# SPDX-License-Identifier: AGPL-3.0"""Tests for VLM failover/backup configuration functionality."""+import timeimport pytest-from unittest.mock import Mock, AsyncMock+from unittest.mock import Mock, AsyncMock, patch-from openviking.models.vlm.base import FailoverVLM, VLMResponse+from openviking.models.vlm.base import FailoverVLM, VLMResponse, PrimaryBackupSwitcherfrom openviking_cli.utils.config.vlm_config import VLMConfig@@ -125,8 +126,8 @@ class TestFailoverVLM:backup.get_completion.assert_not_called()assert failover.is_using_backup is False- def test_primary_fails_rate_limit_fails_to_backup(self):- """Test that rate limit errors trigger failover to backup."""+ def test_primary_fails_rate_limit_does_not_failover(self):+ """Test that rate limit errors do not trigger failover to backup."""primary = Mock()primary.model = "primary-model"primary.provider = "volcengine"@@ -139,6 +140,31 @@ class TestFailoverVLM:failover = FailoverVLM(primary, backup)+ with pytest.raises(Exception, match="rate limit exceeded"):+ failover.get_completion(prompt="test")++ primary.get_completion.assert_called_once()+ backup.get_completion.assert_not_called()+ assert failover.is_using_backup is False++ def test_primary_fails_quota_exceeded_fails_to_backup(self):+ """Test that AccountQuotaExceeded triggers immediate failover."""+ primary = Mock()+ primary.model = "primary-model"+ primary.provider = "volcengine"+ primary.get_completion.side_effect = Exception(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded",'+ '"message":"You have exceeded the 5-hour usage quota. '+ 'It will reset at 2026-05-14 17:18:52 +0800 CST."}}'+ )++ backup = Mock()+ backup.model = "backup-model"+ backup.provider = "openai"+ backup.get_completion.return_value = "backup response"++ failover = FailoverVLM(primary, backup)+result = failover.get_completion(prompt="test")assert result == "backup response"@@ -146,8 +172,8 @@ class TestFailoverVLM:backup.get_completion.assert_called_once()assert failover.is_using_backup is True- def test_primary_fails_timeout_fails_to_backup(self):- """Test that timeout errors trigger failover to backup."""+ def test_primary_fails_timeout_does_not_failover(self):+ """Test that timeout errors do not trigger failover to backup."""primary = Mock()primary.model = "primary-model"primary.provider = "volcengine"@@ -160,13 +186,13 @@ class TestFailoverVLM:failover = FailoverVLM(primary, backup)- result = failover.get_completion(prompt="test")+ with pytest.raises(Exception, match="request timeout"):+ failover.get_completion(prompt="test")- assert result == "backup response"- assert failover.is_using_backup is True+ assert failover.is_using_backup is False- def test_primary_fails_server_error_fails_to_backup(self):- """Test that server errors trigger failover to backup."""+ def test_primary_fails_server_error_does_not_failover(self):+ """Test that server errors do not trigger failover to backup."""primary = Mock()primary.model = "primary-model"primary.provider = "volcengine"@@ -179,17 +205,19 @@ class TestFailoverVLM:failover = FailoverVLM(primary, backup)- result = failover.get_completion(prompt="test")+ with pytest.raises(Exception, match="server error 503"):+ failover.get_completion(prompt="test")- assert result == "backup response"- assert failover.is_using_backup is True+ assert failover.is_using_backup is Falsedef test_both_fail_raises_last_error(self):"""Test that if both primary and backup fail, the last error is raised."""primary = Mock()primary.model = "primary-model"primary.provider = "volcengine"- primary.get_completion.side_effect = Exception("rate limit exceeded (429)")+ primary.get_completion.side_effect = Exception(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded"}}'+ )backup = Mock()backup.model = "backup-model"@@ -209,7 +237,9 @@ class TestFailoverVLM:primary = Mock()primary.model = "primary-model"primary.provider = "volcengine"- primary.get_completion.side_effect = Exception("rate limit exceeded (429)")+ primary.get_completion.side_effect = Exception(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded"}}'+ )backup = Mock()backup.model = "backup-model"@@ -234,7 +264,9 @@ class TestFailoverVLM:primary = Mock()primary.model = "primary-model"primary.provider = "volcengine"- primary.get_vision_completion.side_effect = Exception("rate limit exceeded (429)")+ primary.get_vision_completion.side_effect = Exception(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded"}}'+ )backup = Mock()backup.model = "backup-model"@@ -256,7 +288,9 @@ class TestFailoverVLM:primary.model = "primary-model"primary.provider = "volcengine"primary.get_completion_async = AsyncMock(- side_effect=Exception("rate limit exceeded (429)")+ side_effect=Exception(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded"}}'+ ))backup = Mock()@@ -279,7 +313,9 @@ class TestFailoverVLM:primary.model = "primary-model"primary.provider = "volcengine"primary.get_vision_completion_async = AsyncMock(- side_effect=Exception("rate limit exceeded (429)")+ side_effect=Exception(+ 'API Error: 429 {"error":{"code":"AccountQuotaExceeded"}}'+ ))backup = Mock()@@ -346,3 +382,242 @@ class TestVLMConfigWithBackup:# Should be a FailoverVLM instanceassert hasattr(instance, "primary")assert hasattr(instance, "backup")+++class TestPrimaryBackupSwitcher:+ """Tests for PrimaryBackupSwitcher."""++ def test_initial_state(self):+ """Test initial state is using primary."""+ switcher = PrimaryBackupSwitcher()+ assert switcher.is_using_backup is False+ assert switcher.should_try_primary() is True++ def test_record_primary_success_no_change(self):+ """Test successful primary calls keep us on primary."""+ switcher = PrimaryBackupSwitcher()+ switcher.record_primary_success()+ assert switcher.is_using_backup is False++ def test_switch_to_backup_on_permanent_error(self):+ """Test permanent error triggers switch to backup."""+ switcher = PrimaryBackupSwitcher()+ error = Exception("403 forbidden")+ switched = switcher.record_primary_failure(error)+ assert switched is True+ assert switcher.is_using_backup is True++ def test_switch_to_backup_on_quota_error(self):+ """Test quota error triggers switch to backup."""+ switcher = PrimaryBackupSwitcher()+ error = Exception("quota exceeded")+ switched = switcher.record_primary_failure(error)+ assert switched is True+ assert switcher.is_using_backup is True++ def test_no_switch_on_other_errors(self):+ """Test other errors don't trigger switch."""+ switcher = PrimaryBackupSwitcher()+ error = Exception("invalid prompt")+ switched = switcher.record_primary_failure(error)+ assert switched is False+ assert switcher.is_using_backup is False++ def test_should_try_primary_after_request_count(self):+ """Test failback attempt after enough backup requests."""+ switcher = PrimaryBackupSwitcher(failback_request_count=3)++ # Switch to backup+ error = Exception("quota exceeded")+ switcher.record_primary_failure(error)+ assert switcher.is_using_backup is True++ # Record backup requests+ assert switcher.should_try_primary() is False+ switcher.record_backup_request()+ assert switcher.should_try_primary() is False+ switcher.record_backup_request()+ assert switcher.should_try_primary() is False+ switcher.record_backup_request()+ assert switcher.should_try_primary() is True++ def test_should_try_primary_after_timeout(self):+ """Test failback attempt after timeout."""+ switcher = PrimaryBackupSwitcher(failback_timeout_seconds=0.1)++ # Switch to backup+ error = Exception("quota exceeded")+ switcher.record_primary_failure(error)+ assert switcher.is_using_backup is True++ # Before timeout+ assert switcher.should_try_primary() is False++ # After timeout+ time.sleep(0.15)+ assert switcher.should_try_primary() is True++ def test_failback_success_stays_on_primary(self):+ """Test successful failback keeps us on primary."""+ switcher = PrimaryBackupSwitcher(failback_request_count=1)++ # Switch to backup+ error = Exception("quota exceeded")+ switcher.record_primary_failure(error)+ switcher.record_backup_request()++ # Now try primary and succeed+ assert switcher.should_try_primary() is True+ switcher.record_primary_success()++ assert switcher.is_using_backup is False++ def test_failback_failure_goes_back_to_backup(self):+ """Test failed failback goes back to backup and resets counter."""+ switcher = PrimaryBackupSwitcher(failback_request_count=2)++ # Switch to backup+ error = Exception("quota exceeded")+ switcher.record_primary_failure(error)+ switcher.record_backup_request()+ switcher.record_backup_request()++ # Now try primary and fail again+ assert switcher.should_try_primary() is True+ switched = switcher.record_primary_failure(Exception("quota exceeded again"))++ assert switched is True+ assert switcher.is_using_backup is True++ # Counter should be reset+ switcher.record_backup_request()+ assert switcher.should_try_primary() is False+++class TestFailoverVLMAutomaticFailback:+ """Tests for FailoverVLM automatic failback functionality."""++ def test_failback_after_request_count(self):+ """Test automatic failback after enough backup requests."""+ primary = Mock()+ primary.model = "primary-model"+ primary.provider = "volcengine"+ # First call fails, then succeeds+ primary.get_completion.side_effect = [+ Exception("quota exceeded"),+ "primary is back!",+ ]++ backup = Mock()+ backup.model = "backup-model"+ backup.provider = "openai"+ backup.get_completion.return_value = "backup response"++ failover = FailoverVLM(primary, backup, failback_request_count=2)++ # First call - fails over to backup+ result1 = failover.get_completion(prompt="test1")+ assert result1 == "backup response"+ assert failover.is_using_backup is True++ # Second call - still using backup+ result2 = failover.get_completion(prompt="test2")+ assert result2 == "backup response"++ # Third call - should try primary again and succeed+ result3 = failover.get_completion(prompt="test3")+ assert result3 == "primary is back!"+ assert failover.is_using_backup is False++ def test_failback_failure_stays_on_backup(self):+ """Test if failback fails, it stays on backup and resets counter."""+ primary = Mock()+ primary.model = "primary-model"+ primary.provider = "volcengine"+ # Always fails+ primary.get_completion.side_effect = Exception("quota exceeded")++ backup = Mock()+ backup.model = "backup-model"+ backup.provider = "openai"+ backup.get_completion.return_value = "backup response"++ failover = FailoverVLM(primary, backup, failback_request_count=2)++ # First call - fails over+ result1 = failover.get_completion(prompt="test1")+ assert result1 == "backup response"++ # Second call - still on backup+ result2 = failover.get_completion(prompt="test2")+ assert result2 == "backup response"++ # Third call - tries primary, fails again, goes back to backup+ result3 = failover.get_completion(prompt="test3")+ assert result3 == "backup response"+ assert failover.is_using_backup is True++ # Counter should be reset - next call doesn't try primary yet+ result4 = failover.get_completion(prompt="test4")+ assert result4 == "backup response"++ def test_failback_after_timeout(self):+ """Test automatic failback after timeout."""+ primary = Mock()+ primary.model = "primary-model"+ primary.provider = "volcengine"+ primary.get_completion.side_effect = [+ Exception("quota exceeded"),+ "primary is back!",+ ]++ backup = Mock()+ backup.model = "backup-model"+ backup.provider = "openai"+ backup.get_completion.return_value = "backup response"++ failover = FailoverVLM(primary, backup, failback_timeout_seconds=0.1)++ # First call - fails over+ result1 = failover.get_completion(prompt="test1")+ assert result1 == "backup response"+ assert failover.is_using_backup is True++ # Wait for timeout+ time.sleep(0.15)++ # Next call - should try primary again+ result2 = failover.get_completion(prompt="test2")+ assert result2 == "primary is back!"+ assert failover.is_using_backup is False++ @pytest.mark.asyncio+ async def test_async_failback_after_request_count(self):+ """Test automatic failback works with async methods."""+ primary = Mock()+ primary.model = "primary-model"+ primary.provider = "volcengine"+ primary.get_completion_async = AsyncMock(side_effect=[+ Exception("quota exceeded"),+ "primary async is back!",+ ])++ backup = Mock()+ backup.model = "backup-model"+ backup.provider = "openai"+ backup.get_completion_async = AsyncMock(return_value="backup async response")++ failover = FailoverVLM(primary, backup, failback_request_count=2)++ # First call - fails over+ result1 = await failover.get_completion_async(prompt="test1")+ assert result1 == "backup async response"++ # Second call - still on backup+ result2 = await failover.get_completion_async(prompt="test2")+ assert result2 == "backup async response"++ # Third call - tries primary and succeeds+ result3 = await failover.get_completion_async(prompt="test3")+ assert result3 == "primary async is back!"+ assert failover.is_using_backup is Falsediff --git a/tests/utils/test_circuit_breaker.py b/tests/utils/test_circuit_breaker.pyindex 8ec4a9981..32d67ad71 100644--- a/tests/utils/test_circuit_breaker.py+++ b/tests/utils/test_circuit_breaker.py@@ -161,54 +161,60 @@ def test_thread_safety():def test_classify_filesystem_errors_as_permanent():from openviking.utils.circuit_breaker import classify_api_error+ from openviking.utils.model_retry import ERROR_CLASS_PERMANENT, ERROR_CLASS_TRANSIENT, ERROR_CLASS_UNKNOWN- assert classify_api_error(FileNotFoundError("/path/not/found")) == "permanent"- assert classify_api_error(PermissionError("Permission denied")) == "permanent"- assert classify_api_error(IsADirectoryError("Is a directory")) == "permanent"- assert classify_api_error(NotADirectoryError("Not a directory")) == "permanent"+ assert classify_api_error(FileNotFoundError("/path/not/found")) == ERROR_CLASS_PERMANENT+ assert classify_api_error(PermissionError("Permission denied")) == ERROR_CLASS_PERMANENT+ assert classify_api_error(IsADirectoryError("Is a directory")) == ERROR_CLASS_PERMANENT+ assert classify_api_error(NotADirectoryError("Not a directory")) == ERROR_CLASS_PERMANENTdef test_classify_chained_filesystem_error_as_permanent():from openviking.utils.circuit_breaker import classify_api_error+ from openviking.utils.model_retry import ERROR_CLASS_PERMANENT, ERROR_CLASS_TRANSIENT, ERROR_CLASS_UNKNOWNcause = FileNotFoundError("/missing")wrapper = RuntimeError("storage layer failed")wrapper.__cause__ = cause- assert classify_api_error(wrapper) == "permanent"+ assert classify_api_error(wrapper) == ERROR_CLASS_PERMANENTdef test_classify_permanent_errors():from openviking.utils.circuit_breaker import classify_api_error+ from openviking.utils.model_retry import ERROR_CLASS_PERMANENT, ERROR_CLASS_TRANSIENT, ERROR_CLASS_UNKNOWN- assert classify_api_error(RuntimeError("403 Forbidden")) == "permanent"- assert classify_api_error(RuntimeError("AccountOverdueError: 403")) == "permanent"- assert classify_api_error(RuntimeError("401 Unauthorized")) == "permanent"- assert classify_api_error(RuntimeError("Forbidden")) == "permanent"+ assert classify_api_error(RuntimeError("403 Forbidden")) == ERROR_CLASS_PERMANENT+ assert classify_api_error(RuntimeError("AccountOverdueError: 403")) == ERROR_CLASS_PERMANENT+ assert classify_api_error(RuntimeError("401 Unauthorized")) == ERROR_CLASS_PERMANENT+ assert classify_api_error(RuntimeError("Forbidden")) == ERROR_CLASS_PERMANENTdef test_classify_transient_errors():from openviking.utils.circuit_breaker import classify_api_error+ from openviking.utils.model_retry import ERROR_CLASS_PERMANENT, ERROR_CLASS_TRANSIENT, ERROR_CLASS_UNKNOWN- assert classify_api_error(RuntimeError("429 TooManyRequests")) == "transient"- assert classify_api_error(RuntimeError("RateLimitError")) == "transient"- assert classify_api_error(RuntimeError("500 Internal Server Error")) == "transient"- assert classify_api_error(RuntimeError("502 Bad Gateway")) == "transient"- assert classify_api_error(RuntimeError("503 Service Unavailable")) == "transient"- assert classify_api_error(RuntimeError("Connection timeout")) == "transient"- assert classify_api_error(RuntimeError("ConnectionError: refused")) == "transient"+ assert classify_api_error(RuntimeError("429 TooManyRequests")) == ERROR_CLASS_TRANSIENT+ assert classify_api_error(RuntimeError("RateLimitError")) == ERROR_CLASS_TRANSIENT+ assert classify_api_error(RuntimeError("500 Internal Server Error")) == ERROR_CLASS_TRANSIENT+ assert classify_api_error(RuntimeError("502 Bad Gateway")) == ERROR_CLASS_TRANSIENT+ assert classify_api_error(RuntimeError("503 Service Unavailable")) == ERROR_CLASS_TRANSIENT+ assert classify_api_error(RuntimeError("Connection timeout")) == ERROR_CLASS_TRANSIENT+ assert classify_api_error(RuntimeError("ConnectionError: refused")) == ERROR_CLASS_TRANSIENTdef test_classify_unknown_errors():from openviking.utils.circuit_breaker import classify_api_error+ from openviking.utils.model_retry import ERROR_CLASS_PERMANENT, ERROR_CLASS_TRANSIENT, ERROR_CLASS_UNKNOWN- assert classify_api_error(RuntimeError("something unexpected")) == "unknown"- assert classify_api_error(ValueError("bad value")) == "unknown"+ assert classify_api_error(RuntimeError("something unexpected")) == ERROR_CLASS_UNKNOWN+ assert classify_api_error(ValueError("bad value")) == ERROR_CLASS_UNKNOWNdef test_classify_chained_exception():from openviking.utils.circuit_breaker import classify_api_error+ from openviking.utils.model_retry import ERROR_CLASS_PERMANENT, ERROR_CLASS_TRANSIENT, ERROR_CLASS_UNKNOWNcause = RuntimeError("403 Forbidden")wrapper = RuntimeError("API call failed")wrapper.__cause__ = cause- assert classify_api_error(wrapper) == "permanent"+ assert classify_api_error(wrapper) == ERROR_CLASS_PERMANENT