Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(vertex): keep the ADC project path alive at boot, and stop paying auth + TLS per client

Harald9707f36cd081
diff --git a/docs/BUGS.md b/docs/BUGS.md
index ffa0056dc7..7334a2cd96 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -9650,3 +9650,120 @@ install; uninstall removes the copy the user actually clicks) and
`tests/unit/ui/test_desktop_discoverability.py` (the announcement step on
Linux and macOS, including that an unchanged entry is still announced so a
half-finished earlier run heals). All run on every OS.
+
+## BUG-139: the router runs on the AI Studio account while the user's Vertex project sits idle — a key-slot check dead-lists the keyless credential family (HIGH, FIXED 2026-08-17)
+
+**Symptom.** With `brain.primary = "vertex"` and a configured
+`[google].vertex_project`, small talk answered fine on Vertex Live, but every
+delegated turn (anything the router handles) came back as "the account of my
+language model is blocked — credit exhausted or limit reached". The log showed
+`Brain gemini(...) failed: 429 ... Your prepayment credits are depleted` and
+`All 1 provider attempts failed`: the chain held ONE entry, and it was the
+AI Studio brain, not Vertex.
+
+**Root.** The pre-boot key check in `BrainManager.from_config` walks
+`PROVIDER_SECRET_CANDIDATES` and pushes every provider without a stored key
+into `_dead_providers`. Commit `59aa705f` (same day) gave Vertex a credential
+family of its own — and on the Google Cloud project path Vertex stores no key
+at all: Application Default Credentials (a `gcloud` login, a service account,
+workload identity) sign every request. So each boot logged
+`no key in ['vertex'] -> provider 'vertex' disabled`, `_build_fallback_chain`
+filtered the active provider out, and the cross-provider fallback (`gemini`,
+AI Studio, prepaid, empty) answered instead. `config.py` already had
+`vertex_credential_configured()` — with a docstring warning that any probe
+asking "is this provider set up" must use it "or the whole family is
+dead-listed" — and `app_control.KEYLESS_CREDENTIAL_PROBES` already declared
+the same for every card. The key check knew neither.
+
+**Fix.** `_keyless_provider_is_rescued_by_oauth` (`jarvis/brain/manager.py`)
+now consults the declarative `KEYLESS_CREDENTIAL_PROBES` table after the codex
+branch, so the pre-boot check gives the SAME answer every provider card and
+every switch already gives. Log lines translated to English while touched.
+
+**Class.** Two truths for one question. "Is this provider configured?" had a
+declarative, capability-aware answer used by the UI, and a second, key-only
+answer used by the boot path — and they disagreed exactly on the setup Google
+documents for production. Any predicate that exists in two places will drift
+on the case only one of them was taught. Same shape as BUG-138's "success
+reported against a read that goes through the same lie as the write": here the
+UI showed Vertex as configured while the brain had already buried it.
+
+**Verification.** Live: the boot log line for `vertex` reads "kept active";
+the fallback chain leads with `vertex` again; delegated turns answer on
+`gemini-3-flash-preview` via Vertex (0.7-1.4 s measured) instead of the 429.
+
+**Tests.** `tests/unit/brain/test_codex_oauth_rescue.py` — a project without a
+key is rescued for `vertex` and `vertex-live`; no project and no key stays
+dead.
+
+## BUG-140: every Vertex Live handshake and every first brain call pays 5-8 s of local auth work — each client resolves credentials and builds its TLS trust store on its own (HIGH, FIXED 2026-08-17)
+
+**Symptom.** "Session ready" 5.7-12.2 s after the wake word on Vertex Live
+(one call ran past the 6 s provider budget and fell back to the classic
+pipeline); the first turn of every brain instance 5-18 s; the log line
+`vertex-live: Application Default Credentials warmed` at boot with no visible
+effect. The user could not tell whether the internet or Vertex was slow.
+
+**Root.** Measured on the maintainer box (Windows, gcloud login as ADC):
+
+- DNS/TCP/TLS to every Google host under 200 ms; Vertex Live's first audio
+ 270-750 ms; text models 0.7-2.8 s. Neither the line nor Vertex was slow.
+- `google.auth.default()` cost 5.3-8.5 s: google-auth reads the ADC file,
+ finds no project id in it, and spawns `gcloud config config-helper` for one
+ — a full CLI start — regardless of the project the caller already passes.
+ Every `genai.Client` that is handed no `credentials` runs that call on its
+ first request, and Jarvis built a fresh client per Live session and per
+ brain instance.
+- The boot warm-up built such a client and made no call — nothing was
+ resolved, no token minted; the log claimed otherwise.
+- `genai.Client()` itself cost 1.34 s: three `ssl.create_default_context()`
+ calls (httpx, aiohttp, websocket), each parsing the certifi bundle, on the
+ event loop for the Live path.
+
+**Fix.** `jarvis/core/google_genai.py`:
+
+- `vertex_credentials()` loads Application Default Credentials ONCE per
+ process (thread-safe, keyed by the credential file in effect, failures not
+ cached); every Vertex client build on the project path is handed the shared
+ object. A cold cache is filled only off the event loop — the sync builder
+ probes for a running loop, the async twin loads in a worker thread.
+- `warm_vertex_credentials()` loads AND mints the token; `VertexLiveProvider.
+ warm_transport` calls it and logs whether it succeeded.
+- One shared TLS context, built with the SDK's exact parameters
+ (`SSL_CERT_FILE`/certifi, `SSL_CERT_DIR`), handed to every google-genai
+ client via `http_options` — the SDK's own escape hatch — for the AI Studio
+ route as well; caller-supplied transport args always win. Both Live routes
+ warm it at boot (`GeminiLiveProvider.warm_transport` builds the context,
+ `VertexLiveProvider.warm_transport` builds it and resolves the credentials),
+ and the async builders fill a cold context in a worker thread, so no first
+ client of the process parses the CA bundle on the event loop.
+
+Measured through the real code path afterwards: session open 1.07-1.5 s
+(client build 2-4 ms, handshake ~1.1 s); first brain call 0.9 s.
+
+**Class.** Per-instance resolution of a process-wide fact. Credentials and a
+trust store describe the process, not the client; resolving them per client
+multiplies a fixed cost by the number of sessions and hides it inside the
+first request of each. The tell was a warm-up that reported success without
+producing the artifact later callers would read — a warm-up must warm the
+object that is actually shared, or it warms nothing.
+
+**Tests.** `tests/unit/core/test_google_vertex_project_path.py` (loaded once
+and shared; failures not cached; project clients receive the credentials, an
+express key never touches ADC; the sync build never fills a cold cache on the
+loop; the async build resolves off the loop; warm mints once; a service
+account exported later gets its own load; every builder hands over the shared
+TLS context; caller options merged not replaced; unbuildable context leaves
+options untouched) and `tests/unit/brain/test_vertex_family_parity.py`
+(`warm_transport` goes through the shared loader, off the loop).
+
+## BUG-141: "handshake-budget probe failed ... not 'property'" ten times per voice call — a class-level read of an instance declaration (LOW, FIXED 2026-08-17)
+
+**Root.** `realtime_handshake_budget_s` reads `handshake_budget_s` off the
+instance when the factory instantiated the provider, and off the CLASS
+otherwise. The local card declares it as a `property`; installed but not
+selected, it was never instantiated, so the class read yielded the descriptor
+and `float()` raised — logged as a WARNING on every probe. A provider that was
+not instantiated has no handshake this session could wait for, so its
+declaration cannot stretch the budget; the probe now skips a descriptor
+quietly. **Tests.** `tests/unit/realtime/test_factory_handshake_budget.py`.
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 3c35e18d5f..38b397cf53 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -2753,18 +2753,20 @@ class BrainManager:
except Exception: # noqa: BLE001
key_value = None
if not key_value:
- # An OAuth-login brain (codex via ChatGPT) has no API key but a
- # usable on-disk login — don't dead-list it (open-source AP-22).
+ # A keyless-but-credentialed provider — an OAuth login on disk
+ # (codex via ChatGPT) or a Google Cloud project signing with
+ # Application Default Credentials (vertex) — is NOT dead-listed
+ # (open-source AP-22).
if _keyless_provider_is_rescued_by_oauth(provider_name):
log.info(
- "Pre-Boot-Key-Check: '%s' ohne API-Key, aber verbundene "
- "OAuth-Anmeldung -> NICHT deaktiviert.",
+ "Pre-boot key check: '%s' has no API key but a login / "
+ "Cloud project credential -> kept active.",
provider_name,
)
continue
manager._dead_providers.add(provider_name)
log.info(
- "Pre-Boot-Key-Check: kein Key in %s -> Provider '%s' deaktiviert.",
+ "Pre-boot key check: no key in %s -> provider '%s' disabled.",
provider_to_slots.get(provider_name, [provider_name]),
provider_name,
)
@@ -12285,6 +12287,17 @@ def _keyless_provider_is_rescued_by_oauth(provider_name: str) -> bool:
chat AND voice turn bricks with the provider-down apology. The OAuth login IS a
usable credential. Open-source single-provider mandate (AP-22). Any import/probe
failure is treated as "not rescued" (fail-safe → dead-list).
+
+ Vertex AI is the second shape: its Google Cloud project path signs with
+ Application Default Credentials (a ``gcloud`` login, a service account,
+ workload identity), so a fully configured install stores no key in any of
+ the family's slots. The declarative ``KEYLESS_CREDENTIAL_PROBES`` table in
+ ``app_control`` is the ONE place that names the probe, and it is the same
+ answer every provider card and every switch already gives — so this check
+ can never dead-list a family the UI shows as configured. Live 2026-08-17:
+ the check knew only key slots, pushed ``vertex`` into ``_dead_providers``
+ at every boot, and the router silently ran on the AI Studio account (whose
+ prepaid credit was empty) while the user's Vertex project sat idle.
"""
if provider_name == "codex":
try:
@@ -12292,7 +12305,13 @@ def _keyless_provider_is_rescued_by_oauth(provider_name: str) -> bool:
return bool(_codex_oauth_connected())
except Exception: # noqa: BLE001
return False
- return False
+ try:
+ from jarvis.brain.app_control import _keyless_credential_present
+
+ return bool(_keyless_credential_present(provider_name))
+ except Exception as exc: # noqa: BLE001 — a failed probe is not a credential
+ log.debug("Keyless-credential rescue probe failed for %s: %s", provider_name, exc)
+ return False
_PROVIDER_SETUP_HINTS: dict[str, str] = {
diff --git a/jarvis/core/google_genai.py b/jarvis/core/google_genai.py
index 9a723631b2..c96719db7a 100644
--- a/jarvis/core/google_genai.py
+++ b/jarvis/core/google_genai.py
@@ -52,10 +52,12 @@ path is the only route in, and the express key is the exception.
from __future__ import annotations
+import asyncio
import hashlib
import logging
import os
import threading
+import time
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Literal
@@ -242,6 +244,275 @@ def _export_service_account(path: str | None) -> None:
log.info("Vertex AI: authenticating via the service account at %s.", resolved)
+# ── Application Default Credentials, loaded ONCE per process ─────────────────
+#
+# On the Cloud project path every ``genai.Client`` that is handed no
+# ``credentials`` resolves them itself on its first call, via
+# ``google.auth.default()``. Measured 2026-08-17 on the maintainer box (Windows,
+# gcloud login as ADC): that call costs 5.3-8.5 s — google-auth reads the ADC
+# file, finds no project id in it, and spawns ``gcloud config config-helper``
+# to ask for one (a full CLI start), regardless of the project we already pass.
+# Jarvis builds a fresh client per Live session and per brain instance, so the
+# price was paid on every voice handshake (5.7-12.2 s to "session ready", one
+# 6 s budget timeout) and on the first turn of every brain. With ONE shared
+# credentials object the very same handshake measured 1.1-1.3 s. The object
+# is safe to share: it is what Google's own client libraries pass around, and
+# the SDK refreshes the token on it only when expired.
+
+#: OAuth scope Vertex AI requests are signed under (what the SDK asks for).
+_CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
+
+_ADC_LOCK = threading.Lock()
+_ADC_CACHE: dict[str, Any] = {}
+
+
+def _adc_cache_key() -> str:
+ """Which credential file google-auth would read right now.
+
+ A service account exported by :func:`_export_service_account` after a
+ gcloud login was cached must not be answered from that cache.
+ """
+ return os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "") or ""
+
+
+def _load_application_default_credentials() -> Any:
+ """The one call into google-auth (test seam). Blocking; raises on failure."""
+ import google.auth # lazy (AP-26)
+
+ credentials, _project = google.auth.default(scopes=[_CLOUD_PLATFORM_SCOPE])
+ return credentials
+
+
+def cached_vertex_credentials() -> Any | None:
+ """The shared credentials if a load already happened; never blocks.
+
+ Deliberately lock-free (a dict read is atomic under the GIL): the event
+ loop asks this while a warm-up thread may be holding ``_ADC_LOCK`` for the
+ whole 5-8 s load, and it must get "not yet" instantly rather than wait.
+ """
+ return _ADC_CACHE.get(_adc_cache_key())
+
+
+def vertex_credentials() -> Any | None:
+ """Application Default Credentials for the Vertex project path, loaded once.
+
+ BLOCKING on the first call (see the measurement above) — call it from a
+ worker thread, never on the event loop. Later calls answer from the cache.
+ ``None`` means google-auth could not resolve a credential; nothing is
+ cached for that case, so a login that appears later is picked up, and the
+ caller leaves the SDK's own lazy resolution in place, which surfaces
+ Google's honest error on the first real call.
+ """
+ key = _adc_cache_key()
+ cached = _ADC_CACHE.get(key)
+ if cached is not None:
+ return cached
+ with _ADC_LOCK:
+ cached = _ADC_CACHE.get(key) # a concurrent loader may have won
+ if cached is not None:
+ return cached
+ started = time.perf_counter()
+ try:
+ credentials = _load_application_default_credentials()
+ except Exception as exc: # noqa: BLE001 — auth trouble surfaces on the first call
+ log.info(
+ "Vertex AI: Application Default Credentials not resolvable (%s: %s) — "
+ "the SDK resolves auth on the first call instead.",
+ type(exc).__name__,
+ exc,
+ )
+ return None
+ if credentials is None:
+ return None
+ _ADC_CACHE[key] = credentials
+ log.info(
+ "Vertex AI: Application Default Credentials loaded once for this "
+ "process in %.0f ms; every client shares them from here on.",
+ (time.perf_counter() - started) * 1000.0,
+ )
+ return credentials
+
+
+def _adc_for_sync_build() -> Any | None:
+ """Credentials for a synchronous client build without ever blocking a loop.
+
+ A cold cache is filled only where blocking is legal — a thread with no
+ running event loop (the brain builds its client under ``to_thread``). On
+ the loop the build proceeds without credentials and the SDK's threaded lazy
+ load applies, exactly as before.
+ """
+ cached = cached_vertex_credentials()
+ if cached is not None:
+ return cached
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError: # no loop in this thread — blocking here is legal
+ return vertex_credentials()
+ return None
+
+
+def warm_vertex_credentials() -> bool:
+ """Load the shared credentials AND mint the first token. Blocking.
+
+ Meant for a boot warm-up off the critical path (a worker thread). After a
+ successful warm the first Live handshake and the first brain call pay for
+ neither the credential resolution nor the OAuth exchange. Returns whether
+ a token is ready; a ``False`` costs nothing but the latency it was meant
+ to save (the first call resolves auth itself, as it always did).
+ """
+ warm_shared_transport() # the trust store is per process too — see below
+ settings = _project_for("vertex")
+ if settings is None or not settings.configured:
+ return False
+ credentials = vertex_credentials()
+ if credentials is None:
+ return False
+ if bool(getattr(credentials, "valid", False)):
+ return True
+ try:
+ from google.auth.transport.requests import Request # lazy (AP-26)
+
+ credentials.refresh(Request())
+ except Exception as exc: # noqa: BLE001 — the first call retries the exchange
+ log.info(
+ "Vertex AI: token pre-mint failed (%s: %s) — the first call refreshes.",
+ type(exc).__name__,
+ exc,
+ )
+ return False
+ return bool(getattr(credentials, "valid", False))
+
+
+def reset_vertex_credentials_cache() -> None:
+ """Forget the shared credentials (tests; login changes)."""
+ with _ADC_LOCK:
+ _ADC_CACHE.clear()
+
+
+# ── one TLS trust store per process ──────────────────────────────────────────
+#
+# ``genai.Client.__init__`` builds THREE ``ssl.SSLContext`` objects (httpx,
+# aiohttp, websocket) unless the caller hands it one, and each parses the whole
+# certifi bundle. Measured 2026-08-17 on the maintainer box: 445 ms apiece,
+# 1.34 s per client — on the event loop for the Live path, on top of every
+# session open and every brain instance. The SDK takes a caller-supplied
+# context from ``client_args["verify"]`` / ``async_client_args["verify"|"ssl"]``
+# and then skips its own. The context below is built with the SDK's exact
+# parameters (``SSL_CERT_FILE``/certifi, ``SSL_CERT_DIR``), so trust behaviour
+# is identical — it is simply built once and shared, which is what an
+# ``SSLContext`` is for.
+
+_TLS_LOCK = threading.Lock()
+_TLS_CONTEXT: Any = None
+
+
+def _shared_tls_context() -> Any:
+ """The process-wide TLS context, built on first use. Raises if it cannot be.
+
+ The fast path reads without the lock (an attribute read is atomic), so a
+ caller on the event loop never waits behind a thread that is mid-build.
+ """
+ global _TLS_CONTEXT
+ if _TLS_CONTEXT is not None:
+ return _TLS_CONTEXT
+ with _TLS_LOCK:
+ if _TLS_CONTEXT is None:
+ import ssl # lazy (AP-26)
+
+ import certifi # lazy — ships with google-genai/httpx
+
+ started = time.perf_counter()
+ _TLS_CONTEXT = ssl.create_default_context(
+ cafile=os.environ.get("SSL_CERT_FILE", certifi.where()),
+ capath=os.environ.get("SSL_CERT_DIR"),
+ )
+ log.debug(
+ "Google GenAI: shared TLS context built in %.0f ms.",
+ (time.perf_counter() - started) * 1000.0,
+ )
+ return _TLS_CONTEXT
+
+
+def _with_shared_tls(http_options: Any) -> Any:
+ """Hand the client the shared TLS context unless the caller set its own.
+
+ Accepts every shape ``genai.Client`` accepts — ``None``, a plain dict, or a
+ typed ``HttpOptions`` — and returns the same shape with the transport args
+ filled in. Anything the caller already put there wins. If the context
+ cannot be built the options pass through untouched and the SDK builds its
+ own, exactly as before.
+ """
+ try:
+ ctx = _shared_tls_context()
+ except Exception as exc: # noqa: BLE001 — the SDK's own default remains
+ log.debug("Shared TLS context unavailable (%s: %s).", type(exc).__name__, exc)
+ return http_options
+
+ def _filled(client_args: Any, async_args: Any) -> tuple[dict[str, Any], dict[str, Any]]:
+ sync_filled = dict(client_args or {})
+ async_filled = dict(async_args or {})
+ sync_filled.setdefault("verify", ctx)
+ async_filled.setdefault("verify", ctx)
+ async_filled.setdefault("ssl", ctx)
+ return sync_filled, async_filled
+
+ if http_options is None:
+ sync_filled, async_filled = _filled(None, None)
+ return {"client_args": sync_filled, "async_client_args": async_filled}
+ if isinstance(http_options, dict):
+ merged = dict(http_options)
+ merged["client_args"], merged["async_client_args"] = _filled(
+ merged.get("client_args"), merged.get("async_client_args")
+ )
+ return merged
+ # A typed HttpOptions (pydantic model): a copy with the args filled in.
+ try:
+ sync_filled, async_filled = _filled(
+ getattr(http_options, "client_args", None),
+ getattr(http_options, "async_client_args", None),
+ )
+ return http_options.model_copy(
+ update={"client_args": sync_filled, "async_client_args": async_filled}
+ )
+ except Exception as exc: # noqa: BLE001 — an unknown shape passes through
+ log.debug("http_options of type %s left untouched: %s", type(http_options).__name__, exc)
+ return http_options
+
+
+def reset_shared_tls_context() -> None:
+ """Forget the shared TLS context (tests)."""
+ global _TLS_CONTEXT
+ with _TLS_LOCK:
+ _TLS_CONTEXT = None
+
+
+def warm_shared_transport() -> bool:
+ """Build the shared TLS context ahead of the first client. Blocking.
+
+ Provider-agnostic: the AI Studio route pays the same three-context build
+ per client as Vertex does, so a boot warm-up on either route calls this
+ from a worker thread. Returns whether the context is ready.
+ """
+ try:
+ _shared_tls_context()
+ except Exception as exc: # noqa: BLE001 — the SDK's own default remains
+ log.debug("Shared TLS context warm failed (%s: %s).", type(exc).__name__, exc)
+ return False
+ return True
+
+
+async def _ensure_shared_tls_off_loop() -> None:
+ """Fill a cold TLS context in a worker thread (async builders only).
+
+ The context build parses the whole certifi bundle (~0.4 s measured); the
+ async twins run on the event loop, so a cold first build must not happen
+ inline. Failures are left to :func:`_with_shared_tls`, which passes the
+ caller's options through untouched.
+ """
+ if _TLS_CONTEXT is None:
+ await asyncio.to_thread(warm_shared_transport)
+
+
def _configured_mode() -> str:
"""``[google].vertex_mode`` with a hard fallback to ``auto``.
@@ -504,6 +775,12 @@ def build_vertex_client(
(:meth:`VertexProject.for_realtime`). The two differ: ``global`` serves the
current Gemini generation for normal requests and no Live session at all, so
a single location cannot drive both tiers.
+
+ On the project path the client is handed the process-wide Application
+ Default Credentials (:func:`vertex_credentials`) whenever they are loaded,
+ so it never resolves — and never re-pays for — auth on its own. A cold cache
+ is filled here only off the event loop; on the loop the SDK's own threaded
+ lazy load stays in charge (see :func:`_adc_for_sync_build`).
"""
from google import genai
@@ -515,7 +792,12 @@ def build_vertex_client(
)
if realtime and settings is not None and settings.configured:
settings = settings.for_realtime()
- return genai.Client(**_client_kwargs(api_key, "vertex", http_options, settings))
+ kwargs = _client_kwargs(api_key, "vertex", _with_shared_tls(http_options), settings)
+ if "project" in kwargs:
+ credentials = _adc_for_sync_build()
+ if credentials is not None:
+ kwargs["credentials"] = credentials
+ return genai.Client(**kwargs)
async def build_vertex_client_async(
@@ -523,10 +805,20 @@ async def build_vertex_client_async(
) -> Any:
"""Async twin of :func:`build_vertex_client`.
- Pinning means there is no probe to keep off the event loop, so this is a
- thin wrapper — it exists so realtime callers reach the Vertex path through
- the same await-shaped door as :func:`build_genai_client_async`.
+ Pinning means there is no probe to keep off the event loop. What this twin
+ does keep off it is the ONE-TIME credential resolution on the project path:
+ a cold cache is filled in a worker thread first, so the client built below
+ already carries the shared credentials and the handshake that follows pays
+ for the socket alone.
"""
+ await _ensure_shared_tls_off_loop()
+ if not api_key and cached_vertex_credentials() is None:
+ # _project_for, not vertex_project_settings: it exports a configured
+ # service account FIRST, so the load below reads that file and the
+ # cache key the sync build looks up afterwards is the same one.
+ settings = _project_for("vertex")
+ if settings is not None and settings.configured:
+ await asyncio.to_thread(vertex_credentials)
return build_vertex_client(api_key, http_options=http_options, realtime=realtime)
@@ -544,11 +836,20 @@ def build_genai_client(
:func:`resolve_google_key_route`. The SDK import stays inside the
function so headless installs without google-genai import this module
cleanly (AP-26).
+
+ The client is handed the shared TLS context (see :func:`_with_shared_tls`)
+ but NOT the shared Application Default Credentials: a key stored in a
+ Gemini slot always authenticates by that key, even on the express route.
+ Only the dedicated Vertex family (:func:`build_vertex_client`) walks the
+ Cloud project path where ADC signs — the speed-up for that resolution
+ lives there on purpose.
"""
from google import genai
resolved = route or resolve_google_key_route(api_key)
- return genai.Client(**_client_kwargs(api_key, resolved, http_options, _project_for(resolved)))
+ return genai.Client(
+ **_client_kwargs(api_key, resolved, _with_shared_tls(http_options), _project_for(resolved))
+ )
async def build_genai_client_async(
@@ -566,7 +867,10 @@ async def build_genai_client_async(
from google import genai
resolved = route or await resolve_google_key_route_async(api_key)
- return genai.Client(**_client_kwargs(api_key, resolved, http_options, _project_for(resolved)))
+ await _ensure_shared_tls_off_loop()
+ return genai.Client(
+ **_client_kwargs(api_key, resolved, _with_shared_tls(http_options), _project_for(resolved))
+ )
def reset_route_cache() -> None:
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.py
index b79b4fa1c5..ba463194e4 100644
--- a/jarvis/plugins/realtime/gemini_live.py
+++ b/jarvis/plugins/realtime/gemini_live.py
@@ -779,6 +779,26 @@ class GeminiLiveProvider:
def _unconfigured_message(self) -> str:
return "Gemini Live API key is not configured"
+ @staticmethod
+ async def warm_transport(cfg: Any = None) -> None:
+ """Build the shared TLS trust store at boot, off the first handshake.
+
+ Every ``genai.Client`` used to build three SSL contexts of its own —
+ each parsing the certifi bundle, ~1.3 s per client on the maintainer
+ box, on the event loop for a Live open. The process now shares ONE
+ context (``jarvis.core.google_genai``); warming it here means the first
+ session of the call pays for the socket alone. Best-effort by contract
+ — a warm that did not happen only costs the latency it was meant to
+ save. Overridden by :class:`VertexLiveProvider`, which additionally
+ resolves its Cloud credentials.
+ """
+ del cfg # nothing session-specific about a trust store
+ import asyncio # lazy (AP-26)
+ import importlib
+
+ google_genai = importlib.import_module("jarvis.core.google_genai")
+ await asyncio.to_thread(google_genai.warm_shared_transport)
+
async def open_session(self, cfg: Any) -> _GeminiLiveSession:
if not await self.can_open_duplex_session():
raise RuntimeError(self._unconfigured_message())
@@ -937,14 +957,18 @@ class VertexLiveProvider(GeminiLiveProvider):
#: regions (europe-west4 and us-central1, live publisher catalogue
#: 2026-08-17). A per-card model pin still overrides it.
default_model = "gemini-live-2.5-flash-native-audio"
- #: Measured 2026-08-17 on an idle machine: 3.7-5.5 s per open, of which
- #: 1.6-2.8 s is minting an OAuth token from Application Default Credentials
- #: before the socket is even attempted — a cost the API-key providers never
- #: pay. The shared 12 s ceiling divided by the candidate count handed this
- #: adapter 6.0 s, i.e. the measured worst case plus half a second, so a
- #: busy machine timed out the handshake and dropped the call to the
- #: pipeline. Declaring the real need (a capability, never a provider-name
- #: check — AP-21) is what the session's deadline stretch exists for.
+ #: Measured 2026-08-17 on an idle machine: 3.7-6.5 s per open when the
+ #: client resolves Application Default Credentials itself (a ``gcloud``
+ #: subprocess plus the OAuth exchange, 5.3-8.5 s on a busy box) before the
+ #: socket is even attempted — a cost the API-key providers never pay. The
+ #: shared 12 s ceiling divided by the candidate count handed this adapter
+ #: 6.0 s, i.e. the measured worst case plus half a second, so a busy
+ #: machine timed out the handshake and dropped the call to the pipeline.
+ #: With the process-wide credentials from ``warm_transport`` an open costs
+ #: 1.1-1.3 s; the budget stays generous for the cold path (no warm yet, a
+ #: login that changed) — declaring the real need is a capability, never a
+ #: provider-name check (AP-21), and it is what the session's deadline
+ #: stretch exists for.
handshake_budget_s = 20.0
credential_family = "vertex"
credential_candidates = (
@@ -962,12 +986,17 @@ class VertexLiveProvider(GeminiLiveProvider):
@staticmethod
async def warm_transport(cfg: Any = None) -> None:
- """Mint the ADC token at boot so the first call does not pay for it.
-
- Measured: building the client costs 1.6-2.8 s, nearly all of it the
- OAuth token exchange, and it happens INSIDE the first handshake. Doing
- it once at boot takes that off the first spoken turn; google-auth caches
- the token, so later opens only pay for the socket.
+ """Resolve the ADC and mint the first token at boot, off the first turn.
+
+ Measured 2026-08-17: resolving Application Default Credentials costs
+ 5.3-8.5 s on a gcloud-login host (google-auth spawns ``gcloud config
+ config-helper`` for a project id) and the OAuth exchange another
+ 0.7-1.9 s — and both used to happen INSIDE every handshake, because
+ each session built a client that resolved auth on its own (5.7-12.2 s
+ to "session ready"). ``warm_vertex_credentials`` loads ONE process-wide
+ credentials object and mints its token; every later client build is
+ handed that object, so a session open pays for the socket alone
+ (measured 1.1-1.3 s).
Best-effort by contract — the factory swallows failures, and a warm that
did not happen only costs the latency it was meant to save.
@@ -979,11 +1008,19 @@ class VertexLiveProvider(GeminiLiveProvider):
google_genai = importlib.import_module("jarvis.core.google_genai")
if not VertexLiveProvider.external_login_ready(None):
return
- # Off the event loop: the token exchange is a blocking HTTPS call.
- await asyncio.to_thread(
- google_genai.build_vertex_client, "", realtime=True
- )
- log.info("vertex-live: Application Default Credentials warmed.")
+ # Off the event loop: the credential resolution and the token exchange
+ # are blocking calls (a subprocess and an HTTPS round-trip).
+ ready = await asyncio.to_thread(google_genai.warm_vertex_credentials)
+ if ready:
+ log.info(
+ "vertex-live: Application Default Credentials warmed — token "
+ "minted, later session opens pay for the socket alone."
+ )
+ else:
+ log.info(
+ "vertex-live: Application Default Credentials not warmed — the "
+ "first handshake resolves auth itself."
+ )
@staticmethod
def external_login_ready(cfg: Any = None) -> bool:
diff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.py
index 9e8a0f3bb7..59db6f4219 100644
--- a/jarvis/realtime/factory.py
+++ b/jarvis/realtime/factory.py
@@ -228,7 +228,16 @@ def realtime_handshake_budget_s(cfg: Any) -> float:
source = load(_GROUP, provider_id, protocol=RealtimeProvider)
if not bool(getattr(source, "supports_realtime", False)):
continue
- declared.append(float(getattr(source, "handshake_budget_s", 0.0) or 0.0))
+ budget = getattr(source, "handshake_budget_s", 0.0)
+ if isinstance(budget, property):
+ # A class-level read of a per-instance declaration. The plugin
+ # was NOT instantiated above, i.e. it holds no credential and no
+ # explicit selection this session could open with — so it has
+ # no handshake to stretch the budget for. Skipping is the
+ # correct answer, not a failure (live 2026-08-17: the installed
+ # but unselected local card logged this ~10x per voice call).
+ continue
+ declared.append(float(budget or 0.0))
except Exception as exc: # noqa: BLE001 - one broken plugin is skipped
log.warning("Realtime handshake-budget probe failed for %s: %s", provider_id, exc)
return max(declared)
diff --git a/tests/unit/brain/test_codex_oauth_rescue.py b/tests/unit/brain/test_codex_oauth_rescue.py
index 281d4375f3..73b57af6ba 100644
--- a/tests/unit/brain/test_codex_oauth_rescue.py
+++ b/tests/unit/brain/test_codex_oauth_rescue.py
@@ -27,3 +27,26 @@ def test_api_key_provider_is_never_rescued():
# Only OAuth-login brains get the rescue; an ordinary API provider stays dead.
assert _keyless_provider_is_rescued_by_oauth("openai") is False
assert _keyless_provider_is_rescued_by_oauth("openrouter") is False
+
+
+def test_vertex_project_path_is_rescued_without_a_key(monkeypatch):
+ """Vertex AI on the Google Cloud project path stores NO key at all.
+
+ Live 2026-08-17: ``[google].vertex_project`` was set, Application Default
+ Credentials answered every call, and the check still pushed ``vertex`` into
+ ``_dead_providers`` at every boot ("kein Key in ['vertex']") — so the
+ router ran on the AI Studio account instead. The rescue must give the same
+ answer the provider cards give (``KEYLESS_CREDENTIAL_PROBES``).
+ """
+ from jarvis.core import config as cfg_mod
+
+ monkeypatch.setattr(cfg_mod, "vertex_credential_configured", lambda: True)
+ assert _keyless_provider_is_rescued_by_oauth("vertex") is True
+ assert _keyless_provider_is_rescued_by_oauth("vertex-live") is True
+
+
+def test_vertex_without_project_or_key_stays_dead(monkeypatch):
+ from jarvis.core import config as cfg_mod
+
+ monkeypatch.setattr(cfg_mod, "vertex_credential_configured", lambda: False)
+ assert _keyless_provider_is_rescued_by_oauth("vertex") is False
diff --git a/tests/unit/brain/test_vertex_family_parity.py b/tests/unit/brain/test_vertex_family_parity.py
index 93e25971d9..17c5bb66e7 100644
--- a/tests/unit/brain/test_vertex_family_parity.py
+++ b/tests/unit/brain/test_vertex_family_parity.py
@@ -250,6 +250,66 @@ def test_realtime_is_eligible_on_a_keyless_cloud_project(
assert VertexLiveProvider.external_login_ready(None) is False
+async def test_the_realtime_warm_up_really_warms_the_shared_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``warm_transport`` must resolve ADC and mint the token — off the loop.
+
+ Live 2026-08-17: the warm-up built a client nobody reused and minted no
+ token, so "Application Default Credentials warmed" was logged while every
+ handshake still paid 5-8 s for ``google.auth.default()`` plus the OAuth
+ exchange (5.7-12.2 s to "session ready"). The warm has to go through the
+ process-wide loader that every later client build reads from.
+ """
+ import threading
+
+ from jarvis.core import config as cfg
+ from jarvis.core import google_genai as gg
+ from jarvis.plugins.realtime.gemini_live import VertexLiveProvider
+
+ loop_thread = threading.get_ident()
+ calls: list[int] = []
+
+ def _warm() -> bool:
+ calls.append(threading.get_ident())
+ return True
+
+ monkeypatch.setattr(cfg, "vertex_credential_configured", lambda *_a, **_k: True)
+ monkeypatch.setattr(gg, "warm_vertex_credentials", _warm)
+
+ await VertexLiveProvider.warm_transport(None)
+
+ assert len(calls) == 1
+ assert calls[0] != loop_thread, "the blocking warm ran on the event loop"
+
+
+async def test_the_ai_studio_live_route_warms_the_shared_trust_store(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The plain gemini-live route pays the same per-client TLS build — so it
+ warms the same shared context at boot, off the loop."""
+ import threading
+
+ from jarvis.core import google_genai as gg
+ from jarvis.plugins.realtime.gemini_live import GeminiLiveProvider
+
+ loop_thread = threading.get_ident()
+ calls: list[int] = []
+
+ def _warm() -> bool:
+ calls.append(threading.get_ident())
+ return True
+
+ monkeypatch.setattr(gg, "warm_shared_transport", _warm)
+
+ await GeminiLiveProvider.warm_transport(None)
+
+ assert len(calls) == 1
+ assert calls[0] != loop_thread
+
+
# ── subagents ────────────────────────────────────────────────────────────────
diff --git a/tests/unit/core/test_google_vertex_project_path.py b/tests/unit/core/test_google_vertex_project_path.py
index a5585a1715..7543351b35 100644
--- a/tests/unit/core/test_google_vertex_project_path.py
+++ b/tests/unit/core/test_google_vertex_project_path.py
@@ -30,16 +30,32 @@ from jarvis.core import google_genai as gg
@pytest.fixture(autouse=True)
-def _fresh_cache():
+def _fresh_cache(monkeypatch: pytest.MonkeyPatch):
gg.reset_route_cache()
+ gg.reset_vertex_credentials_cache()
+ gg.reset_shared_tls_context()
+ # No test here may reach google-auth: on a gcloud-login host that call
+ # spawns the gcloud CLI (5-8 s) and on a bare host it raises. The seam
+ # answers "no ambient credential" unless a test installs its own fake.
+ monkeypatch.setattr(gg, "_load_application_default_credentials", lambda: None)
yield
gg.reset_route_cache()
+ gg.reset_vertex_credentials_cache()
+ gg.reset_shared_tls_context()
@pytest.fixture
def _no_ambient_adc(monkeypatch: pytest.MonkeyPatch):
- """Start from a host with no ``GOOGLE_APPLICATION_CREDENTIALS`` set."""
- monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
+ """Start from a host with no ``GOOGLE_APPLICATION_CREDENTIALS`` set.
+
+ ``setenv`` first, then ``delenv``: the SUT writes this variable itself with
+ a raw ``os.environ`` assignment, and ``delenv(raising=False)`` on an unset
+ name records nothing — so a value written during the test would leak into
+ every later test. Recording the original state first makes the teardown
+ restore it whatever the test body did.
+ """
+ monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "")
+ monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS")
def _project(
@@ -238,6 +254,16 @@ def stub_genai(monkeypatch: pytest.MonkeyPatch) -> _StubGenaiModule:
return stub
+def _sans_transport(call: dict) -> dict:
+ """The auth/endpoint shape of a build, without the shared transport args.
+
+ Every builder hands the client the process-wide TLS context via
+ ``http_options`` (see the TLS tests below); the shape tests here are about
+ which credential travels to which host and read past that.
+ """
+ return {k: v for k, v in call.items() if k != "http_options"}
+
+
def test_build_vertex_client_never_probes(
monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule
) -> None:
@@ -256,7 +282,9 @@ def test_build_vertex_client_never_probes(
gg.build_vertex_client("AIza-cloud-restricted")
- assert stub_genai.calls == [{"api_key": "AIza-cloud-restricted", "vertexai": True}]
+ assert [_sans_transport(c) for c in stub_genai.calls] == [
+ {"api_key": "AIza-cloud-restricted", "vertexai": True}
+ ]
def test_the_realtime_build_resolves_its_own_endpoint(
@@ -279,7 +307,7 @@ def test_build_vertex_client_uses_the_project_when_configured(
) -> None:
monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "us-central1"))
gg.build_vertex_client("")
- assert stub_genai.calls == [
+ assert [_sans_transport(c) for c in stub_genai.calls] == [
{"vertexai": True, "project": "prod-proj", "location": "us-central1"}
]
@@ -303,7 +331,9 @@ async def test_async_twin_builds_the_same_client(
) -> None:
monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project(None))
await gg.build_vertex_client_async("AQ.key")
- assert stub_genai.calls == [{"api_key": "AQ.key", "vertexai": True}]
+ assert [_sans_transport(c) for c in stub_genai.calls] == [
+ {"api_key": "AQ.key", "vertexai": True}
+ ]
def test_aistudio_build_does_not_read_the_project_config(
@@ -316,7 +346,7 @@ def test_aistudio_build_does_not_read_the_project_config(
monkeypatch.setattr(gg, "vertex_project_settings", _must_not_run)
gg.build_genai_client("AIza-studio", route="aistudio")
- assert stub_genai.calls == [{"api_key": "AIza-studio"}]
+ assert [_sans_transport(c) for c in stub_genai.calls] == [{"api_key": "AIza-studio"}]
# ── "is Vertex configured" is one question with one answer ───────────────────
@@ -338,3 +368,250 @@ def test_neither_key_nor_project_is_unconfigured() -> None:
config = SimpleNamespace(google=SimpleNamespace(vertex_project=""))
with cfg.override_provider_secrets({"vertex": None}):
assert cfg.vertex_credential_configured(config) is False
+
+
+# ── Application Default Credentials are resolved ONCE per process ────────────
+#
+# Measured 2026-08-17: a client that resolves ADC itself pays 5.3-8.5 s on a
+# gcloud-login host (google-auth spawns ``gcloud config config-helper`` for a
+# project id) plus the OAuth exchange — inside every Live handshake and on the
+# first call of every brain instance. One shared credentials object took the
+# handshake from 5.7-12.2 s to 1.1-1.3 s.
+
+
+class _FakeCredentials:
+ """The shape the SDK and the warm-up read: ``valid`` plus ``refresh``."""
+
+ def __init__(self, *, valid: bool = False) -> None:
+ self.valid = valid
+ self.refreshes = 0
+
+ def refresh(self, _request) -> None:
+ self.refreshes += 1
+ self.valid = True
+
+
+def adc(monkeypatch: pytest.MonkeyPatch) -> dict:
+ """A fake ADC loader that counts how often google-auth would have run."""
+ state = {"loads": 0, "credentials": _FakeCredentials()}
+
+ def _load():
+ state["loads"] += 1
+ return state["credentials"]
+
+ monkeypatch.setattr(gg, "_load_application_default_credentials", _load)
+ return state
+
+
+def test_credentials_are_loaded_once_and_shared(adc: dict) -> None:
+ first = gg.vertex_credentials()
+ second = gg.vertex_credentials()
+ assert first is second is adc["credentials"]
+ assert adc["loads"] == 1, "google.auth.default() must run once per process"
+
+
+def test_a_failed_resolution_is_not_cached(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A login that appears later must be picked up, not shadowed by a miss."""
+ attempts = {"n": 0}
+
+ def _boom():
+ attempts["n"] += 1
+ raise RuntimeError("no ADC on this host")
+
+ monkeypatch.setattr(gg, "_load_application_default_credentials", _boom)
+ assert gg.vertex_credentials() is None
+ assert gg.cached_vertex_credentials() is None
+ assert gg.vertex_credentials() is None
+ assert attempts["n"] == 2
+
+
+def test_the_project_client_is_handed_the_shared_credentials(
+ monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule, adc: dict
+) -> None:
+ """The whole point: no client resolves auth on its own any more."""
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "global"))
+ gg.build_vertex_client("")
+ gg.build_vertex_client("", realtime=True)
+ assert [c["credentials"] for c in stub_genai.calls] == [adc["credentials"]] * 2
+ assert adc["loads"] == 1
+
+
+def test_an_express_key_client_never_touches_adc(
+ monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule, adc: dict
+) -> None:
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project(None))
+ gg.build_vertex_client("AQ.express")
+ assert "credentials" not in stub_genai.calls[0]
+ assert adc["loads"] == 0
+
+
+async def test_a_cold_cache_is_never_filled_on_the_event_loop_by_the_sync_build(
+ monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule, adc: dict
+) -> None:
+ """On a running loop the sync build must not block; the SDK's lazy path stays."""
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "global"))
+ gg.build_vertex_client("")
+ assert adc["loads"] == 0
+ assert "credentials" not in stub_genai.calls[0]
+
+
+async def test_the_async_build_resolves_a_cold_cache_off_the_loop(
+ monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule, adc: dict
+) -> None:
+ """The Live handshake path: pays the resolution once, in a thread, then shares."""
+ import threading
+
+ loop_thread = threading.get_ident()
+ seen: list[int] = []
+ real_load = gg._load_application_default_credentials
+
+ def _load_recording_thread():
+ seen.append(threading.get_ident())
+ return real_load()
+
+ monkeypatch.setattr(gg, "_load_application_default_credentials", _load_recording_thread)
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "global"))
+
+ await gg.build_vertex_client_async("", realtime=True)
+ await gg.build_vertex_client_async("", realtime=True)
+
+ assert adc["loads"] == 1
+ assert seen and all(t != loop_thread for t in seen), "resolution ran on the loop thread"
+ assert [c["credentials"] for c in stub_genai.calls] == [adc["credentials"]] * 2
+
+
+def test_warm_mints_the_token_once(monkeypatch: pytest.MonkeyPatch, adc: dict) -> None:
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "global"))
+ assert gg.warm_vertex_credentials() is True
+ assert adc["credentials"].refreshes == 1
+ # Already valid: a second warm neither reloads nor re-mints.
+ assert gg.warm_vertex_credentials() is True
+ assert adc["loads"] == 1
+ assert adc["credentials"].refreshes == 1
+
+
+def test_warm_is_a_no_op_without_a_project(monkeypatch: pytest.MonkeyPatch, adc: dict) -> None:
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project(None))
+ assert gg.warm_vertex_credentials() is False
+ assert adc["loads"] == 0
+
+
+def test_a_service_account_exported_later_gets_its_own_load(
+ adc: dict, tmp_path, _no_ambient_adc
+) -> None:
+ """The cache is keyed by the credential file google-auth would read."""
+ gg.vertex_credentials()
+ sa = tmp_path / "sa.json"
+ sa.write_text("{}", encoding="utf-8")
+ gg._export_service_account(str(sa))
+ gg.vertex_credentials()
+ assert adc["loads"] == 2
+
+
+# ── one TLS trust store per process ──────────────────────────────────────────
+#
+# Measured 2026-08-17: ``genai.Client()`` builds three SSL contexts and parses
+# the certifi bundle for each — 1.34 s per client on the maintainer box, paid
+# on the event loop for every Live session and by every brain instance. The
+# SDK skips its own contexts when the caller supplies one.
+
+
+def test_every_builder_hands_the_client_the_shared_tls_context(
+ monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule
+) -> None:
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "global"))
+ gg.build_vertex_client("")
+ gg.build_genai_client("AIza-studio", route="aistudio")
+ ctx = gg._shared_tls_context()
+ for call in stub_genai.calls:
+ opts = call["http_options"]
+ assert opts["client_args"]["verify"] is ctx
+ assert opts["async_client_args"]["verify"] is ctx
+ assert opts["async_client_args"]["ssl"] is ctx
+ assert gg._shared_tls_context() is ctx, "built once, shared by every client"
+
+
+def test_a_callers_transport_options_are_merged_not_replaced() -> None:
+ """A dict with a timeout keeps it; a caller-supplied verify wins."""
+ ctx = gg._shared_tls_context()
+ merged = gg._with_shared_tls({"timeout": 1500, "client_args": {"verify": "mine"}})
+ assert merged["timeout"] == 1500
+ assert merged["client_args"]["verify"] == "mine"
+ assert merged["async_client_args"]["verify"] is ctx
+ assert merged["async_client_args"]["ssl"] is ctx
+
+
+def test_a_typed_http_options_object_is_copied_with_the_context() -> None:
+ class _Typed:
+ client_args = None
+ async_client_args = {"ssl": "theirs"}
+
+ def model_copy(self, *, update):
+ copy = _Typed()
+ for key, value in update.items():
+ setattr(copy, key, value)
+ return copy
+
+ ctx = gg._shared_tls_context()
+ typed = gg._with_shared_tls(_Typed())
+ assert typed.client_args["verify"] is ctx
+ assert typed.async_client_args["ssl"] == "theirs"
+ assert typed.async_client_args["verify"] is ctx
+
+
+def test_an_unbuildable_context_leaves_the_options_untouched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def _boom():
+ raise RuntimeError("no certifi here")
+
+ monkeypatch.setattr(gg, "_shared_tls_context", _boom)
+ assert gg._with_shared_tls(None) is None
+ opts = {"timeout": 5}
+ assert gg._with_shared_tls(opts) is opts
+
+
+def test_the_vertex_warm_up_also_builds_the_trust_store(
+ monkeypatch: pytest.MonkeyPatch, adc: dict
+) -> None:
+ """One warm, both process-wide costs: credentials AND the TLS context."""
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project("prod-proj", "global"))
+ assert gg._TLS_CONTEXT is None
+ assert gg.warm_vertex_credentials() is True
+ assert gg._TLS_CONTEXT is not None
+
+
+def test_the_transport_warm_is_provider_agnostic() -> None:
+ assert gg._TLS_CONTEXT is None
+ assert gg.warm_shared_transport() is True
+ assert gg._TLS_CONTEXT is gg._shared_tls_context()
+
+
+async def test_the_async_builders_build_a_cold_trust_store_off_the_loop(
+ monkeypatch: pytest.MonkeyPatch, stub_genai: _StubGenaiModule
+) -> None:
+ """The first client of the process must not parse the CA bundle on the loop."""
+ import threading
+
+ loop_thread = threading.get_ident()
+ built_on: list[int] = []
+ real_build = gg._shared_tls_context
+
+ def _recording_build():
+ built_on.append(threading.get_ident())
+ return real_build()
+
+ monkeypatch.setattr(gg, "_shared_tls_context", _recording_build)
+ monkeypatch.setattr(gg, "vertex_project_settings", lambda: _project(None))
+
+ await gg.build_genai_client_async("AIza-studio", route="aistudio")
+ await gg.build_vertex_client_async("AQ.express")
+
+ assert built_on, "the context was never built"
+ assert built_on[0] != loop_thread, "the cold build ran on the loop thread"
+ ctx = stub_genai.calls[0]["http_options"]["client_args"]["verify"]
+ assert stub_genai.calls[1]["http_options"]["client_args"]["verify"] is ctx
diff --git a/tests/unit/plugins/brain/test_provider_base_url.py b/tests/unit/plugins/brain/test_provider_base_url.py
index 78b5cfa27b..f38fc9977b 100644
--- a/tests/unit/plugins/brain/test_provider_base_url.py
+++ b/tests/unit/plugins/brain/test_provider_base_url.py
@@ -184,5 +184,10 @@ def test_gemini_no_override_omits_http_options(monkeypatch):
from jarvis.plugins.brain.gemini import GeminiBrain
GeminiBrain()._ensure_client()
- assert "http_options" not in _FakeGenaiClient.last_kwargs
+ # No override → no endpoint rewrite. The builder still hands every client
+ # the process-wide TLS context via http_options (google_genai), so the
+ # assertion is about the base_url, not about the key being absent.
+ http_options = _FakeGenaiClient.last_kwargs.get("http_options") or {}
+ assert not getattr(http_options, "base_url", None)
+ assert "base_url" not in http_options
assert _FakeGenaiClient.last_kwargs["api_key"] == "sk-test"
diff --git a/tests/unit/plugins/stt/test_stt_error_classification.py b/tests/unit/plugins/stt/test_stt_error_classification.py
index dc2281aa5e..615d254702 100644
--- a/tests/unit/plugins/stt/test_stt_error_classification.py
+++ b/tests/unit/plugins/stt/test_stt_error_classification.py
@@ -375,7 +375,9 @@ def test_gemini_client_is_built_with_the_timeout(monkeypatch: pytest.MonkeyPatch
GeminiSTT(api_key="k", timeout_s=4.0)._ensure_client()
assert captured["api_key"] == "k"
- assert captured["http_options"] == {"timeout": 4000}
+ # The timeout travels; the builder merges its shared TLS transport args
+ # next to it (google_genai._with_shared_tls) without touching the value.
+ assert captured["http_options"]["timeout"] == 4000
def test_the_factory_forwards_a_configured_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/realtime/test_factory_handshake_budget.py b/tests/unit/realtime/test_factory_handshake_budget.py
index 47ec4b6204..0c593d379e 100644
--- a/tests/unit/realtime/test_factory_handshake_budget.py
+++ b/tests/unit/realtime/test_factory_handshake_budget.py
@@ -203,3 +203,40 @@ def test_installed_local_plugin_declares_a_real_budget() -> None:
budget = factory.realtime_handshake_budget_s(cfg)
assert budget > _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
+
+
+def test_unselected_property_declaration_is_skipped_quietly(monkeypatch, caplog) -> None:
+ """Installed but not selected, and declared as a property: no instance exists.
+
+ Live 2026-08-17: the local card sat installed next to a selected cloud
+ provider; the probe read the class, got the descriptor, and logged
+ ``float() argument must be ... not 'property'`` as a WARNING about ten
+ times per voice call. A plugin that was not instantiated has no handshake
+ this session could wait for, so its declaration must neither raise nor
+ warn — the budget simply comes from the providers that can open.
+ """
+ _fake_registry(
+ monkeypatch,
+ {
+ "plain-budget-realtime": _PlainBudgetProvider,
+ "property-budget-realtime": _PropertyBudgetProvider,
+ },
+ )
+ # Only the plain provider is selected; the property one is merely installed
+ # and gets no key, so it stays a class in the probe.
+ monkeypatch.setattr(
+ factory,
+ "get_secret_any",
+ lambda candidates: "fake-key" if candidates else None,
+ )
+
+ def _identified(cfg_arg, **_kwargs):
+ return [("plain-budget-realtime", _PlainBudgetProvider(api_key="fake-key"))]
+
+ monkeypatch.setattr(factory, "_identified_provider_candidates", _identified)
+
+ with caplog.at_level("WARNING", logger=factory.log.name):
+ budget = factory.realtime_handshake_budget_s(_cfg("plain-budget-realtime"))
+
+ assert budget == pytest.approx(30.0)
+ assert "handshake-budget probe failed" not in caplog.text
diff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.py
index 2f3205bba8..193c88df1e 100644
--- a/tests/unit/realtime/test_gemini_live.py
+++ b/tests/unit/realtime/test_gemini_live.py
@@ -568,7 +568,7 @@ class _FakeGenaiClient:
def _patch_genai_client(monkeypatch: pytest.MonkeyPatch) -> dict:
holder: dict = {}
- def _make_client(*, api_key=None):
+ def _make_client(*, api_key=None, **_transport): # http_options: shared TLS
client = _FakeGenaiClient(api_key=api_key)
holder["client"] = client
return client
@@ -860,7 +860,7 @@ def _patch_seedable_genai_client(monkeypatch: pytest.MonkeyPatch) -> dict:
self.last_cm = _SeedableConnectCM()
return self.last_cm
- def _make_client(*, api_key=None):
+ def _make_client(*, api_key=None, **_transport): # http_options: shared TLS
client = SimpleNamespace(
api_key=api_key,
aio=SimpleNamespace(live=_SeedableLiveAPI()),
@@ -947,7 +947,7 @@ async def test_history_seeding_failure_keeps_the_session_alive(
async def __aexit__(self, *_args):
return None
- def _make_client(*, api_key=None):
+ def _make_client(*, api_key=None, **_transport): # http_options: shared TLS
return SimpleNamespace(
api_key=api_key,
aio=SimpleNamespace(