GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — feast/sdk/python/feast/feature_store.py at master · feast-dev/feast Expand file tree/ Copy pathfeature_store.pyMore file actions 5266 lines (4614 loc) · 207 KB / Copy pathfeature_store.pyFile metadata and controls5266 lines (4614 loc) · 207 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 # Copyright 2019 The Feast Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import copy import itertools import logging import os import time import warnings from contextvars import ContextVar from dataclasses import dataclass, field from datetime import datetime, timedelta from pathlib import Path from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union, cast, ) if TYPE_CHECKING: from feast.diff.apply_progress import ApplyProgressContext from feast.embedder import EmbeddingProvider import pandas as pd import pyarrow as pa from colorama import Fore, Style from fastapi.concurrency import run_in_threadpool from google.protobuf.timestamp_pb2 import Timestamp from tqdm import tqdm from feast import feature_server, flags_helper, ui_server, utils from feast.base_feature_view import BaseFeatureView from feast.batch_feature_view import BatchFeatureView from feast.data_source import ( DataSource, KafkaSource, KinesisSource, PushMode, PushSource, ) from feast.diff.infra_diff import InfraDiff, diff_infra_protos from feast.diff.registry_diff import RegistryDiff, apply_diff_to_registry, diff_between from feast.dqm.errors import ValidationFailed from feast.entity import Entity from feast.errors import ( ConflictingFeatureViewNames, DataFrameSerializationError, DataSourceRepeatNamesException, FeatureViewNotFoundException, PushSourceNotFoundException, RequestDataNotFoundInEntityDfException, ) from feast.feast_object import FeastObject from feast.feature_service import FeatureService from feast.feature_view import ( DUMMY_ENTITY, DUMMY_ENTITY_ID, DUMMY_ENTITY_NAME, FeatureView, FeatureViewState, ) from feast.filter_models import ComparisonFilter, CompoundFilter, convert_dict_to_filter from feast.inference import ( update_data_sources_with_inferred_event_timestamp_col, update_feature_views_with_inferred_features_and_entities, ) from feast.infra.infra_object import Infra from feast.infra.offline_stores.offline_utils import ( DEFAULT_ENTITY_DF_EVENT_TIMESTAMP_COL, ) from feast.infra.provider import Provider, RetrievalJob, get_provider from feast.infra.registry.base_registry import BaseRegistry from feast.infra.registry.registry import Registry from feast.infra.registry.sql import SqlRegistry from feast.labeling.label_view import LabelView from feast.on_demand_feature_view import OnDemandFeatureView from feast.online_response import OnlineResponse from feast.permissions.permission import Permission from feast.project import Project from feast.protos.feast.serving.ServingService_pb2 import ( FieldStatus, GetOnlineFeaturesResponse, ) from feast.protos.feast.types.EntityKey_pb2 import EntityKey from feast.protos.feast.types.Value_pb2 import RepeatedValue, Value from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import RepoConfig, load_repo_config from feast.repo_contents import RepoContents from feast.saved_dataset import SavedDataset, SavedDatasetStorage, ValidationReference from feast.ssl_ca_trust_store_setup import configure_ca_trust_store_env_variables from feast.stream_feature_view import StreamFeatureView from feast.transformation.pandas_transformation import PandasTransformation from feast.transformation.python_transformation import PythonTransformation from feast.utils import ( _distance_to_score, _get_feature_view_vector_field_metadata, _utc_now, ) from feast.value_type import ValueType from feast.vector_store_utils import feature_view_to_vs_id from feast.version_utils import parse_version try: from datetime import timezone as _timezone except ImportError: _timezone = None # type: ignore[assignment,misc] _track_materialization = None # Lazy-loaded on first materialization call _track_materialization_loaded = False _logger = logging.getLogger(__name__) def _get_track_materialization(): """Lazy-import feast.metrics only when materialization tracking is needed. Avoids importing the metrics module (and its prometheus_client / psutil dependencies plus temp-dir creation) for every FeatureStore usage such as ``feast apply`` or simple SDK reads. """ global _track_materialization, _track_materialization_loaded if not _track_materialization_loaded: _track_materialization_loaded = True try: from feast.metrics import track_materialization _track_materialization = track_materialization except Exception: # pragma: no cover _track_materialization = None return _track_materialization warnings.simplefilter("once", DeprecationWarning) _UNSET = object() @dataclass class _MaterializationDateRange: """Per-batch start dates plus shared end date for materialization watermarks.""" end_date: datetime fv_start_dates: dict = field(default_factory=dict) class FeatureStore: """ A FeatureStore object is used to define, create, and retrieve features. Attributes: config: The config for the feature store. repo_path: The path to the feature repo. _registry: The registry for the feature store. _provider: The provider for the feature store. _openlineage_emitter: Optional OpenLineage emitter for lineage tracking. """ config: RepoConfig repo_path: Path _registry: Optional[BaseRegistry] _provider: Optional[Provider] _openlineage_emitter: Optional[Any] = None _embedding_provider: Optional["EmbeddingProvider"] _feature_service_cache: Dict[str, List[str]] def __init__( self, repo_path: Optional[str] = None, config: Optional[RepoConfig] = None, fs_yaml_file: Optional[Path] = None, embedding_provider: Optional["EmbeddingProvider"] = None, ): """ Creates a FeatureStore object. Args: repo_path (optional): Path to the feature repo. Defaults to the current working directory. config (optional): Configuration object used to configure the feature store. fs_yaml_file (optional): Path to the `feature_store.yaml` file used to configure the feature store. At most one of 'fs_yaml_file' and 'config' can be set. embedding_provider (optional): Custom embedding provider implementing the :class:`~feast.embedder.EmbeddingProvider` protocol. When not supplied, a :class:`~feast.embedder.SentenceTransformersEmbeddingProvider` is created from ``embedding_model`` in ``feature_store.yaml``. Raises: ValueError: If both or neither of repo_path and config are specified. """ if fs_yaml_file is not None and config is not None: raise ValueError("You cannot specify both fs_yaml_file and config.") configure_ca_trust_store_env_variables() if repo_path: self.repo_path = Path(repo_path) else: self.repo_path = Path(os.getcwd()) # If config is specified, or fs_yaml_file is specified, those take precedence over # the default feature_store.yaml location under repo_path. if config is not None: self.config = config elif fs_yaml_file is not None: self.config = load_repo_config(self.repo_path, fs_yaml_file) else: self.config = load_repo_config( self.repo_path, utils.get_default_yaml_file_path(self.repo_path) ) # Initialize lazy-loaded components as None self._registry = None self._provider = None self._openlineage_emitter = None self._current_project: ContextVar[Optional[str]] = ContextVar( "current_project", default=None ) self._embedding_provider = embedding_provider # Initialize feature service cache for performance optimization self._feature_service_cache = {} # Cache for _resolve_feature_service_name lookups self._fs_name_cache: Dict[frozenset, Optional[str]] = {} self._fs_name_index: Dict[frozenset, str] = {} self._fs_name_index_ts: float = -self._FS_NAME_INDEX_TTL_SECONDS self._mlflow_client: Any = _UNSET def _init_mlflow(self) -> Optional[Any]: """Bootstrap MLflow integration on first access. Checks the config, imports the module, and creates the integration client. Returns the client or ``None`` if MLflow is disabled or unavailable. """ try: mlflow_cfg = getattr(self.config, "mlflow", None) if mlflow_cfg is None or not mlflow_cfg.enabled: return None from feast.mlflow import _register_store _register_store(self) from feast.mlflow_integration.client import FeastMlflowClient return FeastMlflowClient(self) except ImportError: return None except Exception as e: warnings.warn(f"Failed to configure MLflow tracking: {e}") return None @property def mlflow(self) -> Any: """Access the Feast–MLflow integration client. Lazily initializes on first access. Returns ``None`` when MLflow integration is not enabled, allowing callers to guard with ``if store.mlflow:``. """ if self._mlflow_client is _UNSET: self._mlflow_client = self._init_mlflow() return self._mlflow_client @staticmethod def _count_entities(entity_rows: Any) -> int: """Count entities from either a list or columnar mapping.""" if isinstance(entity_rows, list): return len(entity_rows) if isinstance(entity_rows, Mapping): try: _first_col = next(iter(entity_rows.values())) if isinstance(_first_col, RepeatedValue): return len(_first_col.val) return len(_first_col) except Exception: return 0 return 0 _FS_NAME_INDEX_TTL_SECONDS = 300 def _rebuild_fs_name_index(self) -> None: """Rebuild the {frozenset(refs) → service_name} index from the registry.""" index: Dict[frozenset, str] = {} for fs in self.registry.list_feature_services(self.project, allow_cache=True): fs_refs = frozenset( f"{p.name_to_use()}:{f.name}" for p in fs.feature_view_projections for f in p.features ) index[fs_refs] = fs.name self._fs_name_index = index self._fs_name_cache = {} self._fs_name_index_ts = time.monotonic() def _resolve_feature_service_name(self, feature_refs: List[str]) -> Optional[str]: """Find the best-matching feature service for the given feature refs. Resolution: exact match wins immediately; otherwise the smallest superset (fewest extra features) is returned. The full index is rebuilt from the registry every _FS_NAME_INDEX_TTL_SECONDS and per-query results are cached for O(1) repeated lookups. """ try: now = time.monotonic() if (now - self._fs_name_index_ts) >= self._FS_NAME_INDEX_TTL_SECONDS: self._rebuild_fs_name_index() ref_key = frozenset(feature_refs) if ref_key in self._fs_name_cache: return self._fs_name_cache[ref_key] if ref_key in self._fs_name_index: self._fs_name_cache[ref_key] = self._fs_name_index[ref_key] return self._fs_name_index[ref_key] best_match = None best_extra = float("inf") for fs_refs, fs_name in self._fs_name_index.items(): if ref_key.issubset(fs_refs): extra = len(fs_refs) - len(ref_key) if extra < best_extra: best_match = fs_name best_extra = extra self._fs_name_cache[ref_key] = best_match return best_match except Exception as e: _logger.debug("Failed to resolve feature service name: %s", e) return None def _log_entity_df_metadata(self, entity_df, start_date=None, end_date=None): """Log lightweight entity_df metadata to MLflow.""" try: if self.mlflow is not None: self.mlflow.log_entity_df_metadata(entity_df, start_date, end_date) except Exception as e: _logger.debug("Failed to log entity_df metadata to MLflow: %s", e) def _log_entity_df_artifact(self, entity_df): """Upload entity DataFrame as a parquet artifact to MLflow.""" try: if self.mlflow is not None: self.mlflow.log_entity_df_artifact(entity_df) except Exception as e: _logger.debug("Failed to log entity_df artifact to MLflow: %s", e) def _init_openlineage_emitter(self) -> Optional[Any]: """Initialize OpenLineage emitter if configured and enabled.""" try: if ( hasattr(self.config, "openlineage") and self.config.openlineage is not None and self.config.openlineage.enabled ): from feast.openlineage import FeastOpenLineageEmitter ol_config = self.config.openlineage.to_openlineage_config() emitter = FeastOpenLineageEmitter(ol_config) if emitter.is_enabled: self._wire_local_processor(emitter) return emitter except ImportError: # OpenLineage not installed, silently skip pass except Exception as e: warnings.warn(f"Failed to initialize OpenLineage emitter: {e}") return None def _wire_local_processor(self, emitter: Any) -> None: """Wire the local OL consumer processor into the emitter so Feast-produced events are also stored in the consumer DB.""" try: from feast.api.registry.rest import get_ol_processor processor = get_ol_processor() if processor and hasattr(emitter, "_client") and emitter._client: emitter._client.set_local_processor(processor) _logger.info( "Feast OL emitter wired to local consumer processor (lazy)" ) except Exception as e: _logger.debug(f"Could not wire emitter to local processor: {e}") def __repr__(self) -> str: # Show lazy loading status without triggering initialization registry_status = "not loaded" if self._registry is None else "loaded" provider_status = "not loaded" if self._provider is None else "loaded" return ( f"FeatureStore(\n" f" repo_path={self.repo_path!r},\n" f" config={self.config!r},\n" f" registry={registry_status},\n" f" provider={provider_status}\n" f")" ) @property def embedding_provider(self) -> "EmbeddingProvider": """Return the active embedding provider, creating one from config if needed.""" if self._embedding_provider is None: from feast.embedder import get_embedding_provider embed_cfg = self.config.embedding_model if embed_cfg is None: raise ValueError( "No embedding provider set and embedding_model is not " "configured in feature_store.yaml. Either pass an " "embedding_provider to FeatureStore() or add an " "'embedding_model' section to feature_store.yaml.\n" "Example:\n" " embedding_model:\n" " provider: sentence_transformers\n" " model: all-MiniLM-L6-v2" ) self._embedding_provider = get_embedding_provider(embed_cfg) return self._embedding_provider @embedding_provider.setter def embedding_provider(self, provider: "EmbeddingProvider") -> None: self._embedding_provider = provider @property def registry(self) -> BaseRegistry: """Gets the registry of this feature store.""" if self._registry is None: self._registry = self._create_registry() # Add feature service cache to registry for performance optimization if self._registry and not hasattr(self._registry, "_feature_service_cache"): setattr( self._registry, "_feature_service_cache", self._feature_service_cache, ) if self._registry is None: raise RuntimeError("Registry failed to initialize properly") return self._registry def _create_registry(self) -> BaseRegistry: """Create and initialize the registry.""" registry_config = self.config.registry if registry_config.registry_type == "sql": return SqlRegistry(registry_config, self.config.project, None) elif registry_config.registry_type == "snowflake.registry": from feast.infra.registry.snowflake import SnowflakeRegistry return SnowflakeRegistry(registry_config, self.config.project, None) elif registry_config and registry_config.registry_type == "remote": from feast.infra.registry.remote import RemoteRegistry return RemoteRegistry( registry_config, self.config.project, None, self.config.auth_config ) else: return Registry( self.config.project, registry_config, repo_path=self.repo_path, auth_config=self.config.auth_config, ) @property def project(self) -> str: """Gets the project for the current request context, falling back to the configured project.""" return self._current_project.get() or self.config.project def set_current_project(self, project: Optional[str]): return self._current_project.set(project) def reset_current_project(self, token): self._current_project.reset(token) @property def provider(self) -> Provider: """Gets the provider of this feature store.""" if self._provider is None: self._provider = get_provider(self.config) return self._provider def _get_provider(self) -> Provider: # TODO: Bake self.repo_path into self.config so that we dont only have one interface to paths return self.provider def _rollback_fv_states( self, feature_views: list, previous_states: dict, ) -> None: """Restore feature views to their pre-materialization states.""" for fv in feature_views: prev = previous_states.get(fv.name) if ( hasattr(fv, "state") and prev is not None and prev != FeatureViewState.STATE_UNSPECIFIED ): fv.state = prev self.registry.apply_feature_view(fv, self.project, commit=True) def _transition_fv_to_materializing( self, feature_view, already_transitioned: list, previous_states: dict, ) -> None: """ Transition a feature view to MATERIALIZING state. Rolls back all already-transitioned FVs if this one can't transition. Already MATERIALIZING is a no-op (async server may have reserved the state before returning 202); rollback target is GENERATED in that case. """ current = getattr(feature_view, "state", None) if current == FeatureViewState.MATERIALIZING: previous_states[feature_view.name] = FeatureViewState.GENERATED return previous_states[feature_view.name] = current if ( hasattr(feature_view, "state") and feature_view.state != FeatureViewState.STATE_UNSPECIFIED ): if not feature_view.state.can_transition_to(FeatureViewState.MATERIALIZING): self._rollback_fv_states(already_transitioned, previous_states) raise ValueError( f"FeatureView {feature_view.name} cannot transition " f"from {feature_view.state.name} to MATERIALIZING." ) feature_view.state = FeatureViewState.MATERIALIZING self.registry.apply_feature_view(feature_view, self.project, commit=True) def _submit_and_process_materialization_jobs( self, provider, tasks: list, regular_fvs: list, previous_states: dict, date_range: "_MaterializationDateRange", openlineage_run_id: Optional[str] = None, ) -> None: """ Submit all tasks to the engine in one call and process the results. For each returned job: record watermark on success, roll back state on error. If the engine itself raises, all states are rolled back. """ from feast.infra.common.materialization_job import ( MaterializationJobStatus, ) batch_start = time.monotonic() materialize_kwargs: Dict[str, Any] = {} if openlineage_run_id and self.openlineage_emitter is not None: from feast.openlineage.identity import ( LineageParentContext, materialize_job_name, ) materialize_kwargs["lineage_parent"] = LineageParentContext( job_namespace=self.openlineage_emitter.namespace_for(self.project), job_name=materialize_job_name(self.project), run_id=openlineage_run_id, ) try: jobs = provider.batch_engine.materialize( self.registry, tasks, **materialize_kwargs ) except Exception: self._rollback_fv_states(regular_fvs, previous_states) raise if len(jobs) != len(regular_fvs): self._rollback_fv_states(regular_fvs, previous_states) raise RuntimeError( f"Engine returned {len(jobs)} jobs for {len(regular_fvs)} tasks" ) first_error = None succeeded_fvs = [] failed_fvs = [] for fv, job in zip(regular_fvs, jobs): fv_status = job.status() if fv_status == MaterializationJobStatus.ERROR: failed_fvs.append(fv) if first_error is None and job.error(): first_error = job.error() else: succeeded_fvs.append(fv) if failed_fvs: self._rollback_fv_states(failed_fvs, previous_states) # Engines that apply watermarks themselves (e.g. SparkApplication pod) # must not get a second apply_materialization — that duplicates intervals. if not getattr(provider.batch_engine, "applies_materialization", False): for fv in succeeded_fvs: self.registry.apply_materialization( fv, self.project, date_range.fv_start_dates[fv.name], date_range.end_date, ) _tracker = _get_track_materialization() if _tracker is not None: elapsed = time.monotonic() - batch_start for fv in succeeded_fvs: _tracker(fv.name, True, elapsed) for fv in failed_fvs: _tracker(fv.name, False, elapsed) if first_error: raise first_error def _materialize_fvs_batch( self, provider, fv_with_dates: list, end_date: datetime, tqdm_builder, disable_event_timestamp: bool = False, openlineage_run_id: Optional[str] = None, ) -> None: """Batch path: collect all FVs, submit to engine in one call. Only used when ``provider.batch_engine.supports_batch`` is True. """ from feast.infra.common.materialization_job import MaterializationTask tasks: list = [] regular_fvs: list = [] previous_states: dict = {} date_range = _MaterializationDateRange(end_date=end_date) for feature_view, fv_start in fv_with_dates: self._transition_fv_to_materializing( feature_view, regular_fvs, previous_states ) regular_fvs.append(feature_view) date_range.fv_start_dates[feature_view.name] = fv_start tasks.append( MaterializationTask( project=self.project, feature_view=feature_view, start_time=fv_start, end_time=end_date, tqdm_builder=tqdm_builder, disable_event_timestamp=disable_event_timestamp, ) ) if tasks: self._submit_and_process_materialization_jobs( provider, tasks, regular_fvs, previous_states, date_range, openlineage_run_id=openlineage_run_id, ) @property def openlineage_emitter(self) -> Optional[Any]: """Gets the OpenLineage emitter of this feature store.""" if self._openlineage_emitter is None: self._openlineage_emitter = self._init_openlineage_emitter() return self._openlineage_emitter def _clear_feature_service_cache(self): """Clear feature service cache to avoid stale data after registry refresh.""" self._feature_service_cache.clear() if hasattr(self.registry, "_feature_service_cache"): getattr(self.registry, "_feature_service_cache").clear() self._fs_name_cache.clear() self._fs_name_index.clear() self._fs_name_index_ts = -self._FS_NAME_INDEX_TTL_SECONDS def refresh_registry(self): """Fetches and caches a copy of the feature registry in memory. Explicitly calling this method allows for direct control of the state of the registry cache. Every time this method is called the complete registry state will be retrieved from the remote registry store backend (e.g., GCS, S3), and the cache timer will be reset. If refresh_registry() is run before get_online_features() is called, then get_online_features() will use the cached registry instead of retrieving (and caching) the registry itself. Additionally, the TTL for the registry cache can be set to infinity (by setting it to 0), which means that refresh_registry() will become the only way to update the cached registry. If the TTL is set to a value greater than 0, then once the cache becomes stale (more time than the TTL has passed), a new cache will be downloaded synchronously, which may increase latencies if the triggering method is get_online_features(). """ self.registry.refresh(self.project) self._clear_feature_service_cache() def list_entities( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[Entity]: """ Retrieves the list of entities from the registry. Args: allow_cache: Whether to allow returning entities from a cached registry. tags: Filter by tags. Returns: A list of entities. """ return self._list_entities(allow_cache, tags=tags) def _list_entities( self, allow_cache: bool = False, hide_dummy_entity: bool = True, tags: Optional[dict[str, str]] = None, ) -> List[Entity]: all_entities = self.registry.list_entities( self.project, allow_cache=allow_cache, tags=tags ) return [ entity for entity in all_entities if entity.name != DUMMY_ENTITY_NAME or not hide_dummy_entity ] def list_feature_services( self, tags: Optional[dict[str, str]] = None ) -> List[FeatureService]: """ Retrieves the list of feature services from the registry. Args: tags: Filter by tags. Returns: A list of feature services. """ return self.registry.list_feature_services(self.project, tags=tags) def _list_all_feature_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[BaseFeatureView]: feature_views = [] for fv in self.registry.list_all_feature_views( self.project, allow_cache=allow_cache, tags=tags ): if ( isinstance(fv, FeatureView) and fv.entities and fv.entities[0] == DUMMY_ENTITY_NAME ): fv.entities = [] fv.entity_columns = [] feature_views.append(fv) return feature_views def list_all_feature_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[BaseFeatureView]: """ Retrieves the list of feature views from the registry. Args: allow_cache: Whether to allow returning entities from a cached registry. Returns: A list of feature views. """ return self._list_all_feature_views(allow_cache, tags=tags) def list_feature_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[FeatureView]: """ Retrieves the list of feature views from the registry. Args: allow_cache: Whether to allow returning entities from a cached registry. tags: Filter by tags. Returns: A list of feature views. """ return utils._list_feature_views( self.registry, self.project, allow_cache, tags=tags ) def list_batch_feature_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[FeatureView]: """ Retrieves the list of feature views from the registry. Args: allow_cache: Whether to allow returning entities from a cached registry. tags: Filter by tags. Returns: A list of feature views. """ return self._list_batch_feature_views(allow_cache=allow_cache, tags=tags) def _list_batch_feature_views( self, allow_cache: bool = False, hide_dummy_entity: bool = True, tags: Optional[dict[str, str]] = None, ) -> List[FeatureView]: feature_views = [] for fv in self.registry.list_feature_views( self.project, allow_cache=allow_cache, tags=tags ): if ( hide_dummy_entity and fv.entities and fv.entities[0] == DUMMY_ENTITY_NAME ): fv.entities = [] fv.entity_columns = [] feature_views.append(fv) return feature_views def _list_stream_feature_views( self, allow_cache: bool = False, hide_dummy_entity: bool = True, tags: Optional[dict[str, str]] = None, ) -> List[StreamFeatureView]: stream_feature_views = [] for sfv in self.registry.list_stream_feature_views( self.project, allow_cache=allow_cache, tags=tags ): if hide_dummy_entity and sfv.entities[0] == DUMMY_ENTITY_NAME: sfv.entities = [] sfv.entity_columns = [] stream_feature_views.append(sfv) return stream_feature_views def list_on_demand_feature_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[OnDemandFeatureView]: """ Retrieves the list of on demand feature views from the registry. Args: allow_cache: Whether to allow returning entities from a cached registry. tags: Filter by tags. Returns: A list of on demand feature views. """ return self.registry.list_on_demand_feature_views( self.project, allow_cache=allow_cache, tags=tags ) def list_stream_feature_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[StreamFeatureView]: """ Retrieves the list of stream feature views from the registry. Returns: A list of stream feature views. """ return self._list_stream_feature_views(allow_cache, tags=tags) def list_label_views( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[LabelView]: """ Retrieves the list of label views from the registry. Args: allow_cache: Whether to allow returning label views from a cached registry. tags: Filter by tags. Returns: A list of label views. """ return self.registry.list_label_views( self.project, allow_cache=allow_cache, tags=tags ) def get_label_view( self, name: str, allow_registry_cache: bool = False ) -> LabelView: """ Retrieves a label view by name. Args: name: Name of the label view. allow_registry_cache: Whether to allow returning the label view from a cached registry. Returns: The specified label view. Raises: FeatureViewNotFoundException: The label view could not be found. """ return self.registry.get_label_view( name, self.project, allow_cache=allow_registry_cache ) def list_data_sources( self, allow_cache: bool = False, tags: Optional[dict[str, str]] = None ) -> List[DataSource]: """ Retrieves the list of data sources from the registry. Args: allow_cache: Whether to allow returning data sources from a cached registry. tags: Filter by tags. Returns: A list of data sources. """ return self.registry.list_data_sources( self.project, allow_cache=allow_cache, tags=tags ) def get_entity(self, name: str, allow_registry_cache: bool = False) -> Entity: """ Retrieves an entity. Args: name: Name of entity. allow_registry_cache: (Optional) Whether to allow returning this entity from a cached registry Returns: The specified entity. Raises: EntityNotFoundException: The entity could not be found. """ return self.registry.get_entity( name, self.project, allow_cache=allow_registry_cache ) def get_feature_service( self, name: str, allow_cache: bool = False ) -> FeatureService: """ Retrieves a feature service. Args: name: Name of feature service. allow_cache: Whether to allow returning feature services from a cached registry. Returns: The specified feature service. Raises: FeatureServiceNotFoundException: The feature service could not be found. """ return self.registry.get_feature_service(name, self.project, allow_cache) def get_feature_view( self, name: str, allow_registry_cache: bool = False ) -> FeatureView: """ Retrieves a feature view. Args: name: Name of feature view. allow_registry_cache: (Optional) Whether to allow returning this entity from a cached registry Returns: The specified feature view. Raises: FeatureViewNotFoundException: The feature view could not be found. """ return self._get_feature_view(name, allow_registry_cache=allow_registry_cache) def _get_feature_view( self, name: str, hide_dummy_entity: bool = True, allow_registry_cache: bool = False, |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |