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,14 @@
|
|
|
1
|
+
"""Elementary-style data observability for SQLMesh projects.
|
|
2
|
+
|
|
3
|
+
Enable it from a project's Python ``config.py``::
|
|
4
|
+
|
|
5
|
+
from sqlmesh_observability import install
|
|
6
|
+
|
|
7
|
+
config = install(Config(...), "warehouse")
|
|
8
|
+
|
|
9
|
+
See the documentation in docs/ for configuration and commands.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from sqlmesh_observability.hook import install
|
|
13
|
+
|
|
14
|
+
__all__ = ["install"]
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""``sqlmesh-observe monitor``: one grouped message per owner for new prod issues.
|
|
2
|
+
|
|
3
|
+
It reads the same scoped data as the report, keeps failed or errored audits and anomalous metric
|
|
4
|
+
points that are newer than the environment's watermark and came from an invocation that targeted
|
|
5
|
+
the environment, and groups them by model owner from SQLMesh state. It sends each group through
|
|
6
|
+
the ``alert_target`` given to ``install()``, or prints it. The watermark in ``alert_watermarks``,
|
|
7
|
+
the only table the read side writes, moves only after every send returns.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import datetime
|
|
13
|
+
import sys
|
|
14
|
+
import typing as t
|
|
15
|
+
from dataclasses import asdict, dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from sqlglot import exp
|
|
19
|
+
|
|
20
|
+
if t.TYPE_CHECKING:
|
|
21
|
+
from sqlmesh.core.engine_adapter import EngineAdapter
|
|
22
|
+
|
|
23
|
+
from sqlmesh_observability.reader import AuditRecord, ReportData
|
|
24
|
+
|
|
25
|
+
WATERMARK_TABLE = "alert_watermarks"
|
|
26
|
+
WATERMARK_COLUMNS: t.Dict[str, exp.DataType] = {
|
|
27
|
+
"environment": exp.DataType.build("TEXT"),
|
|
28
|
+
"watermark_at": exp.DataType.build("TIMESTAMP"),
|
|
29
|
+
"invocation_id": exp.DataType.build("TEXT"),
|
|
30
|
+
"updated_at": exp.DataType.build("TIMESTAMP"),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
# Severity order within a message: blocking failures and errors, then warnings, then anomalies.
|
|
34
|
+
_BLOCKING, _WARNING, _ANOMALY = 0, 1, 2
|
|
35
|
+
|
|
36
|
+
Mark = t.Tuple[datetime.datetime, str] # (invocation finished_at, invocation_id)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Alert:
|
|
41
|
+
"""One new issue, as plain values: what the target receives in ``alerts=``."""
|
|
42
|
+
|
|
43
|
+
kind: str # "audit" or "anomaly"
|
|
44
|
+
severity: int
|
|
45
|
+
model_name: str
|
|
46
|
+
owner: t.Optional[str]
|
|
47
|
+
signal: str # audit name with arguments, or metric with column
|
|
48
|
+
interval_start: t.Optional[str]
|
|
49
|
+
status: str # "blocking failure", "non-blocking failure", "audit error", "anomaly"
|
|
50
|
+
detail: str
|
|
51
|
+
invocation_id: str
|
|
52
|
+
|
|
53
|
+
def line(self) -> str:
|
|
54
|
+
day = (self.interval_start or "-")[:10]
|
|
55
|
+
name = self.model_name.replace('"', "")
|
|
56
|
+
return f"- {name} · {self.signal} · {day} · {self.status}" + (
|
|
57
|
+
f" · {self.detail}" if self.detail else ""
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class Group:
|
|
63
|
+
owner: t.Optional[str]
|
|
64
|
+
alerts: t.Tuple[Alert, ...]
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def failing(self) -> bool:
|
|
68
|
+
return any(a.severity == _BLOCKING for a in self.alerts)
|
|
69
|
+
|
|
70
|
+
def message(self, environment: str) -> str:
|
|
71
|
+
count = len(self.alerts)
|
|
72
|
+
whom = f"for {self.owner}" if self.owner else "with no owner"
|
|
73
|
+
noun = "issue" if count == 1 else "issues"
|
|
74
|
+
head = f"sqlmesh-observe: {count} new {noun} in {environment} {whom}"
|
|
75
|
+
return "\n".join([head, *(a.line() for a in self.alerts)])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _rows(count: t.Optional[int]) -> str:
|
|
79
|
+
if count is None:
|
|
80
|
+
return ""
|
|
81
|
+
return f"{count} row" if count == 1 else f"{count} rows"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _audit_alert(record: "AuditRecord", owner: t.Optional[str]) -> Alert:
|
|
85
|
+
from sqlmesh_observability.textfmt import args_text
|
|
86
|
+
|
|
87
|
+
args = args_text(record.args_json)
|
|
88
|
+
signal = f"{record.audit_name}({args})" if args else record.audit_name
|
|
89
|
+
if record.status == "error":
|
|
90
|
+
status, severity, detail = "audit error", _BLOCKING, record.error_message or ""
|
|
91
|
+
elif record.blocking:
|
|
92
|
+
status, severity, detail = "blocking failure", _BLOCKING, _rows(record.violation_count)
|
|
93
|
+
else:
|
|
94
|
+
status, severity, detail = "non-blocking failure", _WARNING, _rows(record.violation_count)
|
|
95
|
+
return Alert(
|
|
96
|
+
kind="audit",
|
|
97
|
+
severity=severity,
|
|
98
|
+
model_name=record.model_name,
|
|
99
|
+
owner=owner,
|
|
100
|
+
signal=signal,
|
|
101
|
+
interval_start=record.interval_start,
|
|
102
|
+
status=status,
|
|
103
|
+
detail=detail,
|
|
104
|
+
invocation_id=record.invocation_id,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def candidates(data: "ReportData") -> t.List[Alert]:
|
|
109
|
+
"""Every failed or errored audit and every anomalous point in scope, old or new."""
|
|
110
|
+
from sqlmesh_observability.textfmt import expected_range as _expected
|
|
111
|
+
from sqlmesh_observability.textfmt import number as _num
|
|
112
|
+
|
|
113
|
+
owners = {m.model_name: m.owner for m in data.models}
|
|
114
|
+
found = [_audit_alert(r, owners.get(r.model_name)) for r in data.incidents]
|
|
115
|
+
for model in data.models:
|
|
116
|
+
for series in model.metrics:
|
|
117
|
+
signal = series.metric_name + (f"({series.column_name})" if series.column_name else "")
|
|
118
|
+
for point in series.points:
|
|
119
|
+
if not point.anomaly or not point.invocation_id:
|
|
120
|
+
continue
|
|
121
|
+
expected = _expected(point.mean, point.stddev, series.threshold)
|
|
122
|
+
found.append(
|
|
123
|
+
Alert(
|
|
124
|
+
kind="anomaly",
|
|
125
|
+
severity=_ANOMALY,
|
|
126
|
+
model_name=model.model_name,
|
|
127
|
+
owner=model.owner,
|
|
128
|
+
signal=f"{signal} anomaly",
|
|
129
|
+
interval_start=point.interval_start,
|
|
130
|
+
status="anomaly",
|
|
131
|
+
detail=f"{_num(point.value)} (expected {expected})",
|
|
132
|
+
invocation_id=point.invocation_id,
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
return found
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def group(alerts: t.Iterable[Alert]) -> t.List[Group]:
|
|
139
|
+
"""One group per owner, ordered by owner with the owner-less group last."""
|
|
140
|
+
by_owner: t.Dict[t.Optional[str], t.List[Alert]] = {}
|
|
141
|
+
for alert in alerts:
|
|
142
|
+
by_owner.setdefault(alert.owner, []).append(alert)
|
|
143
|
+
ordered = sorted(by_owner, key=lambda owner: (owner is None, owner or ""))
|
|
144
|
+
return [
|
|
145
|
+
Group(
|
|
146
|
+
owner=owner,
|
|
147
|
+
alerts=tuple(
|
|
148
|
+
sorted(
|
|
149
|
+
by_owner[owner],
|
|
150
|
+
key=lambda a: (
|
|
151
|
+
a.severity,
|
|
152
|
+
a.model_name,
|
|
153
|
+
a.signal,
|
|
154
|
+
a.interval_start or "",
|
|
155
|
+
a.invocation_id,
|
|
156
|
+
),
|
|
157
|
+
)
|
|
158
|
+
),
|
|
159
|
+
)
|
|
160
|
+
for owner in ordered
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _table(schema: str) -> exp.Table:
|
|
165
|
+
return exp.to_table(f"{schema}.{WATERMARK_TABLE}")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _invocation_marks(
|
|
169
|
+
adapter: "EngineAdapter", schema: str, invocation_ids: t.Collection[str]
|
|
170
|
+
) -> t.Dict[str, t.Tuple[t.Optional[str], Mark]]:
|
|
171
|
+
"""``{invocation_id: (environment, (finished_at or started_at, invocation_id))}``."""
|
|
172
|
+
from sqlmesh_observability.reader import _IN_CHUNK, _naive
|
|
173
|
+
|
|
174
|
+
marks: t.Dict[str, t.Tuple[t.Optional[str], Mark]] = {}
|
|
175
|
+
table = exp.to_table(f"{schema}.invocations")
|
|
176
|
+
ids = sorted(set(invocation_ids))
|
|
177
|
+
if not ids or not adapter.table_exists(table):
|
|
178
|
+
return marks
|
|
179
|
+
for start in range(0, len(ids), _IN_CHUNK):
|
|
180
|
+
chunk = ids[start : start + _IN_CHUNK]
|
|
181
|
+
query = (
|
|
182
|
+
exp.select("invocation_id", "environment", "finished_at", "started_at")
|
|
183
|
+
.from_(table)
|
|
184
|
+
.where(exp.column("invocation_id").isin(*(exp.Literal.string(i) for i in chunk)))
|
|
185
|
+
)
|
|
186
|
+
for invocation_id, environment, finished_at, started_at in adapter.fetchall(query):
|
|
187
|
+
when = _naive(finished_at) or _naive(started_at) or datetime.datetime.min
|
|
188
|
+
marks[str(invocation_id)] = (
|
|
189
|
+
None if environment is None else str(environment),
|
|
190
|
+
(when, str(invocation_id)),
|
|
191
|
+
)
|
|
192
|
+
return marks
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def read_watermark(adapter: "EngineAdapter", schema: str, environment: str) -> t.Optional[Mark]:
|
|
196
|
+
from sqlmesh_observability.reader import _naive
|
|
197
|
+
|
|
198
|
+
table = _table(schema)
|
|
199
|
+
if not adapter.table_exists(table):
|
|
200
|
+
return None
|
|
201
|
+
row = adapter.fetchone(
|
|
202
|
+
exp.select("watermark_at", "invocation_id")
|
|
203
|
+
.from_(table)
|
|
204
|
+
.where(exp.column("environment").eq(exp.Literal.string(environment)))
|
|
205
|
+
.order_by(exp.column("watermark_at").desc(), exp.column("invocation_id").desc())
|
|
206
|
+
.limit(1)
|
|
207
|
+
)
|
|
208
|
+
if row is None or row[0] is None:
|
|
209
|
+
return None
|
|
210
|
+
return (_naive(row[0]) or datetime.datetime.min, str(row[1] or ""))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def write_watermark(adapter: "EngineAdapter", schema: str, environment: str, mark: Mark) -> None:
|
|
214
|
+
"""Replace the environment's watermark row. The read side's only write."""
|
|
215
|
+
from sqlmesh_observability.writer import _literal
|
|
216
|
+
|
|
217
|
+
table = _table(schema)
|
|
218
|
+
adapter.create_table(table, WATERMARK_COLUMNS, exists=True)
|
|
219
|
+
now = datetime.datetime.now(datetime.timezone.utc)
|
|
220
|
+
row = {
|
|
221
|
+
"environment": environment,
|
|
222
|
+
"watermark_at": mark[0],
|
|
223
|
+
"invocation_id": mark[1],
|
|
224
|
+
"updated_at": now,
|
|
225
|
+
}
|
|
226
|
+
values = exp.values(
|
|
227
|
+
[tuple(_literal(row[c], kind) for c, kind in WATERMARK_COLUMNS.items())],
|
|
228
|
+
alias="_rows",
|
|
229
|
+
columns=list(WATERMARK_COLUMNS),
|
|
230
|
+
)
|
|
231
|
+
with adapter.transaction():
|
|
232
|
+
adapter.delete_from(table, exp.column("environment").eq(exp.Literal.string(environment)))
|
|
233
|
+
adapter.insert_append(
|
|
234
|
+
table,
|
|
235
|
+
exp.select(*(exp.column(c) for c in WATERMARK_COLUMNS)).from_(values),
|
|
236
|
+
target_columns_to_types=WATERMARK_COLUMNS,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def run_monitor(
|
|
241
|
+
path: t.Union[str, Path] = ".",
|
|
242
|
+
gateway: t.Optional[str] = None,
|
|
243
|
+
schema: t.Optional[str] = None,
|
|
244
|
+
environment: str = "prod",
|
|
245
|
+
) -> int:
|
|
246
|
+
"""Send (or print) one message per owner for new issues; return the exit code."""
|
|
247
|
+
from sqlmesh.core.notification_target import NotificationStatus
|
|
248
|
+
|
|
249
|
+
from sqlmesh_observability.reader import (
|
|
250
|
+
_load_project_config,
|
|
251
|
+
_resolve_gateway_and_schema,
|
|
252
|
+
load_report_data_for,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
config, settings = _load_project_config(path)
|
|
256
|
+
target = settings.get("alert_target")
|
|
257
|
+
data = load_report_data_for(config, settings, gateway, schema, environment)
|
|
258
|
+
resolved_gateway, resolved_schema = _resolve_gateway_and_schema(
|
|
259
|
+
config, settings, gateway, schema
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
adapter = config.get_connection(resolved_gateway).create_engine_adapter()
|
|
263
|
+
try:
|
|
264
|
+
found = candidates(data)
|
|
265
|
+
marks = _invocation_marks(adapter, resolved_schema, {a.invocation_id for a in found})
|
|
266
|
+
watermark = read_watermark(adapter, resolved_schema, environment)
|
|
267
|
+
new = [
|
|
268
|
+
a
|
|
269
|
+
for a in found
|
|
270
|
+
if a.invocation_id in marks
|
|
271
|
+
and marks[a.invocation_id][0] == environment
|
|
272
|
+
and (watermark is None or marks[a.invocation_id][1] > watermark)
|
|
273
|
+
]
|
|
274
|
+
if not new:
|
|
275
|
+
print(f"sqlmesh-observe: no new issues in {environment}")
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
for item in group(new):
|
|
279
|
+
message = item.message(environment)
|
|
280
|
+
if target is None:
|
|
281
|
+
print(message + "\n")
|
|
282
|
+
continue
|
|
283
|
+
status = NotificationStatus.FAILURE if item.failing else NotificationStatus.WARNING
|
|
284
|
+
try:
|
|
285
|
+
target.send(
|
|
286
|
+
status, message, owner=item.owner, alerts=[asdict(a) for a in item.alerts]
|
|
287
|
+
)
|
|
288
|
+
except Exception as error:
|
|
289
|
+
print(
|
|
290
|
+
f"sqlmesh-observe: sending the alert for {item.owner or 'models with no owner'}"
|
|
291
|
+
f" failed, so the watermark was not moved: {error}",
|
|
292
|
+
file=sys.stderr,
|
|
293
|
+
)
|
|
294
|
+
return 1
|
|
295
|
+
|
|
296
|
+
write_watermark(
|
|
297
|
+
adapter,
|
|
298
|
+
resolved_schema,
|
|
299
|
+
environment,
|
|
300
|
+
max(marks[a.invocation_id][1] for a in new),
|
|
301
|
+
)
|
|
302
|
+
return 0
|
|
303
|
+
finally:
|
|
304
|
+
adapter.close()
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""``sqlmesh-observe serve``: a read-only ASGI app over the observability report.
|
|
2
|
+
|
|
3
|
+
Every route reads the warehouse log and SQLMesh state through ``load_report_data`` and returns
|
|
4
|
+
the same page as ``sqlmesh-observe report``, opened on the requested model or incident, or the
|
|
5
|
+
page's JSON payload (``/data.json``). Only GET (and HEAD) routes exist. Nothing here runs a
|
|
6
|
+
model, applies a plan, loads a ``Context``, or writes.
|
|
7
|
+
|
|
8
|
+
Starlette is an optional dependency (``sqlmesh-observability[serve]``), imported inside
|
|
9
|
+
:func:`create_app`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import html
|
|
15
|
+
import typing as t
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
if t.TYPE_CHECKING:
|
|
19
|
+
from starlette.applications import Starlette
|
|
20
|
+
from starlette.requests import Request
|
|
21
|
+
from starlette.responses import Response
|
|
22
|
+
|
|
23
|
+
from sqlmesh_observability.reader import AuditRecord, ModelReport, ReportData
|
|
24
|
+
|
|
25
|
+
SERVE_EXTRA_HINT = (
|
|
26
|
+
"sqlmesh-observe serve needs Starlette and uvicorn: pip install 'sqlmesh-observability[serve]'"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def find_model(data: "ReportData", name: str) -> t.Optional["ModelReport"]:
|
|
31
|
+
"""The model named ``name``: its full name, the same without quotes, or a unique suffix.
|
|
32
|
+
|
|
33
|
+
``"db"."obs"."events"``, ``db.obs.events`` and ``obs.events`` all find the same model, unless
|
|
34
|
+
another model shares that suffix.
|
|
35
|
+
"""
|
|
36
|
+
plain = name.replace('"', "")
|
|
37
|
+
for model in data.models:
|
|
38
|
+
if model.model_name == name or model.model_name.replace('"', "") == plain:
|
|
39
|
+
return model
|
|
40
|
+
matches = [
|
|
41
|
+
m for m in data.models if m.model_name.replace('"', "").endswith("." + plain.lstrip("."))
|
|
42
|
+
]
|
|
43
|
+
return matches[0] if len(matches) == 1 else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def find_incident(
|
|
47
|
+
data: "ReportData", invocation_id: str, audit_name: str
|
|
48
|
+
) -> t.Optional["AuditRecord"]:
|
|
49
|
+
"""The newest in-scope failed or errored audit with this invocation and audit name."""
|
|
50
|
+
for incident in data.incidents: # newest first
|
|
51
|
+
if incident.invocation_id == invocation_id and incident.audit_name == audit_name:
|
|
52
|
+
return incident
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _message_page(status: int, title: str, detail: str) -> str:
|
|
57
|
+
return (
|
|
58
|
+
'<!DOCTYPE html>\n<html lang="en"><head><meta charset="utf-8">'
|
|
59
|
+
f"<title>{html.escape(title)} · sqlmesh-observe</title></head>"
|
|
60
|
+
f"<body><h1>{status} {html.escape(title)}</h1><p>{html.escape(detail)}</p>"
|
|
61
|
+
'<p><a href="/">Back to the dashboard</a></p></body></html>\n'
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def create_app(
|
|
66
|
+
path: t.Union[str, Path] = ".",
|
|
67
|
+
gateway: t.Optional[str] = None,
|
|
68
|
+
schema: t.Optional[str] = None,
|
|
69
|
+
environment: str = "prod",
|
|
70
|
+
history: t.Optional[int] = None,
|
|
71
|
+
) -> "Starlette":
|
|
72
|
+
"""Build the read-only app for the project whose ``config.py`` is in ``path``."""
|
|
73
|
+
from starlette.applications import Starlette
|
|
74
|
+
from starlette.responses import HTMLResponse, Response
|
|
75
|
+
from starlette.routing import Route
|
|
76
|
+
|
|
77
|
+
from sqlmesh_observability.payload import DEFAULT_HISTORY, build_payload, encode
|
|
78
|
+
from sqlmesh_observability.reader import MissingAuditTableError, load_report_data
|
|
79
|
+
from sqlmesh_observability.report import incident_route, model_route, render_payload
|
|
80
|
+
|
|
81
|
+
keep = DEFAULT_HISTORY if history is None else history
|
|
82
|
+
|
|
83
|
+
def load() -> t.Union["Response", t.Tuple["ReportData", t.Dict[str, t.Any]]]:
|
|
84
|
+
# Runs on the event loop's thread, not Starlette's threadpool: hydrating snapshots from
|
|
85
|
+
# state can start SQLMesh's fork-based process pool, and forking from a worker thread
|
|
86
|
+
# crashes on macOS. Requests are therefore served one at a time.
|
|
87
|
+
try:
|
|
88
|
+
data = load_report_data(
|
|
89
|
+
path=path, gateway=gateway, schema=schema, environment=environment
|
|
90
|
+
)
|
|
91
|
+
except MissingAuditTableError as error:
|
|
92
|
+
return HTMLResponse(_message_page(503, "No observability data", str(error)), 503)
|
|
93
|
+
return data, build_payload(data, history=keep)
|
|
94
|
+
|
|
95
|
+
def page(
|
|
96
|
+
request: "Request",
|
|
97
|
+
pick: t.Callable[["ReportData", t.Dict[str, t.Any]], t.Optional[str]],
|
|
98
|
+
) -> "Response":
|
|
99
|
+
loaded = load()
|
|
100
|
+
if not isinstance(loaded, tuple):
|
|
101
|
+
return loaded
|
|
102
|
+
data, payload = loaded
|
|
103
|
+
start = pick(data, payload)
|
|
104
|
+
if start is None:
|
|
105
|
+
return HTMLResponse(
|
|
106
|
+
_message_page(404, "Not found", f"Nothing in scope for {request.url.path}."), 404
|
|
107
|
+
)
|
|
108
|
+
return HTMLResponse(render_payload(payload, start=start or None))
|
|
109
|
+
|
|
110
|
+
async def overview(request: "Request") -> "Response":
|
|
111
|
+
return page(request, lambda data, payload: "")
|
|
112
|
+
|
|
113
|
+
async def model(request: "Request") -> "Response":
|
|
114
|
+
name = request.path_params["name"]
|
|
115
|
+
|
|
116
|
+
def pick(data: "ReportData", payload: t.Dict[str, t.Any]) -> t.Optional[str]:
|
|
117
|
+
found = find_model(data, name)
|
|
118
|
+
return model_route(found.model_name) if found else None
|
|
119
|
+
|
|
120
|
+
return page(request, pick)
|
|
121
|
+
|
|
122
|
+
async def incident(request: "Request") -> "Response":
|
|
123
|
+
invocation_id = request.path_params["invocation_id"]
|
|
124
|
+
audit_name = request.path_params["audit_name"]
|
|
125
|
+
|
|
126
|
+
def pick(data: "ReportData", payload: t.Dict[str, t.Any]) -> t.Optional[str]:
|
|
127
|
+
if find_incident(data, invocation_id, audit_name) is None:
|
|
128
|
+
return None
|
|
129
|
+
matches = [
|
|
130
|
+
(stored.get("started_at") or "", index)
|
|
131
|
+
for index, stored in enumerate(payload["incidents"])
|
|
132
|
+
if stored["invocation"] == invocation_id
|
|
133
|
+
and payload["audits"][stored["use"]][0] == audit_name
|
|
134
|
+
]
|
|
135
|
+
# Outside the retained history window: open the incident list instead.
|
|
136
|
+
return incident_route(max(matches)[1]) if matches else "incidents"
|
|
137
|
+
|
|
138
|
+
return page(request, pick)
|
|
139
|
+
|
|
140
|
+
async def data_json(request: "Request") -> "Response":
|
|
141
|
+
loaded = load()
|
|
142
|
+
if not isinstance(loaded, tuple):
|
|
143
|
+
return loaded
|
|
144
|
+
return Response(encode(loaded[1]), media_type="application/json")
|
|
145
|
+
|
|
146
|
+
return Starlette(
|
|
147
|
+
routes=[
|
|
148
|
+
Route("/", overview, methods=["GET"]),
|
|
149
|
+
Route("/data.json", data_json, methods=["GET"]),
|
|
150
|
+
Route("/models/{name:path}", model, methods=["GET"]),
|
|
151
|
+
Route("/incidents/{invocation_id}/{audit_name}", incident, methods=["GET"]),
|
|
152
|
+
]
|
|
153
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""SQL audit files shipped with the package.
|
|
2
|
+
|
|
3
|
+
They are copied into a project's ``audits/`` directory, with the macros they call in ``macros/``,
|
|
4
|
+
so they are versioned with the project and need no custom loader.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import typing as t
|
|
10
|
+
from importlib import resources
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
MACROS_FILE = "macros/observability_audits.py"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def shipped_audits() -> t.Dict[str, str]:
|
|
17
|
+
"""Map of file name to contents for every shipped ``.sql`` audit."""
|
|
18
|
+
root = resources.files(__name__)
|
|
19
|
+
return {
|
|
20
|
+
entry.name: entry.read_text(encoding="utf-8")
|
|
21
|
+
for entry in sorted(root.iterdir(), key=lambda e: e.name)
|
|
22
|
+
if entry.name.endswith(".sql")
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def shipped_files() -> t.Dict[str, str]:
|
|
27
|
+
"""Project-relative path to contents: the audits plus the macros they call."""
|
|
28
|
+
files = {f"audits/{name}": text for name, text in shipped_audits().items()}
|
|
29
|
+
files[MACROS_FILE] = resources.files(__name__).joinpath("macros.py").read_text(encoding="utf-8")
|
|
30
|
+
return files
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def copy_audits(project: t.Union[str, Path], force: bool = False) -> t.List[Path]:
|
|
34
|
+
"""Copy the shipped audits to ``<project>/audits/`` and their macros to ``<project>/macros/``.
|
|
35
|
+
|
|
36
|
+
Files that already match are left alone. A file that differs (for example a local edit) is
|
|
37
|
+
only overwritten with ``force``.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
The files that were written.
|
|
41
|
+
|
|
42
|
+
Raises:
|
|
43
|
+
FileExistsError: a file differs and ``force`` is false. Nothing is written in that case.
|
|
44
|
+
"""
|
|
45
|
+
root = Path(project)
|
|
46
|
+
files = {root / relative: text for relative, text in shipped_files().items()}
|
|
47
|
+
conflicts = [
|
|
48
|
+
path
|
|
49
|
+
for path, text in files.items()
|
|
50
|
+
if path.exists() and path.read_text(encoding="utf-8") != text
|
|
51
|
+
]
|
|
52
|
+
if conflicts and not force:
|
|
53
|
+
raise FileExistsError(
|
|
54
|
+
"These files differ from the shipped audits (use --force to overwrite): "
|
|
55
|
+
+ ", ".join(str(path) for path in conflicts)
|
|
56
|
+
)
|
|
57
|
+
written = []
|
|
58
|
+
for path, text in files.items():
|
|
59
|
+
if not path.exists() or path.read_text(encoding="utf-8") != text:
|
|
60
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
path.write_text(text, encoding="utf-8")
|
|
62
|
+
written.append(path)
|
|
63
|
+
return written
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/*
|
|
2
|
+
column_anomaly: flags days whose null rate or mean of one column deviates from recent history.
|
|
3
|
+
|
|
4
|
+
Shipped by sqlmesh-observability; copy with `sqlmesh-observe init-audits`, which also copies the
|
|
5
|
+
macros it uses (macros/observability_audits.py).
|
|
6
|
+
|
|
7
|
+
audits (
|
|
8
|
+
column_anomaly(column := status, metric := null_rate, time_column := ds,
|
|
9
|
+
source := analytics.orders),
|
|
10
|
+
column_anomaly(column := amount, metric := mean, time_column := ds,
|
|
11
|
+
source := analytics.orders)
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
column the column to watch
|
|
15
|
+
metric null_rate (share of rows where column is null, 0 to 1) or mean (average of the
|
|
16
|
+
non-null values)
|
|
17
|
+
time_column, source, training_days, min_buckets, threshold,
|
|
18
|
+
spike_failure_percent_threshold, drop_failure_percent_threshold
|
|
19
|
+
as in volume_anomaly, with the same defaults
|
|
20
|
+
|
|
21
|
+
Returns one row per flagged day in the processed interval. A day with no value (no rows, or a
|
|
22
|
+
mean over only nulls) is neither scored nor counted as history: missing data is what
|
|
23
|
+
volume_anomaly reports. min_buckets counts days that have a value.
|
|
24
|
+
*/
|
|
25
|
+
AUDIT (
|
|
26
|
+
name column_anomaly,
|
|
27
|
+
blocking false,
|
|
28
|
+
defaults (
|
|
29
|
+
training_days = 14,
|
|
30
|
+
min_buckets = 7,
|
|
31
|
+
threshold = 3,
|
|
32
|
+
spike_failure_percent_threshold = NULL,
|
|
33
|
+
drop_failure_percent_threshold = NULL
|
|
34
|
+
)
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
WITH spine AS (
|
|
38
|
+
SELECT bucket
|
|
39
|
+
FROM (@obs_day_spine(@start_ds, @end_ds, @training_days)) AS days
|
|
40
|
+
), daily AS (
|
|
41
|
+
SELECT CAST(@time_column AS DATE) AS bucket, @obs_column_metric(@column, @metric) AS metric_value
|
|
42
|
+
FROM @source
|
|
43
|
+
WHERE CAST(@time_column AS DATE) BETWEEN @obs_days_before(@start_ds, @training_days)
|
|
44
|
+
AND CAST(@end_ds AS DATE)
|
|
45
|
+
GROUP BY CAST(@time_column AS DATE)
|
|
46
|
+
), series AS (
|
|
47
|
+
SELECT spine.bucket, daily.metric_value
|
|
48
|
+
FROM spine
|
|
49
|
+
LEFT JOIN daily
|
|
50
|
+
ON spine.bucket = daily.bucket
|
|
51
|
+
), training AS (
|
|
52
|
+
SELECT
|
|
53
|
+
COUNT(series.metric_value) AS training_buckets,
|
|
54
|
+
AVG(series.metric_value) AS mean_value,
|
|
55
|
+
COALESCE(STDDEV_SAMP(series.metric_value), 0) AS stddev_value
|
|
56
|
+
FROM series
|
|
57
|
+
WHERE series.bucket < CAST(@start_ds AS DATE)
|
|
58
|
+
)
|
|
59
|
+
SELECT
|
|
60
|
+
series.bucket,
|
|
61
|
+
series.metric_value,
|
|
62
|
+
training.mean_value,
|
|
63
|
+
training.stddev_value,
|
|
64
|
+
(series.metric_value - training.mean_value) / NULLIF(training.stddev_value, 0) AS z_score,
|
|
65
|
+
training.training_buckets
|
|
66
|
+
FROM series
|
|
67
|
+
CROSS JOIN training
|
|
68
|
+
WHERE series.bucket >= CAST(@start_ds AS DATE)
|
|
69
|
+
AND NOT series.metric_value IS NULL
|
|
70
|
+
AND training.training_buckets >= @min_buckets
|
|
71
|
+
AND ABS(series.metric_value - training.mean_value) > @threshold * training.stddev_value
|
|
72
|
+
AND (
|
|
73
|
+
(
|
|
74
|
+
series.metric_value >= training.mean_value
|
|
75
|
+
AND (
|
|
76
|
+
@spike_failure_percent_threshold IS NULL
|
|
77
|
+
OR series.metric_value > (1 + @spike_failure_percent_threshold / 100.0) * training.mean_value
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
OR (
|
|
81
|
+
series.metric_value < training.mean_value
|
|
82
|
+
AND (
|
|
83
|
+
@drop_failure_percent_threshold IS NULL
|
|
84
|
+
OR series.metric_value < (1 - @drop_failure_percent_threshold / 100.0) * training.mean_value
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/*
|
|
2
|
+
freshness_anomaly: flags a model whose newest data is too old.
|
|
3
|
+
|
|
4
|
+
Shipped by sqlmesh-observability; copy with `sqlmesh-observe init-audits`, which also copies the
|
|
5
|
+
macros it uses (macros/observability_audits.py).
|
|
6
|
+
|
|
7
|
+
audits (freshness_anomaly(time_column := updated_at, source := analytics.orders, warn_after_hours := 24))
|
|
8
|
+
|
|
9
|
+
time_column timestamp or date column whose maximum is the data's freshness
|
|
10
|
+
source the audited model itself (unfiltered; see volume_anomaly)
|
|
11
|
+
warn_after_hours allowed lag in hours (default 24)
|
|
12
|
+
|
|
13
|
+
The lag is measured against the end of the processed interval, capped at execution time:
|
|
14
|
+
min(@execution_ts, @end_ts) - warn_after_hours. During a backfill each batch is judged by its own
|
|
15
|
+
interval, so loading history oldest-first does not fail every early batch. In a normal run the
|
|
16
|
+
processed interval ends just before execution time.
|
|
17
|
+
|
|
18
|
+
Returns one row (the latest value found, and the cutoff) when the data is stale or the source is
|
|
19
|
+
empty. Times are compared as timezone-naive timestamps; SQLMesh's execution time is UTC.
|
|
20
|
+
*/
|
|
21
|
+
AUDIT (
|
|
22
|
+
name freshness_anomaly,
|
|
23
|
+
blocking false,
|
|
24
|
+
defaults (
|
|
25
|
+
warn_after_hours = 24
|
|
26
|
+
)
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
SELECT
|
|
30
|
+
latest.max_time,
|
|
31
|
+
@obs_freshness_cutoff(@execution_ts, @end_ts, @warn_after_hours) AS cutoff
|
|
32
|
+
FROM (
|
|
33
|
+
SELECT MAX(CAST(@time_column AS TIMESTAMP)) AS max_time
|
|
34
|
+
FROM @source
|
|
35
|
+
) AS latest
|
|
36
|
+
WHERE latest.max_time IS NULL
|
|
37
|
+
OR latest.max_time < @obs_freshness_cutoff(@execution_ts, @end_ts, @warn_after_hours)
|