mlrun 1.7.0rc14__py3-none-any.whl → 1.7.0rc22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mlrun might be problematic. Click here for more details.

Files changed (160) hide show
  1. mlrun/__init__.py +10 -1
  2. mlrun/__main__.py +23 -111
  3. mlrun/alerts/__init__.py +15 -0
  4. mlrun/alerts/alert.py +169 -0
  5. mlrun/api/schemas/__init__.py +4 -3
  6. mlrun/artifacts/__init__.py +8 -3
  7. mlrun/artifacts/base.py +36 -253
  8. mlrun/artifacts/dataset.py +9 -190
  9. mlrun/artifacts/manager.py +46 -42
  10. mlrun/artifacts/model.py +9 -141
  11. mlrun/artifacts/plots.py +14 -375
  12. mlrun/common/constants.py +65 -3
  13. mlrun/common/formatters/__init__.py +19 -0
  14. mlrun/{runtimes/mpijob/v1alpha1.py → common/formatters/artifact.py} +6 -14
  15. mlrun/common/formatters/base.py +113 -0
  16. mlrun/common/formatters/function.py +46 -0
  17. mlrun/common/formatters/pipeline.py +53 -0
  18. mlrun/common/formatters/project.py +51 -0
  19. mlrun/{runtimes → common/runtimes}/constants.py +32 -4
  20. mlrun/common/schemas/__init__.py +10 -5
  21. mlrun/common/schemas/alert.py +92 -11
  22. mlrun/common/schemas/api_gateway.py +56 -0
  23. mlrun/common/schemas/artifact.py +15 -5
  24. mlrun/common/schemas/auth.py +2 -0
  25. mlrun/common/schemas/client_spec.py +1 -0
  26. mlrun/common/schemas/frontend_spec.py +1 -0
  27. mlrun/common/schemas/function.py +4 -0
  28. mlrun/common/schemas/model_monitoring/__init__.py +15 -3
  29. mlrun/common/schemas/model_monitoring/constants.py +58 -7
  30. mlrun/common/schemas/model_monitoring/grafana.py +9 -5
  31. mlrun/common/schemas/model_monitoring/model_endpoints.py +86 -2
  32. mlrun/common/schemas/pipeline.py +0 -9
  33. mlrun/common/schemas/project.py +5 -11
  34. mlrun/common/types.py +1 -0
  35. mlrun/config.py +30 -9
  36. mlrun/data_types/to_pandas.py +9 -9
  37. mlrun/datastore/base.py +41 -9
  38. mlrun/datastore/datastore.py +6 -2
  39. mlrun/datastore/datastore_profile.py +56 -4
  40. mlrun/datastore/inmem.py +2 -2
  41. mlrun/datastore/redis.py +2 -2
  42. mlrun/datastore/s3.py +5 -0
  43. mlrun/datastore/sources.py +147 -7
  44. mlrun/datastore/store_resources.py +7 -7
  45. mlrun/datastore/targets.py +110 -42
  46. mlrun/datastore/utils.py +42 -0
  47. mlrun/db/base.py +54 -10
  48. mlrun/db/httpdb.py +282 -79
  49. mlrun/db/nopdb.py +52 -10
  50. mlrun/errors.py +11 -0
  51. mlrun/execution.py +26 -9
  52. mlrun/feature_store/__init__.py +0 -2
  53. mlrun/feature_store/api.py +12 -47
  54. mlrun/feature_store/feature_set.py +9 -0
  55. mlrun/feature_store/feature_vector.py +8 -0
  56. mlrun/feature_store/ingestion.py +7 -6
  57. mlrun/feature_store/retrieval/base.py +9 -4
  58. mlrun/feature_store/retrieval/conversion.py +9 -9
  59. mlrun/feature_store/retrieval/dask_merger.py +2 -0
  60. mlrun/feature_store/retrieval/job.py +9 -3
  61. mlrun/feature_store/retrieval/local_merger.py +2 -0
  62. mlrun/feature_store/retrieval/spark_merger.py +16 -0
  63. mlrun/frameworks/__init__.py +6 -0
  64. mlrun/frameworks/_dl_common/loggers/tensorboard_logger.py +7 -12
  65. mlrun/frameworks/parallel_coordinates.py +2 -1
  66. mlrun/frameworks/tf_keras/__init__.py +4 -1
  67. mlrun/k8s_utils.py +10 -11
  68. mlrun/launcher/base.py +4 -3
  69. mlrun/launcher/client.py +5 -3
  70. mlrun/launcher/local.py +12 -2
  71. mlrun/launcher/remote.py +9 -2
  72. mlrun/lists.py +6 -2
  73. mlrun/model.py +47 -21
  74. mlrun/model_monitoring/__init__.py +1 -1
  75. mlrun/model_monitoring/api.py +42 -18
  76. mlrun/model_monitoring/application.py +5 -305
  77. mlrun/model_monitoring/applications/__init__.py +11 -0
  78. mlrun/model_monitoring/applications/_application_steps.py +157 -0
  79. mlrun/model_monitoring/applications/base.py +280 -0
  80. mlrun/model_monitoring/applications/context.py +214 -0
  81. mlrun/model_monitoring/applications/evidently_base.py +211 -0
  82. mlrun/model_monitoring/applications/histogram_data_drift.py +132 -91
  83. mlrun/model_monitoring/applications/results.py +99 -0
  84. mlrun/model_monitoring/controller.py +3 -1
  85. mlrun/model_monitoring/db/__init__.py +2 -0
  86. mlrun/model_monitoring/db/stores/__init__.py +0 -2
  87. mlrun/model_monitoring/db/stores/base/store.py +22 -37
  88. mlrun/model_monitoring/db/stores/sqldb/models/__init__.py +43 -21
  89. mlrun/model_monitoring/db/stores/sqldb/models/base.py +39 -8
  90. mlrun/model_monitoring/db/stores/sqldb/models/mysql.py +27 -7
  91. mlrun/model_monitoring/db/stores/sqldb/models/sqlite.py +5 -0
  92. mlrun/model_monitoring/db/stores/sqldb/sql_store.py +246 -224
  93. mlrun/model_monitoring/db/stores/v3io_kv/kv_store.py +232 -216
  94. mlrun/model_monitoring/db/tsdb/__init__.py +100 -0
  95. mlrun/model_monitoring/db/tsdb/base.py +316 -0
  96. mlrun/model_monitoring/db/tsdb/helpers.py +30 -0
  97. mlrun/model_monitoring/db/tsdb/tdengine/__init__.py +15 -0
  98. mlrun/model_monitoring/db/tsdb/tdengine/schemas.py +240 -0
  99. mlrun/model_monitoring/db/tsdb/tdengine/stream_graph_steps.py +45 -0
  100. mlrun/model_monitoring/db/tsdb/tdengine/tdengine_connector.py +401 -0
  101. mlrun/model_monitoring/db/tsdb/v3io/__init__.py +15 -0
  102. mlrun/model_monitoring/db/tsdb/v3io/stream_graph_steps.py +117 -0
  103. mlrun/model_monitoring/db/tsdb/v3io/v3io_connector.py +658 -0
  104. mlrun/model_monitoring/evidently_application.py +6 -118
  105. mlrun/model_monitoring/helpers.py +63 -1
  106. mlrun/model_monitoring/model_endpoint.py +3 -2
  107. mlrun/model_monitoring/stream_processing.py +57 -216
  108. mlrun/model_monitoring/writer.py +134 -124
  109. mlrun/package/__init__.py +13 -1
  110. mlrun/package/packagers/__init__.py +6 -1
  111. mlrun/package/utils/_formatter.py +2 -2
  112. mlrun/platforms/__init__.py +10 -9
  113. mlrun/platforms/iguazio.py +21 -202
  114. mlrun/projects/operations.py +24 -12
  115. mlrun/projects/pipelines.py +79 -102
  116. mlrun/projects/project.py +271 -103
  117. mlrun/render.py +15 -14
  118. mlrun/run.py +16 -46
  119. mlrun/runtimes/__init__.py +6 -3
  120. mlrun/runtimes/base.py +14 -7
  121. mlrun/runtimes/daskjob.py +1 -0
  122. mlrun/runtimes/databricks_job/databricks_runtime.py +1 -0
  123. mlrun/runtimes/databricks_job/databricks_wrapper.py +1 -1
  124. mlrun/runtimes/funcdoc.py +0 -28
  125. mlrun/runtimes/kubejob.py +2 -1
  126. mlrun/runtimes/local.py +12 -3
  127. mlrun/runtimes/mpijob/__init__.py +0 -20
  128. mlrun/runtimes/mpijob/v1.py +1 -1
  129. mlrun/runtimes/nuclio/api_gateway.py +194 -84
  130. mlrun/runtimes/nuclio/application/application.py +170 -8
  131. mlrun/runtimes/nuclio/function.py +39 -49
  132. mlrun/runtimes/pod.py +16 -36
  133. mlrun/runtimes/remotesparkjob.py +9 -3
  134. mlrun/runtimes/sparkjob/spark3job.py +1 -1
  135. mlrun/runtimes/utils.py +6 -45
  136. mlrun/serving/__init__.py +8 -1
  137. mlrun/serving/server.py +2 -1
  138. mlrun/serving/states.py +51 -8
  139. mlrun/serving/utils.py +19 -11
  140. mlrun/serving/v2_serving.py +5 -1
  141. mlrun/track/tracker.py +2 -1
  142. mlrun/utils/async_http.py +25 -5
  143. mlrun/utils/helpers.py +157 -83
  144. mlrun/utils/logger.py +39 -7
  145. mlrun/utils/notifications/notification/__init__.py +14 -9
  146. mlrun/utils/notifications/notification/base.py +1 -1
  147. mlrun/utils/notifications/notification/slack.py +34 -7
  148. mlrun/utils/notifications/notification/webhook.py +1 -1
  149. mlrun/utils/notifications/notification_pusher.py +147 -16
  150. mlrun/utils/regex.py +9 -0
  151. mlrun/utils/v3io_clients.py +0 -1
  152. mlrun/utils/version/version.json +2 -2
  153. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc22.dist-info}/METADATA +14 -6
  154. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc22.dist-info}/RECORD +158 -138
  155. mlrun/kfpops.py +0 -865
  156. mlrun/platforms/other.py +0 -305
  157. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc22.dist-info}/LICENSE +0 -0
  158. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc22.dist-info}/WHEEL +0 -0
  159. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc22.dist-info}/entry_points.txt +0 -0
  160. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc22.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,100 @@
