Skip to content

BigQueryAgentAnalyticsPlugin: first invocation after every start waits ~1 minute while 27 analytics views are recreated #8470

In review

Description

@GermanGerken

🔴 Required Information

Describe the Bug:

With BigQueryAgentAnalyticsPlugin and the default create_views=True, the first agent invocation in each process takes about a minute. During lazy setup the plugin runs CREATE OR REPLACE VIEW for every entry in _EVENT_VIEW_DEFS (27 views), one at a time, each waiting on client.query(sql).result() (_create_analytics_views). _lazy_setup awaits this before the first event is written (L7294), so the first user request waits for all 27 jobs. It happens on every process start, also when the views already exist, so every deploy or container restart adds this delay to a real request.

Steps to Reproduce:

  1. Create a dataset: bq --location=US mk --dataset PROJECT:agent_analytics, and log in with Application Default Credentials.
  2. pip install "google-adk[bigquery-analytics]"
  3. Run the script below (scripted model, no LLM provider): python repro.py PROJECT agent_analytics.
import asyncio, sys, time

from google.adk.agents import LlmAgent
from google.adk.apps import App
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.adk.plugins.bigquery_agent_analytics_plugin import BigQueryAgentAnalyticsPlugin, BigQueryLoggerConfig
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types


class EchoLlm(BaseLlm):
  model: str = "scripted-model"

  async def generate_content_async(self, llm_request: LlmRequest, stream: bool = False):
    yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="ok")]))


async def run(project, dataset, create_views):
  plugin = BigQueryAgentAnalyticsPlugin(
      project_id=project, dataset_id=dataset, table_id="agent_events",
      config=BigQueryLoggerConfig(create_views=create_views))
  app = App(name="repro", root_agent=LlmAgent(name="a", model=EchoLlm()), plugins=[plugin])
  sessions = InMemorySessionService()
  runner = Runner(app=app, session_service=sessions)
  timings = []
  for _ in range(3):
    session = await sessions.create_session(app_name="repro", user_id="u")
    msg = types.Content(role="user", parts=[types.Part(text="hi")])
    start = time.perf_counter()
    async for _ in runner.run_async(user_id="u", session_id=session.id, new_message=msg):
      pass
    timings.append(time.perf_counter() - start)
  await plugin.close()
  print(f"create_views={create_views}: " + ", ".join(f"{t:.2f}s" for t in timings))


asyncio.run(run(sys.argv[1], sys.argv[2], create_views=True))
asyncio.run(run(sys.argv[1], sys.argv[2], create_views=False))

Expected Behavior:

Creating or refreshing the analytics views does not block user requests, or happens only when the views are missing or out of date.

Observed Behavior:

Wall-clock time of three consecutive invocations, same process, views already present from an earlier run:

create_views=True: 65.07s, 4.28s, 4.05s
create_views=False: 8.59s, 3.49s, 3.72s

In an earlier run of a larger agent, INVOCATION_COMPLETED.latency_ms.total_ms was 51,824 ms and 57,807 ms for the first invocation of two separate processes and 17-31 ms afterwards. The BigQuery client's own OpenTelemetry spans show 27 BigQuery.job.begin calls in a 50.4 s and a 55.9 s window, matching that delay.

(The remaining ~3.5-4 s per invocation is the documented flush_on_run_end=True wait and is not part of this report.)

Environment Details:

  • ADK Library Version: 2.15.1 (main at bee78e7, plugin file unchanged on main)
  • Desktop OS: macOS
  • Python Version: 3.12.8

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: scripted BaseLlm (no provider); the delay is independent of the model

🟡 Optional Information

Workaround: BigQueryLoggerConfig(create_views=False), then call await plugin.create_analytics_views() once from a deploy step.

Possible fixes (happy to send a PR for whichever you prefer):

  • create the views in the background after the table is ready, so the first event is written without waiting for them;
  • or create them in parallel (they are independent);
  • or skip CREATE OR REPLACE when the view already exists with the same definition, so restarts do not repeat the work.

