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.
@@ -0,0 +1,506 @@
1
+ """The report's data: one compact, versioned JSON payload that the page draws in the browser.
2
+
3
+ Status, scope, and anomaly flags are decided here in Python. The browser only displays, filters,
4
+ and sorts. Repeated values go into tables and per-interval rows are short arrays, so a project
5
+ with 1,500 models stays a few megabytes.
6
+
7
+ Schema version 1::
8
+
9
+ schema_version, environment, schema, gateway, generated_at, state_available,
10
+ state_gateway, history, monitors
11
+ dates ["2024-03-31", ...] every interval start referenced below, sorted
12
+ owners ["team-00", ...] owner names; models refer to them by index
13
+ audits [[name, args_text], ...] audit uses (name plus arguments)
14
+ metrics ["row_count", ...] metric names
15
+ models [{n: full name, o: owner index or -1, st: "pass" | "warn" | "fail",
16
+ c: [[column, type], ...],
17
+ h: [dates, health codes] oldest first
18
+ r: [dates, durations_ms] oldest first
19
+ a: [[date, use, status, violations, blocking, incident], ...] newest first
20
+ m: [[metric, column, threshold, dates, values, means, sds, flags], ...]
21
+ x: [[column, change, old_type, new_type, recorded_at, to_version], ...]}]
22
+
23
+ ``dates`` inside ``h``, ``r`` and ``m`` are delta-coded: the first entry is an index into
24
+ the top-level ``dates`` and each later one is the step from the previous index. A run of
25
+ consecutive dates is shortened to ``[-count, first]``. Means and
26
+ standard deviations keep four significant digits, values six.
27
+ incidents [{model, use, interval, invocation, snapshot, version, environment, status,
28
+ blocking, violations, sql, error, started_at, samples: [{...}]}]
29
+ issues [{kind, model, signal, interval, value, lo, hi, incident, metric, column}]
30
+ trend [[date, executions, failures, warnings_and_anomalies], ...]
31
+ summary {models: {pass, warn, fail}, audits: {pass, warn, fail, error},
32
+ monitored: {monitored, unmonitored}}
33
+ signals {audits, volume, freshness, schema, columns: {pass, warn, fail} | null}
34
+ runs [{id, command, environment, status, started_at, finished_at, duration_ms,
35
+ model_runs, failed_runs, audits, failing_audits, blocking_failures}]
36
+
37
+ Codes: ``health`` 0 pass, 1 warn, 2 fail, 3 error, 4 skip. Audit ``status`` 0 pass, 1 fail,
38
+ 2 error, 3 skip. Point ``flags`` bit 1 anomaly, bit 2 error, bit 4 still training. Indexes are
39
+ -1 when absent.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import json
45
+ import typing as t
46
+
47
+ from sqlmesh_observability.reader import audit_key
48
+ from sqlmesh_observability.textfmt import args_text
49
+
50
+ if t.TYPE_CHECKING:
51
+ from sqlmesh_observability.reader import (
52
+ AuditRecord,
53
+ MetricSeries,
54
+ ModelReport,
55
+ ReportData,
56
+ )
57
+
58
+ SCHEMA_VERSION = 1
59
+ DEFAULT_HISTORY = 30
60
+
61
+ _HEALTH = {"pass": 0, "warn": 1, "fail": 2, "error": 3, "skip": 4}
62
+ _AUDIT_STATUS = {"pass": 0, "fail": 1, "error": 2, "skip": 3}
63
+ _VOLUME = "row_count"
64
+ _FRESHNESS = "freshness_lag_seconds"
65
+
66
+
67
+ def _num(value: t.Optional[float], digits: int = 6) -> t.Optional[float]:
68
+ """``digits`` significant digits; integers stay integers."""
69
+ if value is None:
70
+ return None
71
+ rounded = float(f"{value:.{digits}g}")
72
+ return int(rounded) if rounded.is_integer() and abs(rounded) < 1e15 else rounded
73
+
74
+
75
+ def _day(value: str) -> str:
76
+ return value[:10] if value.endswith(" 00:00:00") else value
77
+
78
+
79
+ def model_status(model: "ModelReport") -> str:
80
+ """``fail`` (blocking failure or error), ``warn`` (non-blocking failure or a latest-point
81
+ anomaly), or ``pass``."""
82
+ if model.failing_blocking_audits:
83
+ return "fail"
84
+ if model.warning_audits or any(s.points and s.points[-1].anomaly for s in model.metrics):
85
+ return "warn"
86
+ return "pass"
87
+
88
+
89
+ def _latest_per_interval(audits: t.Sequence["AuditRecord"]) -> t.List["AuditRecord"]:
90
+ """The latest run of each (audit use, interval), newest interval first."""
91
+ latest: t.Dict[t.Tuple[t.Any, ...], "AuditRecord"] = {}
92
+ for audit in audits:
93
+ key = audit_key(audit)
94
+ seen = latest.get(key)
95
+ if seen is None or (audit.started_at or "", audit.invocation_id) > (
96
+ seen.started_at or "",
97
+ seen.invocation_id,
98
+ ):
99
+ latest[key] = audit
100
+ return sorted(
101
+ latest.values(),
102
+ key=lambda a: (a.interval_start or "", a.audit_name, a.args_json or ""),
103
+ reverse=True,
104
+ )
105
+
106
+
107
+ def _incident_key(audit: "AuditRecord") -> t.Tuple[t.Any, ...]:
108
+ return (audit.invocation_id, *audit_key(audit))
109
+
110
+
111
+ def _samples(raw: t.Sequence[str]) -> t.List[t.Any]:
112
+ rows = []
113
+ for row in raw:
114
+ try:
115
+ rows.append(json.loads(row))
116
+ except ValueError:
117
+ rows.append(row)
118
+ return rows
119
+
120
+
121
+ class _Tables:
122
+ """Interning tables for repeated strings."""
123
+
124
+ def __init__(self) -> None:
125
+ self.dates: t.Dict[str, int] = {}
126
+ self.owners: t.Dict[str, int] = {}
127
+ self.uses: t.Dict[t.Tuple[str, str], int] = {}
128
+ self.metrics: t.Dict[str, int] = {}
129
+
130
+ @staticmethod
131
+ def _index(table: t.Dict[t.Any, int], value: t.Any) -> int:
132
+ if value not in table:
133
+ table[value] = len(table)
134
+ return table[value]
135
+
136
+ def date(self, value: str) -> int:
137
+ return self._index(self.dates, _day(value))
138
+
139
+ def owner(self, value: t.Optional[str]) -> int:
140
+ return -1 if value is None else self._index(self.owners, value)
141
+
142
+ def use(self, audit: "AuditRecord") -> int:
143
+ return self._index(self.uses, (audit.audit_name, args_text(audit.args_json)))
144
+
145
+ def metric(self, value: str) -> int:
146
+ return self._index(self.metrics, value)
147
+
148
+
149
+ def _split(statuses: t.Iterable[str]) -> t.Dict[str, int]:
150
+ counts = {"pass": 0, "warn": 0, "fail": 0}
151
+ for status in statuses:
152
+ counts[status] += 1
153
+ return counts
154
+
155
+
156
+ def _series_status(series: "MetricSeries") -> str:
157
+ point = series.points[-1]
158
+ if point.error_message:
159
+ return "fail"
160
+ return "warn" if point.anomaly else "pass"
161
+
162
+
163
+ def _signals(
164
+ data: "ReportData", latest: t.Mapping[str, t.List["AuditRecord"]]
165
+ ) -> t.Dict[str, t.Any]:
166
+ def audit_status(audit: "AuditRecord") -> str:
167
+ if audit.status == "error" or (audit.status == "fail" and audit.blocking):
168
+ return "fail"
169
+ return "warn" if audit.status == "fail" else "pass"
170
+
171
+ newest: t.List["AuditRecord"] = []
172
+ for rows in latest.values():
173
+ seen: t.Set[t.Tuple[str, str]] = set()
174
+ for audit in rows: # newest interval first: the first row per use is its latest
175
+ use = (audit.audit_name, audit.args_json or "")
176
+ if use not in seen:
177
+ seen.add(use)
178
+ newest.append(audit)
179
+
180
+ def metric_signal(match: t.Callable[[str], bool], monitor: str) -> t.Optional[t.Dict[str, int]]:
181
+ series = [s for m in data.models for s in m.metrics if match(s.metric_name) and s.points]
182
+ if not series and monitor not in data.monitors:
183
+ return None
184
+ return _split(_series_status(s) for s in series)
185
+
186
+ schema: t.Optional[t.Dict[str, int]] = None
187
+ if "schema" in data.monitors or any(m.schema_changes for m in data.models):
188
+ statuses = []
189
+ for model in data.models:
190
+ kinds = {c.change_type for c in model.schema_changes}
191
+ statuses.append("pass" if not kinds else ("warn" if kinds <= {"added"} else "fail"))
192
+ schema = _split(statuses)
193
+
194
+ return {
195
+ "audits": _split(audit_status(a) for a in newest),
196
+ "volume": metric_signal(lambda name: name == _VOLUME, "volume"),
197
+ "freshness": metric_signal(lambda name: name == _FRESHNESS, "freshness"),
198
+ "schema": schema,
199
+ "columns": metric_signal(lambda name: name not in (_VOLUME, _FRESHNESS), "columns"),
200
+ }
201
+
202
+
203
+ def build_payload(data: "ReportData", history: int = DEFAULT_HISTORY) -> t.Dict[str, t.Any]:
204
+ """Everything the page shows, with each per-interval history cut to its last ``history``
205
+ intervals. Anomaly flags come from the reader, which scored the full history."""
206
+ tables = _Tables()
207
+ model_index = {m.model_name: i for i, m in enumerate(data.models)}
208
+
209
+ latest = {m.model_name: _latest_per_interval(m.audits) for m in data.models}
210
+ open_audits = [a for m in data.failing_models for a in m.failing_blocking_audits] + [
211
+ a for m in data.warning_models for a in m.warning_audits
212
+ ]
213
+ open_keys = {_incident_key(a) for a in open_audits}
214
+
215
+ # Retained audit rows: the latest run of each use for the last ``history`` intervals.
216
+ kept: t.Dict[str, t.List["AuditRecord"]] = {}
217
+ for name, rows in latest.items():
218
+ starts = sorted({a.interval_start or "" for a in rows}, reverse=True)[:history]
219
+ window = set(starts)
220
+ kept[name] = [a for a in rows if (a.interval_start or "") in window]
221
+
222
+ kept_keys = {_incident_key(a) for rows in kept.values() for a in rows}
223
+ incidents: t.List[t.Dict[str, t.Any]] = []
224
+ incident_index: t.Dict[t.Tuple[t.Any, ...], int] = {}
225
+ for audit in data.incidents:
226
+ key = _incident_key(audit)
227
+ if key in incident_index or (key not in kept_keys and key not in open_keys):
228
+ continue
229
+ incident_index[key] = len(incidents)
230
+ incidents.append(
231
+ {
232
+ "model": model_index.get(audit.model_name, -1),
233
+ "use": tables.use(audit),
234
+ "interval": _day(audit.interval_start) if audit.interval_start else None,
235
+ "invocation": audit.invocation_id,
236
+ "snapshot": audit.snapshot_id,
237
+ "version": audit.version,
238
+ "environment": audit.environment,
239
+ "status": audit.status,
240
+ "blocking": audit.blocking,
241
+ "violations": audit.violation_count,
242
+ "sql": audit.query_sql,
243
+ "error": audit.error_message,
244
+ "started_at": audit.started_at,
245
+ "samples": _samples(audit.samples),
246
+ }
247
+ )
248
+
249
+ models: t.List[t.Dict[str, t.Any]] = []
250
+ for model in data.models:
251
+ audit_rows: t.List[t.List[t.Any]] = []
252
+ for audit in kept[model.model_name]:
253
+ audit_rows.append(
254
+ [
255
+ tables.date(audit.interval_start or ""),
256
+ tables.use(audit),
257
+ _AUDIT_STATUS.get(audit.status, 3),
258
+ audit.violation_count,
259
+ 1 if audit.blocking else 0,
260
+ incident_index.get(_incident_key(audit), -1),
261
+ ]
262
+ )
263
+ run_by_interval: t.Dict[str, int] = {}
264
+ for run in model.runs: # oldest first: the latest run of an interval wins
265
+ if run.interval_start is not None and run.duration_ms is not None:
266
+ run_by_interval[run.interval_start] = run.duration_ms
267
+ series = []
268
+ for s in model.metrics:
269
+ points = s.points[-history:]
270
+ series.append(
271
+ [
272
+ tables.metric(s.metric_name),
273
+ s.column_name,
274
+ s.threshold,
275
+ [tables.date(p.interval_start) for p in points],
276
+ [_num(p.value) for p in points],
277
+ [_num(p.mean, 4) for p in points],
278
+ [_num(p.stddev, 4) for p in points],
279
+ [
280
+ (1 if p.anomaly else 0)
281
+ | (2 if p.error_message else 0)
282
+ | (4 if p.mean is None else 0)
283
+ for p in points
284
+ ],
285
+ ]
286
+ )
287
+ health = model.health[-history:]
288
+ durations = sorted(run_by_interval.items())[-history:]
289
+ models.append(
290
+ {
291
+ "n": model.model_name,
292
+ "o": tables.owner(model.owner),
293
+ "st": model_status(model),
294
+ "c": [list(c) for c in model.columns],
295
+ "h": [
296
+ [tables.date(h.interval_start) for h in health],
297
+ [_HEALTH.get(h.status, 4) for h in health],
298
+ ],
299
+ "r": [[tables.date(k) for k, _ in durations], [v for _, v in durations]],
300
+ "a": audit_rows,
301
+ "m": series,
302
+ "x": [
303
+ [
304
+ c.column_name,
305
+ c.change_type,
306
+ c.old_type,
307
+ c.new_type,
308
+ c.recorded_at,
309
+ c.to_version,
310
+ ]
311
+ for c in model.schema_changes
312
+ ],
313
+ }
314
+ )
315
+
316
+ issues: t.List[t.Dict[str, t.Any]] = []
317
+ for m in data.failing_models:
318
+ for audit in m.failing_blocking_audits:
319
+ issues.append(
320
+ _audit_issue(
321
+ audit,
322
+ "error" if audit.status == "error" else "blocking",
323
+ model_index,
324
+ incident_index,
325
+ tables,
326
+ )
327
+ )
328
+ for anomaly in data.anomalies:
329
+ point = anomaly.point
330
+ threshold = (
331
+ next(
332
+ (
333
+ s.threshold
334
+ for s in data.models[model_index[anomaly.model_name]].metrics
335
+ if s.metric_name == anomaly.metric_name and s.column_name == anomaly.column_name
336
+ ),
337
+ 3.0,
338
+ )
339
+ if anomaly.model_name in model_index
340
+ else 3.0
341
+ )
342
+ lo = hi = None
343
+ if point.mean is not None and point.stddev is not None:
344
+ lo, hi = point.mean - threshold * point.stddev, point.mean + threshold * point.stddev
345
+ issues.append(
346
+ {
347
+ "kind": "anomaly",
348
+ "model": model_index.get(anomaly.model_name, -1),
349
+ "signal": anomaly.metric_name,
350
+ "column": anomaly.column_name,
351
+ "interval": _day(point.interval_start),
352
+ "value": _num(point.value),
353
+ "lo": _num(lo),
354
+ "hi": _num(hi),
355
+ "incident": -1,
356
+ }
357
+ )
358
+ for m in data.warning_models:
359
+ for audit in m.warning_audits:
360
+ issues.append(_audit_issue(audit, "warning", model_index, incident_index, tables))
361
+
362
+ # Daily trend over the retained window: one row per interval day with audit results or an
363
+ # anomaly. Days with no data get no row, so the chart draws no false zeros.
364
+ trend: t.Dict[str, t.List[int]] = {}
365
+ for rows in kept.values():
366
+ for audit in rows:
367
+ day = _day(audit.interval_start or "")
368
+ counts = trend.setdefault(day, [0, 0, 0])
369
+ counts[0] += 1
370
+ if audit.status == "error" or (audit.status == "fail" and audit.blocking):
371
+ counts[1] += 1
372
+ elif audit.status == "fail":
373
+ counts[2] += 1
374
+ for model in data.models:
375
+ for s in model.metrics:
376
+ for p in s.points[-history:]:
377
+ if p.anomaly:
378
+ trend.setdefault(_day(p.interval_start), [0, 0, 0])[2] += 1
379
+
380
+ audit_summary = {"pass": 0, "warn": 0, "fail": 0, "error": 0}
381
+ for rows in latest.values():
382
+ seen: t.Set[t.Tuple[str, str]] = set()
383
+ for audit in rows:
384
+ use = (audit.audit_name, audit.args_json or "")
385
+ if use in seen:
386
+ continue
387
+ seen.add(use)
388
+ if audit.status == "error":
389
+ audit_summary["error"] += 1
390
+ elif audit.status == "fail":
391
+ audit_summary["fail" if audit.blocking else "warn"] += 1
392
+ elif audit.status == "pass":
393
+ audit_summary["pass"] += 1
394
+ monitored = sum(1 for m in data.models if m.metrics)
395
+
396
+ payload = {
397
+ "schema_version": SCHEMA_VERSION,
398
+ "environment": data.environment,
399
+ "schema": data.schema,
400
+ "gateway": data.gateway,
401
+ "generated_at": data.generated_at,
402
+ "state_available": data.state_available,
403
+ "state_gateway": data.state_gateway,
404
+ "history": history,
405
+ "monitors": list(data.monitors),
406
+ "models": models,
407
+ "incidents": incidents,
408
+ "issues": issues,
409
+ "trend": [[tables.date(day), *counts] for day, counts in sorted(trend.items())],
410
+ "summary": {
411
+ "models": _split(m["st"] for m in models),
412
+ "audits": audit_summary,
413
+ "monitored": {"monitored": monitored, "unmonitored": len(models) - monitored},
414
+ },
415
+ "signals": _signals(data, latest),
416
+ "runs": [
417
+ {
418
+ "id": inv.invocation_id,
419
+ "command": inv.command,
420
+ "environment": inv.environment,
421
+ "status": inv.status,
422
+ "started_at": inv.started_at,
423
+ "finished_at": inv.finished_at,
424
+ "duration_ms": inv.duration_ms,
425
+ "model_runs": inv.model_runs,
426
+ "failed_runs": inv.failed_runs,
427
+ "audits": inv.audits,
428
+ "failing_audits": inv.failing_audits,
429
+ "blocking_failures": inv.blocking_failures,
430
+ }
431
+ for inv in data.invocations
432
+ ],
433
+ }
434
+ # Tables last: everything above interned into them.
435
+ payload["dates"] = list(tables.dates)
436
+ payload["owners"] = list(tables.owners)
437
+ payload["audits"] = [list(use) for use in tables.uses]
438
+ payload["metrics"] = list(tables.metrics)
439
+ return _sort_dates(payload)
440
+
441
+
442
+ def _audit_issue(
443
+ audit: "AuditRecord",
444
+ kind: str,
445
+ model_index: t.Mapping[str, int],
446
+ incident_index: t.Mapping[t.Tuple[t.Any, ...], int],
447
+ tables: _Tables,
448
+ ) -> t.Dict[str, t.Any]:
449
+ return {
450
+ "kind": kind,
451
+ "model": model_index.get(audit.model_name, -1),
452
+ "signal": audit.audit_name,
453
+ "use": tables.use(audit),
454
+ "interval": _day(audit.interval_start) if audit.interval_start else None,
455
+ "value": audit.violation_count,
456
+ "lo": 0,
457
+ "hi": 0,
458
+ "incident": incident_index.get(_incident_key(audit), -1),
459
+ }
460
+
461
+
462
+ def _sort_dates(payload: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
463
+ """Renumber ``dates`` into sorted order so the browser can compare indexes as dates."""
464
+ dates: t.List[str] = payload["dates"]
465
+ order = sorted(range(len(dates)), key=lambda i: dates[i])
466
+ remap = {old: new for new, old in enumerate(order)}
467
+ payload["dates"] = [dates[i] for i in order]
468
+ for model in payload["models"]:
469
+ for row in model["a"]:
470
+ row[0] = remap[row[0]]
471
+ for column in (model["h"], model["r"], *model["m"]):
472
+ index = 0 if column is model["h"] or column is model["r"] else 3
473
+ column[index] = _deltas([remap[d] for d in column[index]])
474
+ for row in payload["trend"]:
475
+ row[0] = remap[row[0]]
476
+ payload["trend"].sort(key=lambda row: row[0])
477
+ return payload
478
+
479
+
480
+ def _deltas(indexes: t.List[int]) -> t.List[int]:
481
+ if len(indexes) > 2 and indexes == list(range(indexes[0], indexes[0] + len(indexes))):
482
+ return [-len(indexes), indexes[0]]
483
+ return [d - (indexes[i - 1] if i else 0) for i, d in enumerate(indexes)]
484
+
485
+
486
+ def undelta(deltas: t.Sequence[int]) -> t.List[int]:
487
+ """Decode a delta-coded date list back into indexes (the browser does the same)."""
488
+ if len(deltas) == 2 and deltas[0] < 0:
489
+ return list(range(deltas[1], deltas[1] - deltas[0]))
490
+ out: t.List[int] = []
491
+ for d in deltas:
492
+ out.append(d + (out[-1] if out else 0))
493
+ return out
494
+
495
+
496
+ def encode(payload: t.Mapping[str, t.Any]) -> str:
497
+ """JSON that is safe inside ``<script type="application/json">``: nothing in it can close
498
+ the element or start markup."""
499
+ text = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
500
+ return (
501
+ text.replace("&", "\\u0026")
502
+ .replace("<", "\\u003c")
503
+ .replace(">", "\\u003e")
504
+ .replace("
", "\\u2028")
505
+ .replace("
", "\\u2029")
506
+ )