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
2568 lines (2252 loc) · 83.7 KB
/
bigquery_agent_analytics_plugin.py
File metadata and controls
2568 lines (2252 loc) · 83.7 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 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 context
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 ..version import __version__
from .base_plugin import BasePlugin
if TYPE_CHECKING:
from ..agents.invocation_context import InvocationContext
logger: logging.Logger = logging.getLogger("google_adk." + __name__)
tracer = trace.get_tracer(
"google.adk.plugins.bigquery_agent_analytics", __version__
)
# 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 _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.
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():
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.
"""
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"
# 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)
# ==============================================================================
# HELPER: TRACE MANAGER (Async-Safe with ContextVars)
# ==============================================================================
_root_agent_name_ctx = contextvars.ContextVar(
"_bq_analytics_root_agent_name", default=None
)
_span_stack_ctx: contextvars.ContextVar[list[trace.Span]] = (
contextvars.ContextVar("_bq_analytics_span_stack", default=None)
)
_span_token_stack_ctx: contextvars.ContextVar[list[trace.Token]] = (
contextvars.ContextVar("_bq_analytics_span_token_stack", default=None)
)
_span_first_token_times_ctx: contextvars.ContextVar[dict[str, float]] = (
contextvars.ContextVar("_bq_analytics_span_first_token_times", default=None)
)
_span_map_ctx: contextvars.ContextVar[dict[str, trace.Span]] = (
contextvars.ContextVar("_bq_analytics_span_map", default=None)
)
_span_id_stack_ctx: contextvars.ContextVar[list[str]] = contextvars.ContextVar(
"_bq_analytics_span_id_stack", default=None
)
_span_start_time_ctx: contextvars.ContextVar[dict[str, int]] = (
contextvars.ContextVar("_bq_analytics_span_start_time", default=None)
)
_span_ownership_stack_ctx: contextvars.ContextVar[list[bool]] = (
contextvars.ContextVar("_bq_analytics_span_ownership_stack", default=None)
)
class TraceManager:
"""Manages OpenTelemetry-style trace and span context using contextvars."""
@staticmethod
def init_trace(callback_context: CallbackContext) -> None:
if _root_agent_name_ctx.get() is None:
try:
root_agent = callback_context._invocation_context.agent.root_agent
_root_agent_name_ctx.set(root_agent.name)
except (AttributeError, ValueError):
pass
if _span_first_token_times_ctx.get() is None:
_span_first_token_times_ctx.set({})
if _span_map_ctx.get() is None:
_span_map_ctx.set({})
if _span_start_time_ctx.get() is None:
_span_start_time_ctx.set({})
if _span_ownership_stack_ctx.get() is None:
_span_ownership_stack_ctx.set([])
@staticmethod
def get_trace_id(callback_context: CallbackContext) -> Optional[str]:
"""Gets the trace ID from the current span or invocation_id."""
# Prefer internal stack if available
stack = _span_stack_ctx.get()
if stack:
current_span = stack[-1]
if current_span.get_span_context().is_valid:
return format(current_span.get_span_context().trace_id, "032x")
# Fallback to OTel context to satisfy "Trace Context Extraction" requirement
current_span = trace.get_current_span()
if current_span.get_span_context().is_valid:
return format(current_span.get_span_context().trace_id, "032x")
return callback_context.invocation_id
@staticmethod
def push_span(
callback_context: CallbackContext, span_name: Optional[str] = "adk-span"
) -> str:
"""Starts a new span and pushes it onto the stack.
If OTel is not configured (returning non-recording spans), a UUID fallback
is generated to ensure span_id and parent_span_id are populated in logs.
"""
# Ensure init_trace logic (root agent name) runs if needed
TraceManager.init_trace(callback_context)
span = tracer.start_span(span_name)
token = context.attach(trace.set_span_in_context(span))
stack = _span_stack_ctx.get() or []
new_stack = list(stack) + [span]
_span_stack_ctx.set(new_stack)
token_stack = _span_token_stack_ctx.get() or []
new_token_stack = list(token_stack) + [token]
_span_token_stack_ctx.set(new_token_stack)
if span.get_span_context().is_valid:
span_id_str = format(span.get_span_context().span_id, "016x")
else:
# Fallback: Generate a UUID-based ID if OTel span is invalid (NoOp)
# using 32-char hex to avoid collision, treated as string in BQ.
span_id_str = uuid.uuid4().hex
id_stack = _span_id_stack_ctx.get() or []
new_id_stack = list(id_stack) + [span_id_str]
_span_id_stack_ctx.set(new_id_stack)
span_map = _span_map_ctx.get() or {}
new_span_map = span_map.copy()
new_span_map[span_id_str] = span
_span_map_ctx.set(new_span_map)
# Record start time manually for fallback support (NoOpSpan lacks start_time)
start_times = _span_start_time_ctx.get() or {}
new_start_times = start_times.copy()
new_start_times[span_id_str] = time.time_ns()
_span_start_time_ctx.set(new_start_times)
ownership_stack = _span_ownership_stack_ctx.get() or []
new_ownership_stack = list(ownership_stack) + [True]
_span_ownership_stack_ctx.set(new_ownership_stack)
return span_id_str
@staticmethod
def attach_current_span(
callback_context: CallbackContext,
) -> str:
"""Attaches the current OTEL span to the stack without owning it."""
TraceManager.init_trace(callback_context)
# Get current span but don't start a new one
span = trace.get_current_span()
# We still need to attach it to context to keep stacks symmetric with token
token = context.attach(trace.set_span_in_context(span))
stack = _span_stack_ctx.get() or []
new_stack = list(stack) + [span]
_span_stack_ctx.set(new_stack)
token_stack = _span_token_stack_ctx.get() or []
new_token_stack = list(token_stack) + [token]
_span_token_stack_ctx.set(new_token_stack)
if span.get_span_context().is_valid:
span_id_str = format(span.get_span_context().span_id, "016x")
else:
# Fallback: Generate a UUID-based ID if OTel span is invalid (NoOp)
span_id_str = uuid.uuid4().hex
id_stack = _span_id_stack_ctx.get() or []
new_id_stack = list(id_stack) + [span_id_str]
_span_id_stack_ctx.set(new_id_stack)
span_map = _span_map_ctx.get() or {}
new_span_map = span_map.copy()
new_span_map[span_id_str] = span
_span_map_ctx.set(new_span_map)
ownership_stack = _span_ownership_stack_ctx.get() or []
new_ownership_stack = list(ownership_stack) + [False]
_span_ownership_stack_ctx.set(new_ownership_stack)
return span_id_str
@staticmethod
def pop_span() -> tuple[Optional[str], Optional[int]]:
"""Ends the current span and pops it from the stack."""
stack = _span_stack_ctx.get()
token_stack = _span_token_stack_ctx.get()
if not stack or not token_stack:
return None, None
new_stack = list(stack)
new_token_stack = list(token_stack)
span = new_stack.pop()
token = new_token_stack.pop()
_span_stack_ctx.set(new_stack)
_span_token_stack_ctx.set(new_token_stack)
# Pop from ID stack regarding fallback support
id_stack = _span_id_stack_ctx.get()
if id_stack:
new_id_stack = list(id_stack)
span_id = new_id_stack.pop()
_span_id_stack_ctx.set(new_id_stack)
else:
# Should not happen if stacks are in sync, but robust fallback:
if span.get_span_context().is_valid:
span_id = format(span.get_span_context().span_id, "016x")
else:
span_id = "unknown-id"
duration_ms = None
# Try getting start time from OTel span first, then fallback to manual tracking
if hasattr(span, "start_time") and span.start_time:
duration_ms = int((time.time_ns() - span.start_time) / 1_000_000)
else:
start_times = _span_start_time_ctx.get()
if start_times and span_id in start_times:
start_ns = start_times[span_id]
duration_ms = int((time.time_ns() - start_ns) / 1_000_000)
should_end = True
ownership_stack = _span_ownership_stack_ctx.get()
if ownership_stack:
new_ownership_stack = list(ownership_stack)
should_end = new_ownership_stack.pop()
_span_ownership_stack_ctx.set(new_ownership_stack)
if should_end:
span.end()
context.detach(token)
first_tokens = _span_first_token_times_ctx.get()
if first_tokens:
# Copy to modify
new_first_tokens = first_tokens.copy()
new_first_tokens.pop(span_id, None)
_span_first_token_times_ctx.set(new_first_tokens)
span_map = _span_map_ctx.get()
if span_map:
new_span_map = span_map.copy()
new_span_map.pop(span_id, None)
_span_map_ctx.set(new_span_map)
start_times = _span_start_time_ctx.get()
if start_times:
new_start_times = start_times.copy()
new_start_times.pop(span_id, None)
_span_start_time_ctx.set(new_start_times)
return span_id, duration_ms
@staticmethod
def get_current_span_and_parent() -> tuple[Optional[str], Optional[str]]:
"""Gets current span_id and parent span_id from OTEL context or fallback stack."""
# Use internal ID stack for robust resolution (handling both OTel and fallback IDs)
id_stack = _span_id_stack_ctx.get()
if id_stack:
span_id = id_stack[-1]
parent_id = None
# Walk backwards to find a different span_id for parent
for i in range(len(id_stack) - 2, -1, -1):
if id_stack[i] != span_id:
parent_id = id_stack[i]
break
return span_id, parent_id
return None, None
@staticmethod
def get_current_span_id() -> Optional[str]:
"""Gets current span_id from OTEL context or fallback stack."""
id_stack = _span_id_stack_ctx.get()
if id_stack:
return id_stack[-1]
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."""
# Try OTel Object first
span_map = _span_map_ctx.get()
if span_map:
span = span_map.get(span_id)
if (
span
and span.get_span_context().is_valid
and hasattr(span, "start_time")
):
return span.start_time / 1_000_000_000.0
# Fallback to manual start time
start_times = _span_start_time_ctx.get()
if start_times and span_id in start_times:
return start_times[span_id] / 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."""
first_tokens = _span_first_token_times_ctx.get()
if span_id not in first_tokens:
new_first_tokens = first_tokens.copy()
new_first_tokens[span_id] = time.time()
_span_first_token_times_ctx.set(new_first_tokens)
return True
return False
@staticmethod
def get_first_token_time(span_id: str) -> Optional[float]:
"""Gets the recorded first token time."""
first_tokens = _span_first_token_times_ctx.get()
return first_tokens.get(span_id) if first_tokens else 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.
batch_size: Number of rows per batch.
flush_interval: Max time to wait before flushing a batch.
retry_config: Retry configuration.
queue_max_size: Max size of the in-memory queue.
shutdown_timeout: Max time to wait for shutdown.
"""
self.write_client = write_client
self.arrow_schema = arrow_schema
self.write_stream = write_stream
self.batch_size = batch_size
self.flush_interval = flush_interval
self.retry_config = retry_config
self.shutdown_timeout = shutdown_timeout
self._queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(
maxsize=queue_max_size
)
self._batch_processor_task: Optional[asyncio.Task] = None
self._shutdown = False
async def flush(self) -> None:
"""Flushes the queue by waiting for it to be empty."""
if self._queue.empty():
return
# Wait for all items in the queue to be processed
await self._queue.join()
async def start(self):
"""Starts the batch writer worker task."""
if self._batch_processor_task is None:
self._batch_processor_task = asyncio.create_task(self._batch_writer())
async def append(self, row: dict[str, Any]) -> None:
"""Appends a row to the queue for batching.
Args:
row: Dictionary representing a single row.
"""
try:
self._queue.put_nowait(row)
except asyncio.QueueFull:
logger.warning("BigQuery log queue full, dropping event.")
def _prepare_arrow_batch(self, rows: list[dict[str, Any]]) -> pa.RecordBatch:
"""Prepares a PyArrow RecordBatch from a list of rows.
Args:
rows: list of row dictionaries.
Returns:
pa.RecordBatch for writing.
"""
data = {field.name: [] for field in self.arrow_schema}
for row in rows:
for field in self.arrow_schema:
value = row.get(field.name)
# JSON fields must be serialized to strings for the Arrow layer
field_metadata = self.arrow_schema.field(field.name).metadata
is_json = False
if field_metadata and b"ARROW:extension:name" in field_metadata:
if field_metadata[b"ARROW:extension:name"] == b"google:sqlType:json":
is_json = True
arrow_field_type = self.arrow_schema.field(field.name).type
is_struct = pa.types.is_struct(arrow_field_type)
is_list = pa.types.is_list(arrow_field_type)
if is_json:
if value is not None:
if isinstance(value, (dict, list)):
try:
value = json.dumps(value)
except (TypeError, ValueError):
value = str(value)
elif isinstance(value, (str, bytes)):
if isinstance(value, bytes):
try:
value = value.decode("utf-8")
except UnicodeDecodeError:
value = str(value)
# Check if it's already a valid JSON object or array to avoid double-encoding
is_already_json = False
if isinstance(value, str):
stripped = value.strip()
if stripped.startswith(("{", "[")) and stripped.endswith(
("}", "]")
):
try:
json.loads(value)
is_already_json = True
except (ValueError, TypeError):
pass
if not is_already_json:
try:
value = json.dumps(value)
except (TypeError, ValueError):
value = str(value)
# If is_already_json is True, we keep value as-is
else:
# For other types (int, float, bool), serialize to JSON equivalents
try:
value = json.dumps(value)
except (TypeError, ValueError):
value = str(value)
elif isinstance(value, (dict, list)) and not is_struct and not is_list:
if value is not None and not isinstance(value, (str, bytes)):
try:
value = json.dumps(value)
except (TypeError, ValueError):
value = str(value)
data[field.name].append(value)
return pa.RecordBatch.from_pydict(data, schema=self.arrow_schema)
async def _batch_writer(self) -> None:
"""Worker task that batches and writes rows to BigQuery."""
while not self._shutdown or not self._queue.empty():
batch = []
try:
if self._shutdown:
try:
first_item = self._queue.get_nowait()
except asyncio.QueueEmpty:
break
else:
first_item = await asyncio.wait_for(
self._queue.get(), timeout=self.flush_interval
)
if first_item is _SHUTDOWN_SENTINEL:
self._queue.task_done()
continue
batch.append(first_item)
while len(batch) < self.batch_size:
try:
item = self._queue.get_nowait()
if item is _SHUTDOWN_SENTINEL:
self._queue.task_done()
continue
batch.append(item)
except asyncio.QueueEmpty:
break
if batch:
try:
await self._write_rows_with_retry(batch)
finally:
# Mark tasks as done ONLY after processing (write attempt)
for _ in batch:
self._queue.task_done()
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
logger.info("Batch writer task cancelled.")
break
except Exception as e:
logger.error("Error in batch writer loop: %s", e, exc_info=True)
# Avoid sleeping if we are shutting down or if the task was cancelled
if not self._shutdown:
try:
await asyncio.sleep(1)
except (asyncio.CancelledError, RuntimeError):
break
else:
break
async def _write_rows_with_retry(self, rows: list[dict[str, Any]]) -> None:
"""Writes a batch of rows to BigQuery with retry logic.
Args:
rows: list of row dictionaries to write.
"""
attempt = 0
delay = self.retry_config.initial_delay
try:
arrow_batch = self._prepare_arrow_batch(rows)
serialized_schema = self.arrow_schema.serialize().to_pybytes()
serialized_batch = arrow_batch.serialize().to_pybytes()
req = bq_storage_types.AppendRowsRequest(
write_stream=self.write_stream,
trace_id=f"google-adk-bq-logger/{__version__}",
)
req.arrow_rows.writer_schema.serialized_schema = serialized_schema
req.arrow_rows.rows.serialized_record_batch = serialized_batch
except Exception as e:
logger.error(
"Failed to prepare Arrow batch (Data Loss): %s", e, exc_info=True
)
return
while attempt <= self.retry_config.max_retries:
try:
async def requests_iter():
yield req
async def perform_write():
responses = await self.write_client.append_rows(requests_iter())
async for response in responses:
error = getattr(response, "error", None)
error_code = getattr(error, "code", None)
if error_code and error_code != 0:
error_message = getattr(error, "message", "Unknown error")
logger.warning(
"BigQuery Write API returned error code %s: %s",
error_code,
error_message,
)
if error_code in [
_GRPC_DEADLINE_EXCEEDED,
_GRPC_INTERNAL,
_GRPC_UNAVAILABLE,
]:
raise ServiceUnavailable(error_message)
if "schema mismatch" in error_message.lower():
logger.error(
"BigQuery Schema Mismatch: %s. This usually means the"
" table schema does not match the expected schema.",
error_message,
)
else:
logger.error("Non-retryable BigQuery error: %s", error_message)
row_errors = getattr(response, "row_errors", [])
if row_errors:
for row_error in row_errors:
logger.error("Row error details: %s", row_error)
logger.error("Row content causing error: %s", rows)
return
return
await asyncio.wait_for(perform_write(), timeout=30.0)
return
except (
ServiceUnavailable,
TooManyRequests,
InternalServerError,
asyncio.TimeoutError,
) as e:
attempt += 1
if attempt > self.retry_config.max_retries:
logger.error(
"BigQuery Batch Dropped after %s attempts. Last error: %s",
self.retry_config.max_retries + 1,