mlrun 1.7.0rc4__py3-none-any.whl → 1.7.0rc20__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 (200) hide show
  1. mlrun/__init__.py +11 -1
  2. mlrun/__main__.py +25 -111
  3. mlrun/{datastore/helpers.py → alerts/__init__.py} +2 -5
  4. mlrun/alerts/alert.py +144 -0
  5. mlrun/api/schemas/__init__.py +4 -3
  6. mlrun/artifacts/__init__.py +8 -3
  7. mlrun/artifacts/base.py +38 -254
  8. mlrun/artifacts/dataset.py +9 -190
  9. mlrun/artifacts/manager.py +41 -47
  10. mlrun/artifacts/model.py +30 -158
  11. mlrun/artifacts/plots.py +23 -380
  12. mlrun/common/constants.py +68 -0
  13. mlrun/common/formatters/__init__.py +19 -0
  14. mlrun/{model_monitoring/stores/models/sqlite.py → common/formatters/artifact.py} +6 -8
  15. mlrun/common/formatters/base.py +78 -0
  16. mlrun/common/formatters/function.py +41 -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 +25 -4
  21. mlrun/common/schemas/alert.py +203 -0
  22. mlrun/common/schemas/api_gateway.py +148 -0
  23. mlrun/common/schemas/artifact.py +15 -5
  24. mlrun/common/schemas/auth.py +8 -2
  25. mlrun/common/schemas/client_spec.py +2 -0
  26. mlrun/common/schemas/frontend_spec.py +1 -0
  27. mlrun/common/schemas/function.py +4 -0
  28. mlrun/common/schemas/hub.py +7 -9
  29. mlrun/common/schemas/model_monitoring/__init__.py +19 -3
  30. mlrun/common/schemas/model_monitoring/constants.py +96 -26
  31. mlrun/common/schemas/model_monitoring/grafana.py +9 -5
  32. mlrun/common/schemas/model_monitoring/model_endpoints.py +86 -2
  33. mlrun/{runtimes/mpijob/v1alpha1.py → common/schemas/pagination.py} +10 -13
  34. mlrun/common/schemas/pipeline.py +0 -9
  35. mlrun/common/schemas/project.py +22 -21
  36. mlrun/common/types.py +7 -1
  37. mlrun/config.py +87 -19
  38. mlrun/data_types/data_types.py +4 -0
  39. mlrun/data_types/to_pandas.py +9 -9
  40. mlrun/datastore/__init__.py +5 -8
  41. mlrun/datastore/alibaba_oss.py +130 -0
  42. mlrun/datastore/azure_blob.py +4 -5
  43. mlrun/datastore/base.py +69 -30
  44. mlrun/datastore/datastore.py +10 -2
  45. mlrun/datastore/datastore_profile.py +90 -6
  46. mlrun/datastore/google_cloud_storage.py +1 -1
  47. mlrun/datastore/hdfs.py +5 -0
  48. mlrun/datastore/inmem.py +2 -2
  49. mlrun/datastore/redis.py +2 -2
  50. mlrun/datastore/s3.py +5 -0
  51. mlrun/datastore/snowflake_utils.py +43 -0
  52. mlrun/datastore/sources.py +172 -44
  53. mlrun/datastore/store_resources.py +7 -7
  54. mlrun/datastore/targets.py +285 -41
  55. mlrun/datastore/utils.py +68 -5
  56. mlrun/datastore/v3io.py +27 -50
  57. mlrun/db/auth_utils.py +152 -0
  58. mlrun/db/base.py +149 -14
  59. mlrun/db/factory.py +1 -1
  60. mlrun/db/httpdb.py +608 -178
  61. mlrun/db/nopdb.py +191 -7
  62. mlrun/errors.py +11 -0
  63. mlrun/execution.py +37 -20
  64. mlrun/feature_store/__init__.py +0 -2
  65. mlrun/feature_store/api.py +21 -52
  66. mlrun/feature_store/feature_set.py +48 -23
  67. mlrun/feature_store/feature_vector.py +2 -1
  68. mlrun/feature_store/ingestion.py +7 -6
  69. mlrun/feature_store/retrieval/base.py +9 -4
  70. mlrun/feature_store/retrieval/conversion.py +9 -9
  71. mlrun/feature_store/retrieval/dask_merger.py +2 -0
  72. mlrun/feature_store/retrieval/job.py +9 -3
  73. mlrun/feature_store/retrieval/local_merger.py +2 -0
  74. mlrun/feature_store/retrieval/spark_merger.py +34 -24
  75. mlrun/feature_store/steps.py +30 -19
  76. mlrun/features.py +4 -13
  77. mlrun/frameworks/_dl_common/loggers/tensorboard_logger.py +7 -12
  78. mlrun/frameworks/auto_mlrun/auto_mlrun.py +2 -2
  79. mlrun/frameworks/lgbm/__init__.py +1 -1
  80. mlrun/frameworks/lgbm/callbacks/callback.py +2 -4
  81. mlrun/frameworks/lgbm/model_handler.py +1 -1
  82. mlrun/frameworks/parallel_coordinates.py +2 -1
  83. mlrun/frameworks/pytorch/__init__.py +2 -2
  84. mlrun/frameworks/sklearn/__init__.py +1 -1
  85. mlrun/frameworks/tf_keras/__init__.py +5 -2
  86. mlrun/frameworks/tf_keras/callbacks/logging_callback.py +1 -1
  87. mlrun/frameworks/tf_keras/mlrun_interface.py +2 -2
  88. mlrun/frameworks/xgboost/__init__.py +1 -1
  89. mlrun/k8s_utils.py +10 -11
  90. mlrun/launcher/__init__.py +1 -1
  91. mlrun/launcher/base.py +6 -5
  92. mlrun/launcher/client.py +8 -6
  93. mlrun/launcher/factory.py +1 -1
  94. mlrun/launcher/local.py +9 -3
  95. mlrun/launcher/remote.py +9 -3
  96. mlrun/lists.py +6 -2
  97. mlrun/model.py +58 -19
  98. mlrun/model_monitoring/__init__.py +1 -1
  99. mlrun/model_monitoring/api.py +127 -301
  100. mlrun/model_monitoring/application.py +5 -296
  101. mlrun/model_monitoring/applications/__init__.py +11 -0
  102. mlrun/model_monitoring/applications/_application_steps.py +157 -0
  103. mlrun/model_monitoring/applications/base.py +282 -0
  104. mlrun/model_monitoring/applications/context.py +214 -0
  105. mlrun/model_monitoring/applications/evidently_base.py +211 -0
  106. mlrun/model_monitoring/applications/histogram_data_drift.py +224 -93
  107. mlrun/model_monitoring/applications/results.py +99 -0
  108. mlrun/model_monitoring/controller.py +30 -36
  109. mlrun/model_monitoring/db/__init__.py +18 -0
  110. mlrun/model_monitoring/{stores → db/stores}/__init__.py +43 -36
  111. mlrun/model_monitoring/db/stores/base/__init__.py +15 -0
  112. mlrun/model_monitoring/{stores/model_endpoint_store.py → db/stores/base/store.py} +58 -32
  113. mlrun/model_monitoring/db/stores/sqldb/__init__.py +13 -0
  114. mlrun/model_monitoring/db/stores/sqldb/models/__init__.py +71 -0
  115. mlrun/model_monitoring/{stores → db/stores/sqldb}/models/base.py +109 -5
  116. mlrun/model_monitoring/db/stores/sqldb/models/mysql.py +88 -0
  117. mlrun/model_monitoring/{stores/models/mysql.py → db/stores/sqldb/models/sqlite.py} +19 -13
  118. mlrun/model_monitoring/db/stores/sqldb/sql_store.py +684 -0
  119. mlrun/model_monitoring/db/stores/v3io_kv/__init__.py +13 -0
  120. mlrun/model_monitoring/{stores/kv_model_endpoint_store.py → db/stores/v3io_kv/kv_store.py} +302 -155
  121. mlrun/model_monitoring/db/tsdb/__init__.py +100 -0
  122. mlrun/model_monitoring/db/tsdb/base.py +329 -0
  123. mlrun/model_monitoring/db/tsdb/helpers.py +30 -0
  124. mlrun/model_monitoring/db/tsdb/tdengine/__init__.py +15 -0
  125. mlrun/model_monitoring/db/tsdb/tdengine/schemas.py +240 -0
  126. mlrun/model_monitoring/db/tsdb/tdengine/stream_graph_steps.py +45 -0
  127. mlrun/model_monitoring/db/tsdb/tdengine/tdengine_connector.py +397 -0
  128. mlrun/model_monitoring/db/tsdb/v3io/__init__.py +15 -0
  129. mlrun/model_monitoring/db/tsdb/v3io/stream_graph_steps.py +117 -0
  130. mlrun/model_monitoring/db/tsdb/v3io/v3io_connector.py +630 -0
  131. mlrun/model_monitoring/evidently_application.py +6 -118
  132. mlrun/model_monitoring/features_drift_table.py +34 -22
  133. mlrun/model_monitoring/helpers.py +100 -7
  134. mlrun/model_monitoring/model_endpoint.py +3 -2
  135. mlrun/model_monitoring/stream_processing.py +93 -228
  136. mlrun/model_monitoring/tracking_policy.py +7 -1
  137. mlrun/model_monitoring/writer.py +152 -124
  138. mlrun/package/packagers_manager.py +1 -0
  139. mlrun/package/utils/_formatter.py +2 -2
  140. mlrun/platforms/__init__.py +11 -10
  141. mlrun/platforms/iguazio.py +21 -202
  142. mlrun/projects/operations.py +30 -16
  143. mlrun/projects/pipelines.py +92 -99
  144. mlrun/projects/project.py +757 -268
  145. mlrun/render.py +15 -14
  146. mlrun/run.py +160 -162
  147. mlrun/runtimes/__init__.py +55 -3
  148. mlrun/runtimes/base.py +33 -19
  149. mlrun/runtimes/databricks_job/databricks_wrapper.py +1 -1
  150. mlrun/runtimes/funcdoc.py +0 -28
  151. mlrun/runtimes/kubejob.py +28 -122
  152. mlrun/runtimes/local.py +5 -2
  153. mlrun/runtimes/mpijob/__init__.py +0 -20
  154. mlrun/runtimes/mpijob/abstract.py +8 -8
  155. mlrun/runtimes/mpijob/v1.py +1 -1
  156. mlrun/runtimes/nuclio/__init__.py +1 -0
  157. mlrun/runtimes/nuclio/api_gateway.py +709 -0
  158. mlrun/runtimes/nuclio/application/__init__.py +15 -0
  159. mlrun/runtimes/nuclio/application/application.py +523 -0
  160. mlrun/runtimes/nuclio/application/reverse_proxy.go +95 -0
  161. mlrun/runtimes/nuclio/function.py +98 -58
  162. mlrun/runtimes/nuclio/serving.py +36 -42
  163. mlrun/runtimes/pod.py +196 -45
  164. mlrun/runtimes/remotesparkjob.py +1 -1
  165. mlrun/runtimes/sparkjob/spark3job.py +1 -1
  166. mlrun/runtimes/utils.py +6 -73
  167. mlrun/secrets.py +6 -2
  168. mlrun/serving/remote.py +2 -3
  169. mlrun/serving/routers.py +7 -4
  170. mlrun/serving/server.py +7 -8
  171. mlrun/serving/states.py +73 -43
  172. mlrun/serving/v2_serving.py +8 -7
  173. mlrun/track/tracker.py +2 -1
  174. mlrun/utils/async_http.py +25 -5
  175. mlrun/utils/helpers.py +141 -75
  176. mlrun/utils/http.py +1 -1
  177. mlrun/utils/logger.py +39 -7
  178. mlrun/utils/notifications/notification/__init__.py +14 -9
  179. mlrun/utils/notifications/notification/base.py +12 -0
  180. mlrun/utils/notifications/notification/console.py +2 -0
  181. mlrun/utils/notifications/notification/git.py +3 -1
  182. mlrun/utils/notifications/notification/ipython.py +2 -0
  183. mlrun/utils/notifications/notification/slack.py +101 -21
  184. mlrun/utils/notifications/notification/webhook.py +11 -1
  185. mlrun/utils/notifications/notification_pusher.py +147 -16
  186. mlrun/utils/retryer.py +3 -2
  187. mlrun/utils/v3io_clients.py +0 -1
  188. mlrun/utils/version/version.json +2 -2
  189. {mlrun-1.7.0rc4.dist-info → mlrun-1.7.0rc20.dist-info}/METADATA +33 -18
  190. mlrun-1.7.0rc20.dist-info/RECORD +353 -0
  191. {mlrun-1.7.0rc4.dist-info → mlrun-1.7.0rc20.dist-info}/WHEEL +1 -1
  192. mlrun/kfpops.py +0 -868
  193. mlrun/model_monitoring/batch.py +0 -974
  194. mlrun/model_monitoring/stores/models/__init__.py +0 -27
  195. mlrun/model_monitoring/stores/sql_model_endpoint_store.py +0 -382
  196. mlrun/platforms/other.py +0 -305
  197. mlrun-1.7.0rc4.dist-info/RECORD +0 -321
  198. {mlrun-1.7.0rc4.dist-info → mlrun-1.7.0rc20.dist-info}/LICENSE +0 -0
  199. {mlrun-1.7.0rc4.dist-info → mlrun-1.7.0rc20.dist-info}/entry_points.txt +0 -0
  200. {mlrun-1.7.0rc4.dist-info → mlrun-1.7.0rc20.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,329 @@
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
+ @abstractmethod
181
+ def read_prediction_metric_for_endpoint_if_exists(
182
+ self, endpoint_id: str
183
+ ) -> typing.Optional[mm_schemas.ModelEndpointMonitoringMetric]:
184
+ """
185
+ Read the "invocations" metric for the provided model endpoint, and return the metric object
186
+ if it exists.
187
+
188
+ :param endpoint_id: The model endpoint identifier.
189
+ :return: `None` if the invocations metric does not exist, otherwise return the
190
+ corresponding metric object.
191
+ """
192
+
193
+ @staticmethod
194
+ def df_to_metrics_values(
195
+ *,
196
+ df: pd.DataFrame,
197
+ metrics: list[mm_schemas.ModelEndpointMonitoringMetric],
198
+ project: str,
199
+ ) -> list[
200
+ typing.Union[
201
+ mm_schemas.ModelEndpointMonitoringMetricValues,
202
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
203
+ ]
204
+ ]:
205
+ """
206
+ Parse a time-indexed DataFrame of metrics from the TSDB into a list of
207
+ metrics values per distinct results.
208
+ When a metric is not found in the DataFrame, it is represented in a no-data object.
209
+ """
210
+ metrics_without_data = {metric.full_name: metric for metric in metrics}
211
+
212
+ metrics_values: list[
213
+ typing.Union[
214
+ mm_schemas.ModelEndpointMonitoringMetricValues,
215
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
216
+ ]
217
+ ] = []
218
+ if not df.empty:
219
+ grouped = df.groupby(
220
+ [
221
+ mm_schemas.WriterEvent.APPLICATION_NAME,
222
+ mm_schemas.MetricData.METRIC_NAME,
223
+ ],
224
+ observed=False,
225
+ )
226
+ else:
227
+ logger.debug("No metrics", missing_metrics=metrics_without_data.keys())
228
+ grouped = []
229
+ for (app_name, name), sub_df in grouped:
230
+ full_name = mlrun.model_monitoring.helpers._compose_full_name(
231
+ project=project,
232
+ app=app_name,
233
+ name=name,
234
+ type=mm_schemas.ModelEndpointMonitoringMetricType.METRIC,
235
+ )
236
+ metrics_values.append(
237
+ mm_schemas.ModelEndpointMonitoringMetricValues(
238
+ full_name=full_name,
239
+ values=list(
240
+ zip(
241
+ sub_df.index,
242
+ sub_df[mm_schemas.MetricData.METRIC_VALUE],
243
+ )
244
+ ), # pyright: ignore[reportArgumentType]
245
+ )
246
+ )
247
+ del metrics_without_data[full_name]
248
+
249
+ for metric in metrics_without_data.values():
250
+ metrics_values.append(
251
+ mm_schemas.ModelEndpointMonitoringMetricNoData(
252
+ full_name=metric.full_name,
253
+ type=mm_schemas.ModelEndpointMonitoringMetricType.METRIC,
254
+ )
255
+ )
256
+
257
+ return metrics_values
258
+
259
+ @staticmethod
260
+ def df_to_results_values(
261
+ *,
262
+ df: pd.DataFrame,
263
+ metrics: list[mm_schemas.ModelEndpointMonitoringMetric],
264
+ project: str,
265
+ ) -> list[
266
+ typing.Union[
267
+ mm_schemas.ModelEndpointMonitoringResultValues,
268
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
269
+ ]
270
+ ]:
271
+ """
272
+ Parse a time-indexed DataFrame of results from the TSDB into a list of
273
+ results values per distinct results.
274
+ When a result is not found in the DataFrame, it is represented in no-data object.
275
+ """
276
+ metrics_without_data = {metric.full_name: metric for metric in metrics}
277
+
278
+ metrics_values: list[
279
+ typing.Union[
280
+ mm_schemas.ModelEndpointMonitoringResultValues,
281
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
282
+ ]
283
+ ] = []
284
+ if not df.empty:
285
+ grouped = df.groupby(
286
+ [
287
+ mm_schemas.WriterEvent.APPLICATION_NAME,
288
+ mm_schemas.ResultData.RESULT_NAME,
289
+ ],
290
+ observed=False,
291
+ )
292
+ else:
293
+ grouped = []
294
+ logger.debug("No results", missing_results=metrics_without_data.keys())
295
+ for (app_name, name), sub_df in grouped:
296
+ result_kind = mlrun.model_monitoring.db.tsdb.helpers._get_result_kind(
297
+ sub_df
298
+ )
299
+ full_name = mlrun.model_monitoring.helpers._compose_full_name(
300
+ project=project, app=app_name, name=name
301
+ )
302
+ metrics_values.append(
303
+ mm_schemas.ModelEndpointMonitoringResultValues(
304
+ full_name=full_name,
305
+ result_kind=result_kind,
306
+ values=list(
307
+ zip(
308
+ sub_df.index,
309
+ sub_df[mm_schemas.ResultData.RESULT_VALUE],
310
+ sub_df[mm_schemas.ResultData.RESULT_STATUS],
311
+ )
312
+ ), # pyright: ignore[reportArgumentType]
313
+ )
314
+ )
315
+ del metrics_without_data[full_name]
316
+
317
+ for metric in metrics_without_data.values():
318
+ if metric.full_name == mlrun.model_monitoring.helpers.get_invocations_fqn(
319
+ project
320
+ ):
321
+ continue
322
+ metrics_values.append(
323
+ mm_schemas.ModelEndpointMonitoringMetricNoData(
324
+ full_name=metric.full_name,
325
+ type=mm_schemas.ModelEndpointMonitoringMetricType.RESULT,
326
+ )
327
+ )
328
+
329
+ 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
@@ -0,0 +1,240 @@
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 datetime
16
+ from dataclasses import dataclass
17
+ from io import StringIO
18
+ from typing import Optional, Union
19
+
20
+ import mlrun.common.schemas.model_monitoring as mm_schemas
21
+ import mlrun.common.types
22
+
23
+ _MODEL_MONITORING_DATABASE = "mlrun_model_monitoring"
24
+
25
+
26
+ class _TDEngineColumnType:
27
+ def __init__(self, data_type: str, length: int = None):
28
+ self.data_type = data_type
29
+ self.length = length
30
+
31
+ def __str__(self):
32
+ if self.length is not None:
33
+ return f"{self.data_type}({self.length})"
34
+ else:
35
+ return self.data_type
36
+
37
+
38
+ class _TDEngineColumn(mlrun.common.types.StrEnum):
39
+ TIMESTAMP = _TDEngineColumnType("TIMESTAMP")
40
+ FLOAT = _TDEngineColumnType("FLOAT")
41
+ INT = _TDEngineColumnType("INT")
42
+ BINARY_40 = _TDEngineColumnType("BINARY", 40)
43
+ BINARY_64 = _TDEngineColumnType("BINARY", 64)
44
+ BINARY_10000 = _TDEngineColumnType("BINARY", 10000)
45
+
46
+
47
+ @dataclass
48
+ class TDEngineSchema:
49
+ """
50
+ A class to represent a supertable schema in TDengine. Using this schema, you can generate the relevant queries to
51
+ create, insert, delete and query data from TDengine. At the moment, there are 3 schemas: AppResultTable,
52
+ Metrics, and Predictions.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ super_table: str,
58
+ columns: dict[str, str],
59
+ tags: dict[str, str],
60
+ ):
61
+ self.super_table = super_table
62
+ self.columns = columns
63
+ self.tags = tags
64
+ self.database = _MODEL_MONITORING_DATABASE
65
+
66
+ def _create_super_table_query(self) -> str:
67
+ columns = ", ".join(f"{col} {val}" for col, val in self.columns.items())
68
+ tags = ", ".join(f"{col} {val}" for col, val in self.tags.items())
69
+ return f"CREATE STABLE if NOT EXISTS {self.database}.{self.super_table} ({columns}) TAGS ({tags});"
70
+
71
+ def _create_subtable_query(
72
+ self,
73
+ subtable: str,
74
+ values: dict[str, Union[str, int, float, datetime.datetime]],
75
+ ) -> str:
76
+ try:
77
+ values = ", ".join(f"'{values[val]}'" for val in self.tags)
78
+ except KeyError:
79
+ raise mlrun.errors.MLRunInvalidArgumentError(
80
+ f"values must contain all tags: {self.tags.keys()}"
81
+ )
82
+ return f"CREATE TABLE if NOT EXISTS {self.database}.{subtable} USING {self.super_table} TAGS ({values});"
83
+
84
+ def _insert_subtable_query(
85
+ self,
86
+ subtable: str,
87
+ values: dict[str, Union[str, int, float, datetime.datetime]],
88
+ ) -> str:
89
+ values = ", ".join(f"'{values[val]}'" for val in self.columns)
90
+ return f"INSERT INTO {self.database}.{subtable} VALUES ({values});"
91
+
92
+ def _delete_subtable_query(
93
+ self,
94
+ subtable: str,
95
+ values: dict[str, Union[str, int, float, datetime.datetime]],
96
+ ) -> str:
97
+ values = " AND ".join(
98
+ f"{val} LIKE '{values[val]}'" for val in self.tags if val in values
99
+ )
100
+ if not values:
101
+ raise mlrun.errors.MLRunInvalidArgumentError(
102
+ f"values must contain at least one tag: {self.tags.keys()}"
103
+ )
104
+ return f"DELETE FROM {self.database}.{subtable} WHERE {values};"
105
+
106
+ def _drop_subtable_query(
107
+ self,
108
+ subtable: str,
109
+ ) -> str:
110
+ return f"DROP TABLE if EXISTS {self.database}.{subtable};"
111
+
112
+ def _get_subtables_query(
113
+ self,
114
+ values: dict[str, Union[str, int, float, datetime.datetime]],
115
+ ) -> str:
116
+ values = " AND ".join(
117
+ f"{val} LIKE '{values[val]}'" for val in self.tags if val in values
118
+ )
119
+ if not values:
120
+ raise mlrun.errors.MLRunInvalidArgumentError(
121
+ f"values must contain at least one tag: {self.tags.keys()}"
122
+ )
123
+ return f"SELECT tbname FROM {self.database}.{self.super_table} WHERE {values};"
124
+
125
+ @staticmethod
126
+ def _get_records_query(
127
+ table: str,
128
+ start: datetime,
129
+ end: datetime,
130
+ columns_to_filter: list[str] = None,
131
+ filter_query: Optional[str] = None,
132
+ interval: Optional[str] = None,
133
+ limit: int = 0,
134
+ agg_funcs: Optional[list] = None,
135
+ sliding_window_step: Optional[str] = None,
136
+ timestamp_column: str = "time",
137
+ database: str = _MODEL_MONITORING_DATABASE,
138
+ ) -> str:
139
+ if agg_funcs and not columns_to_filter:
140
+ raise mlrun.errors.MLRunInvalidArgumentError(
141
+ "`columns_to_filter` must be provided when using aggregate functions"
142
+ )
143
+
144
+ # if aggregate function or interval is provided, the other must be provided as well
145
+ if interval and not agg_funcs:
146
+ raise mlrun.errors.MLRunInvalidArgumentError(
147
+ "`agg_funcs` must be provided when using interval"
148
+ )
149
+
150
+ if sliding_window_step and not interval:
151
+ raise mlrun.errors.MLRunInvalidArgumentError(
152
+ "`interval` must be provided when using sliding window"
153
+ )
154
+
155
+ with StringIO() as query:
156
+ query.write("SELECT ")
157
+ if interval:
158
+ query.write("_wstart, _wend, ")
159
+ if agg_funcs:
160
+ query.write(
161
+ ", ".join(
162
+ [f"{a}({col})" for a in agg_funcs for col in columns_to_filter]
163
+ )
164
+ )
165
+ elif columns_to_filter:
166
+ query.write(", ".join(columns_to_filter))
167
+ else:
168
+ query.write("*")
169
+ query.write(f" FROM {database}.{table}")
170
+
171
+ if any([filter_query, start, end]):
172
+ query.write(" WHERE ")
173
+ if filter_query:
174
+ query.write(f"{filter_query} AND ")
175
+ if start:
176
+ query.write(f"{timestamp_column} >= '{start}'" + " AND ")
177
+ if end:
178
+ query.write(f"{timestamp_column} <= '{end}'")
179
+ if interval:
180
+ query.write(f" INTERVAL({interval})")
181
+ if sliding_window_step:
182
+ query.write(f" SLIDING({sliding_window_step})")
183
+ if limit:
184
+ query.write(f" LIMIT {limit}")
185
+ query.write(";")
186
+ return query.getvalue()
187
+
188
+
189
+ @dataclass
190
+ class AppResultTable(TDEngineSchema):
191
+ super_table = mm_schemas.TDEngineSuperTables.APP_RESULTS
192
+ columns = {
193
+ mm_schemas.WriterEvent.END_INFER_TIME: _TDEngineColumn.TIMESTAMP,
194
+ mm_schemas.WriterEvent.START_INFER_TIME: _TDEngineColumn.TIMESTAMP,
195
+ mm_schemas.ResultData.RESULT_VALUE: _TDEngineColumn.FLOAT,
196
+ mm_schemas.ResultData.RESULT_STATUS: _TDEngineColumn.INT,
197
+ mm_schemas.ResultData.CURRENT_STATS: _TDEngineColumn.BINARY_10000,
198
+ }
199
+
200
+ tags = {
201
+ mm_schemas.EventFieldType.PROJECT: _TDEngineColumn.BINARY_64,
202
+ mm_schemas.WriterEvent.ENDPOINT_ID: _TDEngineColumn.BINARY_64,
203
+ mm_schemas.WriterEvent.APPLICATION_NAME: _TDEngineColumn.BINARY_64,
204
+ mm_schemas.ResultData.RESULT_NAME: _TDEngineColumn.BINARY_64,
205
+ mm_schemas.ResultData.RESULT_KIND: _TDEngineColumn.INT,
206
+ }
207
+ database = _MODEL_MONITORING_DATABASE
208
+
209
+
210
+ @dataclass
211
+ class Metrics(TDEngineSchema):
212
+ super_table = mm_schemas.TDEngineSuperTables.METRICS
213
+ columns = {
214
+ mm_schemas.WriterEvent.END_INFER_TIME: _TDEngineColumn.TIMESTAMP,
215
+ mm_schemas.WriterEvent.START_INFER_TIME: _TDEngineColumn.TIMESTAMP,
216
+ mm_schemas.MetricData.METRIC_VALUE: _TDEngineColumn.FLOAT,
217
+ }
218
+
219
+ tags = {
220
+ mm_schemas.EventFieldType.PROJECT: _TDEngineColumn.BINARY_64,
221
+ mm_schemas.WriterEvent.ENDPOINT_ID: _TDEngineColumn.BINARY_64,
222
+ mm_schemas.WriterEvent.APPLICATION_NAME: _TDEngineColumn.BINARY_64,
223
+ mm_schemas.MetricData.METRIC_NAME: _TDEngineColumn.BINARY_64,
224
+ }
225
+ database = _MODEL_MONITORING_DATABASE
226
+
227
+
228
+ @dataclass
229
+ class Predictions(TDEngineSchema):
230
+ super_table = mm_schemas.TDEngineSuperTables.PREDICTIONS
231
+ columns = {
232
+ mm_schemas.EventFieldType.TIME: _TDEngineColumn.TIMESTAMP,
233
+ mm_schemas.EventFieldType.LATENCY: _TDEngineColumn.FLOAT,
234
+ mm_schemas.EventKeyMetrics.CUSTOM_METRICS: _TDEngineColumn.BINARY_10000,
235
+ }
236
+ tags = {
237
+ mm_schemas.EventFieldType.PROJECT: _TDEngineColumn.BINARY_64,
238
+ mm_schemas.WriterEvent.ENDPOINT_ID: _TDEngineColumn.BINARY_64,
239
+ }
240
+ database = _MODEL_MONITORING_DATABASE
@@ -0,0 +1,45 @@
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
+
16
+ import json
17
+
18
+ import mlrun.feature_store.steps
19
+ from mlrun.common.schemas.model_monitoring import (
20
+ EventFieldType,
21
+ EventKeyMetrics,
22
+ )
23
+
24
+ _TABLE_COLUMN = "table_column"
25
+
26
+
27
+ class ProcessBeforeTDEngine(mlrun.feature_store.steps.MapClass):
28
+ def __init__(self, **kwargs):
29
+ """
30
+ Process the data before writing to TDEngine. This step create the relevant keys for the TDEngine table,
31
+ including project name, custom metrics, time column, and table name column.
32
+
33
+ :returns: Event as a dictionary which will be written into the TDEngine Predictions table.
34
+ """
35
+ super().__init__(**kwargs)
36
+
37
+ def do(self, event):
38
+ event[EventFieldType.PROJECT] = event[EventFieldType.FUNCTION_URI].split("/")[0]
39
+ event[EventKeyMetrics.CUSTOM_METRICS] = json.dumps(
40
+ event.get(EventFieldType.METRICS, {})
41
+ )
42
+ event[EventFieldType.TIME] = event.get(EventFieldType.TIMESTAMP)
43
+ event[EventFieldType.TABLE_COLUMN] = "_" + event.get(EventFieldType.ENDPOINT_ID)
44
+
45
+ return event