Skip to content

[Bug] google_genai: a permanent 4xx from the Interactions, Agents and Files APIs is retried until the activity times out #134

Closed

Description

@avanish-garg

What are you really trying to do?

Call the Gemini Interactions API (and managed Agents, Files, File Search stores) from a workflow with TemporalAsyncClient and have a request that can never succeed, for example a 400 for a bad argument, a 404 for an unknown interaction id, or a 403 for a bad key, fail the workflow promptly, the way client.models.generate_content does.

Describe the bug

The README ("Retries & errors") says API-call activities classify failures: transient statuses (408, 429, 5xx) stay retryable and other statuses (e.g. 4xx) are non-retryable, so the workflow fails fast. In python/google_genai/src/temporalio/google_genai/_gemini_activity.py only gemini_api_client_async_request and gemini_api_client_async_request_streamed call _classify_api_error. The other 14 activities have no error mapping:

  • gemini_interactions_* and gemini_agents_* use google-genai's vendored client, which raises google.genai._gaos.lib.compat_errors.BadRequestError / NotFoundError / APIStatusError. These do not derive from genai.errors.APIError and carry the HTTP status in status_code, not code.
  • gemini_files_upload, gemini_files_download, gemini_files_register and gemini_file_search_stores_upload let genai.errors.ClientError escape unclassified.

Any of these errors is a plain retryable activity failure, so the default (unlimited) retry policy re-sends the same doomed request until the activity's schedule-to-close deadline (unbounded by default). With the script below, the same 400 fails generate_content after 1 request but interactions.create is sent 8 times in 8 seconds and ends in a TimeoutError. The same happens for agents.*, and files.upload against a 400 was also retried (4 requests, activity at attempt 5, within a few seconds).

I read the docstrings of TemporalAsyncInteractions / TemporalAsyncAgents: "a bad argument surfaces as an activity failure (retried per the activity's retry policy)". That describes SDK-side argument validation, not a status error from the server, so I think it does not conflict with this report, but let me know if retrying is intended there.

Minimal Reproduction

Runs against main @ bb34a32 with the plugin installed from the checkout (cd python/google_genai && make sync, then .venv/bin/python repro.py). A local HTTP server stands in for the Gemini API and answers every request with 400, so no credentials are needed.

import asyncio
import uuid
from datetime import timedelta

from temporalio import workflow
from temporalio.client import Client, WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.google_genai import GoogleGenAIPlugin, TemporalAsyncClient
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from temporalio.workflow import ActivityConfig

with workflow.unsafe.imports_passed_through():
    from google import genai
    from google.genai import types

HITS: list[str] = []


def start_fake_gemini() -> str:
    """Fake Gemini API on localhost: every request is a permanent 400."""
    import json
    import threading
    from http.server import BaseHTTPRequestHandler, HTTPServer

    class Handler(BaseHTTPRequestHandler):
        def _respond(self):
            n = int(self.headers.get("content-length") or 0)
            if n:
                self.rfile.read(n)
            HITS.append(self.path)
            body = json.dumps({"error": {"code": 400, "message": "bad", "status": "INVALID_ARGUMENT"}}).encode()
            self.send_response(400)
            self.send_header("content-type", "application/json")
            self.send_header("content-length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        do_GET = do_POST = _respond

        def log_message(self, *args):
            pass

    server = HTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return f"http://127.0.0.1:{server.server_port}"


CONFIG = ActivityConfig(
    schedule_to_close_timeout=timedelta(seconds=8),
    retry_policy=RetryPolicy(initial_interval=timedelta(milliseconds=200), backoff_coefficient=1.0),
)


@workflow.defn
class W:
    @workflow.run
    async def run(self, api: str) -> str:
        client = TemporalAsyncClient(activity_config=CONFIG)
        if api == "models":
            await client.models.generate_content(model="gemini-2.5-flash", contents="hi")
        else:
            await client.interactions.create(model="gemini-2.5-flash", input="hi")
        return "ok"


async def main():
    gemini = genai.Client(api_key="fake", http_options=types.HttpOptions(base_url=start_fake_gemini()))
    async with await WorkflowEnvironment.start_local() as env:
        config = env.client.config()
        config["plugins"] = [GoogleGenAIPlugin(gemini)]
        client = Client(**config)
        async with Worker(client, task_queue="q", workflows=[W]):
            for api in ("models", "interactions"):
                HITS.clear()
                try:
                    await client.execute_workflow(W.run, api, id=f"wf-{uuid.uuid4()}", task_queue="q")
                except WorkflowFailureError as e:
                    cause = e.cause.cause  # ActivityError -> ApplicationError or TimeoutError
                    print(f"{api}: failed after {len(HITS)} HTTP request(s): {type(cause).__name__}: {str(cause)[:70]}")


if __name__ == "__main__":
    asyncio.run(main())

Output on main:

models: failed after 1 HTTP request(s): ApplicationError: ClientError: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 
interactions: failed after 8 HTTP request(s): TimeoutError: Not enough time to schedule next retry before activity ScheduleToClose

Expected: interactions also fails after 1 request with a non-retryable ApplicationError.

Environment/Versions

  • OS and processor: macOS, arm64
  • Temporal Version: temporalio 1.34.0 (local dev server via WorkflowEnvironment.start_local()), temporalio-google-genai from main @ bb34a32, google-genai 2.24.0, Python 3.14.7
  • Are you using Docker or Kubernetes or building Temporal from source? No

Additional context

I have a fix ready: one helper that maps both error families to ApplicationError with the same retryable set as _classify_api_error, used by the Interactions, Agents, Files and File Search store activities. The vendored client's errors are matched by their status_code attribute rather than by importing the private google.genai._gaos module, so it does not depend on that path staying put. I will open a PR for it.

Separate observation, not part of the fix: the vendored Interactions client retries 408/409/429/5xx internally (4 requests per call with a short backoff) before raising, in addition to the Temporal retry policy, which the README says the plugin avoids for the models path.

Activity

  1. added
    bug
    on Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions