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
@@ -11,17 +11,22 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
- #
15
-
16
14
 
17
- from abc import ABC
15
+ import typing
16
+ from abc import ABC, abstractmethod
17
+ from datetime import datetime
18
18
 
19
19
  import pandas as pd
20
20
 
21
- import mlrun.common.schemas.model_monitoring.constants as mm_constants
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
22
25
 
23
26
 
24
27
  class TSDBConnector(ABC):
28
+ type: str = ""
29
+
25
30
  def __init__(self, project: str):
26
31
  """
27
32
  Initialize a new TSDB connector. The connector is used to interact with the TSDB and store monitoring data.
@@ -56,14 +61,13 @@ class TSDBConnector(ABC):
56
61
  def write_application_event(
57
62
  self,
58
63
  event: dict,
59
- kind: mm_constants.WriterEventKind = mm_constants.WriterEventKind.RESULT,
60
- ):
64
+ kind: mm_schemas.WriterEventKind = mm_schemas.WriterEventKind.RESULT,
65
+ ) -> None:
61
66
  """
62
67
  Write a single application or metric to TSDB.
63
68
 
64
69
  :raise mlrun.errors.MLRunRuntimeError: If an error occurred while writing the event.
65
70
  """
66
- pass
67
71
 
68
72
  def delete_tsdb_resources(self):
69
73
  """
@@ -76,8 +80,8 @@ class TSDBConnector(ABC):
76
80
  self,
77
81
  endpoint_id: str,
78
82
  metrics: list[str],
79
- start: str = "now-1h",
80
- end: str = "now",
83
+ start: str,
84
+ end: str,
81
85
  ) -> dict[str, list[tuple[str, float]]]:
82
86
  """
83
87
  Getting real time metrics from the TSDB. There are pre-defined metrics for model endpoints such as
@@ -98,38 +102,228 @@ class TSDBConnector(ABC):
98
102
  """
99
103
  pass
100
104
 
101
- def get_records(
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(
102
115
  self,
103
- table: str,
104
- columns: list[str] = None,
105
- filter_query: str = "",
106
- start: str = "now-1h",
107
- end: str = "now",
108
- ) -> pd.DataFrame:
109
- """
110
- Getting records from TSDB data collection.
111
- :param table: Table name, e.g. 'metrics', 'app_results'.
112
- :param columns: Columns to include in the result.
113
- :param filter_query: Optional filter expression as a string. The filter structure depends on the TSDB
114
- connector type.
115
- :param start: The start time of the metrics. Can be represented by a string containing an RFC
116
- 3339 time, a Unix timestamp in milliseconds, a relative time (`'now'` or
117
- `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, `'d'` = days, and `'s'`
118
- = seconds), or 0 for the earliest time.
119
- :param end: The end time of the metrics. Can be represented by a string containing an RFC
120
- 3339 time, a Unix timestamp in milliseconds, a relative time (`'now'` or
121
- `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, `'d'` = days, and `'s'`
122
- = seconds), or 0 for the earliest time.
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.
123
138
 
124
- :return: DataFrame with the provided attributes from the data collection.
125
- :raise: MLRunNotFoundError if the provided table wasn't found.
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.
126
145
  """
127
- pass
128
146
 
129
- def create_tsdb_application_tables(self):
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
+ ]:
130
161
  """
131
- Create the application tables using the TSDB connector. At the moment we support 2 types of application tables:
132
- - app_results: a detailed result that includes status, kind, extra data, etc.
133
- - metrics: a basic key value that represents a numeric metric.
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.
134
178
  """
135
- pass
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