Repository navigation
Expand file tree
/
Copy pathduckdb.py
More file actions
977 lines (830 loc) · 33.7 KB
/
Copy pathduckdb.py
File metadata and controls
977 lines (830 loc) · 33.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
from __future__ import annotations
import hashlib
import json
import os
from datetime import date, datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
if TYPE_CHECKING:
from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import (
IcebergSource,
)
from feast.infra.data_sources.contrib.lance.lance_source import LanceSource
from feast.infra.data_sources.mlflow.mlflow_dataset_source import (
MlflowDatasetSource,
)
import duckdb
import ibis
import pandas as pd
import pyarrow
import pyarrow as pa
import pyarrow.parquet as pq
from ibis.expr.types import Table
from pydantic import StrictStr
from feast.data_format import DeltaFormat, ParquetFormat
from feast.data_source import DataSource
from feast.errors import SavedDatasetLocationAlreadyExists
from feast.feature_logging import LoggingConfig, LoggingSource
from feast.feature_view import FeatureView
from feast.infra.offline_stores.file_source import FileSource
from feast.infra.offline_stores.ibis import (
get_historical_features_ibis,
offline_write_batch_ibis,
pull_all_from_table_or_query_ibis,
pull_latest_from_table_or_query_ibis,
write_logged_features_ibis,
)
from feast.infra.offline_stores.offline_store import OfflineStore, RetrievalJob
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 (
MONITORING_DIR,
MONITORING_PARQUET_FILES,
MONITORING_TIMESTAMP_FIELDS,
empty_categorical_metric,
empty_numeric_metric,
monitoring_parquet_meta,
normalize_monitoring_row,
opt_float,
)
from feast.repo_config import FeastConfigBaseModel, RepoConfig
def _as_lance_source(data_source: Optional[DataSource]) -> Optional["LanceSource"]:
"""Narrow a DataSource to a LanceSource, or ``None`` if it is not one.
``None`` is accepted so that a caller holding an optional source, such as
``FeatureView.batch_source``, can ask the question without narrowing first.
The import is guarded because the Lance extra is optional: a repo that does
not install it must still be able to read and write every other source
type. Only the ``isinstance`` check is guarded, never the caller's
subsequent work, so an ImportError raised by a Lance read or write itself
surfaces instead of being mistaken for "not a Lance source".
"""
try:
from feast.infra.data_sources.contrib.lance.lance_source import LanceSource
except ImportError:
return None
return data_source if isinstance(data_source, LanceSource) else None
def _read_data_source(data_source: DataSource, repo_path: str) -> Table:
from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import (
IcebergSource,
)
if isinstance(data_source, IcebergSource):
return _read_iceberg_catalog_source(data_source, repo_path)
lance_source = _as_lance_source(data_source)
if lance_source is not None:
return _read_lance_source(lance_source)
try:
from feast.infra.data_sources.mlflow.mlflow_dataset_source import (
MlflowDatasetSource,
)
if isinstance(data_source, MlflowDatasetSource):
return _read_mlflow_source(data_source)
except ImportError:
pass
assert isinstance(data_source, FileSource)
resolved_creds = data_source.resolve_credentials()
# A FileSource without a file_format is Parquet, as in the write path below,
# whether its path is a single file or a directory of Parquet files.
if data_source.file_format is None or isinstance(
data_source.file_format, ParquetFormat
):
if resolved_creds and data_source.path.startswith("s3://"):
storage_options = {
"AWS_ACCESS_KEY_ID": resolved_creds.get("AWS_ACCESS_KEY_ID", ""),
"AWS_SECRET_ACCESS_KEY": resolved_creds.get(
"AWS_SECRET_ACCESS_KEY", ""
),
}
if data_source.s3_endpoint_override:
storage_options["AWS_ENDPOINT_URL"] = data_source.s3_endpoint_override
session_token = resolved_creds.get("AWS_SESSION_TOKEN")
if session_token:
storage_options["AWS_SESSION_TOKEN"] = session_token
return ibis.read_parquet(data_source.path, storage_options=storage_options)
return ibis.read_parquet(data_source.path)
elif isinstance(data_source.file_format, DeltaFormat):
storage_options = {}
if resolved_creds:
storage_options["AWS_ACCESS_KEY_ID"] = resolved_creds.get(
"AWS_ACCESS_KEY_ID", ""
)
storage_options["AWS_SECRET_ACCESS_KEY"] = resolved_creds.get(
"AWS_SECRET_ACCESS_KEY", ""
)
session_token = resolved_creds.get("AWS_SESSION_TOKEN")
if session_token:
storage_options["AWS_SESSION_TOKEN"] = session_token
if data_source.s3_endpoint_override:
storage_options["AWS_ENDPOINT_URL"] = data_source.s3_endpoint_override
if storage_options:
return ibis.read_delta(data_source.path, storage_options=storage_options)
return ibis.read_delta(data_source.path)
raise NotImplementedError(
f"The DuckDB offline store cannot read file source '{data_source.name}' "
f"with file format {type(data_source.file_format).__name__}; only Parquet "
"and Delta are supported."
)
def _read_iceberg_catalog_source(data_source: "IcebergSource", repo_path: str) -> Table:
"""Read from an IcebergSource via PyIceberg.
Loads the table through the configured catalog (REST, SQL, Hive, etc.)
and scans it to Arrow.
"""
table = data_source.load_pyiceberg_table()
return ibis.memtable(table.scan().to_arrow())
def _load_pyiceberg_table_for_write(data_source: "IcebergSource"):
"""Load a PyIceberg table object for write operations.
Reuses the same catalog resolution logic as ``_read_iceberg_catalog_source``
but returns the raw PyIceberg table instead of an ibis memtable, so the
caller can use ``table.append()`` or ``table.overwrite()`` for writes.
"""
return data_source.load_pyiceberg_table()
def _write_iceberg_data_source(
table: Table,
data_source: "IcebergSource",
mode: str = "append",
) -> None:
"""Write an ibis table to an IcebergSource via PyIceberg.
Converts the ibis table to Arrow and uses PyIceberg's append/overwrite
API to produce proper Iceberg snapshots with catalog metadata updates.
"""
iceberg_table = _load_pyiceberg_table_for_write(data_source)
arrow_table = table.to_pyarrow()
if mode == "overwrite":
iceberg_table.overwrite(arrow_table)
else:
iceberg_table.append(arrow_table)
def _read_mlflow_source(data_source: "MlflowDatasetSource") -> Table:
"""Read tabular data from an MLflow-backed DataSource.
Delegates to ``data_source.to_arrow()`` which handles auth scoping,
caching, and mode dispatch internally. The returned PyArrow Table
is eagerly materialized before being wrapped as an ibis memtable,
avoiding any lazy-read vs temp-file-cleanup race.
"""
arrow_table = data_source.to_arrow()
return ibis.memtable(arrow_table)
def _read_lance_source(data_source: "LanceSource") -> Table:
"""Read a Lance dataset without Spark.
``LanceSource`` resolves either a uri or a ``namespace_client`` + ``table_id``
and applies the ``version``/``tag`` pin from its ``LanceFormat``, so the pin
is honoured before any data crosses into ibis. The declared-schema contract
is enforced separately, by ``validate_lance_source_schema``, because the
reader callback is handed a ``DataSource`` without its feature view.
The dataset is registered with DuckDB as a lazy scan rather than read into
memory. A ``LanceDataset`` is a ``pyarrow.dataset.Dataset``, so DuckDB pushes
the query's column projection into the Lance scanner: a retrieval that needs
a few scalar features never reads the embedding columns stored beside them.
The view is named after the dataset's location and resolved version. An
opened dataset is a snapshot, so the name always denotes the same data and
re-registering it is harmless, while a job built before a later write keeps
reading the version it was built against.
"""
dataset = data_source.get_dataset()
digest = hashlib.sha256(f"{dataset.uri}@{dataset.version}".encode()).hexdigest()
view_name = f"__feast_lance_{digest[:16]}"
backend = ibis.get_backend()
backend.con.register(view_name, dataset)
return backend.table(view_name)
def _validate_lance_feature_views(feature_views: List[FeatureView]) -> None:
"""Enforce the Lance pin contract on every Lance-backed feature view.
Runs before a retrieval plan is built. It reads schemas only, so a mismatch
is reported up front instead of surfacing as a short or mis-shaped result.
"""
try:
from feast.infra.data_sources.contrib.lance.lance_source import (
validate_lance_source_schema,
)
except ImportError:
return
for feature_view in feature_views:
validate_lance_source_schema(feature_view)
def _write_lance_data_source(
table: Table,
data_source: "LanceSource",
mode: str = "append",
allow_overwrite: bool = False,
) -> None:
"""Write an ibis table to a LanceSource without Spark.
Mirrors ``_read_lance_source``: the source resolves either a uri or a
``namespace_client`` + ``table_id``, and the same resolution is reused for
the write, so a catalog-addressed dataset is written to the location its
namespace resolves rather than to one assembled here.
How far the namespace is involved depends on the operation. Creating a table
declares it through the namespace; appending only describes the table to
resolve its location, and the version the append produces is not reported
back. A Lance namespace therefore records that a table exists and where it
lives, and does not track its versions. That is why a pin is a Lance-level
concern that ``assert_writable`` has to enforce here: no catalog is going to
reject the write on the pin's behalf.
Three things are settled before Lance is called. A pinned source is refused,
because a commit produces a new version that the pin would not read. An
absent dataset is created rather than appended to, since Lance has no
create-or-append mode. An existing dataset's vector widths are compared
against the incoming data, which closes the one case Lance itself permits
silently.
"""
import lance
from feast.infra.data_sources.contrib.lance.lance_source import (
validate_lance_write_shape,
)
data_source.assert_writable()
arrow_table = table.to_pyarrow()
existing_schema = data_source.get_existing_schema()
if existing_schema is None:
lance_mode = "create"
else:
if mode == "overwrite" and not allow_overwrite:
raise SavedDatasetLocationAlreadyExists(
location=data_source.uri or ".".join(data_source.table_id)
)
validate_lance_write_shape(arrow_table, data_source, existing_schema)
lance_mode = mode
lance.write_dataset(arrow_table, mode=lance_mode, **data_source.get_write_target())
def _write_data_source(
table: Table,
data_source: DataSource,
repo_path: str,
mode: str = "append",
allow_overwrite: bool = False,
):
from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import (
IcebergSource,
)
if isinstance(data_source, IcebergSource):
_write_iceberg_data_source(table, data_source, mode)
return
lance_source = _as_lance_source(data_source)
if lance_source is not None:
_write_lance_data_source(table, lance_source, mode, allow_overwrite)
return
assert isinstance(data_source, FileSource)
file_options = data_source.file_options
absolute_path = FileSource.get_uri_for_file_path(
repo_path=repo_path, uri=file_options.uri
)
if (
mode == "overwrite"
and not allow_overwrite
and os.path.exists(str(absolute_path))
):
raise SavedDatasetLocationAlreadyExists(location=file_options.uri)
if data_source.file_format is None or isinstance(
data_source.file_format, ParquetFormat
):
if mode == "overwrite":
table = table.to_pyarrow()
filesystem, path = FileSource.create_filesystem_and_path(
str(absolute_path),
file_options.s3_endpoint_override,
)
if path.endswith(".parquet"):
pyarrow.parquet.write_table(table, where=path, filesystem=filesystem)
else:
# otherwise assume destination is directory
pyarrow.parquet.write_to_dataset(
table, root_path=path, filesystem=filesystem
)
elif mode == "append":
table = table.to_pyarrow()
prev_table = ibis.read_parquet(file_options.uri).to_pyarrow()
if table.schema != prev_table.schema:
table = table.cast(prev_table.schema)
new_table = pyarrow.concat_tables([table, prev_table])
ibis.memtable(new_table).to_parquet(file_options.uri)
elif isinstance(data_source.file_format, DeltaFormat):
storage_options = {
"AWS_ENDPOINT_URL": str(data_source.s3_endpoint_override),
}
if mode == "append":
from deltalake import DeltaTable
prev_schema = (
DeltaTable(file_options.uri, storage_options=storage_options)
.schema()
.to_pyarrow()
)
table = table.cast(ibis.Schema.from_pyarrow(prev_schema))
write_mode = "append"
elif mode == "overwrite":
write_mode = (
"overwrite"
if allow_overwrite and os.path.exists(file_options.uri)
else "error"
)
table.to_delta(
file_options.uri, mode=write_mode, storage_options=storage_options
)
# ------------------------------------------------------------------ #
# DuckDB monitoring (Parquet-backed)
# ------------------------------------------------------------------ #
def _duckdb_monitoring_base(config: RepoConfig) -> str:
base = config.repo_path
return str(base) if base else "."
def _duckdb_monitoring_path(config: RepoConfig, filename: str) -> str:
return os.path.join(_duckdb_monitoring_base(config), MONITORING_DIR, filename)
def _duckdb_parquet_from_expression(config: RepoConfig, data_source: FileSource) -> str:
absolute_path = FileSource.get_uri_for_file_path(
repo_path=_duckdb_monitoring_base(config),
uri=data_source.file_options.uri,
)
return str(absolute_path).replace("'", "''")
def _duckdb_quote_ident(name: str) -> str:
return f'"{name}"'
def _duckdb_ts_where(ts_filter: str) -> str:
return f"({ts_filter})" if (ts_filter and ts_filter.strip()) else "1=1"
def _duckdb_numeric_stats(
conn: duckdb.DuckDBPyConnection,
from_expr: str,
feature_names: List[str],
ts_filter: str,
histogram_bins: int,
) -> List[Dict[str, Any]]:
select_parts = ["COUNT(*)"]
for col in feature_names:
q = _duckdb_quote_ident(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"PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY {c})",
f"PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY {c})",
f"PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY {c})",
f"PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY {c})",
f"PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY {c})",
]
)
tw = _duckdb_ts_where(ts_filter)
query = f"SELECT {', '.join(select_parts)} FROM {from_expr} AS _src WHERE {tw}"
row = conn.execute(query).fetchone()
if row is None:
return [empty_numeric_metric(n) for n in feature_names]
row_count = row[0]
results: List[Dict[str, Any]] = []
for i, col in enumerate(feature_names):
base = 1 + i * 10
non_null = 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,
"feature_type": "numeric",
"row_count": row_count,
"null_count": null_count,
"null_rate": null_count / row_count if row_count > 0 else 0.0,
"mean": opt_float(row[base + 1]),
"stddev": opt_float(row[base + 2]),
"min_val": min_val,
"max_val": max_val,
"p50": opt_float(row[base + 5]),
"p75": opt_float(row[base + 6]),
"p90": opt_float(row[base + 7]),
"p95": opt_float(row[base + 8]),
"p99": opt_float(row[base + 9]),
"histogram": None,
}
if min_val is not None and max_val is not None and non_null > 0:
result["histogram"] = _duckdb_numeric_histogram(
conn,
from_expr,
col,
ts_filter,
histogram_bins,
min_val,
max_val,
)
results.append(result)
return results
def _duckdb_numeric_histogram(
conn: duckdb.DuckDBPyConnection,
from_expr: str,
col_name: str,
ts_filter: str,
bins: int,
min_val: float,
max_val: float,
) -> Dict[str, Any]:
q_col = _duckdb_quote_ident(col_name)
tw = _duckdb_ts_where(ts_filter)
if min_val == max_val:
row = conn.execute(
f"SELECT COUNT(*) FROM {from_expr} AS _src "
f"WHERE {q_col} IS NOT NULL AND {tw}"
).fetchone()
cnt = row[0] if row else 0
return {"bins": [min_val, max_val], "counts": [cnt], "bin_width": 0.0}
bin_width = (max_val - min_val) / bins
query = (
f"SELECT LEAST(FLOOR((CAST({q_col} AS DOUBLE) - {min_val}) / {bin_width}) + 1, {bins}) AS bucket, "
f"COUNT(*) AS cnt "
f"FROM {from_expr} AS _src "
f"WHERE {q_col} IS NOT NULL AND {tw} "
f"GROUP BY bucket ORDER BY bucket"
)
rows = conn.execute(query).fetchall()
counts = [0] * bins
for bucket, cnt in rows:
b = int(bucket)
if 1 <= b <= bins:
counts[b - 1] = 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 _duckdb_categorical_stats(
conn: duckdb.DuckDBPyConnection,
from_expr: str,
col_name: str,
ts_filter: str,
top_n: int,
) -> Dict[str, Any]:
q_col = _duckdb_quote_ident(col_name)
tw = _duckdb_ts_where(ts_filter)
query = (
f"WITH filtered AS ("
f" SELECT * FROM {from_expr} AS _src WHERE {tw}"
f") "
f"SELECT "
f" (SELECT COUNT(*) FROM filtered) AS row_count, "
f" (SELECT COUNT(*) - COUNT({q_col}) FROM filtered) AS null_count, "
f" (SELECT COUNT(DISTINCT {q_col}) FROM filtered "
f" WHERE {q_col} IS NOT NULL) AS unique_count, "
f" CAST({q_col} AS VARCHAR) AS value, COUNT(*) AS cnt "
f"FROM filtered WHERE {q_col} IS NOT NULL "
f"GROUP BY {q_col} "
f"ORDER BY cnt DESC LIMIT {int(top_n)}"
)
rows = conn.execute(query).fetchall()
if not rows:
return empty_categorical_metric(col_name)
row_count = rows[0][0]
null_count = rows[0][1]
unique_count = rows[0][2]
top_entries = [{"value": r[3], "count": r[4]} for r in rows]
top_total = sum(e["count"] for e in top_entries)
other_count = (row_count - null_count) - top_total
return {
"feature_name": col_name,
"feature_type": "categorical",
"row_count": row_count,
"null_count": null_count,
"null_rate": null_count / row_count if row_count > 0 else 0.0,
"mean": None,
"stddev": None,
"min_val": None,
"max_val": None,
"p50": None,
"p75": None,
"p90": None,
"p95": None,
"p99": None,
"histogram": {
"values": top_entries,
"other_count": max(other_count, 0),
"unique_count": unique_count,
},
}
def _duckdb_mon_table_meta(metric_type: str):
return monitoring_parquet_meta(metric_type)
def _duckdb_read_parquet_if_exists(path: str) -> Optional[pa.Table]:
if not os.path.isfile(path):
return None
return pq.read_table(path)
def _duckdb_parquet_upsert(
path: str,
columns: List[str],
pk_cols: List[str],
new_rows: List[Dict[str, Any]],
) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
prepared: List[Dict[str, Any]] = []
for row in new_rows:
r = dict(row)
if (
"histogram" in r
and r["histogram"] is not None
and not isinstance(r["histogram"], str)
):
r["histogram"] = json.dumps(r["histogram"])
prepared.append(r)
new_df = pd.DataFrame(prepared, columns=columns)
existing = _duckdb_read_parquet_if_exists(path)
if existing is not None:
old_df = existing.to_pandas()
combined = pd.concat([old_df, new_df], ignore_index=True)
else:
combined = new_df
combined = combined.drop_duplicates(subset=pk_cols, keep="last")
table = pa.Table.from_pandas(combined, preserve_index=False)
pq.write_table(table, path)
def _duckdb_parquet_query(
path: str,
columns: List[str],
project: str,
filters: Optional[Dict[str, Any]],
start_date: Optional[date],
end_date: Optional[date],
) -> List[Dict[str, Any]]:
tab = _duckdb_read_parquet_if_exists(path)
if tab is None or tab.num_rows == 0:
return []
df = tab.to_pandas()
if project:
df = df[df["project_id"] == project]
if filters:
for key, value in filters.items():
if value is not None:
df = df[df[key] == value]
if "metric_date" in df.columns:
if start_date is not None:
df = df[df["metric_date"] >= start_date]
if end_date is not None:
df = df[df["metric_date"] <= end_date]
df = df.sort_values("metric_date", ascending=True)
else:
df = df.sort_values("job_id", ascending=True)
results = []
for _, row in df.iterrows():
record = {c: row.get(c) for c in columns}
normalize_monitoring_row(record)
for key in MONITORING_TIMESTAMP_FIELDS:
val = record.get(key)
if (
val is not None
and not isinstance(val, str)
and hasattr(val, "isoformat")
):
record[key] = val.isoformat()
results.append(record)
return results
def _duckdb_sql_from_expression(config: RepoConfig, data_source: FileSource) -> str:
p = _duckdb_parquet_from_expression(config, data_source)
if data_source.file_format is None or isinstance(
data_source.file_format, ParquetFormat
):
return f"read_parquet('{p}')"
if isinstance(data_source.file_format, DeltaFormat):
return f"delta_scan('{p}')"
raise NotImplementedError(
"DuckDB monitoring compute supports Parquet and Delta file sources only."
)
class DuckDBOfflineStoreConfig(FeastConfigBaseModel):
type: StrictStr = "duckdb"
# """ Offline store type selector"""
staging_location: Optional[str] = None
staging_location_endpoint_override: Optional[str] = None
class DuckDBOfflineStore(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,
) -> RetrievalJob:
return pull_latest_from_table_or_query_ibis(
config=config,
data_source=data_source,
join_key_columns=join_key_columns,
feature_name_columns=feature_name_columns,
timestamp_field=timestamp_field,
created_timestamp_column=created_timestamp_column,
start_date=start_date,
end_date=end_date,
data_source_reader=_read_data_source,
data_source_writer=_write_data_source,
staging_location=config.offline_store.staging_location,
staging_location_endpoint_override=config.offline_store.staging_location_endpoint_override,
)
@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,
) -> RetrievalJob:
# A Lance pin selects data, never shape: reject a pinned version whose
# schema cannot satisfy the declared schema before planning any reads.
_validate_lance_feature_views(feature_views)
return get_historical_features_ibis(
config=config,
feature_views=feature_views,
feature_refs=feature_refs,
entity_df=entity_df,
registry=registry,
project=project,
full_feature_names=full_feature_names,
data_source_reader=_read_data_source,
data_source_writer=_write_data_source,
staging_location=config.offline_store.staging_location,
staging_location_endpoint_override=config.offline_store.staging_location_endpoint_override,
filter_by_created_timestamp=filter_by_created_timestamp,
)
@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:
return pull_all_from_table_or_query_ibis(
config=config,
data_source=data_source,
join_key_columns=join_key_columns,
feature_name_columns=feature_name_columns,
timestamp_field=timestamp_field,
created_timestamp_column=created_timestamp_column,
start_date=start_date,
end_date=end_date,
data_source_reader=_read_data_source,
data_source_writer=_write_data_source,
staging_location=config.offline_store.staging_location,
staging_location_endpoint_override=config.offline_store.staging_location_endpoint_override,
)
@staticmethod
def offline_write_batch(
config: RepoConfig,
feature_view: FeatureView,
table: pyarrow.Table,
progress: Optional[Callable[[int], Any]],
):
# Checked here rather than in the writer callback, which is handed a
# DataSource and so cannot see the declared schema. Creating a Lance
# dataset whose vectors are a different width from the declared
# vector_length would otherwise succeed and fail only on the next read.
if _as_lance_source(feature_view.batch_source) is not None:
from feast.utils import _validate_vector_field_lengths
_validate_vector_field_lengths(table, feature_view)
offline_write_batch_ibis(
config=config,
feature_view=feature_view,
table=table,
progress=progress,
data_source_writer=_write_data_source,
)
@staticmethod
def write_logged_features(
config: RepoConfig,
data: Union[pyarrow.Table, Path],
source: LoggingSource,
logging_config: LoggingConfig,
registry: BaseRegistry,
):
write_logged_features_ibis(
config=config,
data=data,
source=source,
logging_config=logging_config,
registry=registry,
)
@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, DuckDBOfflineStoreConfig)
assert isinstance(data_source, FileSource)
from_expr = _duckdb_sql_from_expression(config, data_source)
ts_filter = get_timestamp_filter_sql(
start_date,
end_date,
timestamp_field,
tz=timezone.utc,
cast_style="timestamp",
date_time_separator=" ",
)
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]] = []
conn = duckdb.connect()
if numeric_features:
results.extend(
_duckdb_numeric_stats(
conn,
from_expr,
numeric_features,
ts_filter,
histogram_bins,
)
)
for col_name in categorical_features:
results.append(
_duckdb_categorical_stats(
conn,
from_expr,
col_name,
ts_filter,
top_n,
)
)
conn.close()
return results
@staticmethod
def get_monitoring_max_timestamp(
config: RepoConfig,
data_source: DataSource,
timestamp_field: str,
) -> Optional[datetime]:
assert isinstance(config.offline_store, DuckDBOfflineStoreConfig)
assert isinstance(data_source, FileSource)
from_expr = _duckdb_sql_from_expression(config, data_source)
ts_col = _duckdb_quote_ident(timestamp_field)
conn = duckdb.connect()
row = conn.execute(
f"SELECT MAX({ts_col}) AS m FROM {from_expr} AS _src"
).fetchone()
conn.close()
if row is None or row[0] is None:
return None
val = row[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 None
@staticmethod
def ensure_monitoring_tables(config: RepoConfig) -> None:
assert isinstance(config.offline_store, DuckDBOfflineStoreConfig)
base = os.path.join(_duckdb_monitoring_base(config), MONITORING_DIR)
os.makedirs(base, exist_ok=True)
tables = [
monitoring_parquet_meta(t)
for t in ("feature", "feature_view", "feature_service", "job")
]
for fname, columns, _ in tables:
path = _duckdb_monitoring_path(config, fname)
if not os.path.isfile(path):
os.makedirs(os.path.dirname(path), exist_ok=True)
pd.DataFrame(columns=columns).to_parquet(path, index=False)
@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, DuckDBOfflineStoreConfig)
fname, columns, pk = _duckdb_mon_table_meta(metric_type)
path = _duckdb_monitoring_path(config, fname)
_duckdb_parquet_upsert(path, columns, pk, 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, DuckDBOfflineStoreConfig)
fname, columns, _ = _duckdb_mon_table_meta(metric_type)
path = _duckdb_monitoring_path(config, fname)
return _duckdb_parquet_query(
path, columns, project, 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, DuckDBOfflineStoreConfig)
path = _duckdb_monitoring_path(config, MONITORING_PARQUET_FILES["feature"])
tab = _duckdb_read_parquet_if_exists(path)
if tab is None or tab.num_rows == 0:
return
df = tab.to_pandas()
mask = df["project_id"] == project
if feature_view_name is not None:
mask = mask & (df["feature_view_name"] == feature_view_name)
if feature_name is not None:
mask = mask & (df["feature_name"] == feature_name)
if data_source_type is not None:
mask = mask & (df["data_source_type"] == data_source_type)
mask = mask & (df["is_baseline"].isin([True, 1]))
df.loc[mask, "is_baseline"] = False
pq.write_table(pa.Table.from_pandas(df, preserve_index=False), path)