mlrun 1.7.0rc17__py3-none-any.whl → 1.7.0rc19__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 (90) hide show
  1. mlrun/__main__.py +5 -2
  2. mlrun/alerts/alert.py +1 -1
  3. mlrun/artifacts/manager.py +5 -1
  4. mlrun/common/constants.py +64 -3
  5. mlrun/common/formatters/__init__.py +16 -0
  6. mlrun/common/formatters/base.py +59 -0
  7. mlrun/common/formatters/function.py +41 -0
  8. mlrun/common/runtimes/constants.py +32 -4
  9. mlrun/common/schemas/__init__.py +1 -2
  10. mlrun/common/schemas/alert.py +31 -9
  11. mlrun/common/schemas/api_gateway.py +52 -0
  12. mlrun/common/schemas/client_spec.py +1 -0
  13. mlrun/common/schemas/frontend_spec.py +1 -0
  14. mlrun/common/schemas/function.py +4 -0
  15. mlrun/common/schemas/model_monitoring/__init__.py +9 -4
  16. mlrun/common/schemas/model_monitoring/constants.py +22 -8
  17. mlrun/common/schemas/model_monitoring/grafana.py +9 -5
  18. mlrun/common/schemas/model_monitoring/model_endpoints.py +17 -6
  19. mlrun/config.py +9 -2
  20. mlrun/data_types/to_pandas.py +5 -5
  21. mlrun/datastore/datastore.py +6 -2
  22. mlrun/datastore/redis.py +2 -2
  23. mlrun/datastore/s3.py +5 -0
  24. mlrun/datastore/sources.py +106 -7
  25. mlrun/datastore/store_resources.py +5 -1
  26. mlrun/datastore/targets.py +5 -4
  27. mlrun/datastore/utils.py +42 -0
  28. mlrun/db/base.py +5 -1
  29. mlrun/db/httpdb.py +22 -3
  30. mlrun/db/nopdb.py +5 -1
  31. mlrun/errors.py +6 -0
  32. mlrun/execution.py +16 -6
  33. mlrun/feature_store/ingestion.py +7 -6
  34. mlrun/feature_store/retrieval/conversion.py +5 -5
  35. mlrun/feature_store/retrieval/job.py +7 -3
  36. mlrun/feature_store/retrieval/spark_merger.py +2 -1
  37. mlrun/frameworks/_dl_common/loggers/tensorboard_logger.py +2 -2
  38. mlrun/frameworks/parallel_coordinates.py +2 -1
  39. mlrun/frameworks/tf_keras/__init__.py +4 -1
  40. mlrun/launcher/client.py +4 -2
  41. mlrun/launcher/local.py +8 -2
  42. mlrun/launcher/remote.py +8 -2
  43. mlrun/model.py +5 -1
  44. mlrun/model_monitoring/db/stores/__init__.py +0 -2
  45. mlrun/model_monitoring/db/stores/base/store.py +16 -4
  46. mlrun/model_monitoring/db/stores/sqldb/models/__init__.py +43 -21
  47. mlrun/model_monitoring/db/stores/sqldb/models/base.py +32 -2
  48. mlrun/model_monitoring/db/stores/sqldb/models/mysql.py +25 -5
  49. mlrun/model_monitoring/db/stores/sqldb/models/sqlite.py +5 -0
  50. mlrun/model_monitoring/db/stores/sqldb/sql_store.py +235 -166
  51. mlrun/model_monitoring/db/stores/v3io_kv/kv_store.py +190 -91
  52. mlrun/model_monitoring/db/tsdb/__init__.py +35 -6
  53. mlrun/model_monitoring/db/tsdb/base.py +232 -38
  54. mlrun/model_monitoring/db/tsdb/helpers.py +30 -0
  55. mlrun/model_monitoring/db/tsdb/tdengine/__init__.py +15 -0
  56. mlrun/model_monitoring/db/tsdb/tdengine/schemas.py +240 -0
  57. mlrun/model_monitoring/db/tsdb/tdengine/stream_graph_steps.py +45 -0
  58. mlrun/model_monitoring/db/tsdb/tdengine/tdengine_connector.py +397 -0
  59. mlrun/model_monitoring/db/tsdb/v3io/v3io_connector.py +292 -104
  60. mlrun/model_monitoring/helpers.py +45 -0
  61. mlrun/model_monitoring/stream_processing.py +7 -4
  62. mlrun/model_monitoring/writer.py +50 -20
  63. mlrun/package/utils/_formatter.py +2 -2
  64. mlrun/projects/operations.py +8 -5
  65. mlrun/projects/pipelines.py +42 -15
  66. mlrun/projects/project.py +55 -14
  67. mlrun/render.py +8 -5
  68. mlrun/runtimes/base.py +2 -1
  69. mlrun/runtimes/databricks_job/databricks_wrapper.py +1 -1
  70. mlrun/runtimes/local.py +4 -1
  71. mlrun/runtimes/nuclio/api_gateway.py +32 -8
  72. mlrun/runtimes/nuclio/application/application.py +3 -3
  73. mlrun/runtimes/nuclio/function.py +1 -4
  74. mlrun/runtimes/utils.py +5 -6
  75. mlrun/serving/server.py +2 -1
  76. mlrun/utils/async_http.py +25 -5
  77. mlrun/utils/helpers.py +28 -7
  78. mlrun/utils/logger.py +28 -1
  79. mlrun/utils/notifications/notification/__init__.py +14 -9
  80. mlrun/utils/notifications/notification/slack.py +27 -7
  81. mlrun/utils/notifications/notification_pusher.py +47 -42
  82. mlrun/utils/v3io_clients.py +0 -1
  83. mlrun/utils/version/version.json +2 -2
  84. {mlrun-1.7.0rc17.dist-info → mlrun-1.7.0rc19.dist-info}/METADATA +9 -4
  85. {mlrun-1.7.0rc17.dist-info → mlrun-1.7.0rc19.dist-info}/RECORD +89 -82
  86. mlrun/model_monitoring/db/v3io_tsdb_reader.py +0 -134
  87. {mlrun-1.7.0rc17.dist-info → mlrun-1.7.0rc19.dist-info}/LICENSE +0 -0
  88. {mlrun-1.7.0rc17.dist-info → mlrun-1.7.0rc19.dist-info}/WHEEL +0 -0
  89. {mlrun-1.7.0rc17.dist-info → mlrun-1.7.0rc19.dist-info}/entry_points.txt +0 -0
  90. {mlrun-1.7.0rc17.dist-info → mlrun-1.7.0rc19.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,397 @@
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 datetime import datetime
17
+
18
+ import pandas as pd
19
+ import taosws
20
+
21
+ import mlrun.common.schemas.model_monitoring as mm_schemas
22
+ import mlrun.model_monitoring.db.tsdb.tdengine.schemas as tdengine_schemas
23
+ import mlrun.model_monitoring.db.tsdb.tdengine.stream_graph_steps
24
+ from mlrun.model_monitoring.db import TSDBConnector
25
+ from mlrun.model_monitoring.helpers import get_invocations_fqn
26
+ from mlrun.utils import logger
27
+
28
+
29
+ class TDEngineConnector(TSDBConnector):
30
+ """
31
+ Handles the TSDB operations when the TSDB connector is of type TDEngine.
32
+ """
33
+
34
+ type: str = mm_schemas.TSDBTarget.TDEngine
35
+
36
+ def __init__(
37
+ self,
38
+ project: str,
39
+ database: str = tdengine_schemas._MODEL_MONITORING_DATABASE,
40
+ **kwargs,
41
+ ):
42
+ super().__init__(project=project)
43
+ if "connection_string" not in kwargs:
44
+ raise mlrun.errors.MLRunInvalidArgumentError(
45
+ "connection_string is a required parameter for TDEngineConnector."
46
+ )
47
+ self._tdengine_connection_string = kwargs.get("connection_string")
48
+ self.database = database
49
+ self._connection = self._create_connection()
50
+ self._init_super_tables()
51
+
52
+ def _create_connection(self):
53
+ """Establish a connection to the TSDB server."""
54
+ conn = taosws.connect(self._tdengine_connection_string)
55
+ try:
56
+ conn.execute(f"CREATE DATABASE {self.database}")
57
+ except taosws.QueryError:
58
+ # Database already exists
59
+ pass
60
+ conn.execute(f"USE {self.database}")
61
+ return conn
62
+
63
+ def _init_super_tables(self):
64
+ """Initialize the super tables for the TSDB."""
65
+ self.tables = {
66
+ mm_schemas.TDEngineSuperTables.APP_RESULTS: tdengine_schemas.AppResultTable(),
67
+ mm_schemas.TDEngineSuperTables.METRICS: tdengine_schemas.Metrics(),
68
+ mm_schemas.TDEngineSuperTables.PREDICTIONS: tdengine_schemas.Predictions(),
69
+ }
70
+
71
+ def create_tables(self):
72
+ """Create TDEngine supertables."""
73
+ for table in self.tables:
74
+ create_table_query = self.tables[table]._create_super_table_query()
75
+ self._connection.execute(create_table_query)
76
+
77
+ def write_application_event(
78
+ self,
79
+ event: dict,
80
+ kind: mm_schemas.WriterEventKind = mm_schemas.WriterEventKind.RESULT,
81
+ ):
82
+ """
83
+ Write a single result or metric to TSDB.
84
+ """
85
+
86
+ table_name = (
87
+ f"{self.project}_"
88
+ f"{event[mm_schemas.WriterEvent.ENDPOINT_ID]}_"
89
+ f"{event[mm_schemas.WriterEvent.APPLICATION_NAME]}_"
90
+ )
91
+ event[mm_schemas.EventFieldType.PROJECT] = self.project
92
+
93
+ if kind == mm_schemas.WriterEventKind.RESULT:
94
+ # Write a new result
95
+ table = self.tables[mm_schemas.TDEngineSuperTables.APP_RESULTS]
96
+ table_name = (
97
+ f"{table_name}_" f"{event[mm_schemas.ResultData.RESULT_NAME]}"
98
+ ).replace("-", "_")
99
+
100
+ else:
101
+ # Write a new metric
102
+ table = self.tables[mm_schemas.TDEngineSuperTables.METRICS]
103
+ table_name = (
104
+ f"{table_name}_" f"{event[mm_schemas.MetricData.METRIC_NAME]}"
105
+ ).replace("-", "_")
106
+
107
+ create_table_query = table._create_subtable_query(
108
+ subtable=table_name, values=event
109
+ )
110
+ self._connection.execute(create_table_query)
111
+ insert_table_query = table._insert_subtable_query(
112
+ subtable=table_name, values=event
113
+ )
114
+ self._connection.execute(insert_table_query)
115
+
116
+ def apply_monitoring_stream_steps(self, graph):
117
+ """
118
+ Apply TSDB steps on the provided monitoring graph. Throughout these steps, the graph stores live data of
119
+ different key metric dictionaries. This data is being used by the monitoring dashboards in
120
+ grafana. At the moment, we store two types of data:
121
+ - prediction latency.
122
+ - custom metrics.
123
+ """
124
+
125
+ def apply_process_before_tsdb():
126
+ graph.add_step(
127
+ "mlrun.model_monitoring.db.tsdb.tdengine.stream_graph_steps.ProcessBeforeTDEngine",
128
+ name="ProcessBeforeTDEngine",
129
+ after="MapFeatureNames",
130
+ )
131
+
132
+ def apply_tdengine_target(name, after):
133
+ graph.add_step(
134
+ "storey.TDEngineTarget",
135
+ name=name,
136
+ after=after,
137
+ url=self._tdengine_connection_string,
138
+ supertable=mm_schemas.TDEngineSuperTables.PREDICTIONS,
139
+ table_col=mm_schemas.EventFieldType.TABLE_COLUMN,
140
+ time_col=mm_schemas.EventFieldType.TIME,
141
+ database=self.database,
142
+ columns=[
143
+ mm_schemas.EventFieldType.LATENCY,
144
+ mm_schemas.EventKeyMetrics.CUSTOM_METRICS,
145
+ ],
146
+ tag_cols=[
147
+ mm_schemas.EventFieldType.PROJECT,
148
+ mm_schemas.EventFieldType.ENDPOINT_ID,
149
+ ],
150
+ max_events=10,
151
+ )
152
+
153
+ apply_process_before_tsdb()
154
+ apply_tdengine_target(
155
+ name="TDEngineTarget",
156
+ after="ProcessBeforeTDEngine",
157
+ )
158
+
159
+ def delete_tsdb_resources(self):
160
+ """
161
+ Delete all project resources in the TSDB connector, such as model endpoints data and drift results.
162
+ """
163
+ for table in self.tables:
164
+ get_subtable_names_query = self.tables[table]._get_subtables_query(
165
+ values={mm_schemas.EventFieldType.PROJECT: self.project}
166
+ )
167
+ subtables = self._connection.query(get_subtable_names_query)
168
+ for subtable in subtables:
169
+ drop_query = self.tables[table]._drop_subtable_query(
170
+ subtable=subtable[0]
171
+ )
172
+ self._connection.execute(drop_query)
173
+ logger.info(
174
+ f"Deleted all project resources in the TSDB connector for project {self.project}"
175
+ )
176
+
177
+ def get_model_endpoint_real_time_metrics(
178
+ self,
179
+ endpoint_id: str,
180
+ metrics: list[str],
181
+ start: str,
182
+ end: str,
183
+ ) -> dict[str, list[tuple[str, float]]]:
184
+ # Not implemented, use get_records() instead
185
+ pass
186
+
187
+ def _get_records(
188
+ self,
189
+ table: str,
190
+ start: datetime,
191
+ end: datetime,
192
+ columns: typing.Optional[list[str]] = None,
193
+ filter_query: typing.Optional[str] = None,
194
+ interval: typing.Optional[str] = None,
195
+ agg_funcs: typing.Optional[list] = None,
196
+ limit: typing.Optional[int] = None,
197
+ sliding_window_step: typing.Optional[str] = None,
198
+ timestamp_column: str = mm_schemas.EventFieldType.TIME,
199
+ ) -> pd.DataFrame:
200
+ """
201
+ Getting records from TSDB data collection.
202
+ :param table: Either a supertable or a subtable name.
203
+ :param start: The start time of the metrics.
204
+ :param end: The end time of the metrics.
205
+ :param columns: Columns to include in the result.
206
+ :param filter_query: Optional filter expression as a string. TDengine supports SQL-like syntax.
207
+ :param interval: The interval to aggregate the data by. Note that if interval is provided,
208
+ `agg_funcs` must bg provided as well. Provided as a string in the format of '1m',
209
+ '1h', etc.
210
+ :param agg_funcs: The aggregation functions to apply on the columns. Note that if `agg_funcs` is
211
+ provided, `interval` must bg provided as well. Provided as a list of strings in
212
+ the format of ['sum', 'avg', 'count', ...].
213
+ :param limit: The maximum number of records to return.
214
+ :param sliding_window_step: The time step for which the time window moves forward. Note that if
215
+ `sliding_window_step` is provided, interval must be provided as well. Provided
216
+ as a string in the format of '1m', '1h', etc.
217
+ :param timestamp_column: The column name that holds the timestamp index.
218
+
219
+ :return: DataFrame with the provided attributes from the data collection.
220
+ :raise: MLRunInvalidArgumentError if query the provided table failed.
221
+ """
222
+
223
+ project_condition = f"project = '{self.project}'"
224
+ filter_query = (
225
+ f"{filter_query} AND {project_condition}"
226
+ if filter_query
227
+ else project_condition
228
+ )
229
+
230
+ full_query = tdengine_schemas.TDEngineSchema._get_records_query(
231
+ table=table,
232
+ start=start,
233
+ end=end,
234
+ columns_to_filter=columns,
235
+ filter_query=filter_query,
236
+ interval=interval,
237
+ limit=limit,
238
+ agg_funcs=agg_funcs,
239
+ sliding_window_step=sliding_window_step,
240
+ timestamp_column=timestamp_column,
241
+ database=self.database,
242
+ )
243
+ try:
244
+ query_result = self._connection.query(full_query)
245
+ except taosws.QueryError as e:
246
+ raise mlrun.errors.MLRunInvalidArgumentError(
247
+ f"Failed to query table {table} in database {self.database}, {str(e)}"
248
+ )
249
+ columns = []
250
+ for column in query_result.fields:
251
+ columns.append(column.name())
252
+
253
+ return pd.DataFrame(query_result, columns=columns)
254
+
255
+ def read_metrics_data(
256
+ self,
257
+ *,
258
+ endpoint_id: str,
259
+ start: datetime,
260
+ end: datetime,
261
+ metrics: list[mm_schemas.ModelEndpointMonitoringMetric],
262
+ type: typing.Literal["metrics", "results"],
263
+ ) -> typing.Union[
264
+ list[
265
+ typing.Union[
266
+ mm_schemas.ModelEndpointMonitoringResultValues,
267
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
268
+ ],
269
+ ],
270
+ list[
271
+ typing.Union[
272
+ mm_schemas.ModelEndpointMonitoringMetricValues,
273
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
274
+ ],
275
+ ],
276
+ ]:
277
+ if type == "metrics":
278
+ table = mm_schemas.TDEngineSuperTables.METRICS
279
+ name = mm_schemas.MetricData.METRIC_NAME
280
+ df_handler = self.df_to_metrics_values
281
+ elif type == "results":
282
+ table = mm_schemas.TDEngineSuperTables.APP_RESULTS
283
+ name = mm_schemas.ResultData.RESULT_NAME
284
+ df_handler = self.df_to_results_values
285
+ else:
286
+ raise mlrun.errors.MLRunInvalidArgumentError(
287
+ f"Invalid type {type}, must be either 'metrics' or 'results'."
288
+ )
289
+
290
+ metrics_condition = " OR ".join(
291
+ [
292
+ f"({mm_schemas.WriterEvent.APPLICATION_NAME} = '{metric.app}' AND {name} = '{metric.name}')"
293
+ for metric in metrics
294
+ ]
295
+ )
296
+ filter_query = f"endpoint_id='{endpoint_id}' AND ({metrics_condition})"
297
+
298
+ df = self._get_records(
299
+ table=table,
300
+ start=start,
301
+ end=end,
302
+ filter_query=filter_query,
303
+ timestamp_column=mm_schemas.WriterEvent.END_INFER_TIME,
304
+ )
305
+
306
+ df[mm_schemas.WriterEvent.END_INFER_TIME] = pd.to_datetime(
307
+ df[mm_schemas.WriterEvent.END_INFER_TIME]
308
+ )
309
+ df.set_index(mm_schemas.WriterEvent.END_INFER_TIME, inplace=True)
310
+
311
+ logger.debug(
312
+ "Converting a DataFrame to a list of metrics or results values",
313
+ table=table,
314
+ project=self.project,
315
+ endpoint_id=endpoint_id,
316
+ is_empty=df.empty,
317
+ )
318
+
319
+ return df_handler(df=df, metrics=metrics, project=self.project)
320
+
321
+ def read_predictions(
322
+ self,
323
+ *,
324
+ endpoint_id: str,
325
+ start: datetime,
326
+ end: datetime,
327
+ aggregation_window: typing.Optional[str] = None,
328
+ agg_funcs: typing.Optional[list] = None,
329
+ limit: typing.Optional[int] = None,
330
+ ) -> typing.Union[
331
+ mm_schemas.ModelEndpointMonitoringMetricValues,
332
+ mm_schemas.ModelEndpointMonitoringMetricNoData,
333
+ ]:
334
+ if (agg_funcs and not aggregation_window) or (
335
+ aggregation_window and not agg_funcs
336
+ ):
337
+ raise mlrun.errors.MLRunInvalidArgumentError(
338
+ "both or neither of `aggregation_window` and `agg_funcs` must be provided"
339
+ )
340
+ df = self._get_records(
341
+ table=mm_schemas.TDEngineSuperTables.PREDICTIONS,
342
+ start=start,
343
+ end=end,
344
+ columns=[mm_schemas.EventFieldType.LATENCY],
345
+ filter_query=f"endpoint_id='{endpoint_id}'",
346
+ agg_funcs=agg_funcs,
347
+ interval=aggregation_window,
348
+ limit=limit,
349
+ )
350
+
351
+ full_name = get_invocations_fqn(self.project)
352
+
353
+ if df.empty:
354
+ return mm_schemas.ModelEndpointMonitoringMetricNoData(
355
+ full_name=full_name,
356
+ type=mm_schemas.ModelEndpointMonitoringMetricType.METRIC,
357
+ )
358
+
359
+ if aggregation_window:
360
+ # _wend column, which represents the end time of each window, will be used as the time index
361
+ df["_wend"] = pd.to_datetime(df["_wend"])
362
+ df.set_index("_wend", inplace=True)
363
+
364
+ latency_column = (
365
+ f"{agg_funcs[0]}({mm_schemas.EventFieldType.LATENCY})"
366
+ if agg_funcs
367
+ else mm_schemas.EventFieldType.LATENCY
368
+ )
369
+
370
+ return mm_schemas.ModelEndpointMonitoringMetricValues(
371
+ full_name=full_name,
372
+ values=list(
373
+ zip(
374
+ df.index,
375
+ df[latency_column],
376
+ )
377
+ ), # pyright: ignore[reportArgumentType]
378
+ )
379
+
380
+ def read_prediction_metric_for_endpoint_if_exists(
381
+ self, endpoint_id: str
382
+ ) -> typing.Optional[mm_schemas.ModelEndpointMonitoringMetric]:
383
+ # Read just one record, because we just want to check if there is any data for this endpoint_id
384
+ predictions = self.read_predictions(
385
+ endpoint_id=endpoint_id,
386
+ start=datetime.min,
387
+ end=mlrun.utils.now_date(),
388
+ limit=1,
389
+ )
390
+ if predictions:
391
+ return mm_schemas.ModelEndpointMonitoringMetric(
392
+ project=self.project,
393
+ app=mm_schemas.SpecialApps.MLRUN_INFRA,
394
+ type=mm_schemas.ModelEndpointMonitoringMetricType.METRIC,
395
+ name=mm_schemas.PredictionsQueryConstants.INVOCATIONS,
396
+ full_name=get_invocations_fqn(self.project),
397
+ )