1
+ # Copyright 2024 Iguazio
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import enum
16
+ import typing
17
+
18
+ import mlrun.common.schemas.secret
19
+ import mlrun.errors
20
+
21
+ from .base import TSDBConnector
22
+
23
+
24
+ class ObjectTSDBFactory(enum.Enum):
25
+ """Enum class to handle the different TSDB connector type values for storing real time metrics"""
26
+
27
+ v3io_tsdb = "v3io-tsdb"
28
+ tdengine = "tdengine"
29
+
30
+ def to_tsdb_connector(self, project: str, **kwargs) -> TSDBConnector:
31
+ """
32
+ Return a TSDBConnector object based on the provided enum value.
33
+ :param project: The name of the project.
34
+ :return: `TSDBConnector` object.
35
+ """
36
+
37
+ if self == self.v3io_tsdb:
38
+ if mlrun.mlconf.is_ce_mode():
39
+ raise mlrun.errors.MLRunInvalidArgumentError(
40
+ f"{self.v3io_tsdb} is not supported in CE mode."
41
+ )
42
+
43
+ from .v3io.v3io_connector import V3IOTSDBConnector
44
+
45
+ return V3IOTSDBConnector(project=project, **kwargs)
46
+
47
+ # Assuming TDEngine connector if connector type is not V3IO TSDB.
48
+ # Update these lines once there are more than two connector types.
49
+
50
+ from .tdengine.tdengine_connector import TDEngineConnector
51
+
52
+ return TDEngineConnector(project=project, **kwargs)
53
+
54
+ @classmethod
55
+ def _missing_(cls, value: typing.Any):
56
+ """A lookup function to handle an invalid value.
57
+ :param value: Provided enum (invalid) value.
58
+ """
59
+ valid_values = list(cls.__members__.keys())
60
+ raise mlrun.errors.MLRunInvalidArgumentError(
61
+ f"{value} is not a valid tsdb, please choose a valid value: %{valid_values}."
62
+ )
63
+
64
+
65
+ def get_tsdb_connector(
66
+ project: str,
67
+ tsdb_connector_type: str = "",
68
+ secret_provider: typing.Optional[typing.Callable] = None,
69
+ **kwargs,
70
+ ) -> TSDBConnector:
71
+ """
72
+ Get TSDB connector object.
73
+ :param project: The name of the project.
74
+ :param tsdb_connector_type: The type of the TSDB connector. See mlrun.model_monitoring.db.tsdb.ObjectTSDBFactory
75
+ for available options.
76
+ :param secret_provider: An optional secret provider to get the connection string secret.
77
+
78
+ :return: `TSDBConnector` object. The main goal of this object is to handle different operations on the
79
+ TSDB connector such as updating drift metrics or write application record result.
80
+ """
81
+
82
+ tsdb_connection_string = mlrun.model_monitoring.helpers.get_tsdb_connection_string(
83
+ secret_provider=secret_provider
84
+ )
85
+
86
+ if tsdb_connection_string and tsdb_connection_string.startswith("taosws"):
87
+ tsdb_connector_type = mlrun.common.schemas.model_monitoring.TSDBTarget.TDEngine
88
+ kwargs["connection_string"] = tsdb_connection_string
89
+
90
+ # Set the default TSDB connector type if no connection has been set
91
+ tsdb_connector_type = (
92
+ tsdb_connector_type
93
+ or mlrun.mlconf.model_endpoint_monitoring.tsdb_connector_type
94
+ )
95
+
96
+ # Get connector type value from ObjectTSDBFactory enum class
97
+ tsdb_connector_factory = ObjectTSDBFactory(tsdb_connector_type)
98
+
99
+ # Convert into TSDB connector object
100
+ return tsdb_connector_factory.to_tsdb_connector(project=project, **kwargs)
@@ -0,0 +1,316 @@
1
+ # Copyright 2024 Iguazio
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import typing
16
+ from abc import ABC, abstractmethod
17
+ from datetime import datetime
18
+
19
+ import pandas as pd
20
+
21
+ import mlrun.common.schemas.model_monitoring as mm_schemas
22
+ import mlrun.model_monitoring.db.tsdb.helpers
23
+ import mlrun.model_monitoring.helpers
24
+ from mlrun.utils import logger
25
+
26
+
27
+ class TSDBConnector(ABC):
28
+ type: str = ""
29
+
30
+ def __init__(self, project: str):
31
+ """
32
+ Initialize a new TSDB connector. The connector is used to interact with the TSDB and store monitoring data.
33
+ At the moment we have 3 different types of monitoring data:
34
+ - real time performance metrics: real time performance metrics that are being calculated by the model
35
+ monitoring stream pod.
36
+ Among these metrics are the base metrics (average latency and predictions over time), endpoint features
37
+ (data samples), and custom metrics (user-defined metrics).
38
+ - app_results: a detailed results that include status, kind, extra data, etc. These results are being calculated
39
+ through the monitoring applications and stored in the TSDB using the model monitoring writer.
40
+ - metrics: a basic key value that represents a numeric metric. Similar to the app_results, these metrics
41
+ are being calculated through the monitoring applications and stored in the TSDB using the model monitoring
42
+ writer.
43
+
44
+ :param project: the name of the project.
45
+
46
+ """
47
+ self.project = project
48
+
49
+ def apply_monitoring_stream_steps(self, graph):
50
+ """
51
+ Apply TSDB steps on the provided monitoring graph. Throughout these steps, the graph stores live data of
52
+ different key metric dictionaries. This data is being used by the monitoring dashboards in
53
+ grafana.
54
+ There are 3 different key metric dictionaries that are being generated throughout these steps:
55
+ - base_metrics (average latency and predictions over time)
56
+ - endpoint_features (Prediction and feature names and values)
57
+ - custom_metrics (user-defined metrics)
58
+ """
59
+ pass
60
+
61
+ def write_application_event(
62
+ self,
63
+ event: dict,
64
+ kind: mm_schemas.WriterEventKind = mm_schemas.WriterEventKind.RESULT,
65
+ ) -> None:
66
+ """
67
+ Write a single application or metric to TSDB.
68
+
69
+ :raise mlrun.errors.MLRunRuntimeError: If an error occurred while writing the event.
70
+ """
71
+
72
+ def delete_tsdb_resources(self):
73
+ """
74
+ Delete all project resources in the TSDB connector, such as model endpoints data and drift results.
75
+ """
76
+
77
+ pass
78
+
79
+ def get_model_endpoint_real_time_metrics(
80
+ self,
81
+ endpoint_id: str,
82
+ metrics: list[str],
83
+ start: str,
84
+ end: str,
85
+ ) -> dict[str, list[tuple[str, float]]]:
86
+ """
87
+ Getting real time metrics from the TSDB. There are pre-defined metrics for model endpoints such as
88
+ `predictions_per_second` and `latency_avg_5m` but also custom metrics defined by the user. Note that these
89
+ metrics are being calculated by the model monitoring stream pod.
90
+ :param endpoint_id: The unique id of the model endpoint.
91
+ :param metrics: A list of real-time metrics to return for the model endpoint.
92
+ :param start: The start time of the metrics. Can be represented by a string containing an RFC 3339
93
+ time, a Unix timestamp in milliseconds, a relative time (`'now'` or
94
+ `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, `'d'` = days, and `'s'`
95
+ = seconds), or 0 for the earliest time.
96
+ :param end: The end time of the metrics. Can be represented by a string containing an RFC 3339
97
+ time, a Unix timestamp in milliseconds, a relative time (`'now'` or
98
+ `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, `'d'` = days, and `'s'`
99
+ = seconds), or 0 for the earliest time.
100
+ :return: A dictionary of metrics in which the key is a metric name and the value is a list of tuples that
101
+ includes timestamps and the values.
102
+ """
103
+ pass
104
+
105
+ def create_tables(self) -> None:
106
+ """
107
+ Create the TSDB tables using the TSDB connector. At the moment we support 3 types of tables:
108
+ - app_results: a detailed result that includes status, kind, extra data, etc.
109
+ - metrics: a basic key value that represents a numeric metric.
110
+ - predictions: latency of each prediction.
111
+ """
112
+
113
+ @abstractmethod
114
+ def read_metrics_data(
115
+ self,
116
+ *,
117
+ endpoint_id: str,
118
+ start: datetime,
119
+ end: datetime,
120
+ metrics: list[mm_schemas.ModelEndpointMonitoringMetric],
121
+ type: typing.Literal["metrics", "results"],
122
+ ) -> typing.Union[
123
+ list[
124
+ typing.Union[
125
+ mm_schemas.ModelEndpointMonitoringResultValues,
126
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
127
+ ],
128
+ ],
129
+ list[
130
+ typing.Union[
131
+ mm_schemas.ModelEndpointMonitoringMetricValues,
132
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
133
+ ],
134
+ ],
135
+ ]:
136
+ """
137
+ Read metrics OR results from the TSDB and return as a list.
138
+
139
+ :param endpoint_id: The model endpoint identifier.
140
+ :param start: The start time of the query.
141
+ :param end: The end time of the query.
142
+ :param metrics: The list of metrics to get the values for.
143
+ :param type: "metrics" or "results" - the type of each item in metrics.
144
+ :return: A list of result values or a list of metric values.
145
+ """
146
+
147
+ @abstractmethod
148
+ def read_predictions(
149
+ self,
150
+ *,
151
+ endpoint_id: str,
152
+ start: datetime,
153
+ end: datetime,
154
+ aggregation_window: typing.Optional[str] = None,
155
+ agg_funcs: typing.Optional[list[str]] = None,
156
+ limit: typing.Optional[int] = None,
157
+ ) -> typing.Union[
158
+ mm_schemas.ModelEndpointMonitoringMetricValues,
159
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
160
+ ]:
161
+ """
162
+ Read the "invocations" metric for the provided model endpoint in the given time range,
163
+ and return the metric values if any, otherwise signify with the "no data" object.
164
+
165
+ :param endpoint_id: The model endpoint identifier.
166
+ :param start: The start time of the query.
167
+ :param end: The end time of the query.
168
+ :param aggregation_window: On what time window length should the invocations be aggregated. If provided,
169
+ the `agg_funcs` must be provided as well. Provided as a string in the format of '1m',
170
+ '1h', etc.
171
+ :param agg_funcs: List of aggregation functions to apply on the invocations. If provided, the
172
+ `aggregation_window` must be provided as well. Provided as a list of strings in
173
+ the format of ['sum', 'avg', 'count', ...]
174
+ :param limit: The maximum number of records to return.
175
+
176
+ :raise mlrun.errors.MLRunInvalidArgumentError: If only one of `aggregation_window` and `agg_funcs` is provided.
177
+ :return: Metric values object or no data object.
178
+ """
179
+
180
+ @staticmethod
181
+ def df_to_metrics_values(
182
+ *,
183
+ df: pd.DataFrame,
184
+ metrics: list[mm_schemas.ModelEndpointMonitoringMetric],
185
+ project: str,
186
+ ) -> list[
187
+ typing.Union[
188
+ mm_schemas.ModelEndpointMonitoringMetricValues,
189
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
190
+ ]
191
+ ]:
192
+ """
193
+ Parse a time-indexed DataFrame of metrics from the TSDB into a list of
194
+ metrics values per distinct results.
195
+ When a metric is not found in the DataFrame, it is represented in a no-data object.
196
+ """
197
+ metrics_without_data = {metric.full_name: metric for metric in metrics}
198
+
199
+ metrics_values: list[
200
+ typing.Union[
201
+ mm_schemas.ModelEndpointMonitoringMetricValues,
202
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
203
+ ]
204
+ ] = []
205
+ if not df.empty:
206
+ grouped = df.groupby(
207
+ [
208
+ mm_schemas.WriterEvent.APPLICATION_NAME,
209
+ mm_schemas.MetricData.METRIC_NAME,
210
+ ],
211
+ observed=False,
212
+ )
213
+ else:
214
+ logger.debug("No metrics", missing_metrics=metrics_without_data.keys())
215
+ grouped = []
216
+ for (app_name, name), sub_df in grouped:
217
+ full_name = mlrun.model_monitoring.helpers._compose_full_name(
218
+ project=project,
219
+ app=app_name,
220
+ name=name,
221
+ type=mm_schemas.ModelEndpointMonitoringMetricType.METRIC,
222
+ )
223
+ metrics_values.append(
224
+ mm_schemas.ModelEndpointMonitoringMetricValues(
225
+ full_name=full_name,
226
+ values=list(
227
+ zip(
228
+ sub_df.index,
229
+ sub_df[mm_schemas.MetricData.METRIC_VALUE],
230
+ )
231
+ ), # pyright: ignore[reportArgumentType]
232
+ )
233
+ )
234
+ del metrics_without_data[full_name]
235
+
236
+ for metric in metrics_without_data.values():
237
+ metrics_values.append(
238
+ mm_schemas.ModelEndpointMonitoringMetricNoData(
239
+ full_name=metric.full_name,
240
+ type=mm_schemas.ModelEndpointMonitoringMetricType.METRIC,
241
+ )
242
+ )
243
+
244
+ return metrics_values
245
+
246
+ @staticmethod
247
+ def df_to_results_values(
248
+ *,
249
+ df: pd.DataFrame,
250
+ metrics: list[mm_schemas.ModelEndpointMonitoringMetric],
251
+ project: str,
252
+ ) -> list[
253
+ typing.Union[
254
+ mm_schemas.ModelEndpointMonitoringResultValues,
255
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
256
+ ]
257
+ ]:
258
+ """
259
+ Parse a time-indexed DataFrame of results from the TSDB into a list of
260
+ results values per distinct results.
261
+ When a result is not found in the DataFrame, it is represented in no-data object.
262
+ """
263
+ metrics_without_data = {metric.full_name: metric for metric in metrics}
264
+
265
+ metrics_values: list[
266
+ typing.Union[
267
+ mm_schemas.ModelEndpointMonitoringResultValues,
268
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
269
+ ]
270
+ ] = []
271
+ if not df.empty:
272
+ grouped = df.groupby(
273
+ [
274
+ mm_schemas.WriterEvent.APPLICATION_NAME,
275
+ mm_schemas.ResultData.RESULT_NAME,
276
+ ],
277
+ observed=False,
278
+ )
279
+ else:
280
+ grouped = []
281
+ logger.debug("No results", missing_results=metrics_without_data.keys())
282
+ for (app_name, name), sub_df in grouped:
283
+ result_kind = mlrun.model_monitoring.db.tsdb.helpers._get_result_kind(
284
+ sub_df
285
+ )
286
+ full_name = mlrun.model_monitoring.helpers._compose_full_name(
287
+ project=project, app=app_name, name=name
288
+ )
289
+ metrics_values.append(
290
+ mm_schemas.ModelEndpointMonitoringResultValues(
291
+ full_name=full_name,
292
+ result_kind=result_kind,
293
+ values=list(
294
+ zip(
295
+ sub_df.index,
296
+ sub_df[mm_schemas.ResultData.RESULT_VALUE],
297
+ sub_df[mm_schemas.ResultData.RESULT_STATUS],
298
+ )
299
+ ), # pyright: ignore[reportArgumentType]
300
+ )
301
+ )
302
+ del metrics_without_data[full_name]
303
+
304
+ for metric in metrics_without_data.values():
305
+ if metric.full_name == mlrun.model_monitoring.helpers.get_invocations_fqn(
306
+ project
307
+ ):
308
+ continue
309
+ metrics_values.append(
310
+ mm_schemas.ModelEndpointMonitoringMetricNoData(
311
+ full_name=metric.full_name,
312
+ type=mm_schemas.ModelEndpointMonitoringMetricType.RESULT,
313
+ )
314
+ )
315
+
316
+ return metrics_values
@@ -0,0 +1,30 @@
1
+ # Copyright 2024 Iguazio
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import pandas as pd
15
+
16
+ import mlrun.common.schemas.model_monitoring as mm_schemas
17
+ from mlrun.utils import logger
18
+
19
+
20
+ def _get_result_kind(result_df: pd.DataFrame) -> mm_schemas.ResultKindApp:
21
+ kind_series = result_df[mm_schemas.ResultData.RESULT_KIND]
22
+ unique_kinds = kind_series.unique()
23
+ if len(unique_kinds) > 1:
24
+ logger.warning(
25
+ "The result has more than one kind",
26
+ kinds=list(unique_kinds),
27
+ application_name=result_df[mm_schemas.WriterEvent.APPLICATION_NAME],
28
+ result_name=result_df[mm_schemas.ResultData.RESULT_NAME],
29
+ )
30
+ return unique_kinds[0]
@@ -0,0 +1,15 @@
1
+ # Copyright 2024 Iguazio
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .tdengine_connector import TDEngineConnector