sqlmesh-observability 0.1.0a2__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.
- sqlmesh_observability/__init__.py +14 -0
- sqlmesh_observability/alerts.py +304 -0
- sqlmesh_observability/app.py +153 -0
- sqlmesh_observability/audits/__init__.py +63 -0
- sqlmesh_observability/audits/column_anomaly.sql +87 -0
- sqlmesh_observability/audits/freshness_anomaly.sql +37 -0
- sqlmesh_observability/audits/macros.py +103 -0
- sqlmesh_observability/audits/volume_anomaly.sql +96 -0
- sqlmesh_observability/cli.py +173 -0
- sqlmesh_observability/collector.py +463 -0
- sqlmesh_observability/hook.py +247 -0
- sqlmesh_observability/monitors.py +545 -0
- sqlmesh_observability/payload.py +506 -0
- sqlmesh_observability/reader.py +1197 -0
- sqlmesh_observability/report.py +163 -0
- sqlmesh_observability/textfmt.py +55 -0
- sqlmesh_observability/web/report.css +356 -0
- sqlmesh_observability/web/report.js +1278 -0
- sqlmesh_observability/writer.py +493 -0
- sqlmesh_observability-0.1.0a2.dist-info/METADATA +122 -0
- sqlmesh_observability-0.1.0a2.dist-info/RECORD +26 -0
- sqlmesh_observability-0.1.0a2.dist-info/WHEEL +5 -0
- sqlmesh_observability-0.1.0a2.dist-info/entry_points.txt +2 -0
- sqlmesh_observability-0.1.0a2.dist-info/licenses/LICENSE +202 -0
- sqlmesh_observability-0.1.0a2.dist-info/licenses/NOTICE +4 -0
- sqlmesh_observability-0.1.0a2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""``install()``: the only code in the package that touches SQLMesh objects directly.
|
|
2
|
+
|
|
3
|
+
It makes exactly one patch: an instance attribute ``get_execution_observer`` on the console that
|
|
4
|
+
is current while ``config.py`` loads. It never replaces the process console and never patches a
|
|
5
|
+
class or a module function.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import typing as t
|
|
12
|
+
|
|
13
|
+
from sqlmesh.core.notification_target import (
|
|
14
|
+
GenericNotificationTarget,
|
|
15
|
+
NotificationEvent,
|
|
16
|
+
NotificationStatus,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from sqlmesh_observability.collector import get_collector
|
|
20
|
+
from sqlmesh_observability.monitors import MonitorSettings, normalize_monitors
|
|
21
|
+
|
|
22
|
+
if t.TYPE_CHECKING:
|
|
23
|
+
from sqlmesh.core.config import Config
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
_MARKER = "__sqlmesh_observability_wrapped__"
|
|
28
|
+
|
|
29
|
+
_LIFECYCLE_EVENTS = frozenset(
|
|
30
|
+
{
|
|
31
|
+
NotificationEvent.APPLY_START,
|
|
32
|
+
NotificationEvent.APPLY_END,
|
|
33
|
+
NotificationEvent.APPLY_FAILURE,
|
|
34
|
+
NotificationEvent.RUN_START,
|
|
35
|
+
NotificationEvent.RUN_END,
|
|
36
|
+
NotificationEvent.RUN_FAILURE,
|
|
37
|
+
}
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def install(
|
|
42
|
+
config: "Config",
|
|
43
|
+
connection: t.Any,
|
|
44
|
+
schema: str = "observability",
|
|
45
|
+
monitors: t.Optional[t.Dict[str, t.Any]] = None,
|
|
46
|
+
sample_rows: int = 0,
|
|
47
|
+
alert_target: t.Optional[t.Any] = None,
|
|
48
|
+
) -> "Config":
|
|
49
|
+
"""Enable observability for the SQLMesh project whose ``config.py`` calls this.
|
|
50
|
+
|
|
51
|
+
Call it last in ``config.py``, after any other package that replaces the console::
|
|
52
|
+
|
|
53
|
+
config = install(Config(...), "warehouse")
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
config: The project's SQLMesh ``Config``. It is returned unchanged except for one appended
|
|
57
|
+
notification target.
|
|
58
|
+
connection: Name of the gateway in ``config`` whose warehouse holds the observability
|
|
59
|
+
tables. Nothing connects until the first plan or run finishes.
|
|
60
|
+
schema: Schema (or ``catalog.schema``) for the package's own tables.
|
|
61
|
+
monitors: Passive monitors to run after each plan or run, for example
|
|
62
|
+
``{"volume": True, "freshness": {"column": "updated_at"}, "schema": True}``, plus
|
|
63
|
+
``"columns": {"orders": {"null_rate": ["status"], "mean": ["amount"]}}`` for named
|
|
64
|
+
columns. Off when omitted. ``volume`` and ``freshness`` also take the anomaly
|
|
65
|
+
scoring settings (``training_days``, ``min_buckets``, ``threshold``,
|
|
66
|
+
``spike_failure_percent_threshold``, ``drop_failure_percent_threshold``).
|
|
67
|
+
sample_rows: For a failing audit, store up to this many of its rows as JSON in
|
|
68
|
+
``audit_samples``, by re-running the audit query on the default gateway. 0 is off.
|
|
69
|
+
alert_target: A notification target instance (a ``GenericNotificationTarget`` subclass)
|
|
70
|
+
that ``sqlmesh-observe monitor`` sends its grouped messages through. Only ``monitor``
|
|
71
|
+
uses it: it is not added to ``config.notification_targets``, so SQLMesh never calls
|
|
72
|
+
it during a plan or run.
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
The same ``config`` object.
|
|
76
|
+
"""
|
|
77
|
+
from sqlmesh.core.console import get_console
|
|
78
|
+
|
|
79
|
+
collector = get_collector()
|
|
80
|
+
collector.settings = {
|
|
81
|
+
"connection": connection,
|
|
82
|
+
"schema": schema,
|
|
83
|
+
"monitors": monitors,
|
|
84
|
+
"sample_rows": sample_rows,
|
|
85
|
+
"alert_target": alert_target,
|
|
86
|
+
}
|
|
87
|
+
_configure_writer(
|
|
88
|
+
collector, config, connection, schema, sample_rows, normalize_monitors(monitors)
|
|
89
|
+
)
|
|
90
|
+
wrap_console(get_console())
|
|
91
|
+
if not any(isinstance(target, ObservabilityTarget) for target in config.notification_targets):
|
|
92
|
+
config.notification_targets.append(ObservabilityTarget())
|
|
93
|
+
return config
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _configure_writer(
|
|
97
|
+
collector: t.Any,
|
|
98
|
+
config: "Config",
|
|
99
|
+
gateway: t.Any,
|
|
100
|
+
schema: str,
|
|
101
|
+
sample_rows: int,
|
|
102
|
+
monitors: "MonitorSettings",
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Point the collector at a writer for ``gateway``. Re-loading ``config.py`` reuses it."""
|
|
105
|
+
from sqlmesh_observability.writer import Writer
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
collector.dialect = config.get_connection().DIALECT
|
|
109
|
+
except Exception:
|
|
110
|
+
collector.dialect = None
|
|
111
|
+
if not isinstance(gateway, str):
|
|
112
|
+
logger.warning("sqlmesh-observability: `connection` must be a gateway name; not writing")
|
|
113
|
+
collector.writer = None
|
|
114
|
+
return
|
|
115
|
+
writer = collector.writer
|
|
116
|
+
if writer is not None and writer.settings() == (gateway, schema, sample_rows, monitors):
|
|
117
|
+
writer.config = config # the newest load of config.py wins
|
|
118
|
+
return
|
|
119
|
+
collector.writer = Writer(
|
|
120
|
+
config, gateway, schema=schema, sample_rows=sample_rows, monitors=monitors
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def is_wrapped(console: t.Any) -> bool:
|
|
125
|
+
"""True when ``console.get_execution_observer`` already routes to this package.
|
|
126
|
+
|
|
127
|
+
Reads the attribute, so it also sees through delegating wrappers that forward attribute access
|
|
128
|
+
to a console this package already wrapped.
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
return bool(getattr(console.get_execution_observer, _MARKER, False))
|
|
132
|
+
except Exception:
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def wrap_console(console: t.Any) -> bool:
|
|
137
|
+
"""Wrap ``get_execution_observer`` on this console instance. False if already wrapped."""
|
|
138
|
+
if is_wrapped(console):
|
|
139
|
+
return False
|
|
140
|
+
try:
|
|
141
|
+
previous_getter = console.get_execution_observer
|
|
142
|
+
except Exception:
|
|
143
|
+
logger.debug("sqlmesh-observability: console has no execution observer getter")
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
def get_execution_observer() -> t.Optional[t.Callable[..., None]]:
|
|
147
|
+
previous = None
|
|
148
|
+
try:
|
|
149
|
+
previous = previous_getter()
|
|
150
|
+
except Exception:
|
|
151
|
+
logger.debug("sqlmesh-observability: chained observer getter failed", exc_info=True)
|
|
152
|
+
|
|
153
|
+
try:
|
|
154
|
+
invocation_id: t.Optional[str] = get_collector().begin()
|
|
155
|
+
except Exception:
|
|
156
|
+
logger.debug("sqlmesh-observability: could not start invocation", exc_info=True)
|
|
157
|
+
invocation_id = None
|
|
158
|
+
if invocation_id is None:
|
|
159
|
+
return previous
|
|
160
|
+
|
|
161
|
+
def observe(
|
|
162
|
+
phase: t.Literal["start", "finish"],
|
|
163
|
+
facts: t.Mapping[str, t.Any],
|
|
164
|
+
error: t.Optional[BaseException],
|
|
165
|
+
) -> None:
|
|
166
|
+
if previous is not None:
|
|
167
|
+
try:
|
|
168
|
+
previous(phase, facts, error)
|
|
169
|
+
except Exception:
|
|
170
|
+
logger.debug("sqlmesh-observability: chained observer failed", exc_info=True)
|
|
171
|
+
try:
|
|
172
|
+
get_collector().handle(invocation_id, phase, facts, error) # type: ignore[arg-type]
|
|
173
|
+
except Exception:
|
|
174
|
+
logger.debug("sqlmesh-observability: collector failed", exc_info=True)
|
|
175
|
+
|
|
176
|
+
return observe
|
|
177
|
+
|
|
178
|
+
setattr(get_execution_observer, _MARKER, True)
|
|
179
|
+
try:
|
|
180
|
+
console.get_execution_observer = get_execution_observer
|
|
181
|
+
except Exception:
|
|
182
|
+
logger.debug("sqlmesh-observability: could not wrap console", exc_info=True)
|
|
183
|
+
return False
|
|
184
|
+
return True
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _ensure_current_console_wrapped() -> None:
|
|
188
|
+
"""Re-apply the wrap if another package replaced the console after ``install()``.
|
|
189
|
+
|
|
190
|
+
Runs from the start hooks, which SQLMesh calls before it resolves the observer.
|
|
191
|
+
"""
|
|
192
|
+
from sqlmesh.core.console import get_console
|
|
193
|
+
|
|
194
|
+
wrap_console(get_console())
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# SQLMesh declares BaseNotificationTarget frozen but GenericNotificationTarget not, so mypy rejects
|
|
198
|
+
# any subclass of it, frozen or not. At runtime the model is frozen through its base.
|
|
199
|
+
class ObservabilityTarget(GenericNotificationTarget): # type: ignore[misc]
|
|
200
|
+
"""Supplies environment and plan id per invocation, and closes it. Never raises."""
|
|
201
|
+
|
|
202
|
+
notify_on: t.FrozenSet[NotificationEvent] = _LIFECYCLE_EVENTS
|
|
203
|
+
|
|
204
|
+
def send(self, notification_status: NotificationStatus, msg: str, **kwargs: t.Any) -> None:
|
|
205
|
+
"""No messages: this target only marks invocation boundaries."""
|
|
206
|
+
|
|
207
|
+
def notify_apply_start(
|
|
208
|
+
self, environment: str, plan_id: str, *args: t.Any, **kwargs: t.Any
|
|
209
|
+
) -> None:
|
|
210
|
+
_start("plan", environment, plan_id)
|
|
211
|
+
|
|
212
|
+
def notify_run_start(self, environment: str, *args: t.Any, **kwargs: t.Any) -> None:
|
|
213
|
+
_start("run", environment, None)
|
|
214
|
+
|
|
215
|
+
def notify_apply_end(
|
|
216
|
+
self, environment: str, plan_id: str, *args: t.Any, **kwargs: t.Any
|
|
217
|
+
) -> None:
|
|
218
|
+
_end("success")
|
|
219
|
+
|
|
220
|
+
def notify_run_end(self, environment: str, *args: t.Any, **kwargs: t.Any) -> None:
|
|
221
|
+
_end("success")
|
|
222
|
+
|
|
223
|
+
def notify_apply_failure(
|
|
224
|
+
self, environment: str, plan_id: str, exc: str, *args: t.Any, **kwargs: t.Any
|
|
225
|
+
) -> None:
|
|
226
|
+
_end("failure")
|
|
227
|
+
|
|
228
|
+
def notify_run_failure(self, exc: str, *args: t.Any, **kwargs: t.Any) -> None:
|
|
229
|
+
_end("failure")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _start(command: str, environment: t.Optional[str], plan_id: t.Optional[str]) -> None:
|
|
233
|
+
try:
|
|
234
|
+
_ensure_current_console_wrapped()
|
|
235
|
+
except Exception:
|
|
236
|
+
logger.debug("sqlmesh-observability: console re-check failed", exc_info=True)
|
|
237
|
+
try:
|
|
238
|
+
get_collector().arm(command, environment, plan_id)
|
|
239
|
+
except Exception:
|
|
240
|
+
logger.debug("sqlmesh-observability: could not record start", exc_info=True)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _end(status: t.Literal["success", "failure"]) -> None:
|
|
244
|
+
try:
|
|
245
|
+
get_collector().end(status)
|
|
246
|
+
except Exception:
|
|
247
|
+
logger.debug("sqlmesh-observability: could not record end", exc_info=True)
|