Visitar URL original
live.connect() (Vertex AI) resolves ADC and refreshes the OAuth token synchronously on the event loop on every connect · Issue #3056 · googleapis/python-genai · GitHub
Skip to content

live.connect() (Vertex AI) resolves ADC and refreshes the OAuth token synchronously on the event loop on every connect #3056

Description

@sandeep2rawat

Environment

  • google-genai 2.24.0, google-auth 2.58.0, Python 3.12
  • Vertex AI backend (GOOGLE_GENAI_USE_VERTEXAI=true), service-account ADC
  • Live API with many concurrent sessions per process (telephony voice agent)

What happens

On Vertex, AsyncLive.connect() (google/genai/live.py, ~L1055-1069) runs this before it opens the websocket:

if not self._api_client._credentials:
    creds, _ = google.auth.default(scopes=[...])   # sync, on the event loop
else:
    creds = self._api_client._credentials
if not (creds.token and creds.valid):
    auth_req = _auth_requests().Request()
    creds.refresh(auth_req)                         # sync HTTP, on the event loop

Two problems:

  1. Blocking I/O inside an async API. creds.refresh() makes a synchronous requests call to the token endpoint, on the event loop. Every other coroutine in the process stalls until it returns. For us that is live audio for every other call on the pod.
  2. No caching when the client was built without credentials=. The resolved credentials are a local variable and are never stored on _api_client. Every connect() therefore runs google.auth.default() again and refreshes a fresh, token-less credentials object. The sync refresh runs on every connect, not once an hour.

The async REST path already handles both. _api_client._async_access_token() loads auth via asyncio.to_thread(load_auth, ...) under an async lock and caches it in self._credentials. async_get_token_from_credentials() refreshes via asyncio.to_thread(refresh_auth, ...), only when expired.

Repro

import asyncio, time
from google import genai

async def ticker(stop, worst):
    while not stop.is_set():
        t = time.perf_counter(); await asyncio.sleep(0.01)
        worst[0] = max(worst[0], (time.perf_counter() - t - 0.01) * 1000)

async def main():
    client = genai.Client()  # Vertex via env, no credentials= passed
    for i in range(3):
        stop, worst = asyncio.Event(), [0.0]
        tk = asyncio.create_task(ticker(stop, worst))
        await asyncio.sleep(0.05)  # let the ticker start before connect() blocks
        async with client.aio.live.connect(
            model="gemini-live-2.5-flash-native-audio",
            config={"response_modalities": ["AUDIO"]},
        ):
            pass
        stop.set(); await tk
        print(f"connect #{i+1}: max event-loop stall {worst[0]:.0f} ms")
    await client.aio.aclose()

asyncio.run(main())

Output (Vertex, us-central1). I also counted service_account.Credentials.refresh calls:

connect #1: max event-loop stall 517 ms, token refreshes during connect: 1
connect #2: max event-loop stall 410 ms, token refreshes during connect: 1
connect #3: max event-loop stall 415 ms, token refreshes during connect: 1

Expected: auth resolved once per client, refresh only near expiry, and never on the event loop. Stalls should be a few ms.

Suggested fix

In AsyncLive.connect(), reuse the async REST path: await self._api_client._async_access_token(). That loads ADC off-loop, caches it on the client, and refreshes off-loop under the async auth lock. At minimum, store the resolved credentials on _api_client and wrap google.auth.default() and creds.refresh() in asyncio.to_thread.

Workaround

We build one genai.Client(credentials=creds) per process, in a thread. We keep creds FRESH by calling creds.refresh() via asyncio.to_thread whenever creds.token_state is not TokenState.FRESH. valid turns False at the same REFRESH_THRESHOLD, so connect() never takes the sync branch. With the same ticker, max stall per connect drops to 9–28 ms.

Activity

  1. hossiendehghan989 commented on Oct 6, 2026

    @hossiendehghan989

    I independently traced the current main implementation and the existing async-auth tests. The report is consistent with the source: AsyncLive.connect() still calls google.auth.default() and Credentials.refresh() directly, while BaseApiClient._async_access_token() already provides the desired off-event-loop loading, caching, and per-loop refresh lock.

    One focused regression seam that would make this especially actionable is an AsyncLive.connect() integration test with the websocket handshake mocked:

    • construct a Vertex client without explicit credentials=,
    • patch BaseApiClient._async_access_token to return a deterministic token,
    • patch google.auth.default and Credentials.refresh to fail the test if called directly,
    • assert the mocked async token path is awaited once across repeated connects,
    • keep the existing API-key and custom-base-URL branches unchanged.

    That test would verify the behavior at the call site rather than only testing _async_access_token() in isolation (the latter is already covered by test_async_access_token_locking). It would also catch regressions where the implementation accidentally reintroduces synchronous ADC resolution in the Live path while the shared auth helper remains correct.

    The proposed direction—routing Vertex Live authentication through _async_access_token()—therefore looks narrowly scoped and consistent with the SDK’s existing auth design. The main compatibility points to preserve are explicit credentials, API-key authentication, custom base URLs, and the current Authorization header precedence.

  2. added
    priority: p2Moderately-important priority. Fix may not be included in next release.
    type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.
    and removed
    priority: p2Moderately-important priority. Fix may not be included in next release.
    on Oct 6, 2026
  3. Venkaiahbabuneelam commented on Oct 6, 2026

    @Venkaiahbabuneelam

    Hi @sandeep2rawat, Thank you for bringing this to our attention. We truly appreciate you flagging this issue regarding Vertex AI live.connect() freezing the event loop during token refresh, we will file a bug internally.
    Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions