Merge branch 'simp/r3-03-init' into simp/r3-03

This commit is contained in:
Teknium
2026-09-02 21:19:17 -07:00
8 changed files with 1244 additions and 2212 deletions
+28 -44
View File
@@ -7,6 +7,7 @@ import logging
import os
import threading
import time
from contextlib import suppress
from typing import Optional
from agent.session_activity import ActivityProvenance
@@ -15,6 +16,15 @@ from agent.session_activity import ActivityProvenance
logger = logging.getLogger("run_agent")
def _activity_lock(obj) -> "threading.Lock":
"""Lazy per-instance ``_turn_liveness_activity_lock`` (so ``__new__``/SimpleNamespace doubles work)."""
_lock = getattr(obj, "_turn_liveness_activity_lock", None)
if _lock is None:
_lock = threading.Lock()
obj._turn_liveness_activity_lock = _lock
return _lock
class ActivityTrackingMixin:
"""Liveness timestamps/labels and rate-limited session activity persistence."""
@@ -22,42 +32,29 @@ class ActivityTrackingMixin:
"""Shared lock for the activity clock and its generation counter.
``_touch_activity`` stamps under it and the liveness watchdog samples/commits under it, so a stall
observation can never abort a turn that resumed in between. Lazy so ``__new__``-built doubles work.
observation can never abort a turn that resumed in between.
"""
_lock = getattr(self, "_turn_liveness_activity_lock", None)
if _lock is None:
_lock = threading.Lock()
self._turn_liveness_activity_lock = _lock
return _lock
return _activity_lock(self)
def _touch_activity(
self,
desc: str,
*,
provenance: Optional[ActivityProvenance] = None,
self, desc: str, *, provenance: Optional[ActivityProvenance] = None,
force_persist: bool = False,
) -> None:
"""Update the last-activity timestamp and description (thread-safe).
Bumps a monotonic generation under ``_liveness_activity_lock`` so the watchdog can bind a stall
observation to the exact ``(generation, timestamp)`` it sampled. Also bridges (rate-limited,
best-effort) to the kanban heartbeat when this is a dispatcher-spawned worker, and to the durable
SessionDB activity projection. ``provenance`` names special writers (compression); ``force_persist``
bypasses the SessionDB rate limit.
Bumps a monotonic generation under the activity lock so the watchdog can bind a stall observation to
the exact ``(generation, timestamp)`` it sampled. Also bridges (rate-limited, best-effort) to the
kanban heartbeat when this is a dispatcher-spawned worker, and to the durable SessionDB activity
projection. ``provenance`` names special writers (compression); ``force_persist`` bypasses the
SessionDB rate limit. Module-level lock helper, not ``self._liveness_activity_lock()``: doubles bind
only ``_touch_activity`` (tests/run_agent/test_session_activity_persist.py).
"""
from agent.session_activity import (
bound_activity_description,
normalize_activity_provenance,
bound_activity_description, normalize_activity_provenance,
reset_session_activity_persist_window,
)
# Lazy per-instance lock, inline so SimpleNamespace doubles binding _touch_activity without the
# class keep working (tests/run_agent/test_session_activity_persist.py).
_clock_lock = getattr(self, "_turn_liveness_activity_lock", None)
if _clock_lock is None:
_clock_lock = threading.Lock()
self._turn_liveness_activity_lock = _clock_lock
with _clock_lock:
with _activity_lock(self):
self._turn_liveness_activity_generation = (
getattr(self, "_turn_liveness_activity_generation", 0) + 1
)
@@ -68,18 +65,14 @@ class ActivityTrackingMixin:
# itself at the final mutation edge.
self._turn_liveness_abort_claim = None
if os.environ.get("HERMES_KANBAN_TASK"):
try:
# Never let the bridge break the loop; this guard covers import-time failures.
with suppress(Exception):
from tools.kanban_tools import (
heartbeat_current_worker_from_env,
inject_new_comments_from_env,
heartbeat_current_worker_from_env, inject_new_comments_from_env
)
heartbeat_current_worker_from_env()
# Fold any new operator notes into the running turn (OUT-OF-BAND
# steer) so the user can talk to a live task without a restart.
# Fold new operator notes into the running turn (OUT-OF-BAND steer).
inject_new_comments_from_env(self)
except Exception:
# Never let the bridge break the loop; this guard covers import-time failures.
pass
if force_persist:
reset_session_activity_persist_window(self)
self._persist_session_activity_if_due()
@@ -98,8 +91,7 @@ class ActivityTrackingMixin:
if not callable(touch):
return
from agent.session_activity import (
SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS,
normalize_activity_provenance,
SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS, normalize_activity_provenance
)
now_mono = time.monotonic()
@@ -118,10 +110,7 @@ class ActivityTrackingMixin:
)
except Exception:
# Heartbeat is observation-only; never let its I/O break the loop.
logger.debug(
"session activity heartbeat write failed (ignored)",
exc_info=True,
)
logger.debug("session activity heartbeat write failed (ignored)", exc_info=True)
def _reset_activity_labels_after_turn(self) -> None:
"""Drop mid-turn activity labels once the turn is no longer running.
@@ -129,8 +118,6 @@ class ActivityTrackingMixin:
Keeps ``_last_activity_ts`` so idle/watchdog clocks stay continuous across turns; clears description +
provenance so idle agents / SessionDB listings stop advertising the last mid-turn stamp.
"""
from agent.session_activity import ActivityProvenance
self._last_activity_desc = ""
self._last_activity_provenance = ActivityProvenance.UNKNOWN
session_id = getattr(self, "session_id", None)
@@ -140,8 +127,5 @@ class ActivityTrackingMixin:
clear = getattr(session_db, "clear_session_activity_labels", None)
if not callable(clear):
return
try:
with suppress(Exception): # never let durable cleanup I/O break turn teardown
clear(session_id)
except Exception:
# Never let durable cleanup I/O break turn teardown.
pass
+1060 -1880
View File
File diff suppressed because it is too large Load Diff
+58 -89
View File
@@ -10,14 +10,46 @@ from typing import Any, Dict, Optional
from agent.redact import redact_sensitive_text
# Offline DNS failures are wrapped in a generic "Connection error" by SDKs — inspect the chain.
_NETWORK_RESOLUTION_MARKERS = (
"temporary failure in name resolution",
"name or service not known",
"nodename nor servname provided, or not known",
"getaddrinfo failed",
"no address associated with hostname",
"network is unreachable",
)
_XAI_ENTITLEMENT_HINT = (
" — xAI rejected this OAuth account. NOTE: X Premium+ does NOT "
"include xAI API access — only standalone SuperGrok subscribers "
"can use this provider. Other possible causes: no Grok "
"subscription, your tier doesn't include this model, or your "
"quota is exhausted. Check https://grok.com/?_s=usage to see "
"which, or run `/model` to switch providers."
)
_ERROR_DETAIL_KEYS = ("message", "detail", "error", "code", "type")
def _is_xai_entitlement_text(lower: str) -> bool:
"""xAI's permission-denied body text for an unsubscribed / under-tiered / exhausted account."""
return (
"do not have an active grok subscription" in lower
or ("out of available resources" in lower and "grok" in lower)
or ("does not have permission" in lower and "grok" in lower)
)
def _http_prefix(error: Exception) -> str:
status_code = getattr(error, "status_code", None)
return f"HTTP {status_code}: " if status_code else ""
class ApiErrorSummaryMixin:
"""Provider error -> user/log-safe summary (see module docstring)."""
@staticmethod
def _is_entitlement_failure(
error_context: Optional[Dict[str, Any]],
status_code: Optional[int],
error_context: Optional[Dict[str, Any]], status_code: Optional[int]
) -> bool:
"""Detect subscription/entitlement 401/403s that masquerade as auth failures.
@@ -31,26 +63,14 @@ class ApiErrorSummaryMixin:
if not isinstance(error_context, dict):
return False
# Single lowercase haystack over every field shape (message/reason and raw code/error).
message = str(error_context.get("message") or "").lower()
reason = str(error_context.get("reason") or "").lower()
code = str(error_context.get("code") or "").lower()
err = str(error_context.get("error") or "").lower()
haystack = f"{message} {reason} {code} {err}"
haystack = " ".join(
str(error_context.get(k) or "").lower() for k in ("message", "reason", "code", "error")
)
if not haystack.strip():
return False
# xAI's disambiguator for stale-token vs unsubscribed: same permission-denied text, only one carries
# this suffix. Bail out so a stale OAuth token takes the credential-refresh path (#29344).
if "[wke=unauthenticated:" in haystack:
if "[wke=unauthenticated:" in haystack or "oauth2 access token could not be validated" in haystack:
return False
if "oauth2 access token could not be validated" in haystack:
return False
if "do not have an active grok subscription" in haystack:
return True
if "out of available resources" in haystack and "grok" in haystack:
return True
if "does not have permission" in haystack and "grok" in haystack:
return True
return False
return _is_xai_entitlement_text(haystack)
@staticmethod
def _decorate_xai_entitlement_error(detail: str) -> str:
@@ -58,31 +78,14 @@ class ApiErrorSummaryMixin:
xAI's ``/v1/responses`` uses one body for several causes (no subscription, tier lacks the model, quota
exhausted). The least obvious: X Premium+ does NOT include API access — only SuperGrok does. Lead with
that, keep the raw text, point at https://grok.com/?_s=usage. Matched once per detail string.
that, keep the raw text, point at https://grok.com/?_s=usage. Idempotent: a substring unique to the
hint marks prior decoration.
"""
if not detail:
if not detail or not _is_xai_entitlement_text(detail.lower()):
return detail
lower = detail.lower()
is_entitlement = (
"do not have an active grok subscription" in lower
or ("out of available resources" in lower and "grok" in lower)
or ("does not have permission" in lower and "grok" in lower)
)
if not is_entitlement:
return detail
hint = (
" — xAI rejected this OAuth account. NOTE: X Premium+ does NOT "
"include xAI API access — only standalone SuperGrok subscribers "
"can use this provider. Other possible causes: no Grok "
"subscription, your tier doesn't include this model, or your "
"quota is exhausted. Check https://grok.com/?_s=usage to see "
"which, or run `/model` to switch providers."
)
# Idempotency: detect prior decoration by a substring unique to the
# hint (not present in xAI's own body text).
if "X Premium+ does NOT include" in detail:
return detail
return f"{detail}{hint}"
return f"{detail}{_XAI_ENTITLEMENT_HINT}"
@staticmethod
def _coerce_api_error_detail(value: Any) -> str:
@@ -90,11 +93,11 @@ class ApiErrorSummaryMixin:
if isinstance(value, str):
return value
if isinstance(value, dict):
for key in ("message", "detail", "error", "code", "type"):
for key in _ERROR_DETAIL_KEYS:
nested = value.get(key)
if isinstance(nested, str) and nested.strip():
return nested
for key in ("message", "detail", "error", "code", "type"):
for key in _ERROR_DETAIL_KEYS:
if key in value:
nested_detail = ApiErrorSummaryMixin._coerce_api_error_detail(value[key])
if nested_detail:
@@ -104,10 +107,7 @@ class ApiErrorSummaryMixin:
except TypeError:
return str(value)
if isinstance(value, (list, tuple)):
parts = [
ApiErrorSummaryMixin._coerce_api_error_detail(item)
for item in value
]
parts = [ApiErrorSummaryMixin._coerce_api_error_detail(item) for item in value]
return "; ".join(part for part in parts if part)
if value is None:
return ""
@@ -122,49 +122,30 @@ class ApiErrorSummaryMixin:
"""
raw = str(error)
# Offline DNS failures are wrapped in a generic "Connection error" by SDKs — inspect the chain.
network_resolution_markers = (
"temporary failure in name resolution",
"name or service not known",
"nodename nor servname provided, or not known",
"getaddrinfo failed",
"no address associated with hostname",
"network is unreachable",
)
current: Optional[BaseException] = error
seen: set[int] = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
if any(
marker in str(current).lower()
for marker in network_resolution_markers
):
if any(marker in str(current).lower() for marker in _NETWORK_RESOLUTION_MARKERS):
return (
"Hermes can't reach the model provider. You may be offline. "
"Check your internet connection and try again."
)
current = current.__cause__ or current.__context__
if (
isinstance(error, ValueError)
and "expected ident at line" in raw.lower()
):
if isinstance(error, ValueError) and "expected ident at line" in raw.lower():
return f"Malformed provider streaming response: {raw[:300]}"
# Cloudflare / proxy HTML pages: grab the <title> for a clean summary
prefix = _http_prefix(error)
# Cloudflare / proxy HTML pages: grab the <title> (and Ray ID) for a clean summary
if "<!DOCTYPE" in raw or "<html" in raw:
m = re.search(r"<title[^>]*>([^<]+)</title>", raw, re.IGNORECASE)
title = m.group(1).strip() if m else "HTML error page (title not found)"
# Also grab Cloudflare Ray ID if present
ray = re.search(r"Cloudflare Ray ID:\s*<strong[^>]*>([^<]+)</strong>", raw)
ray_id = ray.group(1).strip() if ray else None
status_code = getattr(error, "status_code", None)
parts = []
if status_code:
parts.append(f"HTTP {status_code}")
parts = [prefix[:-2]] if prefix else []
parts.append(title)
if ray_id:
parts.append(f"Ray {ray_id}")
if ray:
parts.append(f"Ray {ray.group(1).strip()}")
return " — ".join(parts)
# GeminiAPIError already composes a clean one-liner with guidance; don't re-extract the raw body.
@@ -176,13 +157,11 @@ class ApiErrorSummaryMixin:
if isinstance(body, dict):
msg = body.get("error", {}).get("message") if isinstance(body.get("error"), dict) else body.get("message")
if msg:
status_code = getattr(error, "status_code", None)
prefix = f"HTTP {status_code}: " if status_code else ""
msg = ApiErrorSummaryMixin._coerce_api_error_detail(msg)
return ApiErrorSummaryMixin._decorate_xai_entitlement_error(f"{prefix}{msg[:300]}")
# SDK may leave body empty while httpx has the payload (#36109). Redact: the body is
# attacker-influenced and may echo Authorization / x-api-key / request JSON.
# SDK may leave body empty while httpx has the payload. Redact: the body is attacker-influenced
# and may echo Authorization / x-api-key / request JSON.
response = getattr(error, "response", None)
if response is not None:
try:
@@ -190,8 +169,6 @@ class ApiErrorSummaryMixin:
except Exception:
snippet = ""
if snippet:
status_code = getattr(error, "status_code", None)
prefix = f"HTTP {status_code}: " if status_code else ""
try:
payload = json.loads(snippet)
except (json.JSONDecodeError, TypeError):
@@ -205,13 +182,11 @@ class ApiErrorSummaryMixin:
return redact_sensitive_text(f"{prefix}{snippet[:300]}")
# Fallback: truncate the raw string but give more room than 200 chars
status_code = getattr(error, "status_code", None)
prefix = f"HTTP {status_code}: " if status_code else ""
return ApiErrorSummaryMixin._decorate_xai_entitlement_error(f"{prefix}{raw[:500]}")
def _mask_api_key_for_logs(self, key: Any) -> Optional[str]:
# Azure Foundry Entra ID bearer providers are callables — never
# invoke them in log paths; identify the auth surface instead.
# Azure Foundry Entra ID bearer providers are callables — never invoke them in log
# paths; identify the auth surface instead.
if callable(key) and not isinstance(key, str):
return "<entra-id-bearer>"
if not key:
@@ -224,16 +199,10 @@ class ApiErrorSummaryMixin:
"""Clean up error messages for user display, removing HTML content and truncating."""
if not error_msg:
return "Unknown error"
# Remove HTML content (common with CloudFlare and gateway error pages)
# HTML content is common with CloudFlare and gateway error pages
if error_msg.strip().startswith('<!DOCTYPE html') or '<html' in error_msg:
return "Service temporarily unavailable (HTML error page returned)"
# Remove newlines and excessive whitespace
cleaned = ' '.join(error_msg.split())
# Truncate if too long
if len(cleaned) > 150:
cleaned = cleaned[:150] + "..."
return cleaned
+54 -135
View File
@@ -6,11 +6,28 @@ Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO
import json
import os
import time
from contextlib import suppress
from types import SimpleNamespace
from typing import Any, Dict, Optional
from agent.usage_pricing import normalize_usage
_SENSITIVE_HOOK_KEYS = {"api_key", "authorization", "proxy_authorization", "cookie", "set_cookie"}
def _model_dump(value: Any) -> Any:
"""``value.model_dump(mode="json")`` with graceful degradation for older pydantic signatures.
warnings=False: pydantic UserWarnings on generic-union SDK models would leak to the terminal.
"""
try:
return value.model_dump(mode="json", warnings=False)
except TypeError:
try:
return value.model_dump(mode="json")
except TypeError:
return value.model_dump()
class ApiRequestHooksMixin:
"""Hook payload sanitising + ``api_request_error`` dispatch (see module docstring)."""
@@ -44,23 +61,11 @@ class ApiRequestHooksMixin:
if not isinstance(key, str):
return False
lowered = key.lower().replace("-", "_")
exact = {
"api_key",
"authorization",
"proxy_authorization",
"cookie",
"set_cookie",
}
return lowered in exact or lowered.endswith("_api_key")
return lowered in _SENSITIVE_HOOK_KEYS or lowered.endswith("_api_key")
@classmethod
def _hook_jsonable(
cls,
value: Any,
*,
depth: int = 0,
max_depth: int = 8,
max_string: int = 8000,
cls, value: Any, *, depth: int = 0, max_depth: int = 8, max_string: int = 8000,
max_sequence: int = 200,
) -> Any:
if depth > max_depth:
@@ -73,6 +78,13 @@ class ApiRequestHooksMixin:
return value
if isinstance(value, (bytes, bytearray)):
return f"<{len(value)} bytes>"
def recurse(item):
return cls._hook_jsonable(
item, depth=depth + 1, max_depth=max_depth, max_string=max_string,
max_sequence=max_sequence,
)
if isinstance(value, dict):
out: Dict[str, Any] = {}
for idx, (key, item) in enumerate(value.items()):
@@ -80,111 +92,43 @@ class ApiRequestHooksMixin:
out["_truncated_items"] = len(value) - max_sequence
break
str_key = str(key)
if cls._is_sensitive_hook_key(str_key):
out[str_key] = "<redacted>"
else:
out[str_key] = cls._hook_jsonable(
item,
depth=depth + 1,
max_depth=max_depth,
max_string=max_string,
max_sequence=max_sequence,
)
out[str_key] = "<redacted>" if cls._is_sensitive_hook_key(str_key) else recurse(item)
return out
if isinstance(value, (list, tuple, set)):
seq = list(value)
out = [
cls._hook_jsonable(
item,
depth=depth + 1,
max_depth=max_depth,
max_string=max_string,
max_sequence=max_sequence,
)
for item in seq[:max_sequence]
]
out = [recurse(item) for item in seq[:max_sequence]]
if len(seq) > max_sequence:
out.append({"_truncated_items": len(seq) - max_sequence})
return out
try:
with suppress(Exception):
if hasattr(value, "model_dump"):
try:
# warnings=False: pydantic UserWarnings on generic-union SDK models would leak to the
# terminal.
dumped = value.model_dump(mode="json", warnings=False)
except TypeError:
try:
dumped = value.model_dump(mode="json")
except TypeError:
dumped = value.model_dump()
return cls._hook_jsonable(
dumped,
depth=depth + 1,
max_depth=max_depth,
max_string=max_string,
max_sequence=max_sequence,
)
except Exception:
pass
try:
return recurse(_model_dump(value))
with suppress(Exception):
from dataclasses import asdict, is_dataclass
if is_dataclass(value):
return cls._hook_jsonable(
asdict(value),
depth=depth + 1,
max_depth=max_depth,
max_string=max_string,
max_sequence=max_sequence,
)
except Exception:
pass
return recurse(asdict(value))
if isinstance(value, SimpleNamespace):
return cls._hook_jsonable(
vars(value),
depth=depth + 1,
max_depth=max_depth,
max_string=max_string,
max_sequence=max_sequence,
)
return recurse(vars(value))
if hasattr(value, "__dict__"):
try:
public_attrs = {
k: v
for k, v in vars(value).items()
if not str(k).startswith("_")
}
return cls._hook_jsonable(
public_attrs,
depth=depth + 1,
max_depth=max_depth,
max_string=max_string,
max_sequence=max_sequence,
)
except Exception:
pass
with suppress(Exception):
return recurse({k: v for k, v in vars(value).items() if not str(k).startswith("_")})
return str(value)[:max_string]
@classmethod
def _sanitize_hook_payload(cls, value: Any) -> Any:
payload = cls._hook_jsonable(value)
"""JSON-able payload under the size cap: full → reduced caps → truncated preview."""
limit = cls._hook_payload_max_chars()
try:
encoded = json.dumps(payload, ensure_ascii=False, default=str)
except Exception:
return str(payload)[:limit]
if len(encoded) <= limit:
return payload
payload = cls._hook_jsonable(value, max_string=1000, max_sequence=50)
try:
encoded = json.dumps(payload, ensure_ascii=False, default=str)
except Exception:
return str(payload)[:limit]
if len(encoded) <= limit:
return payload
encoded = ""
for caps in ({}, {"max_string": 1000, "max_sequence": 50}):
payload = cls._hook_jsonable(value, **caps)
try:
encoded = json.dumps(payload, ensure_ascii=False, default=str)
except Exception:
return str(payload)[:limit]
if len(encoded) <= limit:
return payload
return {
"_truncated": True,
"original_type": type(value).__name__,
"preview": encoded[:limit],
"_truncated": True, "original_type": type(value).__name__, "preview": encoded[:limit]
}
def _api_request_payload_for_hook(self, api_kwargs: Optional[Dict[str, Any]]) -> Dict[str, Any]:
@@ -193,19 +137,10 @@ class ApiRequestHooksMixin:
for key, value in (api_kwargs or {}).items()
if key not in {"timeout", "http_client"}
}
return self._sanitize_hook_payload(
{
"method": "POST",
"body": body,
}
)
return self._sanitize_hook_payload({"method": "POST", "body": body})
def _api_response_payload_for_hook(
self,
response: Any,
assistant_message: Any,
*,
finish_reason: Optional[str],
self, response: Any, assistant_message: Any, *, finish_reason: Optional[str]
) -> Dict[str, Any]:
# Raw provider SDK tool_call objects are handed to the sanitizer on purpose; `_hook_jsonable` must
# keep normalising them (model_dump / __dict__ / dataclass) or subscribers get str() blobs.
@@ -224,26 +159,15 @@ class ApiRequestHooksMixin:
)
def _invoke_api_request_error_hook(
self,
*,
task_id: str,
turn_id: str,
api_request_id: str,
api_call_count: int,
api_start_time: float,
api_kwargs: Optional[Dict[str, Any]],
error_type: str,
error_message: str,
status_code: Optional[int] = None,
retry_count: Optional[int] = None,
max_retries: Optional[int] = None,
retryable: Optional[bool] = None,
self, *, task_id: str, turn_id: str, api_request_id: str, api_call_count: int,
api_start_time: float, api_kwargs: Optional[Dict[str, Any]], error_type: str,
error_message: str, status_code: Optional[int] = None, retry_count: Optional[int] = None,
max_retries: Optional[int] = None, retryable: Optional[bool] = None,
reason: Optional[str] = None,
) -> None:
# Lazy module import (not from-import) so tests can replace lifecycle dispatch at this call site.
try:
with suppress(Exception):
from hermes_cli import lifecycle as _lifecycle
if not _lifecycle.has_hook("api_request_error"):
return
ended_at = time.time()
@@ -267,11 +191,6 @@ class ApiRequestHooksMixin:
max_retries=max_retries,
retryable=retryable,
reason=reason,
error={
"type": error_type,
"message": error_message,
},
error={"type": error_type, "message": error_message},
request=self._api_request_payload_for_hook(api_kwargs),
)
except Exception:
pass
+33 -58
View File
@@ -1,27 +1,11 @@
"""Single owner for backend identity and failure-scoped skip decisions.
Every fallback / dedup / skip / quarantine decision asks one question: **"is
this candidate the same backend as the one that failed, along the axis that
failure invalidated?"** Answering it inline at each call site (comparing
whatever string was locally convenient) repeatedly reintroduced the same bugs:
same-shim aliases treated as distinct, sibling models skipped for one model's
timeout, dedup ignoring ``base_url`` and stranding multi-endpoint pools.
"provider" conflates three independent identity axes, each invalidated by a
different failure class:
* **credential surface** — auth 401 / payment 402 kill everything sharing the
credential (every model, every host reached with that key/token).
* **endpoint** — DNS failure / connection refused kill everything behind the
URL, regardless of model or credential.
* **model deployment** — timeout / overload / rate limit / model-incompatible
kill ONE model's deployment. A sibling model behind the same URL is an
independent deployment (one model hung while another on the identical
endpoint kept serving).
Call sites build :class:`BackendIdentity` values and ask
:func:`should_skip_candidate`. Do not re-implement any comparison inline —
extend THIS module instead.
Every fallback / dedup / skip / quarantine decision asks: "is this candidate the same backend
as the one that failed, along the axis that failure invalidated?" Answering inline at each
call site kept reintroducing the same bugs (same-shim aliases treated as distinct, sibling
models skipped for one model's timeout, dedup ignoring ``base_url``). "provider" conflates
three axes — credential surface (401/402), endpoint (DNS/refused), model deployment
(timeout/overload/429). Build :class:`BackendIdentity` values, ask :func:`should_skip_candidate`.
"""
from __future__ import annotations
@@ -37,8 +21,8 @@ logger = logging.getLogger(__name__)
class FailureScope(Enum):
"""Which identity axis a failure invalidates."""
#: Timeout, overload/429, connection blip, model-incompatible, invalid
#: response: evidence against ONE model deployment only.
#: Timeout, overload/429, connection blip, model-incompatible, invalid response:
#: evidence against ONE model deployment only.
MODEL = "model"
#: Auth 401 / payment 402: evidence against the shared credential.
CREDENTIAL = "credential"
@@ -54,8 +38,8 @@ def _norm(value: Optional[str]) -> str:
class BackendIdentity:
"""Normalized identity of one (provider, model, endpoint) deployment.
Empty fields mean "unknown" — an unknown axis can neither prove sameness
nor difference on its own; the remaining axes decide."""
Empty fields mean "unknown" — an unknown axis can neither prove sameness nor difference
on its own; the remaining axes decide."""
provider: str = ""
model: str = ""
@@ -63,25 +47,20 @@ class BackendIdentity:
@classmethod
def build(
cls,
provider: Optional[str] = None,
model: Optional[str] = None,
cls, provider: Optional[str] = None, model: Optional[str] = None,
base_url: Optional[str] = None,
) -> "BackendIdentity":
return cls(
provider=_norm(provider),
model=_norm(model),
base_url=_norm(base_url).rstrip("/"),
provider=_norm(provider), model=_norm(model), base_url=_norm(base_url).rstrip("/"),
)
def _both_first_class(a: BackendIdentity, b: BackendIdentity) -> bool:
"""True when both providers are distinct registered first-class providers.
Two different registry providers have distinct credential surfaces even
when they share an inference host (xai-oauth vs xai, openai-codex vs
openai-api). Custom/shim aliases are NOT in the registry, so two aliases
pointing at one URL still count as the same backend."""
Two different registry providers have distinct credential surfaces even when they share an
inference host (xai-oauth vs xai). Custom/shim aliases are NOT in the registry, so two
aliases pointing at one URL still count as the same backend."""
if not a.provider or not b.provider or a.provider == b.provider:
return False
try:
@@ -95,11 +74,9 @@ def _both_first_class(a: BackendIdentity, b: BackendIdentity) -> bool:
def same_credential_surface(a: BackendIdentity, b: BackendIdentity) -> bool:
"""Do two identities share the credential a 401/402 just invalidated?
Conservative on purpose: an unprovable axis answers "different" (one wasted
RTT) rather than "same" (stranded failover). Same label = same configured
credential; different labels = different credential config (custom entries
can each carry their own api_key, so a shared URL alone never proves a
shared credential — it is only a weak signal when a label is missing)."""
Conservative: an unprovable axis answers "different" (one wasted RTT) rather than "same"
(stranded failover). Same label = same configured credential; custom entries can each carry
their own api_key, so a shared URL alone is only a weak signal when a label is missing."""
if a.provider and b.provider:
return a.provider == b.provider
return bool(a.base_url and a.base_url == b.base_url)
@@ -107,8 +84,7 @@ def same_credential_surface(a: BackendIdentity, b: BackendIdentity) -> bool:
def same_endpoint(a: BackendIdentity, b: BackendIdentity) -> bool:
"""Do two identities sit behind the endpoint that just went unreachable?
An unknown base_url inherits the provider default, so a shared provider
label implies the same default endpoint."""
An unknown base_url inherits the provider default, so a shared label implies the same endpoint."""
if a.base_url and b.base_url:
return a.base_url == b.base_url
return bool(a.provider and a.provider == b.provider)
@@ -117,11 +93,10 @@ def same_endpoint(a: BackendIdentity, b: BackendIdentity) -> bool:
def same_deployment(a: BackendIdentity, b: BackendIdentity) -> bool:
"""Are these the exact same model deployment (the thing a timeout kills)?
Provider+model must match; base_url distinguishes only when BOTH sides carry
an explicit URL (same provider+model on two explicit URLs is a pool, not a
dup). Different labels with the same URL + model are still one deployment
(same-host shim aliases) — unless both labels are first-class registry
providers."""
Provider+model must match; base_url distinguishes only when BOTH sides carry an explicit URL
(same provider+model on two explicit URLs is a pool, not a dup). Different labels with the
same URL + model are still one deployment (same-host shim aliases) — unless both labels are
first-class registry providers."""
if not (a.provider and b.provider and a.provider == b.provider):
return bool(
a.base_url
@@ -135,16 +110,16 @@ def same_deployment(a: BackendIdentity, b: BackendIdentity) -> bool:
return not (a.base_url and b.base_url and a.base_url != b.base_url)
_SCOPE_PREDICATES = {
FailureScope.CREDENTIAL: same_credential_surface, FailureScope.ENDPOINT: same_endpoint,
FailureScope.MODEL: same_deployment,
}
def should_skip_candidate(
candidate: BackendIdentity,
failed: BackendIdentity,
scope: FailureScope = FailureScope.MODEL,
candidate: BackendIdentity, failed: BackendIdentity, scope: FailureScope = FailureScope.MODEL
) -> bool:
"""THE skip predicate: would trying ``candidate`` just repeat the failure?
True when it is the same backend as ``failed`` along the axis ``scope``
invalidated. Every fallback/dedup/skip site must call this."""
if scope is FailureScope.CREDENTIAL:
return same_credential_surface(candidate, failed)
if scope is FailureScope.ENDPOINT:
return same_endpoint(candidate, failed)
return same_deployment(candidate, failed)
True when it is the same backend as ``failed`` along the axis ``scope`` invalidated.
Every fallback/dedup/skip site must call this."""
return _SCOPE_PREDICATES.get(scope, same_deployment)(candidate, failed)
@@ -521,7 +521,8 @@ def test_agent_init_suppresses_micro_compaction_under_checkpoint_gate():
source = inspect.getsource(agent_init)
# The suppression must happen before the compressor attribute assignment.
suppress_idx = source.find("if cs.checkpoint_required and cs.micro_compact:")
assign_idx = source.find("_cc._micro_compact_enabled = cs.micro_compact")
# The compressor attribute assignment is table-driven; pin the table entry.
assign_idx = source.find('("_micro_compact_enabled", cs.micro_compact)')
assert suppress_idx != -1, (
"init_agent must suppress micro-compaction when checkpoint_required"
)
+2 -1
View File
@@ -198,4 +198,5 @@ class TestInvalidationSitesClearTurnBaseAnchor:
from agent import agent_init
src = inspect.getsource(agent_init)
assert "_turn_base_usage_anchor = None" in src
# Init defaults are declared in the ``_USAGE_STATE`` table.
assert '"_turn_base_usage_anchor": None' in src
+7 -4
View File
@@ -282,13 +282,16 @@ class TestInlinedDisplayMasks:
from pathlib import Path
src = (Path(__file__).resolve().parent.parent.parent
/ "agent" / "agent_init.py").read_text()
assert src.count("is_token_provider(") >= 2, (
# Both banner paths route through the shared ``_print_key_banner`` helper,
# which owns the single ``is_token_provider`` guard.
assert src.count("_print_key_banner(") >= 3, (
"agent/agent_init.py must guard BOTH masked-banner paths "
"(chat_completions and anthropic_messages) with "
"is_token_provider()."
"is_token_provider() via _print_key_banner()."
)
assert src.count('"🔑 Using credentials: Microsoft Entra ID"') >= 2, (
"agent/agent_init.py banner blocks should print a static "
assert "is_token_provider(" in src
assert '"🔑 Using credentials: Microsoft Entra ID"' in src, (
"agent/agent_init.py banner helper should print a static "
"'Microsoft Entra ID' label for callable api_keys — no "
"placeholder plumbing, no describe-mask fallback."
)