Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): read Google RPC error envelopes on HTTP errors (#3027)

Call White096cad71e7ed
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 7d9b12907..db29091b4 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -1095,6 +1095,15 @@ def _usage_from_scalar_paths(
return report
+# A Google RPC error envelope's integer ``code`` is the HTTP status it answered
+# with; this is the machine code each one projects to.
+GOOGLE_ERROR_STATUS_MACHINE_CODES: Final[Mapping[int, str]] = {
+ 400: "invalid_request_error", 401: "authentication_error",
+ 403: "permission_error", 404: "not_found_error",
+ 429: "rate_limit_error", 500: "server_error",
+ 502: "server_error", 503: "server_error", 504: "server_error",
+}
+
# Container markers for a hosted item's fields; scalars keep their value.
_ARRAY: Final = object()
_MAP: Final = object()
@@ -1465,12 +1474,7 @@ class ProtocolFactProjector:
# Gemini error.code carries an HTTP status even inside SSE.
# Normalize only shaped native errors; classification retains
# sole ownership of retry/health policy.
- value = {
- 400: "invalid_request_error", 401: "authentication_error",
- 403: "permission_error", 404: "not_found_error",
- 429: "rate_limit_error", 500: "server_error",
- 502: "server_error", 503: "server_error", 504: "server_error",
- }.get(value)
+ value = GOOGLE_ERROR_STATUS_MACHINE_CODES.get(value)
if not isinstance(value, str):
continue
if self.machine_error_codes and value not in self.machine_error_codes:
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index b616c7395..47e251522 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -672,7 +672,10 @@ The complete observation surface is limited to these facts:
1. An official error envelope at a terminal position is `failed_terminal`; machine-code
extraction reads only the protocol's declared C12 trust roots. Classification reads
only those machine codes, never the engine client's own account of how the call
- ended.
+ ended. An HTTP error body that matches none of its protocol's roots is also read at
+ Google's array-wrapped RPC envelope (`[{"error": …}]`), and a Google RPC envelope
+ (one with a string `status`) projects its integer `code` to a machine code as a
+ native Gemini error does, whatever protocol the Source speaks.
2. An official success terminal is `served` when its discriminator identity matches. For
named SSE events this is the minimal `(event name, data.type)` match. This is
discriminator-only observation, not validation of the remaining envelope members or
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index f9c946f79..0953bb5d4 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -8909,6 +8909,71 @@ def test_engine_reported_upstream_transport_failure_takes_network_recovery(
assert (outcome.http_status is None) is (kind is RawOutcomeKind.NETWORK_ERROR)
+_GEMINI_SIGNATURE_REFUSAL = "Function call is missing a thought_signature in functionCall parts."
+
+
+ ("body", "surfaced"),
+ [
+ # Gemini's OpenAI-compatible endpoint, relayed as is by the engine.
+ ([{"error": {"code": 400, "message": _GEMINI_SIGNATURE_REFUSAL, "status": "INVALID_ARGUMENT"}}], True),
+ ({"error": {"code": 400, "message": _GEMINI_SIGNATURE_REFUSAL, "status": "INVALID_ARGUMENT"}}, True),
+ # Only a Google RPC envelope's integer code names its class.
+ ({"error": {"code": 400, "message": _GEMINI_SIGNATURE_REFUSAL}}, False),
+ ],
+ ids=["google-array", "google-object", "integer-code-only"],
+)
+def test_engine_google_rpc_http_error_is_a_request_refusal_with_its_detail(body: object, surfaced: bool) -> None:
+ """A Google 400 relayed on a Chat Source names the rejected request, not an unknown Source failure."""
+
+ from aiohttp import web
+
+ async def run():
+ async def respond(_request: web.Request) -> web.Response:
+ return web.json_response(body, status=400)
+
+ app = web.Application()
+ app.router.add_post("/{path:.*}", respond)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ await web.TCPSite(runner, "127.0.0.1", 0).start()
+ try:
+ handle = await EngineClient(
+ EngineConnection(
+ base_url=f"http://127.0.0.1:{runner.addresses[0][1]}",
+ management_key="management-key",
+ gateway_token="gateway-token",
+ )
+ ).invoke(
+ SourceRecord(
+ source_id="src_fixture123",
+ vendor="gemini",
+ protocol="openai_chat",
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai",
+ credential_ref="cred_fixture123",
+ allowed_origins=(),
+ model_ids=("model-a",),
+ prefix="source-fixture123",
+ ),
+ "model-a",
+ {"stream": True},
+ stream=True,
+ )
+ return await handle.outcome()
+ finally:
+ await runner.cleanup()
+
+ outcome = asyncio.run(run())
+ decision = classify_outcome(outcome)
+
+ assert outcome.http_status == 400
+ assert outcome.upstream_detail == _GEMINI_SIGNATURE_REFUSAL
+ if surfaced:
+ assert (decision.action, decision.error_code) == ("surface", "upstream_request_invalid")
+ else:
+ assert (decision.action, decision.reason) == ("fallback", "unclassified_error")
+
+
@pytest.mark.parametrize(
"payload",
[
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index 5449288ac..2ec46fafb 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -47,6 +47,7 @@ from core.handlers.model_hub.json_wire import (
from core.handlers.model_hub.request import FORWARDED_CALLER_HEADERS
from core.os_errors import local_os_errno
from core.handlers.model_hub.stream_wire import (
+ GOOGLE_ERROR_STATUS_MACHINE_CODES,
ErrorEnvelopePath,
ProtocolObservation,
ProtocolSSEState,
@@ -806,6 +807,9 @@ class EngineClient:
observed_payload,
outcome="failed_terminal",
error_payload=payload,
+ error_envelope_paths=(
+ observed_payload.error_envelope_paths or _HTTP_ERROR_ENVELOPE_PATHS
+ ),
message=f"upstream returned HTTP {response.status}",
recovery_verified=False,
),
@@ -1711,14 +1715,21 @@ def _project_root_map(reader: BinaryIO) -> bool:
return root_is_map
+# Where an HTTP error body that matched none of its protocol's envelopes may
+# still carry one: Google answers its REST and OpenAI-compatible endpoints with
+# the RPC envelope wrapped in a one-element array.
+_HTTP_ERROR_ENVELOPE_PATHS: tuple[ErrorEnvelopePath, ...] = (("error",), ("*", "error"))
+
+
def _project_raw_error_fields(
reader: BinaryIO,
envelope_paths: tuple[ErrorEnvelopePath, ...] = (("error",),),
) -> tuple[str | None, str | None, tuple[str, ...]]:
+ fields = ("type", "code", "status")
selected_paths = {
path
for envelope_path in envelope_paths
- for path in (envelope_path, (*envelope_path, "type"), (*envelope_path, "code"))
+ for path in (envelope_path, *((*envelope_path, field) for field in fields))
}
maps: set[ErrorEnvelopePath] = set()
values: dict[JSONPath, object] = {}
@@ -1733,13 +1744,13 @@ def _project_raw_error_fields(
if path == envelope_path:
if event == "replace":
maps.discard(envelope_path)
- values.pop((*envelope_path, "type"), None)
- values.pop((*envelope_path, "code"), None)
+ for field in fields:
+ values.pop((*envelope_path, field), None)
elif event == "start_map":
maps.add(envelope_path)
elif event == "start_array":
maps.discard(envelope_path)
- elif path in {(*envelope_path, "type"), (*envelope_path, "code")}:
+ elif path in {(*envelope_path, field) for field in fields}:
if event == "replace":
values.pop(path, None)
elif event == "scalar":
@@ -1753,11 +1764,19 @@ def _project_raw_error_fields(
if path in maps
if (code := _safe_error_code(values.get((*path, "type")))) is not None
]
+
+ def envelope_code(path: ErrorEnvelopePath) -> str | None:
+ value = values.get((*path, "code"))
+ if type(value) is int and isinstance(values.get((*path, "status")), str):
+ # A Google RPC envelope names its class by HTTP status, as native Gemini errors do.
+ value = GOOGLE_ERROR_STATUS_MACHINE_CODES.get(value)
+ return _safe_error_code(value)
+
codes = [
code
for path in envelope_paths
if path in maps
- if (code := _safe_error_code(values.get((*path, "code")))) is not None
+ if (code := envelope_code(path)) is not None
]
candidates = tuple(dict.fromkeys((*types, *codes)))
return types[0] if types else None, codes[0] if codes else None, candidates