forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbigquery_agent_analytics_plugin.py
More file actions
4091 lines (3655 loc) · 142 KB
/
Copy pathbigquery_agent_analytics_plugin.py
File metadata and controls
4091 lines (3655 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import asyncio
import atexit
from concurrent.futures import ThreadPoolExecutor
import contextvars
import dataclasses
from dataclasses import dataclass
from dataclasses import field
from datetime import datetime
from datetime import timezone
import functools
import json
import logging
import mimetypes
import os
# Enable gRPC fork support so child processes created via os.fork()
# can safely create new gRPC channels. Must be set before grpc's
# C-core is loaded (which happens through the google.api_core
# imports below). setdefault respects any explicit user override.
os.environ.setdefault("GRPC_ENABLE_FORK_SUPPORT", "1")
import random
import time
from types import MappingProxyType
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import Optional
from typing import TYPE_CHECKING
import uuid
import weakref
from google.api_core import client_options
from google.api_core.exceptions import InternalServerError
from google.api_core.exceptions import ServiceUnavailable
from google.api_core.exceptions import TooManyRequests
from google.api_core.gapic_v1 import client_info as gapic_client_info
import google.auth
from google.cloud import bigquery
from google.cloud import exceptions as cloud_exceptions
from google.cloud import storage
from google.cloud.bigquery import schema as bq_schema
from google.cloud.bigquery_storage_v1 import types as bq_storage_types
from google.cloud.bigquery_storage_v1.services.big_query_write.async_client import BigQueryWriteAsyncClient
from google.genai import types
from opentelemetry import trace
import pyarrow as pa
from ..agents.callback_context import CallbackContext
from ..models.llm_request import LlmRequest
from ..models.llm_response import LlmResponse
from ..tools.base_tool import BaseTool
from ..tools.tool_context import ToolContext
from ..utils._telemetry_context import _is_visual_builder
from ..version import __version__
from .base_plugin import BasePlugin
if TYPE_CHECKING:
from ..agents.invocation_context import InvocationContext
from ..events.event import Event
logger: logging.Logger = logging.getLogger("google_adk." + __name__)
tracer = trace.get_tracer(
"google.adk.plugins.bigquery_agent_analytics", __version__
)
# Bumped when the schema changes (1 → 2 → 3 …). Used as a table
# label for governance and to decide whether auto-upgrade should run.
_SCHEMA_VERSION = "1"
_SCHEMA_VERSION_LABEL_KEY = "adk_schema_version"
# ADK 2.0 envelope version. Stamped onto every ADK-enriched row as
# ``attributes.adk.schema_version``. Independent of the BigQuery row
# schema version above — this names the producer's ADK 2.0 attribute
# contract so downstream consumers can gate on it.
_ADK_ENVELOPE_SCHEMA_VERSION = "1"
_HITL_EVENT_MAP = MappingProxyType({
"adk_request_credential": "HITL_CREDENTIAL_REQUEST",
"adk_request_confirmation": "HITL_CONFIRMATION_REQUEST",
"adk_request_input": "HITL_INPUT_REQUEST",
})
# Reverse of _HITL_EVENT_MAP for the long-running-tool pause_kind
# discriminator. The id→name lookup routes ``adk_request_credential``
# → ``hitl_credential`` etc.; everything else is ``tool``.
_HITL_PAUSE_KIND_MAP = MappingProxyType({
"adk_request_credential": "hitl_credential",
"adk_request_confirmation": "hitl_confirmation",
"adk_request_input": "hitl_input",
})
def _derive_scope(
isolation_scope: Optional[str],
) -> Optional[dict[str, str]]:
"""Derives ``attributes.adk.scope`` from an Event's isolation_scope.
Order is fixed: (1) None → null; (2) node-shape (``name@run_id`` or
``parent/name@run_id``) → ``node_run``; (3) any other non-empty
string → ``function_call`` (model-provided FC IDs like ``call_*`` and
``toolu_*`` legitimately match here); (4) empty/non-string → ``unknown``
with a warning. Steps 2 and 3 are intentionally ordered: a bare
``name@run_id`` must classify as ``node_run`` first, not as
``function_call`` by fall-through.
"""
if isolation_scope is None:
return None
if not isinstance(isolation_scope, str) or not isolation_scope:
logger.warning(
"Unexpected isolation_scope shape: %r; classifying as 'unknown'",
isolation_scope,
)
return {"id": str(isolation_scope), "kind": "unknown"}
# Node-shape: last segment contains '@'. The full string may also be
# path-prefixed (e.g. ``wf/A@1/B@2``).
last_segment = isolation_scope.rsplit("/", 1)[-1]
if "@" in last_segment:
return {"id": isolation_scope, "kind": "node_run"}
return {"id": isolation_scope, "kind": "function_call"}
# Track all living plugin instances so the fork handler can reset
# them proactively in the child, before _ensure_started runs.
_LIVE_PLUGINS: weakref.WeakSet = weakref.WeakSet()
def _after_fork_in_child() -> None:
"""Reset every living plugin instance after os.fork()."""
for plugin in list(_LIVE_PLUGINS):
try:
plugin._reset_runtime_state()
except Exception:
pass
if hasattr(os, "register_at_fork"):
os.register_at_fork(after_in_child=_after_fork_in_child)
def _safe_callback(func):
"""Decorator that catches and logs exceptions in plugin callbacks.
Prevents plugin errors from propagating to the runner and crashing
the agent run. All callback exceptions are logged and swallowed.
"""
@functools.wraps(func)
async def wrapper(self, **kwargs):
try:
return await func(self, **kwargs)
except Exception:
logger.exception(
"BigQuery analytics plugin error in %s; skipping.",
func.__name__,
)
return None
return wrapper
# gRPC Error Codes
_GRPC_DEADLINE_EXCEEDED = 4
_GRPC_INTERNAL = 13
_GRPC_UNAVAILABLE = 14
# --- Helper Formatters ---
def _format_content(
content: Optional[types.Content], *, max_len: int = 5000
) -> tuple[str, bool]:
"""Formats an Event content for logging.
Args:
content: The content to format.
max_len: Maximum length for text parts.
Returns:
A tuple of (formatted_string, is_truncated).
"""
if content is None or not content.parts:
return "None", False
parts = []
truncated = False
for p in content.parts:
if p.text:
if max_len != -1 and len(p.text) > max_len:
parts.append(f"text: '{p.text[:max_len]}...'")
truncated = True
else:
parts.append(f"text: '{p.text}'")
elif p.function_call:
parts.append(f"call: {p.function_call.name}")
elif p.function_response:
parts.append(f"resp: {p.function_response.name}")
else:
parts.append("other")
return " | ".join(parts), truncated
def _find_transfer_target(agent, agent_name: str):
"""Find a transfer target agent by name in the accessible agent tree.
Searches the current agent's sub-agents, parent, and peer agents
to locate the transfer target.
Args:
agent: The current agent executing the transfer.
agent_name: The name of the transfer target to find.
Returns:
The matching agent object, or None if not found.
"""
for sub in getattr(agent, "sub_agents", []):
if sub.name == agent_name:
return sub
parent = getattr(agent, "parent_agent", None)
if parent is not None and parent.name == agent_name:
return parent
if parent is not None:
for peer in getattr(parent, "sub_agents", []):
if peer.name == agent_name and peer.name != agent.name:
return peer
return None
def _get_tool_origin(
tool: "BaseTool",
tool_args: Optional[dict[str, Any]] = None,
tool_context: Optional["ToolContext"] = None,
) -> str:
"""Returns the provenance category of a tool.
Uses lazy imports to avoid circular dependencies.
For ``TransferToAgentTool`` the classification is **call-level**: when
*tool_args* and *tool_context* are supplied the selected
``agent_name`` is resolved against the agent tree so that transfers
to a ``RemoteA2aAgent`` are labelled ``TRANSFER_A2A`` rather than
the generic ``TRANSFER_AGENT``.
Args:
tool: The tool instance.
tool_args: Optional tool arguments, used for call-level classification of
TransferToAgentTool.
tool_context: Optional tool context, used to access the agent tree for
TransferToAgentTool classification.
Returns:
One of LOCAL, MCP, A2A, SUB_AGENT, TRANSFER_AGENT,
TRANSFER_A2A, or UNKNOWN.
"""
# Import lazily to avoid circular dependencies.
# pylint: disable=g-import-not-at-top
from ..tools.agent_tool import AgentTool # pytype: disable=import-error
from ..tools.function_tool import FunctionTool # pytype: disable=import-error
from ..tools.transfer_to_agent_tool import TransferToAgentTool # pytype: disable=import-error
try:
from ..tools.mcp_tool.mcp_tool import McpTool # pytype: disable=import-error
except ImportError:
McpTool = None
try:
from ..agents.remote_a2a_agent import RemoteA2aAgent # pytype: disable=import-error
except ImportError:
RemoteA2aAgent = None
# Order matters: TransferToAgentTool is a subclass of FunctionTool.
if McpTool is not None and isinstance(tool, McpTool):
return "MCP"
if isinstance(tool, TransferToAgentTool):
if RemoteA2aAgent is not None and tool_args and tool_context:
agent_name = tool_args.get("agent_name")
if agent_name:
target = _find_transfer_target(
tool_context._invocation_context.agent,
agent_name,
)
if target is not None and isinstance(target, RemoteA2aAgent):
return "TRANSFER_A2A"
return "TRANSFER_AGENT"
if isinstance(tool, AgentTool):
if RemoteA2aAgent is not None and isinstance(tool.agent, RemoteA2aAgent):
return "A2A"
return "SUB_AGENT"
if isinstance(tool, FunctionTool):
return "LOCAL"
return "UNKNOWN"
_SENSITIVE_KEYS = frozenset({
"client_secret",
"access_token",
"refresh_token",
"id_token",
"api_key",
"password",
})
def _recursive_smart_truncate(
obj: Any, max_len: int, seen: Optional[set[int]] = None
) -> tuple[Any, bool]:
"""Recursively truncates string values within a dict or list.
Redacts sensitive keys corresponding to OAuth tokens and secrets
prior to serialization into BigQuery JSON strings.
Args:
obj: The object to truncate.
max_len: Maximum length for string values.
seen: Set of object IDs visited in the current recursion stack.
Returns:
A tuple of (truncated_object, is_truncated).
"""
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return "[CIRCULAR_REFERENCE]", False
# Track compound objects to detect cycles
is_compound = (
isinstance(obj, (dict, list, tuple))
or (dataclasses.is_dataclass(obj) and not isinstance(obj, type))
or hasattr(obj, "model_dump")
or hasattr(obj, "dict")
or hasattr(obj, "to_dict")
)
if is_compound:
seen.add(obj_id)
try:
if isinstance(obj, str):
if max_len != -1 and len(obj) > max_len:
return obj[:max_len] + "...[TRUNCATED]", True
return obj, False
elif isinstance(obj, dict):
truncated_any = False
# Use dict comprehension for potentially slightly better performance,
# but explicit loop is fine for clarity given recursive nature.
new_dict = {}
for k, v in obj.items():
if isinstance(k, str):
k_lower = k.lower()
if k_lower in _SENSITIVE_KEYS or k_lower.startswith("temp:"):
new_dict[k] = "[REDACTED]"
continue
val, trunc = _recursive_smart_truncate(v, max_len, seen)
if trunc:
truncated_any = True
new_dict[k] = val
return new_dict, truncated_any
elif isinstance(obj, (list, tuple)):
truncated_any = False
new_list = []
# Explicit loop to handle flag propagation
for i in obj:
val, trunc = _recursive_smart_truncate(i, max_len, seen)
if trunc:
truncated_any = True
new_list.append(val)
return type(obj)(new_list), truncated_any
elif dataclasses.is_dataclass(obj) and not isinstance(obj, type):
# Manually iterate fields to preserve 'seen' context, avoiding dataclasses.asdict recursion
as_dict = {f.name: getattr(obj, f.name) for f in dataclasses.fields(obj)}
return _recursive_smart_truncate(as_dict, max_len, seen)
elif hasattr(obj, "model_dump") and callable(obj.model_dump):
# Pydantic v2
try:
return _recursive_smart_truncate(obj.model_dump(), max_len, seen)
except Exception:
pass
elif hasattr(obj, "dict") and callable(obj.dict):
# Pydantic v1
try:
return _recursive_smart_truncate(obj.dict(), max_len, seen)
except Exception:
pass
elif hasattr(obj, "to_dict") and callable(obj.to_dict):
# Common pattern for custom objects
try:
return _recursive_smart_truncate(obj.to_dict(), max_len, seen)
except Exception:
pass
elif obj is None or isinstance(obj, (int, float, bool)):
# Basic types are safe
return obj, False
# Fallback for unknown types: Convert to string to ensure JSON validity
# We return string representation of the object, which is a valid JSON string value.
return str(obj), False
finally:
if is_compound:
seen.remove(obj_id)
# --- PyArrow Helper Functions ---
def _pyarrow_datetime() -> pa.DataType:
return pa.timestamp("us", tz=None)
def _pyarrow_numeric() -> pa.DataType:
return pa.decimal128(38, 9)
def _pyarrow_bignumeric() -> pa.DataType:
return pa.decimal256(76, 38)
def _pyarrow_time() -> pa.DataType:
return pa.time64("us")
def _pyarrow_timestamp() -> pa.DataType:
return pa.timestamp("us", tz="UTC")
_BQ_TO_ARROW_SCALARS = MappingProxyType({
"BOOL": pa.bool_,
"BOOLEAN": pa.bool_,
"BYTES": pa.binary,
"DATE": pa.date32,
"DATETIME": _pyarrow_datetime,
"FLOAT": pa.float64,
"FLOAT64": pa.float64,
"GEOGRAPHY": pa.string,
"INT64": pa.int64,
"INTEGER": pa.int64,
"JSON": pa.string,
"NUMERIC": _pyarrow_numeric,
"BIGNUMERIC": _pyarrow_bignumeric,
"STRING": pa.string,
"TIME": _pyarrow_time,
"TIMESTAMP": _pyarrow_timestamp,
})
_BQ_FIELD_TYPE_TO_ARROW_FIELD_METADATA = {
"GEOGRAPHY": {
b"ARROW:extension:name": b"google:sqlType:geography",
b"ARROW:extension:metadata": b'{"encoding": "WKT"}',
},
"DATETIME": {b"ARROW:extension:name": b"google:sqlType:datetime"},
"JSON": {b"ARROW:extension:name": b"google:sqlType:json"},
}
_STRUCT_TYPES = ("RECORD", "STRUCT")
def _bq_to_arrow_scalars(bq_scalar: str) -> Optional[Callable[[], pa.DataType]]:
"""Maps BigQuery scalar types to PyArrow type constructors."""
return _BQ_TO_ARROW_SCALARS.get(bq_scalar)
def _bq_to_arrow_field(bq_field: bq_schema.SchemaField) -> Optional[pa.Field]:
"""Converts a BigQuery SchemaField to a PyArrow Field."""
arrow_type = _bq_to_arrow_data_type(bq_field)
if arrow_type:
metadata = _BQ_FIELD_TYPE_TO_ARROW_FIELD_METADATA.get(
bq_field.field_type.upper() if bq_field.field_type else ""
)
nullable = bq_field.mode.upper() != "REQUIRED"
return pa.field(
bq_field.name, arrow_type, nullable=nullable, metadata=metadata
)
logger.warning(
"Could not determine Arrow type for field '%s' with type '%s'.",
bq_field.name,
bq_field.field_type,
)
return None
def _bq_to_arrow_struct_data_type(
field: bq_schema.SchemaField,
) -> Optional[pa.StructType]:
"""Converts a BigQuery RECORD/STRUCT field to a PyArrow StructType."""
arrow_fields = []
for subfield in field.fields:
arrow_subfield = _bq_to_arrow_field(subfield)
if arrow_subfield:
arrow_fields.append(arrow_subfield)
else:
logger.warning(
"Failed to convert STRUCT/RECORD field '%s' due to subfield '%s'.",
field.name,
subfield.name,
)
return None
return pa.struct(arrow_fields)
def _bq_to_arrow_data_type(
field: bq_schema.SchemaField,
) -> Optional[pa.DataType]:
"""Converts a BigQuery field to a PyArrow DataType."""
if field.mode == "REPEATED":
inner = _bq_to_arrow_data_type(
bq_schema.SchemaField(field.name, field.field_type, fields=field.fields)
)
return pa.list_(inner) if inner else None
field_type_upper = field.field_type.upper() if field.field_type else ""
if field_type_upper in _STRUCT_TYPES:
return _bq_to_arrow_struct_data_type(field)
constructor = _bq_to_arrow_scalars(field_type_upper)
if constructor:
return constructor()
else:
logger.warning(
"Failed to convert BigQuery field '%s': unsupported type '%s'.",
field.name,
field.field_type,
)
return None
def to_arrow_schema(
bq_schema_list: list[bq_schema.SchemaField],
) -> Optional[pa.Schema]:
"""Converts a list of BigQuery SchemaFields to a PyArrow Schema.
Args:
bq_schema_list: list of bigquery.SchemaField objects.
Returns:
pa.Schema or None if conversion fails.
"""
arrow_fields = []
for bq_field in bq_schema_list:
af = _bq_to_arrow_field(bq_field)
if af:
arrow_fields.append(af)
else:
logger.error("Failed to convert schema due to field '%s'.", bq_field.name)
return None
return pa.schema(arrow_fields)
# ==============================================================================
# CONFIGURATION
# ==============================================================================
@dataclass
class RetryConfig:
"""Configuration for retrying failed BigQuery write operations.
Attributes:
max_retries: Maximum number of retry attempts.
initial_delay: Initial delay between retries in seconds.
multiplier: Multiplier for exponential backoff.
max_delay: Maximum delay between retries in seconds.
"""
max_retries: int = 3
initial_delay: float = 1.0
multiplier: float = 2.0
max_delay: float = 10.0
@dataclass
class BigQueryLoggerConfig:
"""Configuration for the BigQueryAgentAnalyticsPlugin.
Attributes:
enabled: Whether logging is enabled.
event_allowlist: list of event types to log. If None, all are allowed.
event_denylist: list of event types to ignore.
max_content_length: Max length for text content before truncation.
table_id: BigQuery table ID.
clustering_fields: Fields to cluster the table by.
log_multi_modal_content: Whether to log detailed content parts.
retry_config: Retry configuration for writes.
batch_size: Number of rows per batch.
batch_flush_interval: Max time to wait before flushing a batch.
shutdown_timeout: Max time to wait for shutdown.
queue_max_size: Max size of the in-memory queue.
content_formatter: Optional custom formatter for content.
gcs_bucket_name: GCS bucket for offloading large content.
connection_id: BigQuery connection ID for ObjectRef columns.
log_session_metadata: Whether to log session metadata.
custom_tags: Static custom tags to attach to every event.
auto_schema_upgrade: Whether to auto-add new columns on schema evolution.
create_views: Whether to auto-create per-event-type views.
view_prefix: Prefix for auto-created view names. Default ``"v"`` produces
views like ``v_llm_request``. Set a distinct prefix per table when
multiple plugin instances share one dataset to avoid view-name
collisions.
"""
enabled: bool = True
# V1 Configuration Parity
event_allowlist: list[str] | None = None
event_denylist: list[str] | None = None
max_content_length: int = 500 * 1024 # Defaults to 500KB per text block
table_id: str = "agent_events"
# V2 Configuration
clustering_fields: list[str] = field(
default_factory=lambda: ["event_type", "agent", "user_id"]
)
log_multi_modal_content: bool = True
retry_config: RetryConfig = field(default_factory=RetryConfig)
batch_size: int = 1
batch_flush_interval: float = 1.0
shutdown_timeout: float = 10.0
queue_max_size: int = 10000
content_formatter: Optional[Callable[[Any, str], Any]] = None
# If provided, large content (images, audio, video, large text) will be offloaded to this GCS bucket.
gcs_bucket_name: Optional[str] = None
# If provided, this connection ID will be used as the authorizer for ObjectRef columns.
# Format: "location.connection_id" (e.g. "us.my-connection")
connection_id: Optional[str] = None
# Toggle for session metadata (e.g. gchat thread-id)
log_session_metadata: bool = True
# Static custom tags (e.g. {"agent_role": "sales"})
custom_tags: dict[str, Any] = field(default_factory=dict)
# Automatically add new columns to existing tables when the plugin
# schema evolves. Only additive changes are made (columns are never
# dropped or altered). Safe to leave enabled; a version label on the
# table ensures the diff runs at most once per schema version.
auto_schema_upgrade: bool = True
# Automatically create per-event-type BigQuery views that unnest
# JSON columns into typed, queryable columns.
create_views: bool = True
# Prefix for auto-created per-event-type view names.
# Default "v" produces views like ``v_llm_request``. Set a distinct
# prefix per table when multiple plugin instances share one dataset
# to avoid view-name collisions (e.g. ``"v_staging"`` →
# ``v_staging_llm_request``).
view_prefix: str = "v"
# ==============================================================================
# HELPER: TRACE MANAGER (Async-Safe with ContextVars)
# ==============================================================================
# NOTE: These contextvars are module-global, not plugin-instance-scoped.
# This is safe in practice for two reasons:
# 1. PluginManager enforces name-uniqueness, preventing two BQ plugin
# instances on the same Runner.
# 2. Concurrent asyncio tasks (e.g. two Runners in asyncio.gather) each
# get an isolated contextvar copy, so they don't interfere.
# The only problematic case would be two plugin instances interleaved
# within the *same* asyncio task without task boundaries — which the
# framework's PluginManager already prevents.
_root_agent_name_ctx = contextvars.ContextVar(
"_bq_analytics_root_agent_name", default=None
)
# Tracks the invocation_id that owns the current span stack so that
# ensure_invocation_span() can distinguish "same invocation re-entry"
# (idempotent) from "stale records from a previous invocation" (clear).
_active_invocation_id_ctx: contextvars.ContextVar[Optional[str]] = (
contextvars.ContextVar("_bq_analytics_active_invocation_id", default=None)
)
@dataclass
class _SpanRecord:
"""A single record on the BQAA plugin's internal span stack.
Stores the IDs and timing the plugin needs to populate BigQuery
``span_id`` / ``parent_span_id`` / ``trace_id`` / ``latency_ms``
columns. Crucially, no OpenTelemetry ``Span`` object is held.
Background — prior approach and the bug it caused:
The previous implementation created real OTel spans via
``tracer.start_span(...)`` purely as ID carriers. When the host
application has an OTel exporter configured (notably Agent Engine
with ``GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY=true``), those
plugin-owned spans were exported to Cloud Trace alongside the
framework's real spans — producing a duplicate-span view for
every BQAA-instrumented operation. See haiyuan-eng-google/BQAA-SDK#94.
The plugin already tracked all parent / child relationships on
this internal stack, so the OTel span object was incidental to
correctness. We now store ``trace_id`` directly on each record
(inherited from the ambient OTel span when present, generated
otherwise) and skip span creation entirely. Cross-system
correlation with Cloud Trace still works via ``trace_id``
inheritance.
``attach_current_span`` (which observes the ambient span without
owning one) is unaffected by this change.
"""
span_id: str
trace_id: str
owns_span: bool
start_time_ns: int
first_token_time: Optional[float] = None
_span_records_ctx: contextvars.ContextVar[list[_SpanRecord]] = (
contextvars.ContextVar("_bq_analytics_span_records", default=None)
)
class TraceManager:
"""Manages OpenTelemetry-style trace and span context using contextvars.
Uses a single stack of _SpanRecord objects to keep span, token, ID,
ownership, and timing in sync by construction.
"""
@staticmethod
def _get_records() -> list[_SpanRecord]:
"""Returns the current records stack, initializing if needed."""
records = _span_records_ctx.get()
if records is None:
records = []
_span_records_ctx.set(records)
return records
@staticmethod
def init_trace(callback_context: CallbackContext) -> None:
# Always refresh root_agent_name — it can change between
# invocations (e.g. different root agents in the same task).
try:
root_agent = callback_context._invocation_context.agent.root_agent
_root_agent_name_ctx.set(root_agent.name)
except (AttributeError, ValueError):
pass
# Ensure records stack is initialized
TraceManager._get_records()
@staticmethod
def get_trace_id(callback_context: CallbackContext) -> Optional[str]:
"""Gets the trace ID from the current span stack or invocation_id."""
records = _span_records_ctx.get()
if records:
return records[-1].trace_id
# Fallback to ambient OTel context (e.g. callbacks fired before
# any plugin span was pushed).
ambient_ctx = trace.get_current_span().get_span_context()
if ambient_ctx.is_valid:
return format(ambient_ctx.trace_id, "032x")
return callback_context.invocation_id
@staticmethod
def push_span(
callback_context: CallbackContext,
span_name: Optional[str] = "adk-span",
) -> str:
"""Pushes a BQAA-internal span record onto the stack.
No OpenTelemetry span is created — see ``_SpanRecord`` for
background. The record carries everything the plugin needs to
populate BigQuery columns:
* ``span_id`` — newly generated 16-hex string.
* ``trace_id`` — inherited by precedence:
1. Top of the existing internal stack (keeps every push
within an invocation under one trace_id).
2. Ambient OTel span when valid (e.g. the framework's Runner
span, or an Agent Engine root span) — keeps BigQuery rows
joinable to Cloud Trace via the shared ``trace_id``.
3. A fresh 32-hex value (no ambient context, e.g. unit tests
or non-OTel runtimes).
* ``start_time_ns`` — for the eventual ``latency_ms`` on pop.
``span_name`` is preserved on the signature for API stability but
is no longer used (no OTel span name is set).
"""
del span_name # No-op: kept for API stability; no OTel span is created.
TraceManager.init_trace(callback_context)
records = TraceManager._get_records()
if records:
trace_id = records[-1].trace_id
else:
ambient_ctx = trace.get_current_span().get_span_context()
if ambient_ctx.is_valid:
trace_id = format(ambient_ctx.trace_id, "032x")
else:
trace_id = uuid.uuid4().hex # 32 hex chars
span_id_str = uuid.uuid4().hex[:16]
record = _SpanRecord(
span_id=span_id_str,
trace_id=trace_id,
owns_span=True,
start_time_ns=time.time_ns(),
)
_span_records_ctx.set(list(records) + [record])
return span_id_str
@staticmethod
def attach_current_span(
callback_context: CallbackContext,
) -> str:
"""Records the ambient OTel span's IDs on the stack without owning it.
No OTel span is created or attached. This path captures the
ambient span's ``trace_id`` / ``span_id`` so plugin-emitted
BigQuery rows correlate with whatever Cloud Trace / external
exporter the host is already running.
"""
TraceManager.init_trace(callback_context)
ambient_ctx = trace.get_current_span().get_span_context()
if ambient_ctx.is_valid:
span_id_str = format(ambient_ctx.span_id, "016x")
trace_id = format(ambient_ctx.trace_id, "032x")
else:
span_id_str = uuid.uuid4().hex[:16]
trace_id = uuid.uuid4().hex
record = _SpanRecord(
span_id=span_id_str,
trace_id=trace_id,
owns_span=False,
start_time_ns=time.time_ns(),
)
records = TraceManager._get_records()
_span_records_ctx.set(list(records) + [record])
return span_id_str
@staticmethod
def ensure_invocation_span(
callback_context: CallbackContext,
) -> None:
"""Ensures a root span exists on the plugin stack for this invocation.
Must be called before any events are logged so that every event in
the invocation shares the same trace_id.
* If the stack has entries for the *current* invocation → no-op
(idempotent within the same invocation).
* If the stack has entries from a *different* invocation → clear
stale records and re-initialise (safety net for abnormal exit).
* If the ambient OTel span is valid → ``attach_current_span``
(reuse the runner's span without owning it).
* Otherwise → ``push_span("invocation")`` (create a new root
span that will be popped in ``after_run_callback``).
"""
current_inv = callback_context.invocation_id
active_inv = _active_invocation_id_ctx.get()
records = _span_records_ctx.get()
if records:
if active_inv == current_inv:
return # Already initialised for this invocation.
# Stale records from a previous invocation that wasn't cleaned
# up (e.g. exception skipped after_run_callback). Clear and
# re-init.
logger.debug(
"Clearing %d stale span records from previous invocation.",
len(records),
)
TraceManager.clear_stack()
_active_invocation_id_ctx.set(current_inv)
# Check for a valid ambient span (e.g. the Runner's invocation span).
ambient = trace.get_current_span()
if ambient.get_span_context().is_valid:
TraceManager.attach_current_span(callback_context)
else:
TraceManager.push_span(callback_context, "invocation")
@staticmethod
def pop_span() -> tuple[Optional[str], Optional[int]]:
"""Pops the top span record from the internal stack.
Returns ``(span_id, duration_ms)``. No OTel span is ended
because the plugin no longer creates one (see ``_SpanRecord``).
"""
records = _span_records_ctx.get()
if not records:
return None, None
new_records = list(records)
record = new_records.pop()
_span_records_ctx.set(new_records)
duration_ms = int((time.time_ns() - record.start_time_ns) / 1_000_000)
return record.span_id, duration_ms
@staticmethod
def clear_stack() -> None:
"""Clears all span records. Safety net for cross-invocation cleanup."""
_span_records_ctx.set([])
@staticmethod
def get_current_span_and_parent() -> tuple[Optional[str], Optional[str]]:
"""Gets current span_id and parent span_id."""
records = _span_records_ctx.get()
if not records:
return None, None
span_id = records[-1].span_id
parent_id = None
for i in range(len(records) - 2, -1, -1):
if records[i].span_id != span_id:
parent_id = records[i].span_id
break
return span_id, parent_id
@staticmethod
def get_current_span_id() -> Optional[str]:
"""Gets current span_id."""
records = _span_records_ctx.get()
if records:
return records[-1].span_id
return None
@staticmethod
def get_root_agent_name() -> Optional[str]:
return _root_agent_name_ctx.get()
@staticmethod
def get_start_time(span_id: str) -> Optional[float]:
"""Gets start time of a span by ID (seconds since epoch)."""
records = _span_records_ctx.get()
if records:
for record in reversed(records):
if record.span_id == span_id:
return record.start_time_ns / 1_000_000_000.0
return None
@staticmethod
def record_first_token(span_id: str) -> bool:
"""Records the current time as first token time if not already recorded."""
records = _span_records_ctx.get()
if records:
for record in reversed(records):
if record.span_id == span_id:
if record.first_token_time is None:
record.first_token_time = time.time()
return True
return False
return False
@staticmethod
def get_first_token_time(span_id: str) -> Optional[float]:
"""Gets the recorded first token time."""
records = _span_records_ctx.get()
if records:
for record in reversed(records):
if record.span_id == span_id:
return record.first_token_time
return None
# ==============================================================================
# HELPER: BATCH PROCESSOR
# ==============================================================================
_SHUTDOWN_SENTINEL = object()
class BatchProcessor:
"""Handles asynchronous batching and writing of events to BigQuery."""
def __init__(
self,
write_client: BigQueryWriteAsyncClient,
arrow_schema: pa.Schema,
write_stream: str,
batch_size: int,
flush_interval: float,
retry_config: RetryConfig,
queue_max_size: int,
shutdown_timeout: float,
):
"""Initializes the instance.
Args:
write_client: BigQueryWriteAsyncClient for writing rows.
arrow_schema: PyArrow schema for serialization.
write_stream: BigQuery write stream name.