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,545 @@
|
|
|
1
|
+
"""Passive volume, freshness, and schema monitors, and per-column metrics.
|
|
2
|
+
|
|
3
|
+
Runs on the writer thread, after an invocation's base rows are committed: it never runs inside an
|
|
4
|
+
observer callback. Metric anomalies are scored at read time (:func:`score_series`), with the same
|
|
5
|
+
rule as the ``volume_anomaly`` audit, so changing thresholds needs no backfill.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import datetime
|
|
11
|
+
import logging
|
|
12
|
+
import math
|
|
13
|
+
import typing as t
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
|
|
16
|
+
from sqlglot import exp
|
|
17
|
+
|
|
18
|
+
if t.TYPE_CHECKING:
|
|
19
|
+
from sqlmesh.core.engine_adapter import EngineAdapter
|
|
20
|
+
|
|
21
|
+
from sqlmesh_observability.collector import Invocation, ModelRun, SchemaCapture
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
ROW_COUNT = "row_count"
|
|
26
|
+
FRESHNESS_LAG = "freshness_lag_seconds"
|
|
27
|
+
NULL_RATE = "null_rate"
|
|
28
|
+
MEAN = "mean"
|
|
29
|
+
COLUMN_METRICS = (NULL_RATE, MEAN)
|
|
30
|
+
|
|
31
|
+
# Kinds whose "table" is a view or does not exist: counting a view re-runs its query.
|
|
32
|
+
_NO_VOLUME_KINDS = frozenset({"VIEW", "EMBEDDED", "EXTERNAL"})
|
|
33
|
+
_SCORE_KEYS = (
|
|
34
|
+
"training_days",
|
|
35
|
+
"min_buckets",
|
|
36
|
+
"threshold",
|
|
37
|
+
"spike_failure_percent_threshold",
|
|
38
|
+
"drop_failure_percent_threshold",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# --- Settings -------------------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class ScoreSettings:
|
|
47
|
+
"""The ``volume_anomaly`` audit's rule, applied to a metric series at read time."""
|
|
48
|
+
|
|
49
|
+
training_days: int = 14
|
|
50
|
+
min_buckets: int = 7
|
|
51
|
+
threshold: float = 3.0
|
|
52
|
+
spike_failure_percent_threshold: t.Optional[float] = None
|
|
53
|
+
drop_failure_percent_threshold: t.Optional[float] = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class FreshnessSettings:
|
|
58
|
+
column: t.Optional[str] = None
|
|
59
|
+
# (model name as written in config, column) overrides, e.g. (("analytics.orders", "order_ts"),)
|
|
60
|
+
columns: t.Tuple[t.Tuple[str, str], ...] = ()
|
|
61
|
+
score: ScoreSettings = field(default_factory=ScoreSettings)
|
|
62
|
+
|
|
63
|
+
def column_for(self, model_name: str) -> t.Optional[str]:
|
|
64
|
+
model_parts = _name_parts(model_name)
|
|
65
|
+
for name, column in self.columns:
|
|
66
|
+
key = _name_parts(name)
|
|
67
|
+
if key and model_parts[-len(key) :] == key:
|
|
68
|
+
return column
|
|
69
|
+
return self.column
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class MonitorSettings:
|
|
74
|
+
volume: t.Optional[ScoreSettings] = None
|
|
75
|
+
freshness: t.Optional[FreshnessSettings] = None
|
|
76
|
+
schema: bool = False
|
|
77
|
+
# (model key as written in config, ((metric, column), ...)).
|
|
78
|
+
columns: t.Tuple[t.Tuple[str, t.Tuple[t.Tuple[str, str], ...]], ...] = ()
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def collects_metrics(self) -> bool:
|
|
82
|
+
return self.volume is not None or self.freshness is not None or bool(self.columns)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def enabled(self) -> bool:
|
|
86
|
+
return self.collects_metrics or self.schema
|
|
87
|
+
|
|
88
|
+
def columns_for(self, model_name: str) -> t.Tuple[t.Tuple[str, str], ...]:
|
|
89
|
+
"""(metric, column) pairs configured for ``model_name``, from every matching key."""
|
|
90
|
+
model_parts = _name_parts(model_name)
|
|
91
|
+
found: t.List[t.Tuple[str, str]] = []
|
|
92
|
+
for key, pairs in self.columns:
|
|
93
|
+
parts = _name_parts(key)
|
|
94
|
+
if parts and model_parts[-len(parts) :] == parts:
|
|
95
|
+
found.extend(pair for pair in pairs if pair not in found)
|
|
96
|
+
return tuple(found)
|
|
97
|
+
|
|
98
|
+
def score_for(self, metric_name: str) -> ScoreSettings:
|
|
99
|
+
if metric_name == ROW_COUNT and self.volume is not None:
|
|
100
|
+
return self.volume
|
|
101
|
+
if metric_name == FRESHNESS_LAG and self.freshness is not None:
|
|
102
|
+
return self.freshness.score
|
|
103
|
+
return ScoreSettings()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _name_parts(name: str) -> t.Tuple[str, ...]:
|
|
107
|
+
try:
|
|
108
|
+
return tuple(part.name.lower() for part in exp.to_table(name).parts)
|
|
109
|
+
except Exception:
|
|
110
|
+
return tuple(part.strip('"`').lower() for part in name.split("."))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _score_settings(options: t.Mapping[str, t.Any], monitor: str) -> ScoreSettings:
|
|
114
|
+
values: t.Dict[str, t.Any] = {}
|
|
115
|
+
for key in _SCORE_KEYS:
|
|
116
|
+
if options.get(key) is not None:
|
|
117
|
+
values[key] = options[key]
|
|
118
|
+
try:
|
|
119
|
+
return ScoreSettings(**values)
|
|
120
|
+
except TypeError:
|
|
121
|
+
logger.warning("sqlmesh-observability: bad scoring settings for %s monitor", monitor)
|
|
122
|
+
return ScoreSettings()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def normalize_monitors(monitors: t.Optional[t.Mapping[str, t.Any]]) -> MonitorSettings:
|
|
126
|
+
"""Turn ``install(monitors=...)`` into settings. Unknown or malformed parts are ignored."""
|
|
127
|
+
if not monitors:
|
|
128
|
+
return MonitorSettings()
|
|
129
|
+
if not isinstance(monitors, t.Mapping):
|
|
130
|
+
logger.warning("sqlmesh-observability: `monitors` must be a dict; passive monitors off")
|
|
131
|
+
return MonitorSettings()
|
|
132
|
+
unknown = set(monitors) - {"volume", "freshness", "schema", "columns"}
|
|
133
|
+
if unknown:
|
|
134
|
+
logger.warning("sqlmesh-observability: unknown monitors ignored: %s", sorted(unknown))
|
|
135
|
+
|
|
136
|
+
volume: t.Optional[ScoreSettings] = None
|
|
137
|
+
raw_volume = monitors.get("volume")
|
|
138
|
+
if raw_volume is True:
|
|
139
|
+
volume = ScoreSettings()
|
|
140
|
+
elif isinstance(raw_volume, t.Mapping):
|
|
141
|
+
volume = _score_settings(raw_volume, "volume")
|
|
142
|
+
|
|
143
|
+
freshness: t.Optional[FreshnessSettings] = None
|
|
144
|
+
raw_freshness = monitors.get("freshness")
|
|
145
|
+
if isinstance(raw_freshness, t.Mapping):
|
|
146
|
+
overrides = raw_freshness.get("columns") or {}
|
|
147
|
+
column = raw_freshness.get("column")
|
|
148
|
+
if column or overrides:
|
|
149
|
+
freshness = FreshnessSettings(
|
|
150
|
+
column=str(column) if column else None,
|
|
151
|
+
columns=tuple((str(k), str(v)) for k, v in dict(overrides).items()),
|
|
152
|
+
score=_score_settings(raw_freshness, "freshness"),
|
|
153
|
+
)
|
|
154
|
+
elif raw_freshness:
|
|
155
|
+
logger.warning(
|
|
156
|
+
"sqlmesh-observability: `freshness` needs {'column': ...}; freshness monitor off"
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return MonitorSettings(
|
|
160
|
+
volume=volume,
|
|
161
|
+
freshness=freshness,
|
|
162
|
+
schema=bool(monitors.get("schema")),
|
|
163
|
+
columns=_column_settings(monitors.get("columns")),
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _column_settings(
|
|
168
|
+
raw: t.Any,
|
|
169
|
+
) -> t.Tuple[t.Tuple[str, t.Tuple[t.Tuple[str, str], ...]], ...]:
|
|
170
|
+
"""``{"orders": {"null_rate": ["status"], "mean": ["amount"]}}`` -> tuples, in config order."""
|
|
171
|
+
if not raw:
|
|
172
|
+
return ()
|
|
173
|
+
if not isinstance(raw, t.Mapping):
|
|
174
|
+
logger.warning("sqlmesh-observability: `columns` must be a dict; column monitors off")
|
|
175
|
+
return ()
|
|
176
|
+
settings: t.List[t.Tuple[str, t.Tuple[t.Tuple[str, str], ...]]] = []
|
|
177
|
+
for model_key, metrics in raw.items():
|
|
178
|
+
if not isinstance(metrics, t.Mapping):
|
|
179
|
+
logger.warning("sqlmesh-observability: columns[%r] must be a dict; ignored", model_key)
|
|
180
|
+
continue
|
|
181
|
+
pairs: t.List[t.Tuple[str, str]] = []
|
|
182
|
+
for metric, columns in metrics.items():
|
|
183
|
+
if metric not in COLUMN_METRICS:
|
|
184
|
+
logger.warning(
|
|
185
|
+
"sqlmesh-observability: unknown column metric %r ignored (use %s)",
|
|
186
|
+
metric,
|
|
187
|
+
", ".join(COLUMN_METRICS),
|
|
188
|
+
)
|
|
189
|
+
continue
|
|
190
|
+
names = [columns] if isinstance(columns, str) else list(columns or ())
|
|
191
|
+
pairs.extend((str(metric), str(column)) for column in names)
|
|
192
|
+
if pairs:
|
|
193
|
+
settings.append((str(model_key), tuple(pairs)))
|
|
194
|
+
return tuple(settings)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# --- Metric collection (writer thread) ------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _ms_to_datetime(value: t.Optional[int]) -> t.Optional[datetime.datetime]:
|
|
201
|
+
if value is None:
|
|
202
|
+
return None
|
|
203
|
+
return datetime.datetime.fromtimestamp(value / 1000, tz=datetime.timezone.utc)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _first(row: t.Optional[t.Tuple[t.Any, ...]]) -> t.Any:
|
|
207
|
+
"""The first value of a fetched row, or None when the query returned no row."""
|
|
208
|
+
return row[0] if row else None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _naive_utc(value: t.Any) -> t.Optional[datetime.datetime]:
|
|
212
|
+
"""A warehouse timestamp as naive UTC (SQLMesh treats naive timestamps as UTC)."""
|
|
213
|
+
if value is None:
|
|
214
|
+
return None
|
|
215
|
+
if isinstance(value, datetime.datetime):
|
|
216
|
+
if value.tzinfo is not None:
|
|
217
|
+
value = value.astimezone(datetime.timezone.utc).replace(tzinfo=None)
|
|
218
|
+
return value
|
|
219
|
+
if isinstance(value, datetime.date):
|
|
220
|
+
return datetime.datetime(value.year, value.month, value.day)
|
|
221
|
+
from sqlmesh.utils.date import to_datetime
|
|
222
|
+
|
|
223
|
+
return to_datetime(value).astimezone(datetime.timezone.utc).replace(tzinfo=None)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _find_column(columns: t.Sequence[t.Tuple[str, str]], wanted: str) -> t.Optional[str]:
|
|
227
|
+
for name, _ in columns:
|
|
228
|
+
if name.lower() == wanted.lower():
|
|
229
|
+
return name
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _interval_filter(run: "ModelRun", adapter: "EngineAdapter") -> t.Optional[exp.Expression]:
|
|
234
|
+
"""SQLMesh's own interval predicate (``Model.render_query``), rebuilt from plain values.
|
|
235
|
+
|
|
236
|
+
The time column's type comes from the physical table, as SQLMesh's audit rendering does.
|
|
237
|
+
"""
|
|
238
|
+
from sqlmesh.utils.date import make_inclusive, to_time_column
|
|
239
|
+
|
|
240
|
+
assert run.time_column is not None and run.physical_table is not None
|
|
241
|
+
if run.interval_start is None or run.interval_end is None:
|
|
242
|
+
return None
|
|
243
|
+
types = adapter.columns(run.physical_table)
|
|
244
|
+
time_type = next((v for k, v in types.items() if k.lower() == run.time_column.lower()), None)
|
|
245
|
+
if time_type is None:
|
|
246
|
+
return None
|
|
247
|
+
dialect = run.model_dialect or "" # SQLMesh's default dialect
|
|
248
|
+
low, high = [
|
|
249
|
+
to_time_column(value, time_type, dialect, run.time_column_format)
|
|
250
|
+
for value in make_inclusive(run.interval_start, run.interval_end, run.model_dialect)
|
|
251
|
+
]
|
|
252
|
+
return exp.column(run.time_column).between(low, high)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _candidates(invocation: "Invocation") -> t.List["ModelRun"]:
|
|
256
|
+
"""Successful, non-audit-only runs, keeping the last batch per (model, version, interval)."""
|
|
257
|
+
latest: t.Dict[t.Tuple[str, str, t.Optional[int]], "ModelRun"] = {}
|
|
258
|
+
for run in invocation.models:
|
|
259
|
+
if run.status != "success" or run.audit_only or not run.physical_table:
|
|
260
|
+
continue
|
|
261
|
+
latest[(run.model_name, run.version, run.interval_start)] = run
|
|
262
|
+
return list(latest.values())
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def collect_metrics(
|
|
266
|
+
invocation: "Invocation",
|
|
267
|
+
data_adapter: "EngineAdapter",
|
|
268
|
+
log_adapter: "EngineAdapter",
|
|
269
|
+
settings: MonitorSettings,
|
|
270
|
+
) -> t.List[t.Dict[str, t.Any]]:
|
|
271
|
+
"""Run the read-only metric queries for ``invocation`` and return ``metrics`` rows.
|
|
272
|
+
|
|
273
|
+
``log_adapter`` is unused here; it is passed so callers (and tests) see one signature.
|
|
274
|
+
"""
|
|
275
|
+
now = datetime.datetime.now(datetime.timezone.utc)
|
|
276
|
+
rows: t.List[t.Dict[str, t.Any]] = []
|
|
277
|
+
for run in _candidates(invocation):
|
|
278
|
+
if (run.kind or "") in _NO_VOLUME_KINDS:
|
|
279
|
+
continue
|
|
280
|
+
measure = _Measure(run, data_adapter, now)
|
|
281
|
+
if settings.volume is not None:
|
|
282
|
+
rows.extend(measure.volume())
|
|
283
|
+
if settings.freshness is not None:
|
|
284
|
+
rows.extend(measure.freshness(settings.freshness))
|
|
285
|
+
pairs = settings.columns_for(run.model_name)
|
|
286
|
+
if pairs:
|
|
287
|
+
rows.extend(measure.columns(pairs))
|
|
288
|
+
return rows
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class _Measure:
|
|
292
|
+
"""Metric queries for one model interval run."""
|
|
293
|
+
|
|
294
|
+
def __init__(self, run: "ModelRun", adapter: "EngineAdapter", now: datetime.datetime) -> None:
|
|
295
|
+
self.run = run
|
|
296
|
+
self.adapter = adapter
|
|
297
|
+
self.table = exp.to_table(str(run.physical_table), dialect=adapter.dialect)
|
|
298
|
+
self.base = {
|
|
299
|
+
"invocation_id": run.invocation_id,
|
|
300
|
+
"model_name": run.model_name,
|
|
301
|
+
"version": run.version,
|
|
302
|
+
"physical_table": run.physical_table,
|
|
303
|
+
"interval_start": _ms_to_datetime(run.interval_start),
|
|
304
|
+
"interval_end": _ms_to_datetime(run.interval_end),
|
|
305
|
+
"column_name": "",
|
|
306
|
+
"updated_at": now,
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
def _row(self, metric: str, column: str = "", **values: t.Any) -> t.Dict[str, t.Any]:
|
|
310
|
+
return {**self.base, "metric_name": metric, "column_name": column, **values}
|
|
311
|
+
|
|
312
|
+
def _interval_query(self, *projections: exp.Expr) -> exp.Select:
|
|
313
|
+
"""``SELECT ... FROM table`` over the evaluated interval, or the whole table."""
|
|
314
|
+
query = exp.select(*projections).from_(self.table)
|
|
315
|
+
if self.run.time_column:
|
|
316
|
+
where = _interval_filter(self.run, self.adapter)
|
|
317
|
+
if where is None:
|
|
318
|
+
raise ValueError("no interval filter for a time-partitioned model")
|
|
319
|
+
query = query.where(where)
|
|
320
|
+
return query
|
|
321
|
+
|
|
322
|
+
def volume(self) -> t.List[t.Dict[str, t.Any]]:
|
|
323
|
+
try:
|
|
324
|
+
count = _first(
|
|
325
|
+
self.adapter.fetchone(self._interval_query(exp.func("COUNT", exp.Star())))
|
|
326
|
+
)
|
|
327
|
+
return [self._row(ROW_COUNT, metric_value=float(count or 0))]
|
|
328
|
+
except Exception as error:
|
|
329
|
+
logger.debug("sqlmesh-observability: row count failed", exc_info=True)
|
|
330
|
+
return [self._row(ROW_COUNT, error_message=str(error))]
|
|
331
|
+
|
|
332
|
+
def freshness(self, settings: FreshnessSettings) -> t.List[t.Dict[str, t.Any]]:
|
|
333
|
+
wanted = settings.column_for(self.run.model_name)
|
|
334
|
+
column = _find_column(self.run.columns, wanted) if wanted else None
|
|
335
|
+
if column is None:
|
|
336
|
+
return [] # the model has no such column: skip without error
|
|
337
|
+
try:
|
|
338
|
+
query = exp.select(exp.func("MAX", exp.column(column))).from_(self.table)
|
|
339
|
+
latest = _naive_utc(_first(self.adapter.fetchone(query)))
|
|
340
|
+
executed = _naive_utc(_ms_to_datetime(self.run.execution_time))
|
|
341
|
+
value = (
|
|
342
|
+
None if latest is None or executed is None else (executed - latest).total_seconds()
|
|
343
|
+
)
|
|
344
|
+
return [self._row(FRESHNESS_LAG, metric_value=value)]
|
|
345
|
+
except Exception as error:
|
|
346
|
+
logger.debug("sqlmesh-observability: freshness query failed", exc_info=True)
|
|
347
|
+
return [self._row(FRESHNESS_LAG, error_message=str(error))]
|
|
348
|
+
|
|
349
|
+
def _available_columns(self) -> t.Sequence[t.Tuple[str, str]]:
|
|
350
|
+
if self.run.columns:
|
|
351
|
+
return self.run.columns
|
|
352
|
+
return [(str(name), "") for name in self.adapter.columns(str(self.run.physical_table))]
|
|
353
|
+
|
|
354
|
+
def columns(self, pairs: t.Sequence[t.Tuple[str, str]]) -> t.List[t.Dict[str, t.Any]]:
|
|
355
|
+
"""``null_rate`` / ``mean`` for configured columns, in one query."""
|
|
356
|
+
rows: t.List[t.Dict[str, t.Any]] = []
|
|
357
|
+
try:
|
|
358
|
+
available = self._available_columns()
|
|
359
|
+
except Exception as error:
|
|
360
|
+
return [self._row(m, c, error_message=str(error)) for m, c in pairs]
|
|
361
|
+
|
|
362
|
+
measured: t.List[t.Tuple[str, str, str]] = [] # (metric, configured name, real name)
|
|
363
|
+
for metric, wanted in pairs:
|
|
364
|
+
real = _find_column(available, wanted)
|
|
365
|
+
if real is None:
|
|
366
|
+
rows.append(self._row(metric, wanted, error_message=f"column {wanted!r} not found"))
|
|
367
|
+
else:
|
|
368
|
+
measured.append((metric, wanted, real))
|
|
369
|
+
if not measured:
|
|
370
|
+
return rows
|
|
371
|
+
|
|
372
|
+
double = exp.DataType.build("DOUBLE")
|
|
373
|
+
projections: t.List[exp.Expr] = [exp.func("COUNT", exp.Star())]
|
|
374
|
+
for metric, _, real in measured:
|
|
375
|
+
if metric == NULL_RATE:
|
|
376
|
+
projections.append(exp.func("COUNT", exp.column(real)))
|
|
377
|
+
else:
|
|
378
|
+
projections.append(exp.func("AVG", exp.cast(exp.column(real), double)))
|
|
379
|
+
try:
|
|
380
|
+
result = self.adapter.fetchone(self._interval_query(*projections))
|
|
381
|
+
except Exception as error:
|
|
382
|
+
logger.debug("sqlmesh-observability: column metrics failed", exc_info=True)
|
|
383
|
+
return rows + [self._row(m, c, error_message=str(error)) for m, c, _ in measured]
|
|
384
|
+
if result is None:
|
|
385
|
+
return rows + [self._row(m, c, error_message="no result") for m, c, _ in measured]
|
|
386
|
+
|
|
387
|
+
total = int(result[0] or 0)
|
|
388
|
+
for (metric, wanted, _), value in zip(measured, result[1:]):
|
|
389
|
+
if metric == NULL_RATE:
|
|
390
|
+
metric_value = None if total == 0 else (total - int(value or 0)) / total
|
|
391
|
+
else:
|
|
392
|
+
metric_value = None if value is None else float(value)
|
|
393
|
+
rows.append(self._row(metric, wanted, metric_value=metric_value))
|
|
394
|
+
return rows
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# --- Schema diffing (writer thread) ------------------------------------------------------------
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
@dataclass
|
|
401
|
+
class RecordedSchema:
|
|
402
|
+
snapshot_id: str
|
|
403
|
+
version: str
|
|
404
|
+
recorded_at: datetime.datetime
|
|
405
|
+
columns: t.Tuple[t.Tuple[str, str], ...]
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _prior(
|
|
409
|
+
capture: "SchemaCapture", recorded: t.Mapping[str, RecordedSchema]
|
|
410
|
+
) -> t.Optional[RecordedSchema]:
|
|
411
|
+
"""The capture this one descends from: its newest recorded ancestor."""
|
|
412
|
+
for snapshot_id in reversed(capture.previous_snapshot_ids):
|
|
413
|
+
if snapshot_id != capture.snapshot_id and snapshot_id in recorded:
|
|
414
|
+
return recorded[snapshot_id]
|
|
415
|
+
if capture.previous_snapshot_ids:
|
|
416
|
+
return None # an ancestry exists but none of it was recorded: nothing to compare with
|
|
417
|
+
others = [r for r in recorded.values() if r.snapshot_id != capture.snapshot_id]
|
|
418
|
+
return max(others, key=lambda r: r.recorded_at) if others else None
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def schema_rows(
|
|
422
|
+
invocation: "Invocation", recorded: t.Dict[str, t.Dict[str, RecordedSchema]]
|
|
423
|
+
) -> t.Tuple[t.List[t.Dict[str, t.Any]], t.List[t.Dict[str, t.Any]]]:
|
|
424
|
+
"""``schema_columns`` and ``schema_changes`` rows for the invocation's captures.
|
|
425
|
+
|
|
426
|
+
``recorded`` maps model name to the captures already in ``schema_columns`` by snapshot id; it
|
|
427
|
+
is updated in place, so two captures of one model in one invocation chain correctly.
|
|
428
|
+
"""
|
|
429
|
+
column_rows: t.List[t.Dict[str, t.Any]] = []
|
|
430
|
+
change_rows: t.List[t.Dict[str, t.Any]] = []
|
|
431
|
+
for capture in invocation.schemas:
|
|
432
|
+
by_snapshot = recorded.setdefault(capture.model_name, {})
|
|
433
|
+
prior = _prior(capture, by_snapshot)
|
|
434
|
+
for ordinal, (name, kind) in enumerate(capture.columns):
|
|
435
|
+
column_rows.append(
|
|
436
|
+
{
|
|
437
|
+
"invocation_id": capture.invocation_id,
|
|
438
|
+
"model_name": capture.model_name,
|
|
439
|
+
"snapshot_id": capture.snapshot_id,
|
|
440
|
+
"version": capture.version,
|
|
441
|
+
"ordinal": ordinal,
|
|
442
|
+
"column_name": name,
|
|
443
|
+
"data_type": kind,
|
|
444
|
+
"recorded_at": capture.recorded_at,
|
|
445
|
+
}
|
|
446
|
+
)
|
|
447
|
+
if prior is not None:
|
|
448
|
+
for name, change, old_type, new_type in diff_columns(prior.columns, capture.columns):
|
|
449
|
+
change_rows.append(
|
|
450
|
+
{
|
|
451
|
+
"invocation_id": capture.invocation_id,
|
|
452
|
+
"model_name": capture.model_name,
|
|
453
|
+
"from_snapshot_id": prior.snapshot_id,
|
|
454
|
+
"to_snapshot_id": capture.snapshot_id,
|
|
455
|
+
"from_version": prior.version,
|
|
456
|
+
"to_version": capture.version,
|
|
457
|
+
"column_name": name,
|
|
458
|
+
"change_type": change,
|
|
459
|
+
"old_type": old_type,
|
|
460
|
+
"new_type": new_type,
|
|
461
|
+
"recorded_at": capture.recorded_at,
|
|
462
|
+
}
|
|
463
|
+
)
|
|
464
|
+
by_snapshot[capture.snapshot_id] = RecordedSchema(
|
|
465
|
+
snapshot_id=capture.snapshot_id,
|
|
466
|
+
version=capture.version,
|
|
467
|
+
recorded_at=capture.recorded_at,
|
|
468
|
+
columns=capture.columns,
|
|
469
|
+
)
|
|
470
|
+
return column_rows, change_rows
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def diff_columns(
|
|
474
|
+
old: t.Sequence[t.Tuple[str, str]], new: t.Sequence[t.Tuple[str, str]]
|
|
475
|
+
) -> t.List[t.Tuple[str, str, t.Optional[str], t.Optional[str]]]:
|
|
476
|
+
"""(column, change_type, old_type, new_type) for added, removed, and retyped columns."""
|
|
477
|
+
old_map, new_map = dict(old), dict(new)
|
|
478
|
+
changes: t.List[t.Tuple[str, str, t.Optional[str], t.Optional[str]]] = []
|
|
479
|
+
for name, kind in new:
|
|
480
|
+
if name not in old_map:
|
|
481
|
+
changes.append((name, "added", None, kind))
|
|
482
|
+
elif old_map[name] != kind:
|
|
483
|
+
changes.append((name, "retyped", old_map[name], kind))
|
|
484
|
+
for name, kind in old:
|
|
485
|
+
if name not in new_map:
|
|
486
|
+
changes.append((name, "removed", kind, None))
|
|
487
|
+
return changes
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
# --- Read-time scoring ----------------------------------------------------------------------------
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
@dataclass(frozen=True)
|
|
494
|
+
class ScoredPoint:
|
|
495
|
+
interval_start: datetime.datetime
|
|
496
|
+
value: t.Optional[float]
|
|
497
|
+
mean: t.Optional[float]
|
|
498
|
+
stddev: t.Optional[float]
|
|
499
|
+
training_points: int
|
|
500
|
+
anomaly: bool
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _flagged(value: float, mean: float, stddev: float, settings: ScoreSettings) -> bool:
|
|
504
|
+
if abs(value - mean) <= settings.threshold * stddev:
|
|
505
|
+
return False
|
|
506
|
+
if value >= mean:
|
|
507
|
+
spike = settings.spike_failure_percent_threshold
|
|
508
|
+
return spike is None or value > (1 + spike / 100.0) * mean
|
|
509
|
+
drop = settings.drop_failure_percent_threshold
|
|
510
|
+
return drop is None or value < (1 - drop / 100.0) * mean
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def score_series(
|
|
514
|
+
points: t.Sequence[t.Tuple[datetime.datetime, t.Optional[float]]],
|
|
515
|
+
settings: ScoreSettings,
|
|
516
|
+
) -> t.List[ScoredPoint]:
|
|
517
|
+
"""Score each point against the earlier points within ``training_days`` before it.
|
|
518
|
+
|
|
519
|
+
``points`` must be sorted by time with one value per interval. Same rule as ``volume_anomaly``:
|
|
520
|
+
sample standard deviation, ``|value - mean| > threshold * stddev``, and the optional
|
|
521
|
+
ignore-small-changes percent thresholds, each only in its own direction.
|
|
522
|
+
"""
|
|
523
|
+
scored: t.List[ScoredPoint] = []
|
|
524
|
+
window = datetime.timedelta(days=settings.training_days)
|
|
525
|
+
for index, (when, value) in enumerate(points):
|
|
526
|
+
training = [v for ts, v in points[:index] if v is not None and when - window <= ts < when]
|
|
527
|
+
n = len(training)
|
|
528
|
+
mean = stddev = None
|
|
529
|
+
anomaly = False
|
|
530
|
+
if n >= max(settings.min_buckets, 2):
|
|
531
|
+
mean = sum(training) / n
|
|
532
|
+
stddev = math.sqrt(sum((x - mean) ** 2 for x in training) / (n - 1))
|
|
533
|
+
if value is not None:
|
|
534
|
+
anomaly = _flagged(value, mean, stddev, settings)
|
|
535
|
+
scored.append(
|
|
536
|
+
ScoredPoint(
|
|
537
|
+
interval_start=when,
|
|
538
|
+
value=value,
|
|
539
|
+
mean=mean,
|
|
540
|
+
stddev=stddev,
|
|
541
|
+
training_points=n,
|
|
542
|
+
anomaly=anomaly,
|
|
543
|
+
)
|
|
544
|
+
)
|
|
545
|
+
return scored
|