Repository navigation
Description
🔴 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:
- Create a dataset:
bq --location=US mk --dataset PROJECT:agent_analytics, and log in with Application Default Credentials. pip install "google-adk[bigquery-analytics]"- 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 REPLACEwhen the view already exists with the same definition, so restarts do not repeat the work.
Activity
chelsealong commentedon Dec 1, 2026
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.
GermanGerken commentedon Dec 1, 2026
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).
surajksharma07 commentedon Dec 3, 2026
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.
GermanGerken commentedon Dec 3, 2026
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_definitionwith the SQL the plugin generates (_VIEW_SQL_TEMPLATE, the part afterAS). 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:
INFORMATION_SCHEMA.VIEWSonce (one query, filtered on the view prefix), and create or replace only the views that are missing or whose trimmed definition differs;CREATE OR REPLACE VIEWjobs concurrently on a small bounded pool;False, so_schema_readystays unset and the next setup retries;create_eval_viewshas 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.
haiyuan-eng-google commentedon Dec 4, 2026
Thanks for the detailed timing breakdown and for putting together #8495, @GermanGerken!
We reproduced the ~1-minute startup delay locally—
_lazy_setupawaits all 27_EVENT_VIEW_DEFS(plus 2 eval views whencreate_eval_views=True) one by one via blockingclient.query(...).result()calls on every fresh process start.Your approach in #8495 (
list_tables+ bounded parallelget_tablelookups + skipping unchanged views + bounded parallel DDL) is a great fit here: unlike queryingINFORMATION_SCHEMA.VIEWS, it avoids creating BigQuery query jobs on warm starts, doesn't needbigquery.jobs.createwhen views are already up to date, and preserves existingclient.querytest/mock behavior.While auditing #8495 against ADK lifecycle edge cases and older
google-cloud-bigqueryversions, we ran into a few small gaps worth tightening up:shutdown(): Callingplugin.shutdown()setsself.client = Noneand closes the underlying BigQuery HTTP session while queuedThreadPoolExecutortasks are still running. Guarding thelist_tables,get_table, and DDL loops on a capturedclientreference (self._is_shutting_down or self.client is not client) prevents post-close()RPCs and keeps_schema_readyFalsewhen setup is aborted mid-pass.page_size=1000):client.list_tables(dataset)defaults to 50 tables per page, which adds extra round-trips on shared datasets. Passingpage_size=1000with aTypeErrorfallback toclient.list_tables(dataset)keeps compatibility withgoogle-cloud-bigquery >= 2.2and simple 1-arg test stubs.get_tableerrors 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\nprevents 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.
GermanGerken commentedon Dec 5, 2026
Thanks for reproducing it and for the careful audit. I've pushed the three changes to #8495:
self._is_shutting_down or self.client is not clientbefore each call. A statement that has not started when shutdown begins is skipped and counted as not created, so_schema_readystaysFalse. The existing shutdown-race test now asserts that, and that only the statements already in flight reach the client.list_tables(dataset, page_size=1000), with aTypeErrorfallback tolist_tables(dataset).get_tablefor one view now recreates only that view, with a warning for that view.\r\nto\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 withoutcreate_eval_views.get_tablereportsview_use_legacy_sql=Falsefor 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.