Activity

  1. chelsealong commented on Dec 1, 2026

    @chelsealong
    Contributor

    May I work on this issue (#8470: BigQueryAgentAnalyticsPlugin: first invocation after every start waits ~1 minute while 27 analytics views are recreated) and, if I can reproduce it, submit a focused fix with regression coverage? Please let me know if someone is already handling it or if you would prefer a different approach. I would use Codex assistance and disclose that in any PR.

  2. GermanGerken commented on Dec 1, 2026

    @GermanGerken
    Author

    Thanks for offering! I'm the reporter and I'd like to send the fix myself, as I did for #8425 / #8428. I'll open a PR once it's clear which approach fits best (views in the background, in parallel, or skipped when unchanged).

  3. surajksharma07 commented on Dec 3, 2026

    @surajksharma07
    Collaborator

    Thanks @GermanGerken for the detailed timings and the OTel span evidence. I can confirm it on 2.15.1 and main. _lazy_setup awaits all 27 CREATE OR REPLACE VIEW jobs one at a time before the first row is written. Nothing checks whether the views already exist so every restart pays for it again.

    A workaround that worked for me locally: override _create_analytics_views() to read INFORMATION_SCHEMA.VIEWS once and then recreate only the missing or changed views on a small thread pool. With fake 0.2s jobs the first invocation dropped from ~6s to ~1.6s on a fresh dataset. On a restart it dropped to ~0.2s since no views were recreated.

    I only tested it against a mocked client so I'm not sure BigQuery's view_definition matches the generated SQL exactly. A hash of the SQL in the view description may be safer to compare. Could you check it against a real dataset first?

    Since you're planning the PR, please test it well before raising it. That means retry when a view fails and shutdown during setup. Your create_views=False + create_analytics_views() workaround stays a good fallback meanwhile.

  4. GermanGerken commented on Dec 3, 2026

    @GermanGerken
    Author

    Thanks for confirming and for the sketch. I checked the open question against a real dataset.

    On a dataset where google-adk 2.15.1 had created all 27 views, I compared INFORMATION_SCHEMA.VIEWS.view_definition with the SQL the plugin generates (_VIEW_SQL_TEMPLATE, the part after AS). All 27 match once surrounding whitespace is trimmed. BigQuery stores the query text as sent, without the trailing newline. So comparing the stored definition is enough, and the plugin doesn't need a hash in the view description. That comparison also picks up a changed projection (denied columns) or a changed table name, because both change the SQL.

    My plan for the PR:

    • read INFORMATION_SCHEMA.VIEWS once (one query, filtered on the view prefix), and create or replace only the views that are missing or whose trimmed definition differs;
    • run the remaining CREATE OR REPLACE VIEW jobs concurrently on a small bounded pool;
    • if the metadata query fails, fall back to the current behaviour (recreate all), so nothing gets worse;
    • keep the existing result contract: a failed view still returns False, so _schema_ready stays unset and the next setup retries;
    • tests for: views already up to date (no DDL jobs), some missing or changed, a failing view and the retry, the metadata query failing, and shutdown while setup is running;
    • the same treatment for the eval views if create_eval_views has the same shape.

    I'll measure it on the real dataset before and after (fresh dataset and restart) and post the numbers in the PR.

  5. added
    needs review
    on Dec 4, 2026
  6. haiyuan-eng-google commented on Dec 4, 2026

    @haiyuan-eng-google
    Collaborator

    Thanks for the detailed timing breakdown and for putting together #8495, @GermanGerken!

    We reproduced the ~1-minute startup delay locally—_lazy_setup awaits all 27 _EVENT_VIEW_DEFS (plus 2 eval views when create_eval_views=True) one by one via blocking client.query(...).result() calls on every fresh process start.

    Your approach in #8495 (list_tables + bounded parallel get_table lookups + skipping unchanged views + bounded parallel DDL) is a great fit here: unlike querying INFORMATION_SCHEMA.VIEWS, it avoids creating BigQuery query jobs on warm starts, doesn't need bigquery.jobs.create when views are already up to date, and preserves existing client.query test/mock behavior.

    While auditing #8495 against ADK lifecycle edge cases and older google-cloud-bigquery versions, we ran into a few small gaps worth tightening up:

    1. Stopping queued workers on shutdown(): Calling plugin.shutdown() sets self.client = None and closes the underlying BigQuery HTTP session while queued ThreadPoolExecutor tasks are still running. Guarding the list_tables, get_table, and DDL loops on a captured client reference (self._is_shutting_down or self.client is not client) prevents post-close() RPCs and keeps _schema_ready False when setup is aborted mid-pass.
    2. Dataset pagination (page_size=1000): client.list_tables(dataset) defaults to 50 tables per page, which adds extra round-trips on shared datasets. Passing page_size=1000 with a TypeError fallback to client.list_tables(dataset) keeps compatibility with google-cloud-bigquery >= 2.2 and simple 1-arg test stubs.
    3. Per-view error isolation & metadata guards: Catching transient get_table errors per view avoids falling back to recreating all 27 views when a single lookup fails; skipping legacy-SQL views (view_use_legacy_sql) and normalizing \r\n prevents false matches; and keeping 0-arg _create_analytics_views() / _create_eval_views() compatibility avoids breaking subclasses that override them.

    We also have a fix with these guards and regression tests moving through review now and can align it cleanly with #8495.

  7. GermanGerken commented on Dec 5, 2026

    @GermanGerken
    Author

    Thanks for reproducing it and for the careful audit. I've pushed the three changes to #8495:

    1. Shutdown. The view lookups and the view DDL check self._is_shutting_down or self.client is not client before each call. A statement that has not started when shutdown begins is skipped and counted as not created, so _schema_ready stays False. The existing shutdown-race test now asserts that, and that only the statements already in flight reach the client.
    2. Listing. list_tables(dataset, page_size=1000), with a TypeError fallback to list_tables(dataset).
    3. Per-view handling.
      • A failed get_table for one view now recreates only that view, with a warning for that view.
      • A legacy-SQL view is never treated as up to date.
      • Stored and generated queries are compared after normalizing \r\n to \n.
      • _create_analytics_views() and _create_eval_views() still work with no arguments.

    New tests cover a single failed lookup, a legacy-SQL view, CRLF line endings, the page size and its fallback, and a pass after shutdown that sends no calls.

    I also checked this on a real dataset whose 27 analytics views and 2 eval views were created by 2.15.1. A fresh process now issues 0 view DDL statements and reaches schema_ready=True, both with and without create_eval_views. get_table reports view_use_legacy_sql=False for those DDL-created views, so the legacy guard does not cause re-creation.

    Happy to align with your internal fix in whatever way is easiest: rebase onto it, or trim this PR to what it still adds.

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

Metadata

Metadata

Labels

needs review

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions