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,493 @@
|
|
|
1
|
+
"""Writes finished invocations to the package's tables in the warehouse.
|
|
2
|
+
|
|
3
|
+
One writer thread owns all warehouse I/O. The notification target's end/failure hook submits a
|
|
4
|
+
finished :class:`~sqlmesh_observability.collector.Invocation` and waits, bounded, until it is
|
|
5
|
+
written. That way a short CLI process persists before it exits, and a long-lived ``sqlmesh ui``
|
|
6
|
+
process writes each apply as it finishes. ``atexit`` drains anything left, as a backstop only.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import atexit
|
|
12
|
+
import datetime
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import queue
|
|
16
|
+
import threading
|
|
17
|
+
import typing as t
|
|
18
|
+
|
|
19
|
+
from sqlglot import exp
|
|
20
|
+
|
|
21
|
+
from sqlmesh_observability import monitors
|
|
22
|
+
from sqlmesh_observability.monitors import MonitorSettings, RecordedSchema
|
|
23
|
+
|
|
24
|
+
if t.TYPE_CHECKING:
|
|
25
|
+
from sqlmesh.core.config import Config
|
|
26
|
+
from sqlmesh.core.engine_adapter import EngineAdapter
|
|
27
|
+
|
|
28
|
+
from sqlmesh_observability.collector import Invocation
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
SCHEMA_VERSION = 2 # 2: metrics, schema_columns, schema_changes
|
|
33
|
+
_INSERT_CHUNK = 500
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _types(**columns: str) -> t.Dict[str, exp.DataType]:
|
|
37
|
+
return {name: exp.DataType.build(kind) for name, kind in columns.items()}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
TABLES: t.Dict[str, t.Dict[str, exp.DataType]] = {
|
|
41
|
+
"schema_version": _types(version="INT"),
|
|
42
|
+
"invocations": _types(
|
|
43
|
+
invocation_id="TEXT",
|
|
44
|
+
command="TEXT",
|
|
45
|
+
environment="TEXT",
|
|
46
|
+
plan_id="TEXT",
|
|
47
|
+
started_at="TIMESTAMP",
|
|
48
|
+
finished_at="TIMESTAMP",
|
|
49
|
+
status="TEXT",
|
|
50
|
+
sqlmesh_version="TEXT",
|
|
51
|
+
),
|
|
52
|
+
"model_runs": _types(
|
|
53
|
+
invocation_id="TEXT",
|
|
54
|
+
model_name="TEXT",
|
|
55
|
+
snapshot_id="TEXT",
|
|
56
|
+
version="TEXT",
|
|
57
|
+
physical_table="TEXT",
|
|
58
|
+
interval_start="TIMESTAMP",
|
|
59
|
+
interval_end="TIMESTAMP",
|
|
60
|
+
batch_index="INT",
|
|
61
|
+
execution_time="TIMESTAMP",
|
|
62
|
+
environment="TEXT",
|
|
63
|
+
audit_only="BOOLEAN",
|
|
64
|
+
status="TEXT",
|
|
65
|
+
duration_ms="BIGINT",
|
|
66
|
+
error_message="TEXT",
|
|
67
|
+
),
|
|
68
|
+
"audit_results": _types(
|
|
69
|
+
invocation_id="TEXT",
|
|
70
|
+
model_name="TEXT",
|
|
71
|
+
snapshot_id="TEXT",
|
|
72
|
+
version="TEXT",
|
|
73
|
+
physical_table="TEXT",
|
|
74
|
+
environment="TEXT",
|
|
75
|
+
audit_name="TEXT",
|
|
76
|
+
args_json="TEXT",
|
|
77
|
+
interval_start="TIMESTAMP",
|
|
78
|
+
interval_end="TIMESTAMP",
|
|
79
|
+
status="TEXT",
|
|
80
|
+
violation_count="BIGINT",
|
|
81
|
+
blocking="BOOLEAN",
|
|
82
|
+
query_sql="TEXT",
|
|
83
|
+
error_message="TEXT",
|
|
84
|
+
),
|
|
85
|
+
"audit_samples": _types(
|
|
86
|
+
invocation_id="TEXT",
|
|
87
|
+
model_name="TEXT",
|
|
88
|
+
audit_name="TEXT",
|
|
89
|
+
interval_start="TIMESTAMP",
|
|
90
|
+
row_json="TEXT",
|
|
91
|
+
),
|
|
92
|
+
"metrics": _types(
|
|
93
|
+
invocation_id="TEXT",
|
|
94
|
+
model_name="TEXT",
|
|
95
|
+
version="TEXT",
|
|
96
|
+
physical_table="TEXT",
|
|
97
|
+
interval_start="TIMESTAMP",
|
|
98
|
+
interval_end="TIMESTAMP",
|
|
99
|
+
metric_name="TEXT",
|
|
100
|
+
column_name="TEXT", # '' for table-level metrics, never NULL
|
|
101
|
+
metric_value="DOUBLE",
|
|
102
|
+
updated_at="TIMESTAMP",
|
|
103
|
+
error_message="TEXT",
|
|
104
|
+
),
|
|
105
|
+
"schema_columns": _types(
|
|
106
|
+
invocation_id="TEXT",
|
|
107
|
+
model_name="TEXT",
|
|
108
|
+
snapshot_id="TEXT",
|
|
109
|
+
version="TEXT",
|
|
110
|
+
ordinal="INT",
|
|
111
|
+
column_name="TEXT",
|
|
112
|
+
data_type="TEXT",
|
|
113
|
+
recorded_at="TIMESTAMP",
|
|
114
|
+
),
|
|
115
|
+
"schema_changes": _types(
|
|
116
|
+
invocation_id="TEXT",
|
|
117
|
+
model_name="TEXT",
|
|
118
|
+
from_snapshot_id="TEXT",
|
|
119
|
+
to_snapshot_id="TEXT",
|
|
120
|
+
from_version="TEXT",
|
|
121
|
+
to_version="TEXT",
|
|
122
|
+
column_name="TEXT",
|
|
123
|
+
change_type="TEXT",
|
|
124
|
+
old_type="TEXT",
|
|
125
|
+
new_type="TEXT",
|
|
126
|
+
recorded_at="TIMESTAMP",
|
|
127
|
+
),
|
|
128
|
+
}
|
|
129
|
+
INVOCATION_TABLES = ("invocations", "model_runs", "audit_results", "audit_samples")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _ms_to_datetime(value: t.Optional[int]) -> t.Optional[datetime.datetime]:
|
|
133
|
+
if value is None:
|
|
134
|
+
return None
|
|
135
|
+
return datetime.datetime.fromtimestamp(value / 1000, tz=datetime.timezone.utc)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _literal(value: t.Any, kind: exp.DataType) -> exp.Expression:
|
|
139
|
+
if value is None:
|
|
140
|
+
return exp.cast(exp.null(), kind)
|
|
141
|
+
if isinstance(value, bool):
|
|
142
|
+
return exp.cast(exp.Boolean(this=value), kind)
|
|
143
|
+
if isinstance(value, (int, float)):
|
|
144
|
+
return exp.cast(exp.Literal.number(value), kind)
|
|
145
|
+
if isinstance(value, datetime.datetime):
|
|
146
|
+
if value.tzinfo is not None:
|
|
147
|
+
value = value.astimezone(datetime.timezone.utc).replace(tzinfo=None)
|
|
148
|
+
return exp.cast(exp.Literal.string(value.isoformat(sep=" ")), kind)
|
|
149
|
+
return exp.cast(exp.Literal.string(str(value)), kind)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _sqlmesh_version() -> str:
|
|
153
|
+
try:
|
|
154
|
+
from sqlmesh import __version__
|
|
155
|
+
|
|
156
|
+
return str(__version__)
|
|
157
|
+
except Exception:
|
|
158
|
+
return "unknown"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class Writer:
|
|
162
|
+
def __init__(
|
|
163
|
+
self,
|
|
164
|
+
config: "Config",
|
|
165
|
+
gateway: str,
|
|
166
|
+
schema: str = "observability",
|
|
167
|
+
sample_rows: int = 0,
|
|
168
|
+
flush_timeout: float = 60.0,
|
|
169
|
+
monitors: t.Optional[MonitorSettings] = None,
|
|
170
|
+
) -> None:
|
|
171
|
+
self.config = config
|
|
172
|
+
self.monitors = monitors or MonitorSettings()
|
|
173
|
+
self.gateway = gateway
|
|
174
|
+
self.schema = schema
|
|
175
|
+
self.sample_rows = sample_rows
|
|
176
|
+
self.flush_timeout = flush_timeout
|
|
177
|
+
# (invocation, done); an invocation of None is a drain marker.
|
|
178
|
+
self._queue: "queue.Queue[t.Tuple[t.Optional[Invocation], threading.Event]]" = queue.Queue()
|
|
179
|
+
self._thread: t.Optional[threading.Thread] = None
|
|
180
|
+
self._start_lock = threading.Lock()
|
|
181
|
+
self._tables_ready = False
|
|
182
|
+
atexit.register(self.drain)
|
|
183
|
+
|
|
184
|
+
def settings(self) -> t.Tuple[str, str, int, MonitorSettings]:
|
|
185
|
+
return (self.gateway, self.schema, self.sample_rows, self.monitors)
|
|
186
|
+
|
|
187
|
+
# --- Submission ------------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
def submit_and_wait(self, invocation: "Invocation", timeout: t.Optional[float] = None) -> bool:
|
|
190
|
+
"""Queue ``invocation`` and wait until it is written. False if the wait timed out."""
|
|
191
|
+
done = threading.Event()
|
|
192
|
+
self._ensure_thread()
|
|
193
|
+
self._queue.put((invocation, done))
|
|
194
|
+
return done.wait(self.flush_timeout if timeout is None else timeout)
|
|
195
|
+
|
|
196
|
+
def drain(self, timeout: float = 30.0) -> None:
|
|
197
|
+
"""Wait for queued invocations to be written (``atexit`` backstop)."""
|
|
198
|
+
if self._thread is None or not self._thread.is_alive():
|
|
199
|
+
return
|
|
200
|
+
finished = threading.Event()
|
|
201
|
+
self._queue.put((None, finished)) # set once everything queued before it is processed
|
|
202
|
+
finished.wait(timeout)
|
|
203
|
+
|
|
204
|
+
def stop(self) -> None:
|
|
205
|
+
self.drain(timeout=5.0)
|
|
206
|
+
|
|
207
|
+
def _ensure_thread(self) -> None:
|
|
208
|
+
with self._start_lock:
|
|
209
|
+
if self._thread is None or not self._thread.is_alive():
|
|
210
|
+
self._thread = threading.Thread(
|
|
211
|
+
target=self._run, name="sqlmesh-observability-writer", daemon=True
|
|
212
|
+
)
|
|
213
|
+
self._thread.start()
|
|
214
|
+
|
|
215
|
+
def _run(self) -> None:
|
|
216
|
+
while True:
|
|
217
|
+
invocation, done = self._queue.get()
|
|
218
|
+
if invocation is None:
|
|
219
|
+
done.set()
|
|
220
|
+
continue
|
|
221
|
+
try:
|
|
222
|
+
self.write(invocation)
|
|
223
|
+
except Exception:
|
|
224
|
+
logger.debug("sqlmesh-observability: writing invocation failed", exc_info=True)
|
|
225
|
+
finally:
|
|
226
|
+
done.set()
|
|
227
|
+
|
|
228
|
+
# --- Writing ---------------------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
def _adapter(self) -> "EngineAdapter":
|
|
231
|
+
return self.config.get_connection(self.gateway).create_engine_adapter()
|
|
232
|
+
|
|
233
|
+
def _sample_adapter(self) -> "EngineAdapter":
|
|
234
|
+
return self.config.get_connection().create_engine_adapter()
|
|
235
|
+
|
|
236
|
+
def _table(self, name: str) -> exp.Table:
|
|
237
|
+
return exp.to_table(f"{self.schema}.{name}")
|
|
238
|
+
|
|
239
|
+
def ensure_tables(self, adapter: "EngineAdapter") -> None:
|
|
240
|
+
if self._tables_ready:
|
|
241
|
+
return
|
|
242
|
+
adapter.create_schema(self.schema)
|
|
243
|
+
for name, columns in TABLES.items():
|
|
244
|
+
adapter.create_table(self._table(name), columns, exists=True)
|
|
245
|
+
version_table = self._table("schema_version")
|
|
246
|
+
row = adapter.fetchone(exp.select("MAX(version)").from_(version_table))
|
|
247
|
+
current = row[0] if row else None
|
|
248
|
+
if current is None or int(current) < SCHEMA_VERSION:
|
|
249
|
+
# Upgrades so far only add tables, which CREATE TABLE IF NOT EXISTS has just done.
|
|
250
|
+
with adapter.transaction():
|
|
251
|
+
adapter.delete_from(version_table, exp.true())
|
|
252
|
+
self._insert(adapter, "schema_version", [{"version": SCHEMA_VERSION}])
|
|
253
|
+
self._tables_ready = True
|
|
254
|
+
|
|
255
|
+
def write(self, invocation: "Invocation") -> None:
|
|
256
|
+
"""Write one invocation, replacing any rows an earlier write of it left (idempotent)."""
|
|
257
|
+
rows = self._rows(invocation)
|
|
258
|
+
rows["audit_samples"] = self._samples(invocation)
|
|
259
|
+
adapter = self._adapter()
|
|
260
|
+
self.ensure_tables(adapter)
|
|
261
|
+
where = exp.column("invocation_id").eq(exp.Literal.string(invocation.invocation_id))
|
|
262
|
+
with adapter.transaction():
|
|
263
|
+
for name in INVOCATION_TABLES:
|
|
264
|
+
adapter.delete_from(self._table(name), where)
|
|
265
|
+
for name in INVOCATION_TABLES:
|
|
266
|
+
self._insert(adapter, name, rows[name])
|
|
267
|
+
# Base rows are committed above; monitors run after, so a slow or failing metric query
|
|
268
|
+
# can lose only metrics.
|
|
269
|
+
if self.monitors.enabled:
|
|
270
|
+
self._write_monitors(invocation, adapter)
|
|
271
|
+
|
|
272
|
+
# --- Passive monitors -----------------------------------------------------------------------
|
|
273
|
+
|
|
274
|
+
def _write_monitors(self, invocation: "Invocation", adapter: "EngineAdapter") -> None:
|
|
275
|
+
settings = self.monitors
|
|
276
|
+
if settings.collects_metrics:
|
|
277
|
+
try:
|
|
278
|
+
rows = monitors.collect_metrics(
|
|
279
|
+
invocation, self._sample_adapter(), adapter, settings
|
|
280
|
+
)
|
|
281
|
+
self._replace_metrics(adapter, rows)
|
|
282
|
+
except Exception:
|
|
283
|
+
logger.debug("sqlmesh-observability: passive metrics failed", exc_info=True)
|
|
284
|
+
if settings.schema and invocation.schemas:
|
|
285
|
+
try:
|
|
286
|
+
self._write_schemas(invocation, adapter)
|
|
287
|
+
except Exception:
|
|
288
|
+
logger.debug("sqlmesh-observability: schema capture failed", exc_info=True)
|
|
289
|
+
|
|
290
|
+
def _replace_metrics(self, adapter: "EngineAdapter", rows: t.List[t.Dict[str, t.Any]]) -> None:
|
|
291
|
+
"""Latest wins per (model, version, interval_start, metric, column)."""
|
|
292
|
+
if not rows:
|
|
293
|
+
return
|
|
294
|
+
groups: t.Dict[t.Tuple[str, str, str, str], t.List[t.Any]] = {}
|
|
295
|
+
for row in rows:
|
|
296
|
+
key = (row["model_name"], row["version"], row["metric_name"], row["column_name"])
|
|
297
|
+
groups.setdefault(key, []).append(row["interval_start"])
|
|
298
|
+
timestamp = TABLES["metrics"]["interval_start"]
|
|
299
|
+
table = self._table("metrics")
|
|
300
|
+
with adapter.transaction():
|
|
301
|
+
for (model_name, version, metric_name, column_name), starts in groups.items():
|
|
302
|
+
where = exp.and_(
|
|
303
|
+
exp.column("model_name").eq(exp.Literal.string(model_name)),
|
|
304
|
+
exp.column("version").eq(exp.Literal.string(version)),
|
|
305
|
+
exp.column("metric_name").eq(exp.Literal.string(metric_name)),
|
|
306
|
+
exp.column("column_name").eq(exp.Literal.string(column_name)),
|
|
307
|
+
)
|
|
308
|
+
known = [s for s in starts if s is not None]
|
|
309
|
+
matches: t.List[exp.Expression] = []
|
|
310
|
+
if known:
|
|
311
|
+
matches.append(
|
|
312
|
+
exp.column("interval_start").isin(*(_literal(s, timestamp) for s in known))
|
|
313
|
+
)
|
|
314
|
+
if len(known) < len(starts):
|
|
315
|
+
matches.append(exp.column("interval_start").is_(exp.null()))
|
|
316
|
+
adapter.delete_from(table, exp.and_(where, exp.or_(*matches)))
|
|
317
|
+
self._insert(adapter, "metrics", rows)
|
|
318
|
+
|
|
319
|
+
def _recorded_schemas(
|
|
320
|
+
self, adapter: "EngineAdapter", model_names: t.Iterable[str]
|
|
321
|
+
) -> t.Dict[str, t.Dict[str, RecordedSchema]]:
|
|
322
|
+
names = sorted(set(model_names))
|
|
323
|
+
query = (
|
|
324
|
+
exp.select(
|
|
325
|
+
"model_name",
|
|
326
|
+
"snapshot_id",
|
|
327
|
+
"version",
|
|
328
|
+
"recorded_at",
|
|
329
|
+
"ordinal",
|
|
330
|
+
"column_name",
|
|
331
|
+
"data_type",
|
|
332
|
+
)
|
|
333
|
+
.from_(self._table("schema_columns"))
|
|
334
|
+
.where(exp.column("model_name").isin(*(exp.Literal.string(n) for n in names)))
|
|
335
|
+
.order_by("model_name", "snapshot_id", "ordinal")
|
|
336
|
+
)
|
|
337
|
+
columns: t.Dict[t.Tuple[str, str], t.List[t.Tuple[str, str]]] = {}
|
|
338
|
+
meta: t.Dict[t.Tuple[str, str], t.Tuple[str, datetime.datetime]] = {}
|
|
339
|
+
for model_name, snapshot_id, version, recorded_at, _, column, kind in adapter.fetchall(
|
|
340
|
+
query
|
|
341
|
+
):
|
|
342
|
+
key = (str(model_name), str(snapshot_id))
|
|
343
|
+
columns.setdefault(key, []).append((str(column), str(kind)))
|
|
344
|
+
meta[key] = (str(version), monitors._naive_utc(recorded_at) or datetime.datetime.min)
|
|
345
|
+
recorded: t.Dict[str, t.Dict[str, RecordedSchema]] = {}
|
|
346
|
+
for (model_name, snapshot_id), cols in columns.items():
|
|
347
|
+
version, recorded_at = meta[(model_name, snapshot_id)]
|
|
348
|
+
recorded.setdefault(model_name, {})[snapshot_id] = RecordedSchema(
|
|
349
|
+
snapshot_id=snapshot_id,
|
|
350
|
+
version=version,
|
|
351
|
+
recorded_at=recorded_at,
|
|
352
|
+
columns=tuple(cols),
|
|
353
|
+
)
|
|
354
|
+
return recorded
|
|
355
|
+
|
|
356
|
+
def _write_schemas(self, invocation: "Invocation", adapter: "EngineAdapter") -> None:
|
|
357
|
+
recorded = self._recorded_schemas(adapter, (s.model_name for s in invocation.schemas))
|
|
358
|
+
# A replay of a capture already recorded is compared with its ancestors, not itself.
|
|
359
|
+
for capture in invocation.schemas:
|
|
360
|
+
recorded.get(capture.model_name, {}).pop(capture.snapshot_id, None)
|
|
361
|
+
column_rows, change_rows = monitors.schema_rows(invocation, recorded)
|
|
362
|
+
with adapter.transaction():
|
|
363
|
+
for capture in invocation.schemas:
|
|
364
|
+
model = exp.column("model_name").eq(exp.Literal.string(capture.model_name))
|
|
365
|
+
snapshot = exp.Literal.string(capture.snapshot_id)
|
|
366
|
+
adapter.delete_from(
|
|
367
|
+
self._table("schema_columns"),
|
|
368
|
+
exp.and_(model, exp.column("snapshot_id").eq(snapshot)),
|
|
369
|
+
)
|
|
370
|
+
adapter.delete_from(
|
|
371
|
+
self._table("schema_changes"),
|
|
372
|
+
exp.and_(model, exp.column("to_snapshot_id").eq(snapshot)),
|
|
373
|
+
)
|
|
374
|
+
self._insert(adapter, "schema_columns", column_rows)
|
|
375
|
+
self._insert(adapter, "schema_changes", change_rows)
|
|
376
|
+
|
|
377
|
+
def _insert(
|
|
378
|
+
self, adapter: "EngineAdapter", name: str, rows: t.List[t.Dict[str, t.Any]]
|
|
379
|
+
) -> None:
|
|
380
|
+
columns = TABLES[name]
|
|
381
|
+
for start in range(0, len(rows), _INSERT_CHUNK):
|
|
382
|
+
chunk = rows[start : start + _INSERT_CHUNK]
|
|
383
|
+
values = exp.values(
|
|
384
|
+
[
|
|
385
|
+
tuple(_literal(row.get(column), kind) for column, kind in columns.items())
|
|
386
|
+
for row in chunk
|
|
387
|
+
],
|
|
388
|
+
alias="_rows",
|
|
389
|
+
columns=list(columns),
|
|
390
|
+
)
|
|
391
|
+
query = exp.select(*(exp.column(c) for c in columns)).from_(values)
|
|
392
|
+
adapter.insert_append(self._table(name), query, target_columns_to_types=columns)
|
|
393
|
+
|
|
394
|
+
def _rows(self, invocation: "Invocation") -> t.Dict[str, t.List[t.Dict[str, t.Any]]]:
|
|
395
|
+
return {
|
|
396
|
+
"invocations": [
|
|
397
|
+
{
|
|
398
|
+
"invocation_id": invocation.invocation_id,
|
|
399
|
+
"command": invocation.command,
|
|
400
|
+
"environment": invocation.environment,
|
|
401
|
+
"plan_id": invocation.plan_id,
|
|
402
|
+
"started_at": invocation.started_at,
|
|
403
|
+
"finished_at": invocation.finished_at,
|
|
404
|
+
"status": invocation.status,
|
|
405
|
+
"sqlmesh_version": _sqlmesh_version(),
|
|
406
|
+
}
|
|
407
|
+
],
|
|
408
|
+
"model_runs": [
|
|
409
|
+
{
|
|
410
|
+
"invocation_id": m.invocation_id,
|
|
411
|
+
"model_name": m.model_name,
|
|
412
|
+
"snapshot_id": m.snapshot_id,
|
|
413
|
+
"version": m.version,
|
|
414
|
+
"physical_table": m.physical_table,
|
|
415
|
+
"interval_start": _ms_to_datetime(m.interval_start),
|
|
416
|
+
"interval_end": _ms_to_datetime(m.interval_end),
|
|
417
|
+
"batch_index": m.batch_index,
|
|
418
|
+
"execution_time": _ms_to_datetime(m.execution_time),
|
|
419
|
+
"environment": m.environment,
|
|
420
|
+
"audit_only": m.audit_only,
|
|
421
|
+
"status": m.status,
|
|
422
|
+
"duration_ms": m.duration_ms,
|
|
423
|
+
"error_message": m.error_message,
|
|
424
|
+
}
|
|
425
|
+
for m in invocation.models
|
|
426
|
+
],
|
|
427
|
+
"audit_results": [
|
|
428
|
+
{
|
|
429
|
+
"invocation_id": a.invocation_id,
|
|
430
|
+
"model_name": a.model_name,
|
|
431
|
+
"snapshot_id": a.snapshot_id,
|
|
432
|
+
"version": a.version,
|
|
433
|
+
"physical_table": a.physical_table,
|
|
434
|
+
"environment": a.environment,
|
|
435
|
+
"audit_name": a.audit_name,
|
|
436
|
+
"args_json": a.args_json,
|
|
437
|
+
"interval_start": _ms_to_datetime(a.interval_start),
|
|
438
|
+
"interval_end": _ms_to_datetime(a.interval_end),
|
|
439
|
+
"status": a.status,
|
|
440
|
+
"violation_count": a.violation_count,
|
|
441
|
+
"blocking": a.blocking,
|
|
442
|
+
"query_sql": a.query_sql,
|
|
443
|
+
"error_message": a.error_message,
|
|
444
|
+
}
|
|
445
|
+
for a in invocation.audits
|
|
446
|
+
],
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
def _samples(self, invocation: "Invocation") -> t.List[t.Dict[str, t.Any]]:
|
|
450
|
+
if self.sample_rows <= 0:
|
|
451
|
+
return []
|
|
452
|
+
failing = [a for a in invocation.audits if a.status == "fail" and a.query_sql]
|
|
453
|
+
if not failing:
|
|
454
|
+
return []
|
|
455
|
+
samples: t.List[t.Dict[str, t.Any]] = []
|
|
456
|
+
adapter = self._sample_adapter()
|
|
457
|
+
for audit in failing:
|
|
458
|
+
try:
|
|
459
|
+
import sqlglot
|
|
460
|
+
|
|
461
|
+
query = sqlglot.parse_one(audit.query_sql or "", read=adapter.dialect)
|
|
462
|
+
if not isinstance(query, exp.Query):
|
|
463
|
+
continue
|
|
464
|
+
limited = exp.select("*").from_(query.subquery("_audit")).limit(self.sample_rows)
|
|
465
|
+
frame = adapter.fetchdf(limited)
|
|
466
|
+
except Exception:
|
|
467
|
+
logger.debug("sqlmesh-observability: sampling failed", exc_info=True)
|
|
468
|
+
continue
|
|
469
|
+
for record in frame.to_dict(orient="records"):
|
|
470
|
+
samples.append(
|
|
471
|
+
{
|
|
472
|
+
"invocation_id": audit.invocation_id,
|
|
473
|
+
"model_name": audit.model_name,
|
|
474
|
+
"audit_name": audit.audit_name,
|
|
475
|
+
"interval_start": _ms_to_datetime(audit.interval_start),
|
|
476
|
+
"row_json": json.dumps(_plain(record), sort_keys=True, default=str),
|
|
477
|
+
}
|
|
478
|
+
)
|
|
479
|
+
return samples
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _plain(record: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:
|
|
483
|
+
"""pandas uses NaN/NaT for missing values; store them as JSON null."""
|
|
484
|
+
out: t.Dict[str, t.Any] = {}
|
|
485
|
+
for key, value in record.items():
|
|
486
|
+
try:
|
|
487
|
+
import pandas as pd
|
|
488
|
+
|
|
489
|
+
missing = bool(pd.isna(value))
|
|
490
|
+
except (TypeError, ValueError):
|
|
491
|
+
missing = False
|
|
492
|
+
out[str(key)] = None if missing else value
|
|
493
|
+
return out
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlmesh-observability
|
|
3
|
+
Version: 0.1.0a2
|
|
4
|
+
Summary: Elementary-style data observability for SQLMesh projects
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: NOTICE
|
|
10
|
+
Requires-Dist: sqlmesh
|
|
11
|
+
Provides-Extra: serve
|
|
12
|
+
Requires-Dist: starlette>=0.27; extra == "serve"
|
|
13
|
+
Requires-Dist: uvicorn>=0.22; extra == "serve"
|
|
14
|
+
Provides-Extra: docs
|
|
15
|
+
Requires-Dist: mkdocs<2,>=1.6; extra == "docs"
|
|
16
|
+
Requires-Dist: mkdocs-material<10,>=9.5; extra == "docs"
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: httpx; extra == "dev"
|
|
19
|
+
Requires-Dist: mypy; extra == "dev"
|
|
20
|
+
Requires-Dist: pytest; extra == "dev"
|
|
21
|
+
Requires-Dist: sqlmesh[web]; extra == "dev"
|
|
22
|
+
Requires-Dist: ruff; extra == "dev"
|
|
23
|
+
Requires-Dist: starlette>=0.27; extra == "dev"
|
|
24
|
+
Requires-Dist: uvicorn>=0.22; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# sqlmesh-observability
|
|
28
|
+
|
|
29
|
+
Elementary-style data observability for [SQLMesh](https://github.com/TobikoData/sqlmesh)
|
|
30
|
+
projects. It installs as a package next to SQLMesh, is enabled from `config.py`, and needs no
|
|
31
|
+
changes to SQLMesh itself.
|
|
32
|
+
|
|
33
|
+
> **Status: pre-alpha.** Expect breaking changes before 1.0. Requires Python 3.9 or newer and a
|
|
34
|
+
> SQLMesh release with the execution-observation API (added after `v0.236.4`).
|
|
35
|
+
|
|
36
|
+
## What it does
|
|
37
|
+
|
|
38
|
+
- **Logs every run.** Each plan and run writes its model runs and audit results to an
|
|
39
|
+
`observability` schema in your warehouse, keyed by model version.
|
|
40
|
+
- **Gates on anomalies.** `volume_anomaly`, `freshness_anomaly`, and `column_anomaly` are SQLMesh
|
|
41
|
+
audits that compute history from your data and can block a plan before promotion.
|
|
42
|
+
- **Watches passively.** It records row counts, freshness lag, column null rates and means, and
|
|
43
|
+
schema changes on every run, and scores them for anomalies when you read them.
|
|
44
|
+
- **Reports.** `sqlmesh-observe report` writes an offline HTML dashboard of what is in prod, and
|
|
45
|
+
`sqlmesh-observe serve` serves the same dashboard as a read-only web app.
|
|
46
|
+
- **Alerts.** `sqlmesh-observe monitor` sends one grouped message per model owner for new prod
|
|
47
|
+
failures and anomalies, through your own notification target.
|
|
48
|
+
|
|
49
|
+
## Quick start
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install sqlmesh-observability
|
|
53
|
+
pip install "sqlmesh-observability[serve]" # optional: the web app
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
# config.py
|
|
58
|
+
from sqlmesh.core.config import Config
|
|
59
|
+
from sqlmesh_observability import install
|
|
60
|
+
|
|
61
|
+
config = install(
|
|
62
|
+
Config(...),
|
|
63
|
+
"warehouse", # gateway that holds the log
|
|
64
|
+
monitors={"volume": True, "schema": True}, # optional passive monitors
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
sqlmesh plan # unchanged; the log is written as it runs
|
|
70
|
+
sqlmesh-observe report -o report.html # open the dashboard
|
|
71
|
+
sqlmesh-observe init-audits # optional: add the anomaly audits to the project
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
See [Getting started](https://w4n2.github.io/sqlmesh-observability/getting-started/) for installation and a full walkthrough.
|
|
75
|
+
|
|
76
|
+
**Docs site and live demo report:** https://w4n2.github.io/sqlmesh-observability/
|
|
77
|
+
|
|
78
|
+
## Documentation
|
|
79
|
+
|
|
80
|
+
| Guide | Covers |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| [Getting started](https://w4n2.github.io/sqlmesh-observability/getting-started/) | Requirements, installation, first report |
|
|
83
|
+
| [Configuration](https://w4n2.github.io/sqlmesh-observability/configuration/) | Every `install()` argument, and what `install()` changes |
|
|
84
|
+
| [CLI reference](https://w4n2.github.io/sqlmesh-observability/cli/) | `init-audits`, `report`, `serve`, `monitor` |
|
|
85
|
+
| [Anomaly audits](https://w4n2.github.io/sqlmesh-observability/audits/) | `volume_anomaly`, `freshness_anomaly`, `column_anomaly` |
|
|
86
|
+
| [Passive monitors](https://w4n2.github.io/sqlmesh-observability/monitors/) | Volume, freshness, schema, and column metrics, and how they are scored |
|
|
87
|
+
| [Report and app](https://w4n2.github.io/sqlmesh-observability/report/) | What the dashboard shows, scope, and deploying `serve` |
|
|
88
|
+
| [Alerts](https://w4n2.github.io/sqlmesh-observability/alerts/) | `monitor`, notification targets, grouping, and delivery |
|
|
89
|
+
| [Warehouse tables](https://w4n2.github.io/sqlmesh-observability/warehouse-tables/) | The tables the package writes, and their columns |
|
|
90
|
+
| [Known limitations](https://w4n2.github.io/sqlmesh-observability/limitations/) | What isn't covered yet |
|
|
91
|
+
|
|
92
|
+
## How it works
|
|
93
|
+
|
|
94
|
+
`install()` adds a notification target and wraps the SQLMesh console's execution observer, on
|
|
95
|
+
that instance only. It never replaces the console and never writes SQLMesh state. As SQLMesh
|
|
96
|
+
works, the observer copies plain facts (model, version, interval, audit result). When each plan
|
|
97
|
+
or run finishes, they are written to the package's own tables. The read side (`report`, `serve`,
|
|
98
|
+
`monitor`) joins those rows to SQLMesh state, so a version built in dev and promoted to prod
|
|
99
|
+
counts as prod, and a dev-only failure never shows up in prod.
|
|
100
|
+
|
|
101
|
+
## Development
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python -m venv .venv && source .venv/bin/activate
|
|
105
|
+
pip install -e ".[dev]"
|
|
106
|
+
scripts/ci.sh # everything a change must pass
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`scripts/ci.sh` runs, in order:
|
|
110
|
+
- the search guards;
|
|
111
|
+
- ruff, the format check, and mypy;
|
|
112
|
+
- a Python 3.9 syntax check;
|
|
113
|
+
- the test suite, against the installed SQLMesh and against SQLMesh `main`.
|
|
114
|
+
|
|
115
|
+
`tests/test_e2e.py` runs one prod-shaped history through every part of the package.
|
|
116
|
+
[docs/verification.md](https://w4n2.github.io/sqlmesh-observability/verification/) maps each SQLMesh behavior the package depends on to
|
|
117
|
+
the test that pins it. See [CONTRIBUTING.md](https://github.com/W4N2/sqlmesh-observability/blob/main/CONTRIBUTING.md) for commit rules and
|
|
118
|
+
[AGENTS.md](https://github.com/W4N2/sqlmesh-observability/blob/main/AGENTS.md) for guidance aimed at coding agents.
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
Apache License 2.0. See [LICENSE](https://github.com/W4N2/sqlmesh-observability/blob/main/LICENSE) and [NOTICE](https://github.com/W4N2/sqlmesh-observability/blob/main/NOTICE).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
sqlmesh_observability/__init__.py,sha256=w51pS9hDEr3FGTPrsH2UqDGpdtT4kRP8BNzadY8V-90,346
|
|
2
|
+
sqlmesh_observability/alerts.py,sha256=bNPE9-LYgmaXrsGn8VFCL4MBh0lh1f3J_0Z0N0XUu7w,11289
|
|
3
|
+
sqlmesh_observability/app.py,sha256=PSTaxWuld24ZVfV8cZpMGE0po6h1x0GqtdOGBBmyM3o,6277
|
|
4
|
+
sqlmesh_observability/cli.py,sha256=vYrpT4jAaQX9-TcF3AEMKd4Bzvlb__7wDxs4Vz7JdVI,5433
|
|
5
|
+
sqlmesh_observability/collector.py,sha256=8MITM52TN1Qwo_PVtZ92GtxS9Oa9l1yuBWmot23KwQU,17979
|
|
6
|
+
sqlmesh_observability/hook.py,sha256=6hglP7dOsf6aXt64unwikIQOHv-4P__7SY4I03iaq2g,9233
|
|
7
|
+
sqlmesh_observability/monitors.py,sha256=aiUlehlEKhgn2jNNGXg1uYiYQK6z8-_sytjRqW6TZR8,22221
|
|
8
|
+
sqlmesh_observability/payload.py,sha256=NaEHxtUU4xH5cN3PH5NFBrZJQmhf-wXuAUwTSfPTyao,20161
|
|
9
|
+
sqlmesh_observability/reader.py,sha256=K7QetQurT0ve2PLXoDjmkJtJBeHsKN8S3VKkmHvGGD4,44107
|
|
10
|
+
sqlmesh_observability/report.py,sha256=svA26dcz3jNYaoGPzmXVnfN-TLxWLY0LaSWkzCCAZ7Q,6424
|
|
11
|
+
sqlmesh_observability/textfmt.py,sha256=7p9yhKnEcrr9BYMzPURDf0lY_gGSiG8UqCwP_mp8yI0,1606
|
|
12
|
+
sqlmesh_observability/writer.py,sha256=LIoS_jvXWjvsNua_X12s3hWLW6Gj3hqOorahFEjKmvI,19831
|
|
13
|
+
sqlmesh_observability/audits/__init__.py,sha256=neJVGIYFtLufT3nnQAvliAw60xonqH6-0nNP5jGFIN8,2278
|
|
14
|
+
sqlmesh_observability/audits/column_anomaly.sql,sha256=WOKq0rVi-yddB3fln4TeO3_-a-Dl3pOIgTMng2mQJ0w,3063
|
|
15
|
+
sqlmesh_observability/audits/freshness_anomaly.sql,sha256=tzFswpYkH3c63uh64kEluPJrL59g-XtenUX4NzhmfQM,1495
|
|
16
|
+
sqlmesh_observability/audits/macros.py,sha256=yqePnVWygdcIJ2Izy7UKsos-a1tmZdYGaf8EIBj68OU,3975
|
|
17
|
+
sqlmesh_observability/audits/volume_anomaly.sql,sha256=UXk1jXNQ1txmEvhktKw3g5gEKQgYTtSLbDIDFAvrA4k,3772
|
|
18
|
+
sqlmesh_observability/web/report.css,sha256=7luasBV919vFya17HalyhB6_6AZ8DQQ5pwcY27izsvI,22006
|
|
19
|
+
sqlmesh_observability/web/report.js,sha256=BBq145Vi2hyWNbU5WvQ_RM7COYU011CaUvMDAa7_UKA,69492
|
|
20
|
+
sqlmesh_observability-0.1.0a2.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
21
|
+
sqlmesh_observability-0.1.0a2.dist-info/licenses/NOTICE,sha256=kglH5LszKFPohqWLgT2orGfXE1BVYIIzwPzzi5i6Mtc,105
|
|
22
|
+
sqlmesh_observability-0.1.0a2.dist-info/METADATA,sha256=l0BhJ-Zdgw3DN9ZUOyg9-TYMr0i3o6JC5Vxc07ZHd4M,5861
|
|
23
|
+
sqlmesh_observability-0.1.0a2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
24
|
+
sqlmesh_observability-0.1.0a2.dist-info/entry_points.txt,sha256=8fcfGLF8m1QLJimcdAyFLtfT88zgNlEPS_7zznlR4Is,73
|
|
25
|
+
sqlmesh_observability-0.1.0a2.dist-info/top_level.txt,sha256=bPyW8HjkkJuzfQjJMBN5CfyhajXY8KDda5jCrqrkuQM,22
|
|
26
|
+
sqlmesh_observability-0.1.0a2.dist-info/RECORD,,
|