-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathbigquery.py
More file actions
1721 lines (1550 loc) · 60.3 KB
/
Copy pathbigquery.py
File metadata and controls
1721 lines (1550 loc) · 60.3 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
import contextlib
import json
import tempfile
import uuid
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import (
Any,
Callable,
ContextManager,
Dict,
Iterator,
List,
Literal,
Optional,
Tuple,
Union,
)
import numpy as np
import pandas as pd
import pyarrow
import pyarrow.parquet
from pydantic import StrictStr, field_validator
from tenacity import Retrying, retry_if_exception_type, stop_after_delay, wait_fixed
from feast import flags_helper
from feast.data_source import DataSource
from feast.errors import (
BigQueryJobCancelled,
BigQueryJobStillRunning,
EntityDFNotDateTime,
EntitySQLEmptyResults,
FeastProviderLoginError,
InvalidEntityType,
)
from feast.feature_logging import LoggingConfig, LoggingSource
from feast.feature_view import DUMMY_ENTITY_ID, DUMMY_ENTITY_VAL, FeatureView
from feast.infra.offline_stores import offline_utils
from feast.infra.offline_stores.offline_store import (
OfflineStore,
RetrievalJob,
RetrievalMetadata,
)
from feast.infra.registry.base_registry import BaseRegistry
from feast.monitoring.monitoring_utils import (
MON_TABLE_FEATURE,
MON_TABLE_FEATURE_SERVICE,
MON_TABLE_FEATURE_VIEW,
MON_TABLE_JOB,
empty_categorical_metric,
empty_numeric_metric,
monitoring_table_meta,
normalize_monitoring_row,
opt_float,
)
from feast.on_demand_feature_view import OnDemandFeatureView
from feast.repo_config import FeastConfigBaseModel, RepoConfig
from feast.saved_dataset import SavedDatasetStorage
from feast.utils import _utc_now, get_user_agent
from .bigquery_source import (
BigQueryLoggingDestination,
BigQuerySource,
SavedDatasetBigQueryStorage,
)
from .offline_utils import get_timestamp_filter_sql
try:
from google.api_core import client_info as http_client_info
from google.api_core.exceptions import NotFound
from google.auth.exceptions import DefaultCredentialsError
from google.cloud import bigquery
from google.cloud.bigquery import Client, SchemaField, Table
from google.cloud.storage import Client as StorageClient
except ImportError as e:
from feast.errors import FeastExtrasDependencyImportError
raise FeastExtrasDependencyImportError("gcp", str(e))
try:
from google.cloud.bigquery._pyarrow_helpers import _ARROW_SCALAR_IDS_TO_BQ
except ImportError:
try:
from google.cloud.bigquery._pandas_helpers import ( # type: ignore
ARROW_SCALAR_IDS_TO_BQ as _ARROW_SCALAR_IDS_TO_BQ,
)
except ImportError as e:
raise FeastExtrasDependencyImportError("gcp", str(e))
def get_http_client_info():
return http_client_info.ClientInfo(user_agent=get_user_agent())
class BigQueryOfflineStoreConfig(FeastConfigBaseModel):
"""Offline store config for GCP BigQuery"""
type: Literal["bigquery"] = "bigquery"
""" Offline store type selector"""
dataset: StrictStr = "feast"
""" (optional) BigQuery Dataset name for temporary tables """
project_id: Optional[StrictStr] = None
""" (optional) GCP project name used for the BigQuery offline store """
billing_project_id: Optional[StrictStr] = None
""" (optional) GCP project name used to run the bigquery jobs at """
location: Optional[StrictStr] = None
""" (optional) GCP location name used for the BigQuery offline store.
Examples of location names include ``US``, ``EU``, ``us-central1``, ``us-west4``.
If a location is not specified, the location defaults to the ``US`` multi-regional location.
For more information on BigQuery data locations see: https://cloud.google.com/bigquery/docs/locations
"""
gcs_staging_location: Optional[str] = None
""" (optional) GCS location used for offloading BigQuery results as parquet files."""
table_create_disposition: Literal["CREATE_NEVER", "CREATE_IF_NEEDED"] = (
"CREATE_IF_NEEDED"
)
""" (optional) Specifies whether the job is allowed to create new tables. The default value is CREATE_IF_NEEDED.
Custom constraint for table_create_disposition. To understand more, see:
https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.create_disposition
"""
@field_validator("billing_project_id")
def project_id_exists(cls, v, values, **kwargs):
if v and not values.data["project_id"]:
raise ValueError(
"please specify project_id if billing_project_id is specified"
)
return v
class BigQueryOfflineStore(OfflineStore):
@staticmethod
def pull_latest_from_table_or_query(
config: RepoConfig,
data_source: DataSource,
join_key_columns: List[str],
feature_name_columns: List[str],
timestamp_field: str,
created_timestamp_column: Optional[str],
start_date: datetime,
end_date: datetime,
) -> RetrievalJob:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
assert isinstance(data_source, BigQuerySource)
from_expression = data_source.get_table_query_string()
partition_by_join_key_string = ", ".join(
BigQueryOfflineStore._escape_query_columns(join_key_columns)
)
if partition_by_join_key_string != "":
partition_by_join_key_string = (
"PARTITION BY " + partition_by_join_key_string
)
timestamps = [timestamp_field]
if created_timestamp_column:
timestamps.append(created_timestamp_column)
timestamp_desc_string = " DESC, ".join(timestamps) + " DESC"
field_string = ", ".join(
BigQueryOfflineStore._escape_query_columns(join_key_columns)
+ BigQueryOfflineStore._escape_query_columns(feature_name_columns)
+ timestamps
)
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
cast_style: Literal["date_func", "timestamp_func"] = (
"date_func"
if data_source.timestamp_field_type == "DATE"
else "timestamp_func"
)
timestamp_filter = get_timestamp_filter_sql(
start_date,
end_date,
timestamp_field,
date_partition_column=data_source.date_partition_column,
quote_fields=False,
cast_style=cast_style,
)
query = f"""
SELECT
{field_string}
{f", {repr(DUMMY_ENTITY_VAL)} AS {DUMMY_ENTITY_ID}" if not join_key_columns else ""}
FROM (
SELECT {field_string},
ROW_NUMBER() OVER({partition_by_join_key_string} ORDER BY {timestamp_desc_string}) AS _feast_row
FROM {from_expression}
WHERE {timestamp_filter}
)
WHERE _feast_row = 1
"""
# When materializing a single feature view, we don't need full feature names. On demand transforms aren't materialized
return BigQueryRetrievalJob(
query=query,
client=client,
config=config,
full_feature_names=False,
)
@staticmethod
def pull_all_from_table_or_query(
config: RepoConfig,
data_source: DataSource,
join_key_columns: List[str],
feature_name_columns: List[str],
timestamp_field: str,
created_timestamp_column: Optional[str] = None,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
) -> RetrievalJob:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
assert isinstance(data_source, BigQuerySource)
from_expression = data_source.get_table_query_string()
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
timestamp_fields = [timestamp_field]
if created_timestamp_column:
timestamp_fields.append(created_timestamp_column)
field_string = ", ".join(
BigQueryOfflineStore._escape_query_columns(join_key_columns)
+ BigQueryOfflineStore._escape_query_columns(feature_name_columns)
+ timestamp_fields
)
cast_style: Literal["date_func", "timestamp_func"] = (
"date_func"
if data_source.timestamp_field_type == "DATE"
else "timestamp_func"
)
timestamp_filter = get_timestamp_filter_sql(
start_date,
end_date,
timestamp_field,
date_partition_column=data_source.date_partition_column,
quote_fields=False,
cast_style=cast_style,
)
query = f"""
SELECT {field_string}
FROM {from_expression}
WHERE {timestamp_filter}
"""
return BigQueryRetrievalJob(
query=query,
client=client,
config=config,
full_feature_names=False,
)
@staticmethod
def get_historical_features(
config: RepoConfig,
feature_views: List[FeatureView],
feature_refs: List[str],
entity_df: Union[pd.DataFrame, str],
registry: BaseRegistry,
project: str,
full_feature_names: bool = False,
) -> RetrievalJob:
# TODO: Add entity_df validation in order to fail before interacting with BigQuery
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
for fv in feature_views:
assert isinstance(fv.batch_source, BigQuerySource)
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
if config.offline_store.billing_project_id:
dataset_project = str(config.offline_store.project_id)
else:
dataset_project = client.project
table_reference = _get_table_reference_for_new_entity(
client,
dataset_project,
config.offline_store.dataset,
config.offline_store.location,
config.offline_store.table_create_disposition,
)
entity_schema = _get_entity_schema(
client=client,
entity_df=entity_df,
)
entity_df_event_timestamp_col = (
offline_utils.infer_event_timestamp_from_entity_df(entity_schema)
)
entity_df_event_timestamp_range = _get_entity_df_event_timestamp_range(
entity_df,
entity_df_event_timestamp_col,
client,
)
@contextlib.contextmanager
def query_generator() -> Iterator[str]:
_upload_entity_df(
client=client,
table_name=table_reference,
entity_df=entity_df,
)
expected_join_keys = offline_utils.get_expected_join_keys(
project, feature_views, registry
)
offline_utils.assert_expected_columns_in_entity_df(
entity_schema, expected_join_keys, entity_df_event_timestamp_col
)
# Build a query context containing all information required to template the BigQuery SQL query
query_context = offline_utils.get_feature_view_query_context(
feature_refs,
feature_views,
registry,
project,
entity_df_event_timestamp_range,
)
# Generate the BigQuery SQL query from the query context
query = offline_utils.build_point_in_time_query(
query_context,
left_table_query_string=table_reference,
entity_df_event_timestamp_col=entity_df_event_timestamp_col,
entity_df_columns=entity_schema.keys(),
query_template=MULTIPLE_FEATURE_VIEW_POINT_IN_TIME_JOIN,
full_feature_names=full_feature_names,
)
try:
yield query
finally:
# Asynchronously clean up the uploaded Bigquery table, which will expire
# if cleanup fails
client.delete_table(table=table_reference, not_found_ok=True)
return BigQueryRetrievalJob(
query=query_generator,
client=client,
config=config,
full_feature_names=full_feature_names,
on_demand_feature_views=OnDemandFeatureView.get_requested_odfvs(
feature_refs, project, registry
),
metadata=RetrievalMetadata(
features=feature_refs,
keys=list(entity_schema.keys() - {entity_df_event_timestamp_col}),
min_event_timestamp=entity_df_event_timestamp_range[0],
max_event_timestamp=entity_df_event_timestamp_range[1],
),
)
@staticmethod
def write_logged_features(
config: RepoConfig,
data: Union[pyarrow.Table, Path],
source: LoggingSource,
logging_config: LoggingConfig,
registry: BaseRegistry,
):
destination = logging_config.destination
assert isinstance(destination, BigQueryLoggingDestination)
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
job_config = bigquery.LoadJobConfig(
source_format=bigquery.SourceFormat.PARQUET,
schema=arrow_schema_to_bq_schema(source.get_schema(registry)),
create_disposition=config.offline_store.table_create_disposition,
time_partitioning=bigquery.TimePartitioning(
type_=bigquery.TimePartitioningType.DAY,
field=source.get_log_timestamp_column(),
),
)
if isinstance(data, Path):
for file in data.iterdir():
with file.open("rb") as f:
client.load_table_from_file(
file_obj=f,
destination=destination.table,
job_config=job_config,
).result()
return
with tempfile.TemporaryFile() as parquet_temp_file:
# In Pyarrow v13.0, the parquet version was upgraded to v2.6 from v2.4.
# Set the coerce_timestamps to "us"(microseconds) for backward compatibility.
pyarrow.parquet.write_table(
table=data,
where=parquet_temp_file,
coerce_timestamps="us",
allow_truncated_timestamps=True,
)
parquet_temp_file.seek(0)
client.load_table_from_file(
file_obj=parquet_temp_file,
destination=destination.table,
job_config=job_config,
).result()
@staticmethod
def offline_write_batch(
config: RepoConfig,
feature_view: FeatureView,
table: pyarrow.Table,
progress: Optional[Callable[[int], Any]],
):
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
assert isinstance(feature_view.batch_source, BigQuerySource)
pa_schema, column_names = offline_utils.get_pyarrow_schema_from_batch_source(
config, feature_view.batch_source, timestamp_unit="ns"
)
if column_names != table.column_names:
raise ValueError(
f"The input pyarrow table has schema {table.schema} with the incorrect columns {table.column_names}. "
f"The schema is expected to be {pa_schema} with the columns (in this exact order) to be {column_names}."
)
if table.schema != pa_schema:
table = offline_utils.cast_arrow_table_to_schema(table, pa_schema)
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
parquet_options = bigquery.ParquetOptions()
parquet_options.enable_list_inference = True
job_config = bigquery.LoadJobConfig(
source_format=bigquery.SourceFormat.PARQUET,
schema=arrow_schema_to_bq_schema(pa_schema),
create_disposition=config.offline_store.table_create_disposition,
write_disposition="WRITE_APPEND", # Default but included for clarity
parquet_options=parquet_options,
)
with tempfile.TemporaryFile() as parquet_temp_file:
# In Pyarrow v13.0, the parquet version was upgraded to v2.6 from v2.4.
# Set the coerce_timestamps to "us"(microseconds) for backward compatibility.
pyarrow.parquet.write_table(
table=table,
where=parquet_temp_file,
coerce_timestamps="us",
allow_truncated_timestamps=True,
)
parquet_temp_file.seek(0)
client.load_table_from_file(
file_obj=parquet_temp_file,
destination=feature_view.batch_source.table,
job_config=job_config,
).result()
@staticmethod
def _escape_query_columns(columns: List[str]) -> List[str]:
return [f"`{x}`" for x in columns]
@staticmethod
def compute_monitoring_metrics(
config: RepoConfig,
data_source: DataSource,
feature_columns: List[Tuple[str, str]],
timestamp_field: str,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
histogram_bins: int = 20,
top_n: int = 10,
) -> List[Dict[str, Any]]:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
assert isinstance(data_source, BigQuerySource)
return _bq_compute_monitoring_metrics(
config,
data_source,
feature_columns,
timestamp_field,
start_date=start_date,
end_date=end_date,
histogram_bins=histogram_bins,
top_n=top_n,
)
@staticmethod
def get_monitoring_max_timestamp(
config: RepoConfig,
data_source: DataSource,
timestamp_field: str,
) -> Optional[datetime]:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
assert isinstance(data_source, BigQuerySource)
return _bq_get_monitoring_max_timestamp(config, data_source, timestamp_field)
@staticmethod
def ensure_monitoring_tables(config: RepoConfig) -> None:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
_bq_ensure_monitoring_tables(config)
@staticmethod
def save_monitoring_metrics(
config: RepoConfig,
metric_type: str,
metrics: List[Dict[str, Any]],
) -> None:
if not metrics:
return
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
_bq_save_monitoring_metrics(config, metric_type, metrics)
@staticmethod
def query_monitoring_metrics(
config: RepoConfig,
project: str,
metric_type: str,
filters: Optional[Dict[str, Any]] = None,
start_date: Optional[date] = None,
end_date: Optional[date] = None,
) -> List[Dict[str, Any]]:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
return _bq_query_monitoring_metrics(
config, project, metric_type, filters, start_date, end_date
)
@staticmethod
def clear_monitoring_baseline(
config: RepoConfig,
project: str,
feature_view_name: Optional[str] = None,
feature_name: Optional[str] = None,
data_source_type: Optional[str] = None,
) -> None:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
_bq_clear_monitoring_baseline(
config, project, feature_view_name, feature_name, data_source_type
)
# ------------------------------------------------------------------ #
# BigQuery monitoring metrics (native)
# ------------------------------------------------------------------ #
def _bq_monitoring_table_fqn(config: RepoConfig, table_name: str) -> str:
assert isinstance(config.offline_store, BigQueryOfflineStoreConfig)
project_id = config.offline_store.project_id
if not project_id:
client = _get_bigquery_client(
project=config.offline_store.billing_project_id,
location=config.offline_store.location,
)
project_id = client.project
return f"`{project_id}.{config.offline_store.dataset}.{table_name}`"
def _bq_scalar_param_type(column: str) -> str:
if column == "is_baseline":
return "BOOL"
if column == "metric_date":
return "DATE"
if column == "computed_at":
return "TIMESTAMP"
if column in {
"row_count",
"null_count",
"total_row_count",
"total_features",
"features_with_nulls",
"total_feature_views",
}:
return "INT64"
if column in {
"null_rate",
"mean",
"stddev",
"min_val",
"max_val",
"p50",
"p75",
"p90",
"p95",
"p99",
"avg_null_rate",
"max_null_rate",
}:
return "FLOAT64"
return "STRING"
def _bq_merge_row(
config: RepoConfig,
table_fqn: str,
columns: List[str],
pk_columns: List[str],
row: Dict[str, Any],
) -> None:
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
non_pk = [c for c in columns if c not in pk_columns]
params: List[Any] = []
using_parts: List[str] = []
on_parts: List[str] = []
merge_idx = 0
for col in columns:
p = f"p{merge_idx}"
merge_idx += 1
val = row.get(col)
if col == "histogram" and val is not None and not isinstance(val, str):
val = json.dumps(val)
param_type = _bq_scalar_param_type(col)
params.append(bigquery.ScalarQueryParameter(p, param_type, val))
using_parts.append(f"@{p} AS {col}")
on_parts = [f"T.{col} = S.{col}" for col in pk_columns]
update_set = ", ".join(f"{c} = S.{c}" for c in non_pk)
merge_sql = f"""
MERGE {table_fqn} T
USING (SELECT {", ".join(using_parts)}) S
ON {" AND ".join(on_parts)}
WHEN MATCHED THEN UPDATE SET {update_set}
WHEN NOT MATCHED THEN INSERT ({", ".join(columns)}) VALUES ({", ".join(f"S.{c}" for c in columns)})
"""
job_config = bigquery.QueryJobConfig(query_parameters=params)
client.query(merge_sql, job_config=job_config).result()
def _bq_save_monitoring_metrics(
config: RepoConfig,
metric_type: str,
metrics: List[Dict[str, Any]],
) -> None:
table_short, columns, pk_columns = monitoring_table_meta(metric_type)
table_fqn = _bq_monitoring_table_fqn(config, table_short)
for row in metrics:
_bq_merge_row(config, table_fqn, columns, pk_columns, row)
def _bq_query_monitoring_metrics(
config: RepoConfig,
project: str,
metric_type: str,
filters: Optional[Dict[str, Any]] = None,
start_date: Optional[date] = None,
end_date: Optional[date] = None,
) -> List[Dict[str, Any]]:
table_short, columns, _ = monitoring_table_meta(metric_type)
table_fqn = _bq_monitoring_table_fqn(config, table_short)
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
params: List[Any] = []
conditions: List[str] = []
if project:
params.append(
bigquery.ScalarQueryParameter("project", "STRING", project),
)
conditions.append("project_id = @project")
if filters:
for key, value in filters.items():
if value is not None:
conditions.append(f"`{key}` = @{key}")
params.append(
bigquery.ScalarQueryParameter(
key, _bq_scalar_param_type(key), value
)
)
if start_date:
conditions.append("metric_date >= @start_date")
params.append(bigquery.ScalarQueryParameter("start_date", "DATE", start_date))
if end_date:
conditions.append("metric_date <= @end_date")
params.append(bigquery.ScalarQueryParameter("end_date", "DATE", end_date))
col_list = ", ".join(f"`{c}`" for c in columns)
where_sql = " AND ".join(conditions) if conditions else "TRUE"
order_col = "metric_date" if "metric_date" in columns else "job_id"
sql = f"SELECT {col_list} FROM {table_fqn} WHERE {where_sql} ORDER BY `{order_col}` ASC"
job_config = bigquery.QueryJobConfig(query_parameters=params)
job = client.query(sql, job_config=job_config)
job.result()
results: List[Dict[str, Any]] = []
for r in job:
record = {columns[i]: r[i] for i in range(len(columns))}
results.append(normalize_monitoring_row(record))
return results
def _bq_clear_monitoring_baseline(
config: RepoConfig,
project: str,
feature_view_name: Optional[str] = None,
feature_name: Optional[str] = None,
data_source_type: Optional[str] = None,
) -> None:
table_fqn = _bq_monitoring_table_fqn(config, MON_TABLE_FEATURE)
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
params: List[Any] = [
bigquery.ScalarQueryParameter("project", "STRING", project),
]
conditions = ["project_id = @project", "is_baseline = TRUE"]
if feature_view_name:
conditions.append("feature_view_name = @feature_view_name")
params.append(
bigquery.ScalarQueryParameter(
"feature_view_name", "STRING", feature_view_name
)
)
if feature_name:
conditions.append("feature_name = @feature_name")
params.append(
bigquery.ScalarQueryParameter("feature_name", "STRING", feature_name)
)
if data_source_type:
conditions.append("data_source_type = @data_source_type")
params.append(
bigquery.ScalarQueryParameter(
"data_source_type", "STRING", data_source_type
)
)
sql = f"UPDATE {table_fqn} SET is_baseline = FALSE WHERE {' AND '.join(conditions)}"
job_config = bigquery.QueryJobConfig(query_parameters=params)
client.query(sql, job_config=job_config).result()
def _bq_ensure_monitoring_tables(config: RepoConfig) -> None:
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
ds = config.offline_store.dataset
proj = config.offline_store.project_id or client.project
feature_ddl = f"""
CREATE TABLE IF NOT EXISTS `{proj}.{ds}.{MON_TABLE_FEATURE}` (
project_id STRING NOT NULL,
feature_view_name STRING NOT NULL,
feature_name STRING NOT NULL,
metric_date DATE NOT NULL,
granularity STRING NOT NULL,
data_source_type STRING NOT NULL,
computed_at TIMESTAMP NOT NULL,
is_baseline BOOL NOT NULL,
feature_type STRING NOT NULL,
row_count INT64,
null_count INT64,
null_rate FLOAT64,
mean FLOAT64,
stddev FLOAT64,
min_val FLOAT64,
max_val FLOAT64,
p50 FLOAT64,
p75 FLOAT64,
p90 FLOAT64,
p95 FLOAT64,
p99 FLOAT64,
histogram STRING
)
PRIMARY KEY (project_id, feature_view_name, feature_name, metric_date, granularity, data_source_type) NOT ENFORCED
"""
view_ddl = f"""
CREATE TABLE IF NOT EXISTS `{proj}.{ds}.{MON_TABLE_FEATURE_VIEW}` (
project_id STRING NOT NULL,
feature_view_name STRING NOT NULL,
metric_date DATE NOT NULL,
granularity STRING NOT NULL,
data_source_type STRING NOT NULL,
computed_at TIMESTAMP NOT NULL,
is_baseline BOOL NOT NULL,
total_row_count INT64,
total_features INT64,
features_with_nulls INT64,
avg_null_rate FLOAT64,
max_null_rate FLOAT64
)
PRIMARY KEY (project_id, feature_view_name, metric_date, granularity, data_source_type) NOT ENFORCED
"""
service_ddl = f"""
CREATE TABLE IF NOT EXISTS `{proj}.{ds}.{MON_TABLE_FEATURE_SERVICE}` (
project_id STRING NOT NULL,
feature_service_name STRING NOT NULL,
metric_date DATE NOT NULL,
granularity STRING NOT NULL,
data_source_type STRING NOT NULL,
computed_at TIMESTAMP NOT NULL,
is_baseline BOOL NOT NULL,
total_feature_views INT64,
total_features INT64,
avg_null_rate FLOAT64,
max_null_rate FLOAT64
)
PRIMARY KEY (project_id, feature_service_name, metric_date, granularity, data_source_type) NOT ENFORCED
"""
job_ddl = f"""
CREATE TABLE IF NOT EXISTS `{proj}.{ds}.{MON_TABLE_JOB}` (
job_id STRING NOT NULL,
project_id STRING NOT NULL,
feature_view_name STRING,
job_type STRING NOT NULL,
status STRING NOT NULL,
parameters STRING,
metric_date DATE NOT NULL,
started_at TIMESTAMP,
completed_at TIMESTAMP,
error_message STRING,
result_summary STRING
)
PRIMARY KEY (job_id) NOT ENFORCED
"""
for ddl in (feature_ddl, view_ddl, service_ddl, job_ddl):
client.query(ddl).result()
def _bq_get_monitoring_max_timestamp(
config: RepoConfig,
data_source: BigQuerySource,
timestamp_field: str,
) -> Optional[datetime]:
from_expression = data_source.get_table_query_string()
ts_col = f"`{timestamp_field}`"
sql = f"SELECT MAX({ts_col}) AS _max_ts FROM {from_expression}"
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
job = client.query(sql)
job.result()
rows = list(job)
if not rows or rows[0][0] is None:
return None
val = rows[0][0]
if isinstance(val, datetime):
return val if val.tzinfo else val.replace(tzinfo=timezone.utc)
if isinstance(val, date):
return datetime.combine(val, datetime.min.time(), tzinfo=timezone.utc)
return val # type: ignore[no-any-return]
def _bq_numeric_histogram(
config: RepoConfig,
from_expression: str,
col_name: str,
ts_filter: str,
bins: int,
min_val: float,
max_val: float,
) -> Dict[str, Any]:
q_col = f"`{col_name}`"
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
if min_val == max_val:
sql = (
f"SELECT COUNT(*) AS cnt FROM {from_expression} AS _src "
f"WHERE {q_col} IS NOT NULL AND {ts_filter}"
)
job = client.query(sql)
job.result()
hrows = list(job)
cnt = int(hrows[0][0]) if hrows else 0
return {"bins": [min_val, max_val], "counts": [cnt], "bin_width": 0.0}
bin_width = (max_val - min_val) / bins
sql = f"""
SELECT
LEAST(
GREATEST(
CAST(FLOOR((CAST({q_col} AS FLOAT64) - {min_val}) / {bin_width}) AS INT64) + 1,
1
),
{bins}
) AS bucket,
COUNT(*) AS cnt
FROM {from_expression} AS _src
WHERE {q_col} IS NOT NULL AND {ts_filter}
GROUP BY bucket
ORDER BY bucket
"""
job = client.query(sql)
job.result()
rows = list(job)
counts = [0] * bins
for bucket, cnt in rows:
b = int(bucket)
if 1 <= b <= bins:
counts[b - 1] += int(cnt)
bin_edges = [min_val + i * bin_width for i in range(bins + 1)]
return {
"bins": [float(b) for b in bin_edges],
"counts": counts,
"bin_width": float(bin_width),
}
def _bq_numeric_stats(
config: RepoConfig,
from_expression: str,
feature_names: List[str],
ts_filter: str,
histogram_bins: int,
) -> List[Dict[str, Any]]:
project_id = (
config.offline_store.billing_project_id or config.offline_store.project_id
)
client = _get_bigquery_client(
project=project_id,
location=config.offline_store.location,
)
select_parts: List[str] = ["COUNT(*) AS _row_count"]
for i, col in enumerate(feature_names):
q = f"`{col}`"
c = f"CAST({q} AS FLOAT64)"
select_parts.extend(
[
f"COUNT({q}) AS c{i}_nn",
f"AVG({c}) AS c{i}_avg",
f"STDDEV_SAMP({c}) AS c{i}_stddev",
f"MIN({c}) AS c{i}_min",
f"MAX({c}) AS c{i}_max",
f"APPROX_QUANTILES({c}, 100)[OFFSET(50)] AS c{i}_p50",
f"APPROX_QUANTILES({c}, 100)[OFFSET(75)] AS c{i}_p75",
f"APPROX_QUANTILES({c}, 100)[OFFSET(90)] AS c{i}_p90",
f"APPROX_QUANTILES({c}, 100)[OFFSET(95)] AS c{i}_p95",
f"APPROX_QUANTILES({c}, 100)[OFFSET(99)] AS c{i}_p99",
]
)
query = (
f"SELECT {', '.join(select_parts)} "
f"FROM {from_expression} AS _src WHERE {ts_filter}"
)
job = client.query(query)
job.result()
rows = list(job)
if not rows:
return [empty_numeric_metric(n) for n in feature_names]
row = rows[0]
row_count = row["_row_count"] or 0
results: List[Dict[str, Any]] = []
for i, col in enumerate(feature_names):
base = f"c{i}_"
non_null = row[f"{base}nn"] or 0
null_count = int(row_count) - int(non_null)
min_v = opt_float(row[f"{base}min"])
max_v = opt_float(row[f"{base}max"])
result: Dict[str, Any] = {
"feature_name": col,
"feature_type": "numeric",
"row_count": int(row_count),