From ce5fb92dc18e54a88a0faacad43a95ab4e1a6fb8 Mon Sep 17 00:00:00 2001 From: germangerken Date: Thu, 3 Dec 2026 12:04:54 +0300 Subject: [PATCH 1/2] fix(plugins): skip up-to-date BigQuery analytics views on setup BigQueryAgentAnalyticsPlugin ran one CREATE OR REPLACE VIEW statement per analytics view, one after the other, on every process start, before the first row was written. The first user request after each start waited for all of them (about a minute for the 27 views). Setup now lists the dataset once, reads the stored query of the views it manages, and replaces only the views that are missing or whose query differs from the SQL the plugin generates, so a changed ADK version, view prefix, table or payload column denylist still updates them. The view DDL that does run is issued in parallel on a small bounded pool. If the existing views cannot be read, every view is replaced as before. The eval views get the same check and are still created in order. The public create_analytics_views() and create_eval_views() helpers still replace every view. Fixes #8470 --- .../bigquery_agent_analytics_plugin.py | 268 +++++++++++++----- .../test_bigquery_agent_analytics_plugin.py | 265 +++++++++++++++++ 2 files changed, 469 insertions(+), 64 deletions(-) diff --git a/src/google/adk/plugins/bigquery_agent_analytics_plugin.py b/src/google/adk/plugins/bigquery_agent_analytics_plugin.py index 40882c621ee..834ae33bd28 100644 --- a/src/google/adk/plugins/bigquery_agent_analytics_plugin.py +++ b/src/google/adk/plugins/bigquery_agent_analytics_plugin.py @@ -6111,6 +6111,27 @@ def _parse_custom_metadata_allowlist( event_type = '{event_type}' """ +# Upper bound on the view lookups and view DDL jobs that setup runs at once. +_VIEW_SETUP_MAX_WORKERS = 8 + +_VIEW_DDL_PREFIX = re.compile(r"\ACREATE OR REPLACE VIEW `[^`]+` AS\s") + +# The agent evaluation views, in creation order. +_EVAL_VIEWS = ( + ("eval_session", _build_eval_session_view_sql), + ("eval_turn", _build_eval_turn_view_sql), +) + + +def _view_query_of(ddl: str) -> str: + """Returns the query of a ``CREATE OR REPLACE VIEW`` statement. + + BigQuery stores a view's query as the text after ``AS``, without the + trailing newline; both sides are trimmed before they are compared. + """ + return _VIEW_DDL_PREFIX.sub("", ddl.strip(), count=1).strip() + + # The eval views rebuild event rows into the # ``google.cloud.aiplatform.v1beta1.AgentData`` JSON in a ``trace`` column # for agent evaluation: @@ -7307,9 +7328,9 @@ def _close() -> None: # missing/unready table. A success is remembered in _schema_ready rather # than in _started, which every close() clears: a host that builds a # short-lived Runner per request over one shared plugin closes it on each - # request, and replaying the pass there costs one CREATE OR REPLACE VIEW - # per analytics view, on the request path, against a daily quota. A view - # that failed leaves the flag False, so the pass runs again. + # request, and replaying the pass there costs a view lookup, plus one + # CREATE OR REPLACE VIEW per view that changed, on the request path. A + # view that failed leaves the flag False, so the pass runs again. if not self._schema_ready: if await loop.run_in_executor(executor, self._ensure_schema_exists): self._schema_ready = True @@ -7445,12 +7466,7 @@ def _ensure_schema_exists_impl(self, client: bigquery.Client) -> bool: existing_table = client.get_table(self.full_table_id) if self.config.auto_schema_upgrade: self._maybe_upgrade_schema(existing_table) - views_ok = True - if self.config.create_views: - views_ok = self._create_analytics_views() and views_ok - if self.config.create_eval_views: - views_ok = self._create_eval_views() and views_ok - return views_ok + return self._ensure_views(client) except cloud_exceptions.NotFound: logger.info("Table %s not found, creating table.", self.full_table_id) tbl = bigquery.Table(self.full_table_id, schema=self._schema) @@ -7482,12 +7498,7 @@ def _ensure_schema_exists_impl(self, client: bigquery.Client) -> bool: exc_info=True, ) raise - views_ok = True - if self.config.create_views: - views_ok = self._create_analytics_views() and views_ok - if self.config.create_eval_views: - views_ok = self._create_eval_views() and views_ok - return views_ok + return self._ensure_views(client) except Exception as e: # Fail setup: swallowing control-plane errors here let # the plugin mark itself started against a missing/unready table. @@ -7670,19 +7681,9 @@ def _project_view_columns(self, extra_cols: list[str]) -> list[str]: kept.append(expr) return kept - def _create_analytics_views(self) -> bool: - """Creates per-event-type BigQuery views (idempotent). - - Each view filters the events table by ``event_type`` and - extracts JSON columns into typed, queryable columns. Uses - ``CREATE OR REPLACE VIEW`` so it is safe to call repeatedly. - Errors are logged but never raised. - - Returns: - True if every view was created, False if any of them failed. - """ - client = self._require_client() - created_all = True + def _analytics_view_ddl(self) -> list[tuple[str, str]]: + """Returns ``(view_name, CREATE OR REPLACE VIEW statement)`` per view.""" + statements = [] for event_type, extra_cols in _EVENT_VIEW_DEFS.items(): view_name = self.config.view_prefix + "_" + event_type.lower() # Projection-aware views -- drop any derived column whose SQL @@ -7690,30 +7691,159 @@ def _create_analytics_views(self) -> bool: # Common columns are all protected, so they always remain. projected_extra = self._project_view_columns(extra_cols) columns = ",\n ".join(list(_VIEW_COMMON_COLUMNS) + projected_extra) - sql = _VIEW_SQL_TEMPLATE.format( - project=self.project_id, - dataset=self.dataset_id, - view_name=view_name, - columns=columns, - table=self.table_id, - event_type=event_type, + statements.append(( + view_name, + _VIEW_SQL_TEMPLATE.format( + project=self.project_id, + dataset=self.dataset_id, + view_name=view_name, + columns=columns, + table=self.table_id, + event_type=event_type, + ), + )) + return statements + + def _run_view_ddl( + self, client: bigquery.Client, view_name: str, sql: str + ) -> bool: + """Runs one view statement; logs a failure instead of raising it. + + The caller passes the client it read once for the whole readiness pass: + shutdown clears ``self.client`` while the statements may still be + running. + """ + try: + client.query(sql).result() + except cloud_exceptions.Conflict: + logger.debug( + "View %s was updated concurrently by another process.", + view_name, ) + except Exception as e: + logger.error( + "Failed to create view %s: %s", + view_name, + e, + exc_info=True, + ) + return False + return True + + def _existing_view_queries( + self, + client: bigquery.Client, + view_names: collections.abc.Collection[str], + ) -> Optional[dict[str, str]]: + """Reads the stored query of each of ``view_names`` that already exists. + + One ``list_tables`` call finds which of the views exist, and their + definitions are fetched in parallel. Other tables and views in the + dataset are not read. + + Returns: + A mapping from view name to its stored query, trimmed, or None when + the lookup failed and every view should be replaced. + """ + dataset = f"{self.project_id}.{self.dataset_id}" + wanted = set(view_names) + + def fetch(view_name: str) -> Optional[tuple[str, str]]: try: - client.query(sql).result() - except cloud_exceptions.Conflict: - logger.debug( - "View %s was updated concurrently by another process.", - view_name, - ) - except Exception as e: - created_all = False - logger.error( - "Failed to create view %s: %s", - view_name, - e, - exc_info=True, - ) - return created_all + view = client.get_table(f"{dataset}.{view_name}") + except cloud_exceptions.NotFound: + return None # Dropped since the listing; create it again. + return view_name, (view.view_query or "").strip() + + try: + existing = [ + item.table_id + for item in client.list_tables(dataset) + if item.table_type == "VIEW" and item.table_id in wanted + ] + if not existing: + return {} + with ThreadPoolExecutor( + max_workers=min(_VIEW_SETUP_MAX_WORKERS, len(existing)), + thread_name_prefix="bqaa-views", + ) as pool: + return dict(found for found in pool.map(fetch, existing) if found) + except Exception as e: + logger.warning( + "Could not read the existing views in %s, recreating all of them: %s", + dataset, + e, + ) + return None + + def _ensure_views(self, client: bigquery.Client) -> bool: + """Creates the configured views that are missing or out of date. + + Runs on every setup, so a process start that finds the views already + matching the SQL this plugin would generate issues no DDL. A view whose + definition differs (another ADK version, view prefix, table, or payload + column denylist) is replaced; if the existing views cannot be read, + every view is replaced as before. + + Returns: + True if every configured view is up to date, False if any failed. + """ + if not (self.config.create_views or self.config.create_eval_views): + return True + wanted = [] + if self.config.create_views: + wanted += [name for name, _ in self._analytics_view_ddl()] + if self.config.create_eval_views: + wanted += [self.config.view_prefix + "_" + s for s, _ in _EVAL_VIEWS] + existing = self._existing_view_queries(client, wanted) + views_ok = True + if self.config.create_views: + views_ok = ( + self._create_analytics_views(existing, client=client) and views_ok + ) + if self.config.create_eval_views: + views_ok = self._create_eval_views(existing, client=client) and views_ok + return views_ok + + def _create_analytics_views( + self, + existing: Optional[collections.abc.Mapping[str, str]] = None, + *, + client: Optional[bigquery.Client] = None, + ) -> bool: + """Creates per-event-type BigQuery views (idempotent). + + Each view filters the events table by ``event_type`` and + extracts JSON columns into typed, queryable columns. Uses + ``CREATE OR REPLACE VIEW`` so it is safe to call repeatedly. + The statements run in parallel. Errors are logged but never raised. + + Args: + existing: Stored queries of the views that already exist, from + ``_existing_view_queries``. A view whose stored query matches is + skipped. None replaces every view. + client: The client of the current readiness pass; defaults to + ``self.client``. + + Returns: + True if every view was created or up to date, False if any failed. + """ + client = client or self._require_client() + statements = [ + (view_name, sql) + for view_name, sql in self._analytics_view_ddl() + if existing is None or existing.get(view_name) != _view_query_of(sql) + ] + if not statements: + return True + with ThreadPoolExecutor( + max_workers=min(_VIEW_SETUP_MAX_WORKERS, len(statements)), + thread_name_prefix="bqaa-views", + ) as pool: + results = list( + pool.map(lambda s: self._run_view_ddl(client, *s), statements) + ) + return all(results) async def create_analytics_views(self) -> None: """Public async helper to (re-)create all analytics views. @@ -7777,23 +7907,33 @@ def _validate_eval_view_config(self, *, from_init: bool = False) -> None: f" missing: {sorted(missing_events)}.{hint}" ) - def _create_eval_views(self) -> bool: + def _create_eval_views( + self, + existing: Optional[collections.abc.Mapping[str, str]] = None, + *, + client: Optional[bigquery.Client] = None, + ) -> bool: """Creates the agent evaluation session and turn views (idempotent). Creates ``{view_prefix}_eval_session`` and ``{view_prefix}_eval_turn`` with ``CREATE OR REPLACE VIEW``, so it is safe to call repeatedly. - Errors are logged but never raised. + They are created one after the other, in that order. Errors are logged + but never raised. + + Args: + existing: Stored queries of the views that already exist, from + ``_existing_view_queries``. A view whose stored query matches is + skipped. None replaces both views. + client: The client of the current readiness pass; defaults to + ``self.client``. Returns: - True if both views were created, False if either of them failed. + True if both views were created or up to date, False if either failed. """ - client = self._require_client() + client = client or self._require_client() full_table_id = f"{self.project_id}.{self.dataset_id}.{self.table_id}" created_all = True - for view_suffix, build_view_sql in ( - ("eval_session", _build_eval_session_view_sql), - ("eval_turn", _build_eval_turn_view_sql), - ): + for view_suffix, build_view_sql in _EVAL_VIEWS: view_name = self.config.view_prefix + "_" + view_suffix try: sql = build_view_sql( @@ -7801,12 +7941,6 @@ def _create_eval_views(self) -> bool: view_prefix=self.config.view_prefix, denied_columns=self._denied_columns, ) - client.query(sql).result() - except cloud_exceptions.Conflict: - logger.debug( - "View %s was updated concurrently by another process.", - view_name, - ) except Exception as e: created_all = False logger.error( @@ -7815,6 +7949,12 @@ def _create_eval_views(self) -> bool: e, exc_info=True, ) + continue + if existing is not None and existing.get(view_name) == _view_query_of( + sql + ): + continue + created_all = self._run_view_ddl(client, view_name, sql) and created_all return created_all async def create_eval_views(self) -> None: diff --git a/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py b/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py index f9240fa9548..f66494f4739 100644 --- a/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py +++ b/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py @@ -12891,6 +12891,271 @@ def test_init_rejects_empty_or_unquotable_identifiers( bigquery_agent_analytics_plugin.BigQueryAgentAnalyticsPlugin(**kwargs) +class _FakeViewDataset: + """In-memory stand-in for the BigQuery client calls of view setup. + + ``query`` runs ``CREATE OR REPLACE VIEW`` statements and stores each view's + query as BigQuery does: the text after ``AS``, without the trailing + newline. ``list_tables`` and ``get_table`` read the views back, and + ``get_table`` returns ``events_table`` for the events table. + """ + + def __init__(self, events_table): + self.events_table = events_table + self.views: dict[str, str] = {} + self.ddl: list[str] = [] + self.fetched: list[str] = [] + self.fail: set[str] = set() + self.ddl_delay = 0.0 + self.active = 0 + self.max_active = 0 + self._lock = threading.Lock() + + def query(self, sql, *args, **kwargs): + del args, kwargs + name = sql.split("`", 2)[1].rsplit(".", 1)[1] + with self._lock: + self.ddl.append(name) + self.active += 1 + self.max_active = max(self.max_active, self.active) + try: + time.sleep(self.ddl_delay) + if name in self.fail: + raise RuntimeError(f"DDL for {name} rejected") + with self._lock: + self.views[name] = sql.split(" AS\n", 1)[1].rstrip("\n") + finally: + with self._lock: + self.active -= 1 + return mock.MagicMock() + + def list_tables(self, dataset, *args, **kwargs): + del dataset, args, kwargs + return [ + SimpleNamespace(table_id=name, table_type="VIEW") + for name in list(self.views) + ] + + def get_table(self, table, *args, **kwargs): + del args, kwargs + name = str(table).rsplit(".", 1)[1] + if name == TABLE_ID: + return self.events_table + with self._lock: + self.fetched.append(name) + view_query = self.views.get(name) + if view_query is None: + raise cloud_exceptions.NotFound(name) + return SimpleNamespace(table_id=name, view_query=view_query) + + +class TestViewsSkippedWhenUnchanged: + """Setup recreates only the views that are missing or out of date.""" + + ANALYTICS_VIEWS = sorted( + "v_" + event_type.lower() + for event_type in bigquery_agent_analytics_plugin._EVENT_VIEW_DEFS + ) + + def _dataset(self): + events_table = mock.MagicMock(spec=bigquery.Table) + events_table.schema = bigquery_agent_analytics_plugin._get_events_schema() + events_table.labels = { + bigquery_agent_analytics_plugin._SCHEMA_VERSION_LABEL_KEY: ( + bigquery_agent_analytics_plugin._SCHEMA_VERSION + ), + } + return _FakeViewDataset(events_table) + + def _make_plugin(self, dataset, **config_kwargs): + config = bigquery_agent_analytics_plugin.BigQueryLoggerConfig( + **config_kwargs + ) + plugin = bigquery_agent_analytics_plugin.BigQueryAgentAnalyticsPlugin( + project_id=PROJECT_ID, + dataset_id=DATASET_ID, + table_id=TABLE_ID, + config=config, + ) + plugin.client = dataset + plugin.full_table_id = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}" + plugin._schema = bigquery_agent_analytics_plugin._project_schema( + bigquery_agent_analytics_plugin._get_events_schema(), + plugin._denied_columns, + ) + return plugin + + def test_restart_does_not_recreate_up_to_date_views(self): + """A new process on a dataset that already has the views runs no DDL.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + assert sorted(dataset.ddl) == self.ANALYTICS_VIEWS + + dataset.ddl.clear() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert dataset.ddl == [] + + def test_missing_and_changed_views_are_recreated(self): + """Only a dropped view and a view with another definition are replaced.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + expected = dict(dataset.views) + del dataset.views["v_llm_request"] + dataset.views["v_tool_error"] = "SELECT 1" + dataset.ddl.clear() + + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert sorted(dataset.ddl) == ["v_llm_request", "v_tool_error"] + assert dataset.views == expected + + def test_changed_projection_recreates_affected_views(self): + """A denylisted payload column changes the SQL, so those views change.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + dataset.ddl.clear() + + plugin = self._make_plugin(dataset, payload_column_denylist=["latency_ms"]) + dataset.events_table.schema = plugin._schema + assert plugin._ensure_schema_exists() is True + + assert dataset.ddl + assert len(dataset.ddl) < len(self.ANALYTICS_VIEWS) + assert not any("latency_ms" in dataset.views[name] for name in dataset.ddl) + + def test_failed_view_is_retried_alone(self): + """A view that failed is created on the next pass, and only that view.""" + dataset = self._dataset() + dataset.fail = {"v_tool_error"} + plugin = self._make_plugin(dataset) + + assert plugin._ensure_schema_exists() is False + assert "v_tool_error" not in dataset.views + + dataset.fail.clear() + dataset.ddl.clear() + assert plugin._ensure_schema_exists() is True + + assert dataset.ddl == ["v_tool_error"] + + def test_lookup_failure_recreates_every_view(self): + """If existing views cannot be read, setup falls back to replacing all.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + dataset.ddl.clear() + plugin = self._make_plugin(dataset) + + with ( + mock.patch.object( + dataset, "list_tables", side_effect=RuntimeError("list denied") + ), + mock.patch.object( + bigquery_agent_analytics_plugin.logger, "warning" + ) as mock_warn, + ): + assert plugin._ensure_schema_exists() is True + + assert sorted(dataset.ddl) == self.ANALYTICS_VIEWS + assert any( + "recreating" in str(call.args[0]) for call in mock_warn.call_args_list + ) + + def test_only_this_plugins_views_are_read(self): + """Other views and tables in the dataset are not fetched or replaced.""" + dataset = self._dataset() + dataset.views["v_custom_report"] = "SELECT 1" + dataset.views["other_view"] = "SELECT 2" + + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert set(dataset.fetched) <= set(self.ANALYTICS_VIEWS) + assert dataset.views["v_custom_report"] == "SELECT 1" + assert dataset.views["other_view"] == "SELECT 2" + + def test_view_ddl_runs_concurrently(self): + """Views that need DDL are created in parallel, not one at a time.""" + dataset = self._dataset() + dataset.ddl_delay = 0.05 + + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert sorted(dataset.ddl) == self.ANALYTICS_VIEWS + assert 1 < dataset.max_active + assert ( + dataset.max_active + <= bigquery_agent_analytics_plugin._VIEW_SETUP_MAX_WORKERS + ) + + def test_up_to_date_eval_views_are_not_recreated(self): + """The eval views are compared the same way, and created in order.""" + dataset = self._dataset() + config = {"create_views": False, "create_eval_views": True} + assert self._make_plugin(dataset, **config)._ensure_schema_exists() is True + assert dataset.ddl == ["v_eval_session", "v_eval_turn"] + + dataset.ddl.clear() + assert self._make_plugin(dataset, **config)._ensure_schema_exists() is True + + assert dataset.ddl == [] + + def test_explicit_refresh_still_replaces_every_view(self): + """create_analytics_views() is a refresh: it does not skip any view.""" + dataset = self._dataset() + plugin = self._make_plugin(dataset) + assert plugin._ensure_schema_exists() is True + dataset.ddl.clear() + + assert plugin._create_analytics_views() is True + + assert sorted(dataset.ddl) == self.ANALYTICS_VIEWS + + @pytest.mark.asyncio + async def test_shutdown_during_view_setup( + self, mock_auth_default, mock_bq_client, mock_write_client + ): + """Shutdown does not wait for view DDL, and the setup it races aborts.""" + plugin = bigquery_agent_analytics_plugin.BigQueryAgentAnalyticsPlugin( + project_id=PROJECT_ID, + dataset_id=DATASET_ID, + table_id=TABLE_ID, + ) + entered = threading.Event() + release = threading.Event() + + def slow_ddl(sql, *args, **kwargs): + del sql, args, kwargs + entered.set() + release.wait(5) + return mock.MagicMock() + + mock_bq_client.query.side_effect = slow_ddl + with mock.patch.object( + bigquery_agent_analytics_plugin.logger, "error" + ) as mock_error: + owner = asyncio.create_task(plugin._ensure_started()) + try: + assert await asyncio.to_thread(entered.wait, 5) + await asyncio.wait_for(plugin.shutdown(), 5) + assert plugin._started is False + assert plugin.client is None + finally: + release.set() + assert await asyncio.wait_for(owner, 5) == "aborted" + + assert plugin._started is False + # The statements still in flight keep the client they started with, so + # shutdown clearing plugin.client does not fail the remaining views. + assert mock_bq_client.query.call_count == len( + bigquery_agent_analytics_plugin._EVENT_VIEW_DEFS + ) + assert not [ + call + for call in mock_error.call_args_list + if "Failed to create view" in str(call.args[0]) + ] + + class TestSchemaReadinessMemo: """Tests that a successful table readiness pass is not repeated.""" From a7304b9886b084f3e375119c72131d796c925aba Mon Sep 17 00:00:00 2001 From: germangerken Date: Sat, 5 Dec 2026 12:07:38 +0300 Subject: [PATCH 2/2] fix(plugins): harden BigQuery view setup for shutdown and lookup failures - Skip view lookups and DDL that have not started once shutdown begins or the client was replaced, so no call goes through a closed client and an aborted pass is not remembered as complete. - List the dataset with page_size=1000, falling back to the one-argument call for older clients and simple stubs. - Recreate only a view whose definition cannot be read instead of every view, never treat a legacy-SQL view as up to date, and normalize CRLF line endings before comparing view queries. --- .../bigquery_agent_analytics_plugin.py | 63 +++++++++-- .../test_bigquery_agent_analytics_plugin.py | 107 +++++++++++++++++- 2 files changed, 155 insertions(+), 15 deletions(-) diff --git a/src/google/adk/plugins/bigquery_agent_analytics_plugin.py b/src/google/adk/plugins/bigquery_agent_analytics_plugin.py index 834ae33bd28..5b597c82914 100644 --- a/src/google/adk/plugins/bigquery_agent_analytics_plugin.py +++ b/src/google/adk/plugins/bigquery_agent_analytics_plugin.py @@ -6113,6 +6113,9 @@ def _parse_custom_metadata_allowlist( # Upper bound on the view lookups and view DDL jobs that setup runs at once. _VIEW_SETUP_MAX_WORKERS = 8 +# Tables per page when listing the dataset for existing views (the API +# default is 50, which costs extra round trips on shared datasets). +_VIEW_LIST_PAGE_SIZE = 1000 _VIEW_DDL_PREFIX = re.compile(r"\ACREATE OR REPLACE VIEW `[^`]+` AS\s") @@ -6127,9 +6130,15 @@ def _view_query_of(ddl: str) -> str: """Returns the query of a ``CREATE OR REPLACE VIEW`` statement. BigQuery stores a view's query as the text after ``AS``, without the - trailing newline; both sides are trimmed before they are compared. + trailing newline; both sides are normalized with ``_normalized_view_query`` + before they are compared. """ - return _VIEW_DDL_PREFIX.sub("", ddl.strip(), count=1).strip() + return _normalized_view_query(_VIEW_DDL_PREFIX.sub("", ddl.strip(), count=1)) + + +def _normalized_view_query(query: str) -> str: + """Trims a view query and normalizes its line endings to ``\\n``.""" + return query.replace("\r\n", "\n").strip() # The eval views rebuild event rows into the @@ -7704,6 +7713,15 @@ def _analytics_view_ddl(self) -> list[tuple[str, str]]: )) return statements + def _view_setup_aborted(self, client: bigquery.Client) -> bool: + """Whether shutdown has started or replaced the client of a setup pass. + + ``shutdown()`` clears ``self.client`` and closes its HTTP session while + queued view lookups and statements may still be waiting for a worker; + they check this first so that no call is sent through a closed client. + """ + return self._is_shutting_down or self.client is not client + def _run_view_ddl( self, client: bigquery.Client, view_name: str, sql: str ) -> bool: @@ -7711,8 +7729,13 @@ def _run_view_ddl( The caller passes the client it read once for the whole readiness pass: shutdown clears ``self.client`` while the statements may still be - running. + running. A statement that has not started when shutdown begins is + skipped and reported as not created, so the pass is not remembered as + complete. """ + if self._view_setup_aborted(client): + logger.debug("Skipping view %s: the plugin is shutting down.", view_name) + return False try: client.query(sql).result() except cloud_exceptions.Conflict: @@ -7739,29 +7762,49 @@ def _existing_view_queries( One ``list_tables`` call finds which of the views exist, and their definitions are fetched in parallel. Other tables and views in the - dataset are not read. + dataset are not read. A view whose definition cannot be read, or that + uses legacy SQL, is left out of the result, so only that view is + replaced. Returns: - A mapping from view name to its stored query, trimmed, or None when - the lookup failed and every view should be replaced. + A mapping from view name to its stored query, normalized, or None when + the listing failed and every view should be replaced. """ dataset = f"{self.project_id}.{self.dataset_id}" wanted = set(view_names) + if self._view_setup_aborted(client): + return {} def fetch(view_name: str) -> Optional[tuple[str, str]]: + if self._view_setup_aborted(client): + return None try: view = client.get_table(f"{dataset}.{view_name}") except cloud_exceptions.NotFound: return None # Dropped since the listing; create it again. - return view_name, (view.view_query or "").strip() + except Exception as e: + logger.warning( + "Could not read view %s, recreating it: %s", view_name, e + ) + return None + if getattr(view, "view_use_legacy_sql", None) is True: + return None # Never equal to the standard SQL this plugin writes. + return view_name, _normalized_view_query(view.view_query or "") + + def listing() -> collections.abc.Iterable[Any]: + try: + return client.list_tables(dataset, page_size=_VIEW_LIST_PAGE_SIZE) + except TypeError: + # An older client or a stub without the page_size argument. + return client.list_tables(dataset) try: existing = [ item.table_id - for item in client.list_tables(dataset) + for item in listing() if item.table_type == "VIEW" and item.table_id in wanted ] - if not existing: + if not existing or self._view_setup_aborted(client): return {} with ThreadPoolExecutor( max_workers=min(_VIEW_SETUP_MAX_WORKERS, len(existing)), @@ -7796,6 +7839,8 @@ def _ensure_views(self, client: bigquery.Client) -> bool: if self.config.create_eval_views: wanted += [self.config.view_prefix + "_" + s for s, _ in _EVAL_VIEWS] existing = self._existing_view_queries(client, wanted) + if self._view_setup_aborted(client): + return False views_ok = True if self.config.create_views: views_ok = ( diff --git a/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py b/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py index f66494f4739..80803f81437 100644 --- a/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py +++ b/tests/unittests/plugins/test_bigquery_agent_analytics_plugin.py @@ -12906,6 +12906,9 @@ def __init__(self, events_table): self.ddl: list[str] = [] self.fetched: list[str] = [] self.fail: set[str] = set() + self.lookup_fail: set[str] = set() + self.legacy: set[str] = set() + self.list_kwargs: list[dict] = [] self.ddl_delay = 0.0 self.active = 0 self.max_active = 0 @@ -12930,7 +12933,8 @@ def query(self, sql, *args, **kwargs): return mock.MagicMock() def list_tables(self, dataset, *args, **kwargs): - del dataset, args, kwargs + del dataset, args + self.list_kwargs.append(kwargs) return [ SimpleNamespace(table_id=name, table_type="VIEW") for name in list(self.views) @@ -12946,7 +12950,13 @@ def get_table(self, table, *args, **kwargs): view_query = self.views.get(name) if view_query is None: raise cloud_exceptions.NotFound(name) - return SimpleNamespace(table_id=name, view_query=view_query) + if name in self.lookup_fail: + raise RuntimeError(f"lookup of {name} failed") + return SimpleNamespace( + table_id=name, + view_query=view_query, + view_use_legacy_sql=name in self.legacy, + ) class TestViewsSkippedWhenUnchanged: @@ -13061,6 +13071,88 @@ def test_lookup_failure_recreates_every_view(self): "recreating" in str(call.args[0]) for call in mock_warn.call_args_list ) + def test_one_failed_lookup_recreates_only_that_view(self): + """A view whose definition cannot be read is the only one replaced.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + dataset.ddl.clear() + dataset.lookup_fail = {"v_tool_error"} + + with mock.patch.object( + bigquery_agent_analytics_plugin.logger, "warning" + ) as mock_warn: + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert dataset.ddl == ["v_tool_error"] + assert any( + "v_tool_error" in str(call.args) for call in mock_warn.call_args_list + ) + + def test_legacy_sql_view_is_replaced(self): + """A legacy SQL view with the same text is not treated as up to date.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + dataset.ddl.clear() + dataset.legacy = {"v_llm_request"} + + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert dataset.ddl == ["v_llm_request"] + + def test_crlf_line_endings_still_match(self): + """A stored query with CRLF line endings matches the generated SQL.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + dataset.views = { + name: query.replace("\n", "\r\n") + for name, query in dataset.views.items() + } + dataset.ddl.clear() + + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert dataset.ddl == [] + + def test_listing_asks_for_large_pages(self): + """The dataset is listed with a page size larger than the default 50.""" + dataset = self._dataset() + + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert dataset.list_kwargs == [ + {"page_size": bigquery_agent_analytics_plugin._VIEW_LIST_PAGE_SIZE} + ] + + def test_listing_falls_back_without_page_size(self): + """A client whose list_tables takes no page_size is still supported.""" + dataset = self._dataset() + assert self._make_plugin(dataset)._ensure_schema_exists() is True + dataset.ddl.clear() + views = dict(dataset.views) + + def list_tables(dataset_id): + del dataset_id + return [ + SimpleNamespace(table_id=name, table_type="VIEW") for name in views + ] + + with mock.patch.object(dataset, "list_tables", side_effect=list_tables): + assert self._make_plugin(dataset)._ensure_schema_exists() is True + + assert dataset.ddl == [] + + def test_aborted_setup_sends_no_calls(self): + """After shutdown replaced the client, a pass reads and creates nothing.""" + dataset = self._dataset() + plugin = self._make_plugin(dataset) + plugin.client = None + + assert plugin._ensure_views(dataset) is False + + assert dataset.list_kwargs == [] + assert dataset.fetched == [] + assert dataset.ddl == [] + def test_only_this_plugins_views_are_read(self): """Other views and tables in the dataset are not fetched or replaced.""" dataset = self._dataset() @@ -13144,10 +13236,13 @@ def slow_ddl(sql, *args, **kwargs): assert await asyncio.wait_for(owner, 5) == "aborted" assert plugin._started is False - # The statements still in flight keep the client they started with, so - # shutdown clearing plugin.client does not fail the remaining views. - assert mock_bq_client.query.call_count == len( - bigquery_agent_analytics_plugin._EVENT_VIEW_DEFS + assert plugin._schema_ready is False + # The statements in flight finish with the client they started with; the + # ones still queued when shutdown began are skipped instead of being sent + # through the closed client, and none of this is logged as a failure. + assert ( + mock_bq_client.query.call_count + <= bigquery_agent_analytics_plugin._VIEW_SETUP_MAX_WORKERS ) assert not [ call