Repository navigation
Expand file tree
/
Copy pathtrino.py
More file actions
1605 lines (1438 loc) · 55.5 KB
/
Copy pathtrino.py
File metadata and controls
1605 lines (1438 loc) · 55.5 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 json
import logging
import time
import uuid
from datetime import date, datetime, timezone
from datetime import time as dt_time
from typing import (
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Tuple,
Union,
)
import numpy as np
import pandas as pd
import pyarrow
from pydantic import Field, FilePath, SecretStr, StrictBool, StrictStr, model_validator
from trino.auth import (
BasicAuthentication,
CertificateAuthentication,
JWTAuthentication,
KerberosAuthentication,
OAuth2Authentication,
)
from trino.exceptions import TrinoQueryError
from feast.data_source import DataSource
from feast.errors import InvalidEntityType
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.contrib.trino_offline_store.connectors.upload import (
upload_pandas_dataframe_to_trino,
)
from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import (
Results,
Trino,
)
from feast.infra.offline_stores.contrib.trino_offline_store.trino_source import (
SavedDatasetTrinoStorage,
TrinoSource,
)
from feast.infra.offline_stores.offline_store import (
OfflineStore,
RetrievalJob,
RetrievalMetadata,
_emit_offline_store_request_metrics,
)
from feast.infra.offline_stores.offline_utils import get_timestamp_filter_sql
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
logger = logging.getLogger(__name__)
def _complex_column_depth(trino_type: str) -> Optional[int]:
"""Array nesting depth of a row(...)/map(...) column, or None for other types."""
t = trino_type.lower().strip()
depth = 0
while t.startswith("array(") and t.endswith(")"):
t = t[len("array(") : -1].strip()
depth += 1
return depth if t.startswith(("row(", "map(")) else None
def _stringify_complex(value: Any, depth: int) -> Any:
if value is None or (isinstance(value, float) and value != value):
return None
if depth == 0:
return str(value)
return [_stringify_complex(v, depth - 1) for v in value]
class BasicAuthModel(FeastConfigBaseModel):
username: StrictStr
password: StrictStr
class KerberosAuthModel(FeastConfigBaseModel):
config: Optional[FilePath] = Field(default=None, alias="config-file")
service_name: Optional[StrictStr] = Field(default=None, alias="service-name")
mutual_authentication: StrictBool = Field(
default=False, alias="mutual-authentication"
)
force_preemptive: StrictBool = Field(default=False, alias="force-preemptive")
hostname_override: Optional[StrictStr] = Field(
default=None, alias="hostname-override"
)
sanitize_mutual_error_response: StrictBool = Field(
default=True, alias="sanitize-mutual-error-response"
)
principal: Optional[StrictStr]
delegate: StrictBool = False
ca_bundle: Optional[FilePath] = Field(default=None, alias="ca-bundle-file")
class JWTAuthModel(FeastConfigBaseModel):
token: SecretStr
class CertificateAuthModel(FeastConfigBaseModel):
cert: Optional[FilePath] = Field(default=None, alias="cert-file")
key: Optional[FilePath] = Field(default=None, alias="key-file")
CLASSES_BY_AUTH_TYPE = {
"kerberos": {
"auth_model": KerberosAuthModel,
"trino_auth": KerberosAuthentication,
},
"basic": {
"auth_model": BasicAuthModel,
"trino_auth": BasicAuthentication,
},
"jwt": {
"auth_model": JWTAuthModel,
"trino_auth": JWTAuthentication,
},
"oauth2": {
"auth_model": None,
"trino_auth": OAuth2Authentication,
},
"certificate": {
"auth_model": CertificateAuthModel,
"trino_auth": CertificateAuthentication,
},
}
class AuthConfig(FeastConfigBaseModel):
type: Literal["kerberos", "basic", "jwt", "oauth2", "certificate"]
config: Optional[Dict[StrictStr, Any]]
@model_validator(mode="after")
def config_only_nullable_for_oauth2(self):
auth_type = self.type
auth_config = self.config
if auth_type != "oauth2" and auth_config is None:
raise ValueError(f"config cannot be null for auth type '{auth_type}'")
return self
def to_trino_auth(self):
auth_type = self.type
trino_auth_cls = CLASSES_BY_AUTH_TYPE[auth_type]["trino_auth"]
if auth_type == "oauth2":
return trino_auth_cls()
model_cls = CLASSES_BY_AUTH_TYPE[auth_type]["auth_model"]
model = model_cls(**self.config)
kwargs = {
field: value.get_secret_value() if isinstance(value, SecretStr) else value
for field, value in model.model_dump().items()
}
return trino_auth_cls(**kwargs)
class TrinoOfflineStoreConfig(FeastConfigBaseModel):
"""Online store config for Trino"""
type: StrictStr = "trino"
""" Offline store type selector """
host: StrictStr
""" Host of the Trino cluster """
port: int
""" Port of the Trino cluster """
catalog: StrictStr
""" Catalog of the Trino cluster """
user: StrictStr
""" User of the Trino cluster """
source: Optional[StrictStr] = "trino-python-client"
""" ID of the feast's Trino Python client, useful for debugging """
http_scheme: Literal["http", "https"] = Field(default="http", alias="http-scheme")
""" HTTP scheme that should be used while establishing a connection to the Trino cluster """
verify: StrictBool = Field(default=True, alias="ssl-verify")
""" Whether the SSL certificate emited by the Trino cluster should be verified or not """
extra_credential: Optional[StrictStr] = Field(
default=None, alias="x-trino-extra-credential-header"
)
""" Specifies the HTTP header X-Trino-Extra-Credential, e.g. user1=pwd1, user2=pwd2 """
connector: Dict[str, str]
"""
Trino connector to use as well as potential extra parameters.
Needs to contain at least the path, for example
{"type": "bigquery"}
or
{"type": "hive", "file_format": "parquet"}
"""
dataset: StrictStr = "feast"
""" (optional) Trino Dataset name for temporary tables """
auth: Optional[AuthConfig] = None
"""
(optional) Authentication mechanism to use when connecting to Trino. Supported options are:
- kerberos
- basic
- jwt
- oauth2
- certificate
"""
streaming_batch_size: int = Field(default=200_000, gt=0)
""" Rows per cursor.fetchmany() page when streaming results via to_arrow_reader() """
class TrinoRetrievalJob(RetrievalJob):
def __init__(
self,
query: str,
client: Trino,
config: RepoConfig,
full_feature_names: bool,
on_demand_feature_views: Optional[List[OnDemandFeatureView]] = None,
metadata: Optional[RetrievalMetadata] = None,
temp_table: Optional[str] = None,
):
self._query = query
self._client = client
self._config = config
self._full_feature_names = full_feature_names
self._on_demand_feature_views = on_demand_feature_views or []
self._metadata = metadata
self._temp_table = temp_table
self._cleaned_up = False
@property
def full_feature_names(self) -> bool:
return self._full_feature_names
@property
def on_demand_feature_views(self) -> List[OnDemandFeatureView]:
return self._on_demand_feature_views
def _drop_temp_table(self) -> None:
if self._cleaned_up or not self._temp_table:
return
self._cleaned_up = True
try:
self._client.execute_query(f"DROP TABLE IF EXISTS {self._temp_table}")
except Exception:
logger.exception(
"Failed to drop temporary entity table %s",
self._temp_table,
)
def __del__(self) -> None:
self._drop_temp_table()
def _to_df_internal(self, timeout: Optional[int] = None) -> pd.DataFrame:
"""Return dataset as Pandas DataFrame synchronously including on demand transforms"""
try:
results = self._client.execute_query(query_text=self._query)
self.pyarrow_schema = results.pyarrow_schema
return results.to_dataframe()
finally:
self._drop_temp_table()
def _to_arrow_internal(self, timeout: Optional[int] = None) -> pyarrow.Table:
"""Return payrrow dataset as synchronously including on demand transforms"""
return pyarrow.Table.from_pandas(self._to_df_internal(timeout=timeout))
def to_arrow_reader(
self, timeout: Optional[int] = None, batch_size: Optional[int] = None
) -> pyarrow.RecordBatchReader:
"""Stream results page-by-page instead of fetchall() -> pandas -> Arrow.
On-demand feature views need the full table, so jobs carrying them use the
materialized default.
"""
if self.on_demand_feature_views:
return super().to_arrow_reader(timeout=timeout)
if batch_size is None:
batch_size = self._config.offline_store.streaming_batch_size
if batch_size <= 0:
raise ValueError(f"batch_size must be positive, got {batch_size}")
start_wall = time.monotonic()
query = self._client.create_query(self._query)
try:
columns = query.start()
schema = Results(data=[], columns=columns).pyarrow_schema
except Exception:
query.close()
self._drop_temp_table()
_emit_offline_store_request_metrics(
job=self,
method="to_arrow_reader",
status_label="error",
row_count=0,
elapsed=time.monotonic() - start_wall,
)
raise
# The type map declares row(...)/map(...) as strings; the cursor returns objects.
complex_depth = {
c["name"]: depth
for c in columns
if (depth := _complex_column_depth(c["type"])) is not None
}
def _batches() -> Iterator[pyarrow.RecordBatch]:
row_count = 0
completed = False
try:
for page in query.iterate_pages(batch_size):
df = page.to_dataframe()
for name, depth in complex_depth.items():
df[name] = df[name].map(
lambda v, depth=depth: _stringify_complex(v, depth)
)
page_table = pyarrow.Table.from_pandas(df, schema=schema)
for batch in page_table.to_batches():
row_count += batch.num_rows
yield batch
completed = True
finally:
self._drop_temp_table()
_emit_offline_store_request_metrics(
job=self,
method="to_arrow_reader",
status_label="success" if completed else "error",
row_count=row_count,
elapsed=time.monotonic() - start_wall,
)
return pyarrow.RecordBatchReader.from_batches(schema, _batches())
def to_sql(self) -> str:
"""Returns the SQL query that will be executed in Trino to build the historical feature table"""
return self._query
def to_trino(
self,
destination_table: Optional[str] = None,
timeout: int = 1800,
retry_cadence: int = 10,
) -> Optional[str]:
"""
Triggers the execution of a historical feature retrieval query and exports the results to a Trino table.
Runs for a maximum amount of time specified by the timeout parameter (defaulting to 30 minutes).
Args:
timeout: An optional number of seconds for setting the time limit of the QueryJob.
retry_cadence: An optional number of seconds for setting how long the job should checked for completion.
Returns:
Returns the destination table name.
"""
if not destination_table:
today = date.today().strftime("%Y%m%d")
rand_id = str(uuid.uuid4())[:7]
destination_table = f"{self._client.catalog}.{self._config.offline_store.dataset}.historical_{today}_{rand_id}"
# TODO: Implement the timeout logic
try:
create_query = f"CREATE TABLE {destination_table} AS ({self._query})"
self._client.execute_query(query_text=create_query)
finally:
self._drop_temp_table()
return destination_table
def persist(
self,
storage: SavedDatasetStorage,
allow_overwrite: Optional[bool] = False,
timeout: Optional[int] = None,
):
"""
Run the retrieval and persist the results in the same offline store used for read.
"""
if not isinstance(storage, SavedDatasetTrinoStorage):
raise ValueError(
f"The storage object is not a `SavedDatasetTrinoStorage` but is instead a {type(storage)}"
)
self.to_trino(destination_table=storage.trino_options.table)
@property
def metadata(self) -> Optional[RetrievalMetadata]:
"""
Return metadata information about retrieval.
Should be available even before materializing the dataset itself.
"""
return self._metadata
class TrinoOfflineStore(OfflineStore):
supports_filter_by_created_timestamp = True
@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,
) -> TrinoRetrievalJob:
assert isinstance(config.offline_store, TrinoOfflineStoreConfig)
assert isinstance(data_source, TrinoSource)
from_expression = data_source.get_table_query_string()
partition_by_join_key_string = ", ".join(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(join_key_columns + feature_name_columns + timestamps)
client = _get_trino_client(config=config)
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_field} BETWEEN TIMESTAMP '{start_date}' AND TIMESTAMP '{end_date}'
)
WHERE _feast_row = 1
"""
# When materializing a single feature view, we don't need full feature names. On demand transforms aren't materialized
return TrinoRetrievalJob(
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,
filter_by_created_timestamp: bool = False,
) -> TrinoRetrievalJob:
assert isinstance(config.offline_store, TrinoOfflineStoreConfig)
for fv in feature_views:
assert isinstance(fv.batch_source, TrinoSource)
client = _get_trino_client(config=config)
table_reference = _get_table_reference_for_new_entity(
catalog=config.offline_store.catalog,
dataset_name=config.offline_store.dataset,
)
entity_schema = _upload_entity_df_and_get_entity_schema(
client=client,
table_name=table_reference,
entity_df=entity_df,
connector=config.offline_store.connector,
)
entity_df_event_timestamp_col = (
offline_utils.infer_event_timestamp_from_entity_df(
entity_schema=entity_schema
)
)
entity_df_event_timestamp_range = _get_entity_df_event_timestamp_range(
entity_df=entity_df,
entity_df_event_timestamp_col=entity_df_event_timestamp_col,
client=client,
)
expected_join_keys = offline_utils.get_expected_join_keys(
project=project, feature_views=feature_views, registry=registry
)
offline_utils.assert_expected_columns_in_entity_df(
entity_schema=entity_schema,
join_keys=expected_join_keys,
entity_df_event_timestamp_col=entity_df_event_timestamp_col,
)
# Build a query context containing all information required to template the Trino SQL query
query_context = offline_utils.get_feature_view_query_context(
feature_refs=feature_refs,
feature_views=feature_views,
registry=registry,
project=project,
entity_df_timestamp_range=entity_df_event_timestamp_range,
)
# Generate the Trino SQL query from the query context
entity_table_ref = table_reference
if type(entity_df) is str:
entity_table_ref = f"({entity_df})"
query = offline_utils.build_point_in_time_query(
query_context,
left_table_query_string=entity_table_ref,
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,
filter_by_created_timestamp=filter_by_created_timestamp,
)
return TrinoRetrievalJob(
query=query,
temp_table=table_reference if isinstance(entity_df, pd.DataFrame) else None,
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(set(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 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, TrinoOfflineStoreConfig)
assert isinstance(data_source, TrinoSource)
from_expression = data_source.get_table_query_string()
client = _get_trino_client(config=config)
timestamp_fields = [timestamp_field]
if created_timestamp_column:
timestamp_fields.append(created_timestamp_column)
field_string = ", ".join(
join_key_columns + feature_name_columns + timestamp_fields
)
timestamp_filter = get_timestamp_filter_sql(
start_date,
end_date,
timestamp_field,
quote_fields=False,
cast_style="timestamp",
date_time_separator=" ",
)
query = f"""
SELECT {field_string}
FROM ( {from_expression} )
WHERE {timestamp_filter}
"""
return TrinoRetrievalJob(
query=query,
client=client,
config=config,
full_feature_names=False,
)
@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, TrinoOfflineStoreConfig)
assert isinstance(data_source, TrinoSource)
client = _get_trino_client(config=config)
from_expression = data_source.get_table_query_string()
ts_filter = get_timestamp_filter_sql(
start_date,
end_date,
timestamp_field,
tz=timezone.utc,
cast_style="timestamp",
date_time_separator=" ",
quote_fields=False,
)
ts_clause = ts_filter if ts_filter else "1=1"
numeric_features = [n for n, t in feature_columns if t == "numeric"]
categorical_features = [n for n, t in feature_columns if t == "categorical"]
results: List[Dict[str, Any]] = []
if numeric_features:
results.extend(
_trino_sql_numeric_stats(
client,
from_expression,
numeric_features,
ts_clause,
histogram_bins,
)
)
for col_name in categorical_features:
results.append(
_trino_sql_categorical_stats(
client,
from_expression,
col_name,
ts_clause,
top_n,
)
)
return results
@staticmethod
def get_monitoring_max_timestamp(
config: RepoConfig,
data_source: DataSource,
timestamp_field: str,
) -> Optional[datetime]:
assert isinstance(config.offline_store, TrinoOfflineStoreConfig)
assert isinstance(data_source, TrinoSource)
client = _get_trino_client(config=config)
from_expression = data_source.get_table_query_string()
q_ts = f'"{timestamp_field}"'
sql = f"SELECT MAX({q_ts}) AS max_ts FROM ({from_expression}) AS _src"
results = client.execute_query(sql)
rows = results.data
if not rows or rows[0] is None 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, dt_time.min, tzinfo=timezone.utc)
return pd.to_datetime(val, utc=True).to_pydatetime()
@staticmethod
def ensure_monitoring_tables(config: RepoConfig) -> None:
assert isinstance(config.offline_store, TrinoOfflineStoreConfig)
client = _get_trino_client(config=config)
catalog = config.offline_store.catalog
dataset = config.offline_store.dataset
if dataset:
try:
client.execute_query(f"CREATE SCHEMA IF NOT EXISTS {catalog}.{dataset}")
except TrinoQueryError as e:
logger.debug(
"Schema %s.%s creation skipped or failed: %s",
catalog,
dataset,
e,
)
with_clause = _trino_table_with_clause(config)
for ddl_template, tbl_name in zip(
_TRINO_MONITORING_DDL_STATEMENTS,
[
MON_TABLE_FEATURE,
MON_TABLE_FEATURE_VIEW,
MON_TABLE_FEATURE_SERVICE,
MON_TABLE_JOB,
],
):
full_table = _trino_monitoring_table_name(config, tbl_name)
stmt = ddl_template.format(
table=full_table,
with_clause=with_clause,
)
client.execute_query(stmt)
for tbl in (
MON_TABLE_FEATURE,
MON_TABLE_FEATURE_VIEW,
MON_TABLE_FEATURE_SERVICE,
):
full_table = _trino_monitoring_table_name(config, tbl)
try:
client.execute_query(
f"ALTER TABLE {full_table} ADD COLUMN max_event_timestamp TIMESTAMP"
)
except TrinoQueryError as e:
if (
e.error_name in ("COLUMN_ALREADY_EXISTS", "NOT_SUPPORTED")
or "already exists" in (e.message or "").lower()
):
logger.debug(
"Column max_event_timestamp already exists or unsupported on %s: %s",
full_table,
e,
)
else:
logger.debug(
"Failed to add column max_event_timestamp to %s: %s",
full_table,
e,
)
raise
@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, TrinoOfflineStoreConfig)
table, columns, _ = monitoring_table_meta(metric_type)
full_table_name = _trino_monitoring_table_name(config, table)
pdf_new = pd.DataFrame([{c: m.get(c) for c in columns} for m in metrics])
pdf_new = _trino_normalize_histogram_column(pdf_new)
client = _get_trino_client(config=config)
_trino_insert_monitoring_metrics(
client=client,
config=config,
table_name=table,
full_table_name=full_table_name,
df=pdf_new,
columns=columns,
)
@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, TrinoOfflineStoreConfig)
table, columns, pk_columns = monitoring_table_meta(metric_type)
full_table_name = _trino_monitoring_table_name(config, table)
client = _get_trino_client(config=config)
conditions: List[str] = []
if project:
conditions.append(f'"project_id" = {_trino_sql_literal(project)}')
if filters:
for key, value in filters.items():
if value is not None:
conditions.append(f'"{key}" = {_trino_sql_literal(value)}')
if start_date is not None:
conditions.append(
f"\"metric_date\" >= DATE '{start_date.strftime('%Y-%m-%d')}'"
)
if end_date is not None:
conditions.append(
f"\"metric_date\" <= DATE '{end_date.strftime('%Y-%m-%d')}'"
)
where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else ""
order_col = '"metric_date"' if metric_type != "job" else '"job_id"'
cols_str = ", ".join(f'"{c}"' for c in columns)
query = f"SELECT {cols_str} FROM {full_table_name} {where_clause} ORDER BY {order_col}"
try:
results = client.execute_query(query)
df = results.to_dataframe()
if df.empty:
return []
if "computed_at" in df.columns:
pk_cols = [c for c in pk_columns if c in df.columns]
order_col_name = order_col.strip('"')
df = df.sort_values("computed_at").drop_duplicates(
subset=pk_cols, keep="last"
)
if order_col_name in df.columns:
df = df.sort_values(order_col_name)
return [normalize_monitoring_row(row.to_dict()) for _, row in df.iterrows()]
except TrinoQueryError as e:
if e.error_name in ("TABLE_NOT_FOUND", "SCHEMA_NOT_FOUND"):
# The monitoring table has not been created yet: no metrics so far.
logger.debug(
"Monitoring metrics table %s does not exist yet: %s",
full_table_name,
e,
)
return []
logger.debug(
"Failed to query monitoring metrics from %s: %s",
full_table_name,
e,
)
raise
@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, TrinoOfflineStoreConfig)
table, columns, _ = monitoring_table_meta("feature")
full_table_name = _trino_monitoring_table_name(config, table)
client = _get_trino_client(config=config)
conditions = [
f'"project_id" = {_trino_sql_literal(project)}',
'"is_baseline" = TRUE',
]
if feature_view_name is not None:
conditions.append(
f'"feature_view_name" = {_trino_sql_literal(feature_view_name)}'
)
if feature_name is not None:
conditions.append(f'"feature_name" = {_trino_sql_literal(feature_name)}')
if data_source_type is not None:
conditions.append(
f'"data_source_type" = {_trino_sql_literal(data_source_type)}'
)
update_sql = f'UPDATE {full_table_name} SET "is_baseline" = FALSE WHERE {" AND ".join(conditions)}'
try:
client.execute_query(update_sql)
except TrinoQueryError as e:
logger.debug(
"In-place UPDATE not supported on %s, falling back to rewrite: %s",
full_table_name,
e,
)
# Fallback for append-only connectors that do not support in-place UPDATE (e.g. Hive/Memory without ACID)
_trino_rewrite_clear_baseline(
client=client,
config=config,
table_name=table,
full_table_name=full_table_name,
columns=columns,
conditions=conditions,
)
def _trino_monitoring_table_name(config: RepoConfig, table: str) -> str:
catalog = config.offline_store.catalog
dataset = config.offline_store.dataset
if dataset:
return f"{catalog}.{dataset}.{table}"
return f"{catalog}.{table}"
def _trino_table_with_clause(config: RepoConfig) -> str:
connector_args = config.offline_store.connector or {}
connector_type = connector_args.get("type", "")
if connector_type in {"hive", "iceberg"}:
file_format = connector_args.get("file_format", "parquet")
return f"WITH (format = '{file_format}')"
return ""
def _trino_normalize_histogram_column(pdf: pd.DataFrame) -> pd.DataFrame:
if "histogram" not in pdf.columns:
return pdf
out = pdf.copy()
def _ser(x: Any) -> Any:
if x is None:
return None
if isinstance(x, str):
return x
return json.dumps(x)
out["histogram"] = out["histogram"].map(_ser)
return out
def _trino_pandas_upsert(
pdf_old: pd.DataFrame,
pdf_new: pd.DataFrame,
pk_columns: List[str],
) -> pd.DataFrame:
if pdf_old.empty:
return pdf_new
pk_cols_present = [
c for c in pk_columns if c in pdf_old.columns and c in pdf_new.columns
]
if not pk_cols_present:
return pd.concat([pdf_old, pdf_new], ignore_index=True)
old_idx = pdf_old.set_index(pk_cols_present)
new_idx = pdf_new.set_index(pk_cols_present)
kept = old_idx.loc[~old_idx.index.isin(new_idx.index)]
kept_df = kept.reset_index()
return pd.concat([kept_df, pdf_new], ignore_index=True)
def _trino_sql_literal(val: Any) -> str:
if val is None or pd.isna(val):
return "NULL"
if isinstance(val, (bool, np.bool_)):
return "TRUE" if val else "FALSE"
if isinstance(val, (int, float, np.integer, np.floating)):
return str(val)
if isinstance(val, (datetime, pd.Timestamp)):
if val.tzinfo is not None and val.tzinfo.utcoffset(val) is not None:
val = val.astimezone(timezone.utc)
return f"TIMESTAMP '{val.strftime('%Y-%m-%d %H:%M:%S.%f')}'"
if isinstance(val, np.datetime64):
val = pd.Timestamp(val)
if val.tzinfo is not None and val.tzinfo.utcoffset(val) is not None:
val = val.astimezone(timezone.utc)
return f"TIMESTAMP '{val.strftime('%Y-%m-%d %H:%M:%S.%f')}'"
if isinstance(val, date):
return f"DATE '{val.strftime('%Y-%m-%d')}'"
escaped = str(val).replace("'", "''")
return f"'{escaped}'"
def _trino_sql_numeric_stats(
client: Trino,
from_expression: str,
feature_names: List[str],
ts_clause: str,
histogram_bins: int,
) -> List[Dict[str, Any]]:
select_parts = ["COUNT(*)"]
for col in feature_names:
q = f'"{col}"'
c = f"CAST({q} AS DOUBLE)"
select_parts.extend(
[
f"COUNT({q})",
f"AVG({c})",
f"STDDEV_SAMP({c})",
f"MIN({c})",
f"MAX({c})",
f"APPROX_PERCENTILE({c}, 0.50)",
f"APPROX_PERCENTILE({c}, 0.75)",
f"APPROX_PERCENTILE({c}, 0.90)",
f"APPROX_PERCENTILE({c}, 0.95)",
f"APPROX_PERCENTILE({c}, 0.99)",
]
)
query = (
f"SELECT {', '.join(select_parts)} "
f"FROM ({from_expression}) AS _src WHERE {ts_clause}"
)
results = client.execute_query(query)
rows = results.data
if not rows or rows[0] is None or rows[0][0] is None:
return [empty_numeric_metric(n) for n in feature_names]
row = rows[0]
row_count = int(row[0] or 0)
metric_results: List[Dict[str, Any]] = []
for i, col in enumerate(feature_names):
base = 1 + i * 10
non_null = int(row[base] or 0)
null_count = row_count - non_null
min_val = opt_float(row[base + 3])
max_val = opt_float(row[base + 4])
result: Dict[str, Any] = {
"feature_name": col,