Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
309 changes: 247 additions & 62 deletions src/google/adk/plugins/bigquery_agent_analytics_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6111,6 +6111,36 @@ 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
# 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")

# 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 normalized with ``_normalized_view_query``
before they are compared.
"""
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
# ``google.cloud.aiplatform.v1beta1.AgentData`` JSON in a ``trace`` column
# for agent evaluation:
Expand Down Expand Up @@ -7307,9 +7337,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
Expand Down Expand Up @@ -7445,12 +7475,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)
Expand Down Expand Up @@ -7482,12 +7507,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.
Expand Down Expand Up @@ -7670,50 +7690,205 @@ 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
# references a denied payload column (content / attributes / latency_ms).
# 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 _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:
"""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. 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:
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. 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, 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:
client.query(sql).result()
except cloud_exceptions.Conflict:
logger.debug(
"View %s was updated concurrently by another process.",
view_name,
)
view = client.get_table(f"{dataset}.{view_name}")
except cloud_exceptions.NotFound:
return None # Dropped since the listing; create it again.
except Exception as e:
created_all = False
logger.error(
"Failed to create view %s: %s",
view_name,
e,
exc_info=True,
logger.warning(
"Could not read view %s, recreating it: %s", view_name, e
)
return created_all
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 listing()
if item.table_type == "VIEW" and item.table_id in wanted
]
if not existing or self._view_setup_aborted(client):
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)
if self._view_setup_aborted(client):
return False
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.
Expand Down Expand Up @@ -7777,36 +7952,40 @@ 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(
full_table_id,
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(
Expand All @@ -7815,6 +7994,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:
Expand Down
Loading