mlrun 1.7.0rc14__py3-none-any.whl → 1.7.0rc21__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 (152) 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 +144 -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 +27 -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 +24 -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/_dl_common/loggers/tensorboard_logger.py +7 -12
  64. mlrun/frameworks/parallel_coordinates.py +2 -1
  65. mlrun/frameworks/tf_keras/__init__.py +4 -1
  66. mlrun/k8s_utils.py +10 -11
  67. mlrun/launcher/base.py +4 -3
  68. mlrun/launcher/client.py +5 -3
  69. mlrun/launcher/local.py +8 -2
  70. mlrun/launcher/remote.py +8 -2
  71. mlrun/lists.py +6 -2
  72. mlrun/model.py +45 -21
  73. mlrun/model_monitoring/__init__.py +1 -1
  74. mlrun/model_monitoring/api.py +41 -18
  75. mlrun/model_monitoring/application.py +5 -305
  76. mlrun/model_monitoring/applications/__init__.py +11 -0
  77. mlrun/model_monitoring/applications/_application_steps.py +157 -0
  78. mlrun/model_monitoring/applications/base.py +280 -0
  79. mlrun/model_monitoring/applications/context.py +214 -0
  80. mlrun/model_monitoring/applications/evidently_base.py +211 -0
  81. mlrun/model_monitoring/applications/histogram_data_drift.py +132 -91
  82. mlrun/model_monitoring/applications/results.py +99 -0
  83. mlrun/model_monitoring/controller.py +3 -1
  84. mlrun/model_monitoring/db/__init__.py +2 -0
  85. mlrun/model_monitoring/db/stores/__init__.py +0 -2
  86. mlrun/model_monitoring/db/stores/base/store.py +22 -37
  87. mlrun/model_monitoring/db/stores/sqldb/models/__init__.py +43 -21
  88. mlrun/model_monitoring/db/stores/sqldb/models/base.py +39 -8
  89. mlrun/model_monitoring/db/stores/sqldb/models/mysql.py +27 -7
  90. mlrun/model_monitoring/db/stores/sqldb/models/sqlite.py +5 -0
  91. mlrun/model_monitoring/db/stores/sqldb/sql_store.py +246 -224
  92. mlrun/model_monitoring/db/stores/v3io_kv/kv_store.py +232 -216
  93. mlrun/model_monitoring/db/tsdb/__init__.py +100 -0
  94. mlrun/model_monitoring/db/tsdb/base.py +329 -0
  95. mlrun/model_monitoring/db/tsdb/helpers.py +30 -0
  96. mlrun/model_monitoring/db/tsdb/tdengine/__init__.py +15 -0
  97. mlrun/model_monitoring/db/tsdb/tdengine/schemas.py +240 -0
  98. mlrun/model_monitoring/db/tsdb/tdengine/stream_graph_steps.py +45 -0
  99. mlrun/model_monitoring/db/tsdb/tdengine/tdengine_connector.py +397 -0
  100. mlrun/model_monitoring/db/tsdb/v3io/__init__.py +15 -0
  101. mlrun/model_monitoring/db/tsdb/v3io/stream_graph_steps.py +117 -0
  102. mlrun/model_monitoring/db/tsdb/v3io/v3io_connector.py +636 -0
  103. mlrun/model_monitoring/evidently_application.py +6 -118
  104. mlrun/model_monitoring/helpers.py +46 -1
  105. mlrun/model_monitoring/model_endpoint.py +3 -2
  106. mlrun/model_monitoring/stream_processing.py +57 -216
  107. mlrun/model_monitoring/writer.py +134 -124
  108. mlrun/package/utils/_formatter.py +2 -2
  109. mlrun/platforms/__init__.py +10 -9
  110. mlrun/platforms/iguazio.py +21 -202
  111. mlrun/projects/operations.py +19 -12
  112. mlrun/projects/pipelines.py +79 -102
  113. mlrun/projects/project.py +265 -103
  114. mlrun/render.py +15 -14
  115. mlrun/run.py +16 -46
  116. mlrun/runtimes/__init__.py +6 -3
  117. mlrun/runtimes/base.py +8 -7
  118. mlrun/runtimes/databricks_job/databricks_wrapper.py +1 -1
  119. mlrun/runtimes/funcdoc.py +0 -28
  120. mlrun/runtimes/kubejob.py +2 -1
  121. mlrun/runtimes/local.py +5 -2
  122. mlrun/runtimes/mpijob/__init__.py +0 -20
  123. mlrun/runtimes/mpijob/v1.py +1 -1
  124. mlrun/runtimes/nuclio/api_gateway.py +194 -84
  125. mlrun/runtimes/nuclio/application/application.py +170 -8
  126. mlrun/runtimes/nuclio/function.py +39 -49
  127. mlrun/runtimes/pod.py +16 -36
  128. mlrun/runtimes/remotesparkjob.py +9 -3
  129. mlrun/runtimes/sparkjob/spark3job.py +1 -1
  130. mlrun/runtimes/utils.py +6 -45
  131. mlrun/serving/server.py +2 -1
  132. mlrun/serving/v2_serving.py +5 -1
  133. mlrun/track/tracker.py +2 -1
  134. mlrun/utils/async_http.py +25 -5
  135. mlrun/utils/helpers.py +107 -75
  136. mlrun/utils/logger.py +39 -7
  137. mlrun/utils/notifications/notification/__init__.py +14 -9
  138. mlrun/utils/notifications/notification/base.py +1 -1
  139. mlrun/utils/notifications/notification/slack.py +34 -7
  140. mlrun/utils/notifications/notification/webhook.py +1 -1
  141. mlrun/utils/notifications/notification_pusher.py +147 -16
  142. mlrun/utils/regex.py +9 -0
  143. mlrun/utils/v3io_clients.py +0 -1
  144. mlrun/utils/version/version.json +2 -2
  145. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc21.dist-info}/METADATA +14 -6
  146. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc21.dist-info}/RECORD +150 -130
  147. mlrun/kfpops.py +0 -865
  148. mlrun/platforms/other.py +0 -305
  149. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc21.dist-info}/LICENSE +0 -0
  150. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc21.dist-info}/WHEEL +0 -0
  151. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc21.dist-info}/entry_points.txt +0 -0
  152. {mlrun-1.7.0rc14.dist-info → mlrun-1.7.0rc21.dist-info}/top_level.txt +0 -0
@@ -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
@@ -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
+ )
@@ -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 .v3io_connector import V3IOTSDBConnector