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,1197 @@
|
|
|
1
|
+
"""Read-only warehouse and SQLMesh state loader for reports and alerts.
|
|
2
|
+
|
|
3
|
+
Loads project gateway settings through ``sqlmesh.core.config.loader.load_configs`` without
|
|
4
|
+
constructing a ``Context``, loading models, or creating a scheduler. SQLMesh state is accessed only
|
|
5
|
+
through ``EngineAdapterStateSync``'s read methods (never raw SQL, never writes).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import datetime
|
|
11
|
+
import logging
|
|
12
|
+
import typing as t
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from sqlglot import exp
|
|
17
|
+
|
|
18
|
+
if t.TYPE_CHECKING:
|
|
19
|
+
from sqlmesh.core.config import Config
|
|
20
|
+
from sqlmesh.core.engine_adapter import EngineAdapter
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
DEFAULT_SCHEMA = "observability"
|
|
25
|
+
DEFAULT_ENVIRONMENT = "prod"
|
|
26
|
+
_IN_CHUNK = 500
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MissingAuditTableError(RuntimeError):
|
|
30
|
+
"""Raised when the configured observability schema has no ``audit_results`` table."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, schema: str) -> None:
|
|
33
|
+
self.schema = schema
|
|
34
|
+
super().__init__(f"No audit_results table found in schema '{schema}'.")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class AuditRecord:
|
|
39
|
+
"""One normalized audit result row, with any sampled failing rows attached."""
|
|
40
|
+
|
|
41
|
+
invocation_id: str
|
|
42
|
+
model_name: str
|
|
43
|
+
snapshot_id: t.Optional[str]
|
|
44
|
+
version: t.Optional[str]
|
|
45
|
+
physical_table: t.Optional[str]
|
|
46
|
+
environment: t.Optional[str]
|
|
47
|
+
audit_name: str
|
|
48
|
+
args_json: t.Optional[str]
|
|
49
|
+
interval_start: t.Optional[str]
|
|
50
|
+
interval_end: t.Optional[str]
|
|
51
|
+
status: str
|
|
52
|
+
violation_count: t.Optional[int]
|
|
53
|
+
blocking: t.Optional[bool]
|
|
54
|
+
query_sql: t.Optional[str]
|
|
55
|
+
error_message: t.Optional[str]
|
|
56
|
+
started_at: t.Optional[str]
|
|
57
|
+
samples: t.Tuple[str, ...] = ()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class MetricPoint:
|
|
62
|
+
"""One interval of a passive metric series, scored at read time."""
|
|
63
|
+
|
|
64
|
+
interval_start: str
|
|
65
|
+
value: t.Optional[float]
|
|
66
|
+
mean: t.Optional[float]
|
|
67
|
+
stddev: t.Optional[float]
|
|
68
|
+
training_points: int
|
|
69
|
+
anomaly: bool
|
|
70
|
+
error_message: t.Optional[str] = None
|
|
71
|
+
invocation_id: t.Optional[str] = None # the invocation that wrote this value (alerts)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class MetricSeries:
|
|
76
|
+
metric_name: str
|
|
77
|
+
column_name: str
|
|
78
|
+
points: t.Tuple[MetricPoint, ...]
|
|
79
|
+
# Scoring threshold the points were flagged with: the expected band is mean ± threshold·sd.
|
|
80
|
+
threshold: float = 3.0
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class RunRecord:
|
|
85
|
+
"""One scoped ``model_runs`` row."""
|
|
86
|
+
|
|
87
|
+
invocation_id: str
|
|
88
|
+
snapshot_id: t.Optional[str]
|
|
89
|
+
version: t.Optional[str]
|
|
90
|
+
interval_start: t.Optional[str]
|
|
91
|
+
interval_end: t.Optional[str]
|
|
92
|
+
status: t.Optional[str]
|
|
93
|
+
duration_ms: t.Optional[int]
|
|
94
|
+
started_at: t.Optional[str] # the invocation's start
|
|
95
|
+
environment: t.Optional[str]
|
|
96
|
+
audit_only: bool
|
|
97
|
+
error_message: t.Optional[str]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True)
|
|
101
|
+
class InvocationRecord:
|
|
102
|
+
"""One plan or run that targeted the environment or produced rows in scope (run log)."""
|
|
103
|
+
|
|
104
|
+
invocation_id: str
|
|
105
|
+
command: t.Optional[str]
|
|
106
|
+
environment: t.Optional[str]
|
|
107
|
+
status: t.Optional[str]
|
|
108
|
+
started_at: t.Optional[str]
|
|
109
|
+
finished_at: t.Optional[str]
|
|
110
|
+
duration_ms: t.Optional[int]
|
|
111
|
+
model_runs: int = 0
|
|
112
|
+
failed_runs: int = 0
|
|
113
|
+
audits: int = 0
|
|
114
|
+
failing_audits: int = 0
|
|
115
|
+
blocking_failures: int = 0 # failing blocking audits plus audit errors
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class IntervalHealth:
|
|
120
|
+
"""Worst outcome of the latest run of one interval."""
|
|
121
|
+
|
|
122
|
+
interval_start: str
|
|
123
|
+
status: str # pass, warn, fail, error, skip
|
|
124
|
+
detail: str
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass(frozen=True)
|
|
128
|
+
class MetricAnomaly:
|
|
129
|
+
"""A series whose latest point is anomalous."""
|
|
130
|
+
|
|
131
|
+
model_name: str
|
|
132
|
+
metric_name: str
|
|
133
|
+
column_name: str
|
|
134
|
+
point: MetricPoint
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class SchemaChange:
|
|
139
|
+
column_name: str
|
|
140
|
+
change_type: str
|
|
141
|
+
old_type: t.Optional[str]
|
|
142
|
+
new_type: t.Optional[str]
|
|
143
|
+
from_version: t.Optional[str]
|
|
144
|
+
to_version: t.Optional[str]
|
|
145
|
+
from_snapshot_id: t.Optional[str]
|
|
146
|
+
to_snapshot_id: t.Optional[str]
|
|
147
|
+
recorded_at: t.Optional[str]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass(frozen=True)
|
|
151
|
+
class ModelReport:
|
|
152
|
+
"""Scoped audit history and state metadata for one model."""
|
|
153
|
+
|
|
154
|
+
model_name: str
|
|
155
|
+
owner: t.Optional[str]
|
|
156
|
+
columns: t.Tuple[t.Tuple[str, str], ...]
|
|
157
|
+
audits: t.Tuple[AuditRecord, ...]
|
|
158
|
+
failing_blocking_audits: t.Tuple[AuditRecord, ...]
|
|
159
|
+
warning_audits: t.Tuple[AuditRecord, ...] = ()
|
|
160
|
+
metrics: t.Tuple[MetricSeries, ...] = ()
|
|
161
|
+
schema_changes: t.Tuple[SchemaChange, ...] = ()
|
|
162
|
+
runs: t.Tuple[RunRecord, ...] = () # oldest first
|
|
163
|
+
health: t.Tuple[IntervalHealth, ...] = () # oldest interval first
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True)
|
|
167
|
+
class ReportData:
|
|
168
|
+
"""Plain data model passed to the static HTML renderer (and later ASGI/alert consumers)."""
|
|
169
|
+
|
|
170
|
+
environment: str
|
|
171
|
+
schema: str
|
|
172
|
+
gateway: str
|
|
173
|
+
generated_at: str
|
|
174
|
+
failing_model_count: int
|
|
175
|
+
passing_audit_count: int
|
|
176
|
+
failing_models: t.Tuple[ModelReport, ...]
|
|
177
|
+
models: t.Tuple[ModelReport, ...]
|
|
178
|
+
incidents: t.Tuple[AuditRecord, ...]
|
|
179
|
+
warning_model_count: int = 0
|
|
180
|
+
warning_models: t.Tuple[ModelReport, ...] = ()
|
|
181
|
+
# False when SQLMesh state for the environment could not be read (or does not exist yet). The
|
|
182
|
+
# report then shows only the latest invocation and says so.
|
|
183
|
+
state_available: bool = True
|
|
184
|
+
state_gateway: t.Optional[str] = None
|
|
185
|
+
anomalies: t.Tuple[MetricAnomaly, ...] = ()
|
|
186
|
+
invocations: t.Tuple["InvocationRecord", ...] = () # newest first
|
|
187
|
+
# Passive monitors configured in install(): any of volume, freshness, schema, columns.
|
|
188
|
+
monitors: t.Tuple[str, ...] = ()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True)
|
|
192
|
+
class _StateSnapshotInfo:
|
|
193
|
+
active_versions: t.FrozenSet[t.Tuple[str, str]]
|
|
194
|
+
owners: t.Dict[str, t.Optional[str]]
|
|
195
|
+
columns: t.Dict[str, t.Tuple[t.Tuple[str, str], ...]]
|
|
196
|
+
gateway: t.Optional[str] = None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _fmt_ts(value: t.Any) -> t.Optional[str]:
|
|
200
|
+
if value is None:
|
|
201
|
+
return None
|
|
202
|
+
if isinstance(value, datetime.datetime):
|
|
203
|
+
if value.tzinfo is not None:
|
|
204
|
+
value = value.astimezone(datetime.timezone.utc).replace(tzinfo=None)
|
|
205
|
+
return value.strftime("%Y-%m-%d %H:%M:%S")
|
|
206
|
+
if isinstance(value, datetime.date):
|
|
207
|
+
return value.isoformat()
|
|
208
|
+
return str(value)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _table(schema: str, name: str) -> exp.Table:
|
|
212
|
+
return exp.to_table(f"{schema}.{name}")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _load_project_config(path: t.Union[str, Path]) -> t.Tuple["Config", t.Dict[str, t.Any]]:
|
|
216
|
+
"""Load SQLMesh ``Config`` without creating a ``Context`` or mutating global collector state.
|
|
217
|
+
|
|
218
|
+
Returns ``(config, install_settings)`` where ``install_settings`` contains any values captured
|
|
219
|
+
if ``config.py`` called ``sqlmesh_observability.install()`` during load.
|
|
220
|
+
"""
|
|
221
|
+
from sqlmesh.core.config import Config
|
|
222
|
+
from sqlmesh.core.config.loader import load_configs
|
|
223
|
+
|
|
224
|
+
from sqlmesh_observability.collector import get_collector
|
|
225
|
+
|
|
226
|
+
collector = get_collector()
|
|
227
|
+
previous_settings = collector.settings
|
|
228
|
+
previous_writer = collector.writer
|
|
229
|
+
previous_dialect = collector.dialect
|
|
230
|
+
collector.settings = {}
|
|
231
|
+
try:
|
|
232
|
+
configs = load_configs(None, Config, [Path(path)])
|
|
233
|
+
loaded_settings = dict(collector.settings)
|
|
234
|
+
finally:
|
|
235
|
+
collector.settings = previous_settings
|
|
236
|
+
collector.writer = previous_writer
|
|
237
|
+
collector.dialect = previous_dialect
|
|
238
|
+
|
|
239
|
+
if not configs:
|
|
240
|
+
raise ValueError(f"No SQLMesh configuration found at {path}")
|
|
241
|
+
return next(iter(configs.values())), loaded_settings
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _resolve_gateway_and_schema(
|
|
245
|
+
config: "Config",
|
|
246
|
+
install_settings: t.Mapping[str, t.Any],
|
|
247
|
+
gateway: t.Optional[str],
|
|
248
|
+
schema: t.Optional[str],
|
|
249
|
+
) -> t.Tuple[str, str]:
|
|
250
|
+
installed_gateway = install_settings.get("connection")
|
|
251
|
+
resolved_gateway = (
|
|
252
|
+
gateway
|
|
253
|
+
or (installed_gateway if isinstance(installed_gateway, str) and installed_gateway else None)
|
|
254
|
+
or config.default_gateway
|
|
255
|
+
)
|
|
256
|
+
if not resolved_gateway:
|
|
257
|
+
gateways = list(config.gateways)
|
|
258
|
+
if not gateways:
|
|
259
|
+
raise ValueError("No gateway configured in SQLMesh config.")
|
|
260
|
+
resolved_gateway = gateways[0]
|
|
261
|
+
|
|
262
|
+
installed_schema = install_settings.get("schema")
|
|
263
|
+
resolved_schema = (
|
|
264
|
+
schema
|
|
265
|
+
or (installed_schema if isinstance(installed_schema, str) and installed_schema else None)
|
|
266
|
+
or DEFAULT_SCHEMA
|
|
267
|
+
)
|
|
268
|
+
return resolved_gateway, resolved_schema
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _read_environment_state(
|
|
272
|
+
config: "Config",
|
|
273
|
+
gateway: str,
|
|
274
|
+
environment: str,
|
|
275
|
+
) -> t.Optional[_StateSnapshotInfo]:
|
|
276
|
+
"""Read active snapshot versions, owners, and columns via SQLMesh's read-only StateReader.
|
|
277
|
+
|
|
278
|
+
Project state lives with the project's default gateway, so that is tried first. The log
|
|
279
|
+
gateway is tried after it, for projects whose state shares the log gateway's connection.
|
|
280
|
+
Returns ``None`` when no candidate has state for ``environment``.
|
|
281
|
+
"""
|
|
282
|
+
candidates: t.List[str] = []
|
|
283
|
+
for candidate in (config.default_gateway, gateway):
|
|
284
|
+
if candidate and candidate not in candidates:
|
|
285
|
+
candidates.append(candidate)
|
|
286
|
+
|
|
287
|
+
for candidate in candidates:
|
|
288
|
+
info = _read_state_from_gateway(config, candidate, environment)
|
|
289
|
+
if info is not None:
|
|
290
|
+
return info
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _read_state_from_gateway(
|
|
295
|
+
config: "Config",
|
|
296
|
+
gateway: str,
|
|
297
|
+
environment: str,
|
|
298
|
+
) -> t.Optional[_StateSnapshotInfo]:
|
|
299
|
+
from sqlmesh.core.state_sync import EngineAdapterStateSync
|
|
300
|
+
|
|
301
|
+
_prepare_for_fork()
|
|
302
|
+
state_connection = config.get_state_connection(gateway) or config.get_connection(gateway)
|
|
303
|
+
adapter = state_connection.create_engine_adapter()
|
|
304
|
+
try:
|
|
305
|
+
reader = EngineAdapterStateSync(adapter, schema=config.get_state_schema(gateway))
|
|
306
|
+
env = reader.get_environment(environment)
|
|
307
|
+
if env is None or not env.snapshots:
|
|
308
|
+
return None
|
|
309
|
+
|
|
310
|
+
active_versions = frozenset(
|
|
311
|
+
(snap.name, snap.version) for snap in env.snapshots if snap.version is not None
|
|
312
|
+
)
|
|
313
|
+
owners: t.Dict[str, t.Optional[str]] = {}
|
|
314
|
+
columns: t.Dict[str, t.Tuple[t.Tuple[str, str], ...]] = {}
|
|
315
|
+
try:
|
|
316
|
+
snapshots = reader.get_snapshots(env.snapshots)
|
|
317
|
+
except Exception:
|
|
318
|
+
logger.debug(
|
|
319
|
+
"sqlmesh-observability: failed to hydrate snapshots from state",
|
|
320
|
+
exc_info=True,
|
|
321
|
+
)
|
|
322
|
+
snapshots = {}
|
|
323
|
+
|
|
324
|
+
for snapshot in snapshots.values():
|
|
325
|
+
owner, cols = _node_metadata(snapshot)
|
|
326
|
+
owners[snapshot.name] = owner
|
|
327
|
+
if cols:
|
|
328
|
+
columns[snapshot.name] = cols
|
|
329
|
+
return _StateSnapshotInfo(
|
|
330
|
+
active_versions=active_versions, owners=owners, columns=columns, gateway=gateway
|
|
331
|
+
)
|
|
332
|
+
except Exception:
|
|
333
|
+
logger.debug(
|
|
334
|
+
"sqlmesh-observability: state lookup for environment '%s' on gateway '%s' unavailable",
|
|
335
|
+
environment,
|
|
336
|
+
gateway,
|
|
337
|
+
exc_info=True,
|
|
338
|
+
)
|
|
339
|
+
return None
|
|
340
|
+
finally:
|
|
341
|
+
adapter.close()
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _prepare_for_fork() -> None:
|
|
345
|
+
"""Import pandas before SQLMesh reads snapshots from state.
|
|
346
|
+
|
|
347
|
+
``get_snapshots`` runs SQLMesh's fork-based process pool (``sqlmesh/core/snapshot/cache.py``).
|
|
348
|
+
On macOS a child forked before pandas is loaded crashes in Objective-C initialization, and the
|
|
349
|
+
read then fails, silently dropping owners and columns. SQLMesh's own ``Loader`` imports pandas
|
|
350
|
+
first for the same reason. Imported here, not at module level (project rule).
|
|
351
|
+
"""
|
|
352
|
+
import pandas # noqa: F401
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _node_metadata(snapshot: t.Any) -> t.Tuple[t.Optional[str], t.Tuple[t.Tuple[str, str], ...]]:
|
|
356
|
+
node = snapshot.node
|
|
357
|
+
owner = getattr(node, "owner", None)
|
|
358
|
+
cols_to_types = getattr(node, "columns_to_types", None) or {}
|
|
359
|
+
columns = tuple(
|
|
360
|
+
(str(col), kind.sql() if hasattr(kind, "sql") else str(kind))
|
|
361
|
+
for col, kind in cols_to_types.items()
|
|
362
|
+
)
|
|
363
|
+
return owner, columns
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _hydrate_snapshots(
|
|
367
|
+
config: "Config", gateway: str, wanted: t.Mapping[str, str]
|
|
368
|
+
) -> t.Tuple[t.Dict[str, t.Optional[str]], t.Dict[str, t.Tuple[t.Tuple[str, str], ...]]]:
|
|
369
|
+
"""Owner and columns for snapshots outside the environment, by ``{model_name: snapshot_id}``.
|
|
370
|
+
|
|
371
|
+
Read-only, through the state reader, with the same gateway order as the environment read.
|
|
372
|
+
A plan that stops before promotion has already stored its snapshots in state.
|
|
373
|
+
"""
|
|
374
|
+
from sqlmesh.core.snapshot import SnapshotId
|
|
375
|
+
from sqlmesh.core.state_sync import EngineAdapterStateSync
|
|
376
|
+
|
|
377
|
+
owners: t.Dict[str, t.Optional[str]] = {}
|
|
378
|
+
columns: t.Dict[str, t.Tuple[t.Tuple[str, str], ...]] = {}
|
|
379
|
+
if not wanted:
|
|
380
|
+
return owners, columns
|
|
381
|
+
_prepare_for_fork()
|
|
382
|
+
ids = [SnapshotId(name=name, identifier=identifier) for name, identifier in wanted.items()]
|
|
383
|
+
candidates: t.List[str] = []
|
|
384
|
+
for candidate in (config.default_gateway, gateway):
|
|
385
|
+
if candidate and candidate not in candidates:
|
|
386
|
+
candidates.append(candidate)
|
|
387
|
+
for candidate in candidates:
|
|
388
|
+
try:
|
|
389
|
+
connection = config.get_state_connection(candidate) or config.get_connection(candidate)
|
|
390
|
+
adapter = connection.create_engine_adapter()
|
|
391
|
+
except Exception:
|
|
392
|
+
continue
|
|
393
|
+
try:
|
|
394
|
+
state = EngineAdapterStateSync(adapter, schema=config.get_state_schema(candidate))
|
|
395
|
+
snapshots = state.get_snapshots(ids)
|
|
396
|
+
except Exception:
|
|
397
|
+
logger.debug("sqlmesh-observability: snapshot hydration failed", exc_info=True)
|
|
398
|
+
snapshots = {}
|
|
399
|
+
finally:
|
|
400
|
+
adapter.close()
|
|
401
|
+
for snapshot in snapshots.values():
|
|
402
|
+
owner, cols = _node_metadata(snapshot)
|
|
403
|
+
owners[snapshot.name] = owner
|
|
404
|
+
if cols:
|
|
405
|
+
columns[snapshot.name] = cols
|
|
406
|
+
if snapshots:
|
|
407
|
+
break
|
|
408
|
+
return owners, columns
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _fetch_model_runs(
|
|
412
|
+
adapter: "EngineAdapter",
|
|
413
|
+
schema: str,
|
|
414
|
+
active_versions: t.FrozenSet[t.Tuple[str, str]],
|
|
415
|
+
latest_inv_id: t.Optional[str],
|
|
416
|
+
) -> t.Dict[str, t.List[RunRecord]]:
|
|
417
|
+
"""Scoped ``model_runs`` per model, oldest first."""
|
|
418
|
+
runs_table = _table(schema, "model_runs")
|
|
419
|
+
inv_table = _table(schema, "invocations")
|
|
420
|
+
scope = _version_scope({v for _, v in active_versions}, latest_inv_id, "version")
|
|
421
|
+
if scope is None or not adapter.table_exists(runs_table):
|
|
422
|
+
return {}
|
|
423
|
+
scope = scope.transform(
|
|
424
|
+
lambda node: exp.column(node.name, table="r") if isinstance(node, exp.Column) else node
|
|
425
|
+
)
|
|
426
|
+
columns = (
|
|
427
|
+
"model_name",
|
|
428
|
+
"invocation_id",
|
|
429
|
+
"snapshot_id",
|
|
430
|
+
"version",
|
|
431
|
+
"interval_start",
|
|
432
|
+
"interval_end",
|
|
433
|
+
"status",
|
|
434
|
+
"duration_ms",
|
|
435
|
+
"environment",
|
|
436
|
+
"audit_only",
|
|
437
|
+
"error_message",
|
|
438
|
+
)
|
|
439
|
+
query = (
|
|
440
|
+
exp.select(
|
|
441
|
+
*(exp.column(c, table="r") for c in columns), exp.column("started_at", table="i")
|
|
442
|
+
)
|
|
443
|
+
.from_(runs_table.as_("r"))
|
|
444
|
+
.join(
|
|
445
|
+
inv_table.as_("i"),
|
|
446
|
+
on=exp.column("invocation_id", table="r").eq(exp.column("invocation_id", table="i")),
|
|
447
|
+
join_type="left",
|
|
448
|
+
)
|
|
449
|
+
.where(scope)
|
|
450
|
+
)
|
|
451
|
+
runs: t.Dict[str, t.List[RunRecord]] = {}
|
|
452
|
+
for row in adapter.fetchall(query):
|
|
453
|
+
model_name, invocation_id, version = str(row[0]), str(row[1]), row[3]
|
|
454
|
+
if not _pair_in_scope(model_name, version, invocation_id, active_versions, latest_inv_id):
|
|
455
|
+
continue
|
|
456
|
+
runs.setdefault(model_name, []).append(
|
|
457
|
+
RunRecord(
|
|
458
|
+
invocation_id=invocation_id,
|
|
459
|
+
snapshot_id=None if row[2] is None else str(row[2]),
|
|
460
|
+
version=None if version is None else str(version),
|
|
461
|
+
interval_start=_fmt_ts(row[4]),
|
|
462
|
+
interval_end=_fmt_ts(row[5]),
|
|
463
|
+
status=None if row[6] is None else str(row[6]),
|
|
464
|
+
duration_ms=None if row[7] is None else int(row[7]),
|
|
465
|
+
environment=None if row[8] is None else str(row[8]),
|
|
466
|
+
audit_only=bool(row[9]),
|
|
467
|
+
error_message=None if row[10] is None else str(row[10]),
|
|
468
|
+
started_at=_fmt_ts(row[11]),
|
|
469
|
+
)
|
|
470
|
+
)
|
|
471
|
+
for items in runs.values():
|
|
472
|
+
items.sort(key=lambda r: (r.started_at or "", r.invocation_id, r.interval_start or ""))
|
|
473
|
+
return runs
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
_HEALTH_RANK = {"pass": 0, "skip": 1, "warn": 2, "fail": 3, "error": 4}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _interval_health(
|
|
480
|
+
runs: t.Sequence[RunRecord], audits: t.Sequence["AuditRecord"]
|
|
481
|
+
) -> t.Tuple[IntervalHealth, ...]:
|
|
482
|
+
"""Per interval, the latest run's worst outcome: error > fail > warn > skip > pass.
|
|
483
|
+
|
|
484
|
+
A run that failed because its blocking audit failed is ``fail``; a run that failed with no
|
|
485
|
+
failing audit is ``error`` (the model itself raised).
|
|
486
|
+
"""
|
|
487
|
+
latest: t.Dict[str, RunRecord] = {}
|
|
488
|
+
for run in runs: # oldest first, so the last one wins
|
|
489
|
+
if run.interval_start is not None:
|
|
490
|
+
latest[run.interval_start] = run
|
|
491
|
+
health: t.List[IntervalHealth] = []
|
|
492
|
+
for start in sorted(latest):
|
|
493
|
+
run = latest[start]
|
|
494
|
+
mine = [
|
|
495
|
+
a for a in audits if a.invocation_id == run.invocation_id and a.interval_start == start
|
|
496
|
+
]
|
|
497
|
+
statuses = []
|
|
498
|
+
for audit in mine:
|
|
499
|
+
if audit.status == "error":
|
|
500
|
+
statuses.append("error")
|
|
501
|
+
elif audit.status == "fail":
|
|
502
|
+
statuses.append("fail" if audit.blocking else "warn")
|
|
503
|
+
elif audit.status == "skip":
|
|
504
|
+
statuses.append("skip")
|
|
505
|
+
else:
|
|
506
|
+
statuses.append("pass")
|
|
507
|
+
if run.status == "failure" and "fail" not in statuses:
|
|
508
|
+
statuses.append("error")
|
|
509
|
+
status = max(statuses or ["pass"], key=lambda s: _HEALTH_RANK[s])
|
|
510
|
+
failing = [a.audit_name for a in mine if a.status in ("fail", "error")]
|
|
511
|
+
parts = [f"run {run.status or 'unknown'}"]
|
|
512
|
+
if mine:
|
|
513
|
+
parts.append(f"{len(mine)} audit{'s' if len(mine) != 1 else ''}")
|
|
514
|
+
if failing:
|
|
515
|
+
parts.append("failing: " + ", ".join(sorted(set(failing))))
|
|
516
|
+
if run.error_message and status == "error":
|
|
517
|
+
parts.append(run.error_message.splitlines()[0][:200])
|
|
518
|
+
health.append(IntervalHealth(interval_start=start, status=status, detail="; ".join(parts)))
|
|
519
|
+
return tuple(health)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
_RUN_LOG_LIMIT = 50
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _fetch_invocations(
|
|
526
|
+
adapter: "EngineAdapter",
|
|
527
|
+
schema: str,
|
|
528
|
+
environment: str,
|
|
529
|
+
in_scope_ids: t.Collection[str],
|
|
530
|
+
) -> t.List[InvocationRecord]:
|
|
531
|
+
"""Recent invocations that targeted ``environment`` or produced rows in scope, newest first."""
|
|
532
|
+
table = _table(schema, "invocations")
|
|
533
|
+
if not adapter.table_exists(table):
|
|
534
|
+
return []
|
|
535
|
+
conditions: t.List[exp.Expression] = [
|
|
536
|
+
exp.column("environment").eq(exp.Literal.string(environment))
|
|
537
|
+
]
|
|
538
|
+
ordered = sorted(set(in_scope_ids))
|
|
539
|
+
for start in range(0, len(ordered), _IN_CHUNK):
|
|
540
|
+
chunk = ordered[start : start + _IN_CHUNK]
|
|
541
|
+
conditions.append(exp.column("invocation_id").isin(*(exp.Literal.string(i) for i in chunk)))
|
|
542
|
+
query = (
|
|
543
|
+
exp.select("invocation_id", "command", "environment", "status", "started_at", "finished_at")
|
|
544
|
+
.from_(table)
|
|
545
|
+
.where(exp.or_(*conditions))
|
|
546
|
+
.order_by(exp.column("started_at").desc(), exp.column("invocation_id").desc())
|
|
547
|
+
.limit(_RUN_LOG_LIMIT)
|
|
548
|
+
)
|
|
549
|
+
records: t.List[InvocationRecord] = []
|
|
550
|
+
for row in adapter.fetchall(query):
|
|
551
|
+
started, finished = _naive(row[4]), _naive(row[5])
|
|
552
|
+
duration = (
|
|
553
|
+
int((finished - started).total_seconds() * 1000) if started and finished else None
|
|
554
|
+
)
|
|
555
|
+
records.append(
|
|
556
|
+
InvocationRecord(
|
|
557
|
+
invocation_id=str(row[0]),
|
|
558
|
+
command=None if row[1] is None else str(row[1]),
|
|
559
|
+
environment=None if row[2] is None else str(row[2]),
|
|
560
|
+
status=None if row[3] is None else str(row[3]),
|
|
561
|
+
started_at=_fmt_ts(row[4]),
|
|
562
|
+
finished_at=_fmt_ts(row[5]),
|
|
563
|
+
duration_ms=duration,
|
|
564
|
+
)
|
|
565
|
+
)
|
|
566
|
+
return records
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _with_counts(
|
|
570
|
+
invocations: t.Sequence[InvocationRecord],
|
|
571
|
+
runs: t.Mapping[str, t.Sequence[RunRecord]],
|
|
572
|
+
audits: t.Sequence["AuditRecord"],
|
|
573
|
+
) -> t.Tuple[InvocationRecord, ...]:
|
|
574
|
+
"""Attach scoped model-run and audit counts to each invocation."""
|
|
575
|
+
from dataclasses import replace
|
|
576
|
+
|
|
577
|
+
counts: t.Dict[str, t.List[int]] = {}
|
|
578
|
+
for run_list in runs.values():
|
|
579
|
+
for run in run_list:
|
|
580
|
+
c = counts.setdefault(run.invocation_id, [0, 0, 0, 0, 0])
|
|
581
|
+
c[0] += 1
|
|
582
|
+
c[1] += run.status == "failure"
|
|
583
|
+
for audit in audits:
|
|
584
|
+
c = counts.setdefault(audit.invocation_id, [0, 0, 0, 0, 0])
|
|
585
|
+
c[2] += 1
|
|
586
|
+
c[3] += audit.status in ("fail", "error")
|
|
587
|
+
c[4] += audit.status == "error" or (audit.status == "fail" and bool(audit.blocking))
|
|
588
|
+
empty = [0, 0, 0, 0, 0]
|
|
589
|
+
return tuple(
|
|
590
|
+
replace(
|
|
591
|
+
inv,
|
|
592
|
+
model_runs=counts.get(inv.invocation_id, empty)[0],
|
|
593
|
+
failed_runs=counts.get(inv.invocation_id, empty)[1],
|
|
594
|
+
audits=counts.get(inv.invocation_id, empty)[2],
|
|
595
|
+
failing_audits=counts.get(inv.invocation_id, empty)[3],
|
|
596
|
+
blocking_failures=counts.get(inv.invocation_id, empty)[4],
|
|
597
|
+
)
|
|
598
|
+
for inv in invocations
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _latest_invocation_id(
|
|
603
|
+
adapter: "EngineAdapter",
|
|
604
|
+
schema: str,
|
|
605
|
+
environment: str,
|
|
606
|
+
) -> t.Optional[str]:
|
|
607
|
+
inv_table = _table(schema, "invocations")
|
|
608
|
+
if not adapter.table_exists(inv_table):
|
|
609
|
+
return None
|
|
610
|
+
query = (
|
|
611
|
+
exp.select(exp.column("invocation_id"))
|
|
612
|
+
.from_(inv_table)
|
|
613
|
+
.where(exp.column("environment").eq(exp.Literal.string(environment)))
|
|
614
|
+
.order_by(exp.column("started_at").desc(), exp.column("invocation_id").desc())
|
|
615
|
+
.limit(1)
|
|
616
|
+
)
|
|
617
|
+
row = adapter.fetchone(query)
|
|
618
|
+
if row is None or row[0] is None:
|
|
619
|
+
return None
|
|
620
|
+
return str(row[0])
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _scope_condition(
|
|
624
|
+
versions: t.Collection[str],
|
|
625
|
+
latest_inv_id: t.Optional[str],
|
|
626
|
+
environment: str,
|
|
627
|
+
) -> exp.Condition:
|
|
628
|
+
"""SQL pre-filter matching :func:`_in_scope`; the exact (model, version) check runs after.
|
|
629
|
+
|
|
630
|
+
Versions are fingerprints, so ``version IN (...)`` is already nearly exact and keeps the scan
|
|
631
|
+
to the environment's rows instead of the whole history.
|
|
632
|
+
"""
|
|
633
|
+
version_col = exp.column("version", table="a")
|
|
634
|
+
conditions: t.List[exp.Expression] = []
|
|
635
|
+
ordered = sorted(versions)
|
|
636
|
+
for start in range(0, len(ordered), _IN_CHUNK):
|
|
637
|
+
chunk = ordered[start : start + _IN_CHUNK]
|
|
638
|
+
conditions.append(version_col.isin(*(exp.Literal.string(v) for v in chunk)))
|
|
639
|
+
if latest_inv_id is not None:
|
|
640
|
+
conditions.append(
|
|
641
|
+
exp.column("invocation_id", table="a").eq(exp.Literal.string(latest_inv_id))
|
|
642
|
+
)
|
|
643
|
+
if not versions and latest_inv_id is None:
|
|
644
|
+
conditions.append(exp.column("environment", table="a").eq(exp.Literal.string(environment)))
|
|
645
|
+
return exp.or_(*conditions)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _fetch_audit_rows(
|
|
649
|
+
adapter: "EngineAdapter",
|
|
650
|
+
schema: str,
|
|
651
|
+
scope: t.Optional[exp.Condition] = None,
|
|
652
|
+
) -> t.List[AuditRecord]:
|
|
653
|
+
audit_tbl = _table(schema, "audit_results").as_("a")
|
|
654
|
+
inv_tbl = _table(schema, "invocations")
|
|
655
|
+
has_invocations = adapter.table_exists(inv_tbl)
|
|
656
|
+
|
|
657
|
+
started_col = (
|
|
658
|
+
exp.column("started_at", table="i")
|
|
659
|
+
if has_invocations
|
|
660
|
+
else exp.alias_(exp.null(), "started_at")
|
|
661
|
+
)
|
|
662
|
+
query = exp.select(
|
|
663
|
+
exp.column("invocation_id", table="a"),
|
|
664
|
+
exp.column("model_name", table="a"),
|
|
665
|
+
exp.column("snapshot_id", table="a"),
|
|
666
|
+
exp.column("version", table="a"),
|
|
667
|
+
exp.column("physical_table", table="a"),
|
|
668
|
+
exp.column("environment", table="a"),
|
|
669
|
+
exp.column("audit_name", table="a"),
|
|
670
|
+
exp.column("args_json", table="a"),
|
|
671
|
+
exp.column("interval_start", table="a"),
|
|
672
|
+
exp.column("interval_end", table="a"),
|
|
673
|
+
exp.column("status", table="a"),
|
|
674
|
+
exp.column("violation_count", table="a"),
|
|
675
|
+
exp.column("blocking", table="a"),
|
|
676
|
+
exp.column("query_sql", table="a"),
|
|
677
|
+
exp.column("error_message", table="a"),
|
|
678
|
+
started_col,
|
|
679
|
+
).from_(audit_tbl)
|
|
680
|
+
if has_invocations:
|
|
681
|
+
query = query.join(
|
|
682
|
+
inv_tbl.as_("i"),
|
|
683
|
+
on=exp.column("invocation_id", table="a").eq(exp.column("invocation_id", table="i")),
|
|
684
|
+
join_type="left",
|
|
685
|
+
)
|
|
686
|
+
if scope is not None:
|
|
687
|
+
query = query.where(scope)
|
|
688
|
+
|
|
689
|
+
records: t.List[AuditRecord] = []
|
|
690
|
+
for row in adapter.fetchall(query):
|
|
691
|
+
records.append(
|
|
692
|
+
AuditRecord(
|
|
693
|
+
invocation_id=str(row[0]),
|
|
694
|
+
model_name=str(row[1]),
|
|
695
|
+
snapshot_id=str(row[2]) if row[2] is not None else None,
|
|
696
|
+
version=str(row[3]) if row[3] is not None else None,
|
|
697
|
+
physical_table=str(row[4]) if row[4] is not None else None,
|
|
698
|
+
environment=str(row[5]) if row[5] is not None else None,
|
|
699
|
+
audit_name=str(row[6]),
|
|
700
|
+
args_json=str(row[7]) if row[7] is not None else None,
|
|
701
|
+
interval_start=_fmt_ts(row[8]),
|
|
702
|
+
interval_end=_fmt_ts(row[9]),
|
|
703
|
+
status=str(row[10]),
|
|
704
|
+
violation_count=int(row[11]) if row[11] is not None else None,
|
|
705
|
+
blocking=bool(row[12]) if row[12] is not None else None,
|
|
706
|
+
query_sql=str(row[13]) if row[13] is not None else None,
|
|
707
|
+
error_message=str(row[14]) if row[14] is not None else None,
|
|
708
|
+
started_at=_fmt_ts(row[15]),
|
|
709
|
+
)
|
|
710
|
+
)
|
|
711
|
+
return records
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def _fetch_samples(
|
|
715
|
+
adapter: "EngineAdapter",
|
|
716
|
+
schema: str,
|
|
717
|
+
invocation_ids: t.Sequence[str],
|
|
718
|
+
) -> t.Dict[t.Tuple[str, str, str, t.Optional[str]], t.Tuple[str, ...]]:
|
|
719
|
+
if not invocation_ids:
|
|
720
|
+
return {}
|
|
721
|
+
samples_table = _table(schema, "audit_samples")
|
|
722
|
+
if not adapter.table_exists(samples_table):
|
|
723
|
+
return {}
|
|
724
|
+
|
|
725
|
+
grouped: t.Dict[t.Tuple[str, str, str, t.Optional[str]], t.List[str]] = {}
|
|
726
|
+
unique_ids = sorted(set(invocation_ids))
|
|
727
|
+
for start in range(0, len(unique_ids), _IN_CHUNK):
|
|
728
|
+
chunk = unique_ids[start : start + _IN_CHUNK]
|
|
729
|
+
query = (
|
|
730
|
+
exp.select(
|
|
731
|
+
exp.column("invocation_id"),
|
|
732
|
+
exp.column("model_name"),
|
|
733
|
+
exp.column("audit_name"),
|
|
734
|
+
exp.column("interval_start"),
|
|
735
|
+
exp.column("row_json"),
|
|
736
|
+
)
|
|
737
|
+
.from_(samples_table)
|
|
738
|
+
.where(exp.column("invocation_id").isin(*(exp.Literal.string(i) for i in chunk)))
|
|
739
|
+
)
|
|
740
|
+
for row in adapter.fetchall(query):
|
|
741
|
+
key = (str(row[0]), str(row[1]), str(row[2]), _fmt_ts(row[3]))
|
|
742
|
+
grouped.setdefault(key, []).append(str(row[4]))
|
|
743
|
+
|
|
744
|
+
return {key: tuple(values) for key, values in grouped.items()}
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def _version_scope(
|
|
748
|
+
versions: t.Collection[str], latest_inv_id: t.Optional[str], version_column: str
|
|
749
|
+
) -> t.Optional[exp.Condition]:
|
|
750
|
+
conditions: t.List[exp.Expression] = []
|
|
751
|
+
ordered = sorted(versions)
|
|
752
|
+
for start in range(0, len(ordered), _IN_CHUNK):
|
|
753
|
+
chunk = ordered[start : start + _IN_CHUNK]
|
|
754
|
+
conditions.append(exp.column(version_column).isin(*(exp.Literal.string(v) for v in chunk)))
|
|
755
|
+
if latest_inv_id is not None:
|
|
756
|
+
conditions.append(exp.column("invocation_id").eq(exp.Literal.string(latest_inv_id)))
|
|
757
|
+
return exp.or_(*conditions) if conditions else None
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _pair_in_scope(
|
|
761
|
+
model_name: str,
|
|
762
|
+
version: t.Optional[str],
|
|
763
|
+
invocation_id: str,
|
|
764
|
+
active_versions: t.FrozenSet[t.Tuple[str, str]],
|
|
765
|
+
latest_inv_id: t.Optional[str],
|
|
766
|
+
) -> bool:
|
|
767
|
+
return (model_name, version or "") in active_versions or invocation_id == latest_inv_id
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def _naive(value: t.Any) -> t.Optional[datetime.datetime]:
|
|
771
|
+
from sqlmesh_observability.monitors import _naive_utc
|
|
772
|
+
|
|
773
|
+
try:
|
|
774
|
+
return _naive_utc(value)
|
|
775
|
+
except Exception:
|
|
776
|
+
return None
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def _fetch_metric_series(
|
|
780
|
+
adapter: "EngineAdapter",
|
|
781
|
+
schema: str,
|
|
782
|
+
active_versions: t.FrozenSet[t.Tuple[str, str]],
|
|
783
|
+
latest_inv_id: t.Optional[str],
|
|
784
|
+
monitor_settings: t.Any,
|
|
785
|
+
) -> t.Dict[str, t.Tuple[MetricSeries, ...]]:
|
|
786
|
+
"""Scoped metric series per model: latest value per interval, scored at read time."""
|
|
787
|
+
from sqlmesh_observability.monitors import score_series
|
|
788
|
+
|
|
789
|
+
table = _table(schema, "metrics")
|
|
790
|
+
scope = _version_scope({v for _, v in active_versions}, latest_inv_id, "version")
|
|
791
|
+
if scope is None or not adapter.table_exists(table):
|
|
792
|
+
return {}
|
|
793
|
+
query = (
|
|
794
|
+
exp.select(
|
|
795
|
+
"model_name",
|
|
796
|
+
"version",
|
|
797
|
+
"invocation_id",
|
|
798
|
+
"interval_start",
|
|
799
|
+
"metric_name",
|
|
800
|
+
"column_name",
|
|
801
|
+
"metric_value",
|
|
802
|
+
"updated_at",
|
|
803
|
+
"error_message",
|
|
804
|
+
)
|
|
805
|
+
.from_(table)
|
|
806
|
+
.where(scope)
|
|
807
|
+
)
|
|
808
|
+
# (model, metric, column) -> interval_start -> (updated_at, value, error, invocation_id)
|
|
809
|
+
latest: t.Dict[
|
|
810
|
+
t.Tuple[str, str, str],
|
|
811
|
+
t.Dict[
|
|
812
|
+
datetime.datetime,
|
|
813
|
+
t.Tuple[datetime.datetime, t.Optional[float], t.Optional[str], str],
|
|
814
|
+
],
|
|
815
|
+
] = {}
|
|
816
|
+
for row in adapter.fetchall(query):
|
|
817
|
+
model_name, version, invocation_id, start, metric, column, value, updated, error = row
|
|
818
|
+
if not _pair_in_scope(
|
|
819
|
+
str(model_name), version, str(invocation_id), active_versions, latest_inv_id
|
|
820
|
+
):
|
|
821
|
+
continue
|
|
822
|
+
when = _naive(start)
|
|
823
|
+
if when is None:
|
|
824
|
+
continue
|
|
825
|
+
stamp = _naive(updated) or datetime.datetime.min
|
|
826
|
+
key = (str(model_name), str(metric), str(column or ""))
|
|
827
|
+
by_interval = latest.setdefault(key, {})
|
|
828
|
+
if when not in by_interval or stamp > by_interval[when][0]:
|
|
829
|
+
by_interval[when] = (
|
|
830
|
+
stamp,
|
|
831
|
+
None if value is None else float(value),
|
|
832
|
+
None if error is None else str(error),
|
|
833
|
+
str(invocation_id),
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
series: t.Dict[str, t.List[MetricSeries]] = {}
|
|
837
|
+
for (model_name, metric, column), by_start in sorted(latest.items()):
|
|
838
|
+
ordered = sorted(by_start.items())
|
|
839
|
+
scored = score_series(
|
|
840
|
+
[(when, value) for when, (_, value, _, _) in ordered],
|
|
841
|
+
monitor_settings.score_for(metric),
|
|
842
|
+
)
|
|
843
|
+
points = tuple(
|
|
844
|
+
MetricPoint(
|
|
845
|
+
interval_start=_fmt_ts(p.interval_start) or "",
|
|
846
|
+
value=p.value,
|
|
847
|
+
mean=p.mean,
|
|
848
|
+
stddev=p.stddev,
|
|
849
|
+
training_points=p.training_points,
|
|
850
|
+
anomaly=p.anomaly,
|
|
851
|
+
error_message=error,
|
|
852
|
+
invocation_id=invocation_id,
|
|
853
|
+
)
|
|
854
|
+
for p, (_, (_, _, error, invocation_id)) in zip(scored, ordered)
|
|
855
|
+
)
|
|
856
|
+
series.setdefault(model_name, []).append(
|
|
857
|
+
MetricSeries(
|
|
858
|
+
metric_name=metric,
|
|
859
|
+
column_name=column,
|
|
860
|
+
points=points,
|
|
861
|
+
threshold=float(monitor_settings.score_for(metric).threshold),
|
|
862
|
+
)
|
|
863
|
+
)
|
|
864
|
+
return {name: tuple(items) for name, items in series.items()}
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def _fetch_schema_changes(
|
|
868
|
+
adapter: "EngineAdapter",
|
|
869
|
+
schema: str,
|
|
870
|
+
active_versions: t.FrozenSet[t.Tuple[str, str]],
|
|
871
|
+
latest_inv_id: t.Optional[str],
|
|
872
|
+
) -> t.Dict[str, t.Tuple[SchemaChange, ...]]:
|
|
873
|
+
table = _table(schema, "schema_changes")
|
|
874
|
+
scope = _version_scope({v for _, v in active_versions}, latest_inv_id, "to_version")
|
|
875
|
+
if scope is None or not adapter.table_exists(table):
|
|
876
|
+
return {}
|
|
877
|
+
query = (
|
|
878
|
+
exp.select(
|
|
879
|
+
"model_name",
|
|
880
|
+
"to_version",
|
|
881
|
+
"invocation_id",
|
|
882
|
+
"column_name",
|
|
883
|
+
"change_type",
|
|
884
|
+
"old_type",
|
|
885
|
+
"new_type",
|
|
886
|
+
"from_version",
|
|
887
|
+
"from_snapshot_id",
|
|
888
|
+
"to_snapshot_id",
|
|
889
|
+
"recorded_at",
|
|
890
|
+
)
|
|
891
|
+
.from_(table)
|
|
892
|
+
.where(scope)
|
|
893
|
+
)
|
|
894
|
+
changes: t.Dict[str, t.List[t.Tuple[str, SchemaChange]]] = {}
|
|
895
|
+
for row in adapter.fetchall(query):
|
|
896
|
+
model_name, to_version, invocation_id = str(row[0]), row[1], str(row[2])
|
|
897
|
+
if not _pair_in_scope(
|
|
898
|
+
model_name, to_version, invocation_id, active_versions, latest_inv_id
|
|
899
|
+
):
|
|
900
|
+
continue
|
|
901
|
+
recorded_at = _fmt_ts(row[10])
|
|
902
|
+
change = SchemaChange(
|
|
903
|
+
column_name=str(row[3]),
|
|
904
|
+
change_type=str(row[4]),
|
|
905
|
+
old_type=None if row[5] is None else str(row[5]),
|
|
906
|
+
new_type=None if row[6] is None else str(row[6]),
|
|
907
|
+
from_version=None if row[7] is None else str(row[7]),
|
|
908
|
+
to_version=None if to_version is None else str(to_version),
|
|
909
|
+
from_snapshot_id=None if row[8] is None else str(row[8]),
|
|
910
|
+
to_snapshot_id=None if row[9] is None else str(row[9]),
|
|
911
|
+
recorded_at=recorded_at,
|
|
912
|
+
)
|
|
913
|
+
changes.setdefault(model_name, []).append((recorded_at or "", change))
|
|
914
|
+
return {
|
|
915
|
+
name: tuple(
|
|
916
|
+
c for _, c in sorted(items, key=lambda i: (i[0], i[1].column_name), reverse=True)
|
|
917
|
+
)
|
|
918
|
+
for name, items in changes.items()
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
def _in_scope(
|
|
923
|
+
record: AuditRecord,
|
|
924
|
+
environment: str,
|
|
925
|
+
active_versions: t.FrozenSet[t.Tuple[str, str]],
|
|
926
|
+
latest_inv_id: t.Optional[str],
|
|
927
|
+
) -> bool:
|
|
928
|
+
if record.version is not None and (record.model_name, record.version) in active_versions:
|
|
929
|
+
return True
|
|
930
|
+
if latest_inv_id is not None and record.invocation_id == latest_inv_id:
|
|
931
|
+
return True
|
|
932
|
+
if not active_versions and latest_inv_id is None:
|
|
933
|
+
return record.environment == environment
|
|
934
|
+
return False
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def audit_key(record: AuditRecord) -> t.Tuple[str, str, t.Optional[str], t.Optional[str]]:
|
|
938
|
+
"""Identity of one audit use on one interval.
|
|
939
|
+
|
|
940
|
+
A model may list the same audit twice with different arguments, so the arguments are part of
|
|
941
|
+
the key: without them one use's result would hide the other's.
|
|
942
|
+
"""
|
|
943
|
+
return (record.model_name, record.audit_name, record.args_json, record.interval_start)
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _is_warning(record: AuditRecord) -> bool:
|
|
947
|
+
return record.status == "fail" and not record.blocking
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _is_overview_failure(record: AuditRecord) -> bool:
|
|
951
|
+
if record.status == "error":
|
|
952
|
+
return True
|
|
953
|
+
return record.status == "fail" and bool(record.blocking)
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _sort_key(record: AuditRecord) -> t.Tuple[str, str, str, str, str]:
|
|
957
|
+
return (
|
|
958
|
+
record.interval_start or "",
|
|
959
|
+
record.started_at or "",
|
|
960
|
+
record.invocation_id,
|
|
961
|
+
record.audit_name,
|
|
962
|
+
record.args_json or "",
|
|
963
|
+
)
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def _build_report_data(
|
|
967
|
+
records: t.Sequence[AuditRecord],
|
|
968
|
+
state_info: t.Optional[_StateSnapshotInfo],
|
|
969
|
+
environment: str,
|
|
970
|
+
schema: str,
|
|
971
|
+
gateway: str,
|
|
972
|
+
metrics: t.Optional[t.Mapping[str, t.Tuple[MetricSeries, ...]]] = None,
|
|
973
|
+
schema_changes: t.Optional[t.Mapping[str, t.Tuple[SchemaChange, ...]]] = None,
|
|
974
|
+
runs: t.Optional[t.Mapping[str, t.Sequence[RunRecord]]] = None,
|
|
975
|
+
extra_owners: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
|
976
|
+
extra_columns: t.Optional[t.Mapping[str, t.Tuple[t.Tuple[str, str], ...]]] = None,
|
|
977
|
+
invocations: t.Sequence[InvocationRecord] = (),
|
|
978
|
+
monitors: t.Tuple[str, ...] = (),
|
|
979
|
+
) -> ReportData:
|
|
980
|
+
by_model: t.Dict[str, t.List[AuditRecord]] = {}
|
|
981
|
+
for record in records:
|
|
982
|
+
by_model.setdefault(record.model_name, []).append(record)
|
|
983
|
+
|
|
984
|
+
models: t.List[ModelReport] = []
|
|
985
|
+
failing_models: t.List[ModelReport] = []
|
|
986
|
+
warning_models: t.List[ModelReport] = []
|
|
987
|
+
passing_audit_count = 0
|
|
988
|
+
owners = {**(extra_owners or {}), **(state_info.owners if state_info else {})}
|
|
989
|
+
columns = {**(extra_columns or {}), **(state_info.columns if state_info else {})}
|
|
990
|
+
|
|
991
|
+
metrics = metrics or {}
|
|
992
|
+
schema_changes = schema_changes or {}
|
|
993
|
+
runs = runs or {}
|
|
994
|
+
anomalies: t.List[MetricAnomaly] = []
|
|
995
|
+
for model_name in sorted(set(by_model) | set(metrics) | set(schema_changes) | set(runs)):
|
|
996
|
+
model_audits = sorted(by_model.get(model_name, ()), key=_sort_key, reverse=True)
|
|
997
|
+
for series in metrics.get(model_name, ()):
|
|
998
|
+
if series.points and series.points[-1].anomaly:
|
|
999
|
+
anomalies.append(
|
|
1000
|
+
MetricAnomaly(
|
|
1001
|
+
model_name=model_name,
|
|
1002
|
+
metric_name=series.metric_name,
|
|
1003
|
+
column_name=series.column_name,
|
|
1004
|
+
point=series.points[-1],
|
|
1005
|
+
)
|
|
1006
|
+
)
|
|
1007
|
+
|
|
1008
|
+
# Latest run per audit use and interval, for Overview counts/status.
|
|
1009
|
+
latest_by_key: t.Dict[t.Tuple[str, str, t.Optional[str], t.Optional[str]], AuditRecord] = {}
|
|
1010
|
+
for audit in model_audits:
|
|
1011
|
+
dedup_key = audit_key(audit)
|
|
1012
|
+
existing = latest_by_key.get(dedup_key)
|
|
1013
|
+
if existing is None or (audit.started_at or "", audit.invocation_id) > (
|
|
1014
|
+
existing.started_at or "",
|
|
1015
|
+
existing.invocation_id,
|
|
1016
|
+
):
|
|
1017
|
+
latest_by_key[dedup_key] = audit
|
|
1018
|
+
|
|
1019
|
+
latest_audits = list(latest_by_key.values())
|
|
1020
|
+
passing_audit_count += sum(1 for a in latest_audits if a.status == "pass")
|
|
1021
|
+
failing_blocking = tuple(
|
|
1022
|
+
sorted(
|
|
1023
|
+
(a for a in latest_audits if _is_overview_failure(a)),
|
|
1024
|
+
key=_sort_key,
|
|
1025
|
+
reverse=True,
|
|
1026
|
+
)
|
|
1027
|
+
)
|
|
1028
|
+
warnings = tuple(
|
|
1029
|
+
sorted((a for a in latest_audits if _is_warning(a)), key=_sort_key, reverse=True)
|
|
1030
|
+
)
|
|
1031
|
+
model_report = ModelReport(
|
|
1032
|
+
model_name=model_name,
|
|
1033
|
+
owner=owners.get(model_name),
|
|
1034
|
+
columns=columns.get(model_name, ()),
|
|
1035
|
+
audits=tuple(model_audits),
|
|
1036
|
+
failing_blocking_audits=failing_blocking,
|
|
1037
|
+
warning_audits=warnings,
|
|
1038
|
+
metrics=metrics.get(model_name, ()),
|
|
1039
|
+
schema_changes=schema_changes.get(model_name, ()),
|
|
1040
|
+
runs=tuple(runs.get(model_name, ())),
|
|
1041
|
+
health=_interval_health(runs.get(model_name, ()), model_audits),
|
|
1042
|
+
)
|
|
1043
|
+
models.append(model_report)
|
|
1044
|
+
if failing_blocking:
|
|
1045
|
+
failing_models.append(model_report)
|
|
1046
|
+
if warnings:
|
|
1047
|
+
warning_models.append(model_report)
|
|
1048
|
+
|
|
1049
|
+
incidents = tuple(
|
|
1050
|
+
sorted(
|
|
1051
|
+
(r for r in records if r.status in ("fail", "error")),
|
|
1052
|
+
key=_sort_key,
|
|
1053
|
+
reverse=True,
|
|
1054
|
+
)
|
|
1055
|
+
)
|
|
1056
|
+
generated_at = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
|
1057
|
+
return ReportData(
|
|
1058
|
+
environment=environment,
|
|
1059
|
+
schema=schema,
|
|
1060
|
+
gateway=gateway,
|
|
1061
|
+
generated_at=generated_at,
|
|
1062
|
+
failing_model_count=len(failing_models),
|
|
1063
|
+
passing_audit_count=passing_audit_count,
|
|
1064
|
+
failing_models=tuple(failing_models),
|
|
1065
|
+
models=tuple(models),
|
|
1066
|
+
incidents=incidents,
|
|
1067
|
+
warning_model_count=len(warning_models),
|
|
1068
|
+
warning_models=tuple(warning_models),
|
|
1069
|
+
state_available=state_info is not None,
|
|
1070
|
+
state_gateway=state_info.gateway if state_info else None,
|
|
1071
|
+
anomalies=tuple(anomalies),
|
|
1072
|
+
invocations=_with_counts(invocations, runs, records),
|
|
1073
|
+
monitors=monitors,
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _configured_monitors(settings: t.Any) -> t.Tuple[str, ...]:
|
|
1078
|
+
"""Names of the passive monitors ``install(monitors=...)`` turned on, in a fixed order."""
|
|
1079
|
+
on = {
|
|
1080
|
+
"volume": settings.volume is not None,
|
|
1081
|
+
"freshness": settings.freshness is not None,
|
|
1082
|
+
"schema": bool(settings.schema),
|
|
1083
|
+
"columns": bool(settings.columns),
|
|
1084
|
+
}
|
|
1085
|
+
return tuple(name for name, enabled in on.items() if enabled)
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def load_report_data(
|
|
1089
|
+
path: t.Union[str, Path] = ".",
|
|
1090
|
+
gateway: t.Optional[str] = None,
|
|
1091
|
+
schema: t.Optional[str] = None,
|
|
1092
|
+
environment: str = DEFAULT_ENVIRONMENT,
|
|
1093
|
+
) -> ReportData:
|
|
1094
|
+
"""Load scoped observability data for ``environment`` from the warehouse and SQLMesh state."""
|
|
1095
|
+
config, install_settings = _load_project_config(path)
|
|
1096
|
+
return load_report_data_for(config, install_settings, gateway, schema, environment)
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def load_report_data_for(
|
|
1100
|
+
config: "Config",
|
|
1101
|
+
install_settings: t.Mapping[str, t.Any],
|
|
1102
|
+
gateway: t.Optional[str] = None,
|
|
1103
|
+
schema: t.Optional[str] = None,
|
|
1104
|
+
environment: str = DEFAULT_ENVIRONMENT,
|
|
1105
|
+
) -> ReportData:
|
|
1106
|
+
""":func:`load_report_data` for a ``config.py`` that is already loaded."""
|
|
1107
|
+
resolved_gateway, resolved_schema = _resolve_gateway_and_schema(
|
|
1108
|
+
config, install_settings, gateway, schema
|
|
1109
|
+
)
|
|
1110
|
+
|
|
1111
|
+
adapter = config.get_connection(resolved_gateway).create_engine_adapter()
|
|
1112
|
+
try:
|
|
1113
|
+
if not adapter.table_exists(_table(resolved_schema, "audit_results")):
|
|
1114
|
+
raise MissingAuditTableError(resolved_schema)
|
|
1115
|
+
|
|
1116
|
+
latest_inv_id = _latest_invocation_id(adapter, resolved_schema, environment)
|
|
1117
|
+
state_info = _read_environment_state(config, resolved_gateway, environment)
|
|
1118
|
+
active_versions = state_info.active_versions if state_info else frozenset()
|
|
1119
|
+
scope = _scope_condition({v for _, v in active_versions}, latest_inv_id, environment)
|
|
1120
|
+
scoped = [
|
|
1121
|
+
row
|
|
1122
|
+
for row in _fetch_audit_rows(adapter, resolved_schema, scope)
|
|
1123
|
+
if _in_scope(row, environment, active_versions, latest_inv_id)
|
|
1124
|
+
]
|
|
1125
|
+
|
|
1126
|
+
from sqlmesh_observability.monitors import normalize_monitors
|
|
1127
|
+
|
|
1128
|
+
monitor_settings = normalize_monitors(install_settings.get("monitors"))
|
|
1129
|
+
metric_series = _fetch_metric_series(
|
|
1130
|
+
adapter, resolved_schema, active_versions, latest_inv_id, monitor_settings
|
|
1131
|
+
)
|
|
1132
|
+
changes = _fetch_schema_changes(adapter, resolved_schema, active_versions, latest_inv_id)
|
|
1133
|
+
runs = _fetch_model_runs(adapter, resolved_schema, active_versions, latest_inv_id)
|
|
1134
|
+
in_scope_ids = {r.invocation_id for r in scoped} | {
|
|
1135
|
+
run.invocation_id for run_list in runs.values() for run in run_list
|
|
1136
|
+
}
|
|
1137
|
+
invocations = _fetch_invocations(adapter, resolved_schema, environment, in_scope_ids)
|
|
1138
|
+
|
|
1139
|
+
samples_map = _fetch_samples(
|
|
1140
|
+
adapter,
|
|
1141
|
+
resolved_schema,
|
|
1142
|
+
[r.invocation_id for r in scoped if r.status == "fail"],
|
|
1143
|
+
)
|
|
1144
|
+
hydrated = [
|
|
1145
|
+
AuditRecord(
|
|
1146
|
+
invocation_id=r.invocation_id,
|
|
1147
|
+
model_name=r.model_name,
|
|
1148
|
+
snapshot_id=r.snapshot_id,
|
|
1149
|
+
version=r.version,
|
|
1150
|
+
physical_table=r.physical_table,
|
|
1151
|
+
environment=r.environment,
|
|
1152
|
+
audit_name=r.audit_name,
|
|
1153
|
+
args_json=r.args_json,
|
|
1154
|
+
interval_start=r.interval_start,
|
|
1155
|
+
interval_end=r.interval_end,
|
|
1156
|
+
status=r.status,
|
|
1157
|
+
violation_count=r.violation_count,
|
|
1158
|
+
blocking=r.blocking,
|
|
1159
|
+
query_sql=r.query_sql,
|
|
1160
|
+
error_message=r.error_message,
|
|
1161
|
+
started_at=r.started_at,
|
|
1162
|
+
samples=samples_map.get(
|
|
1163
|
+
(r.invocation_id, r.model_name, r.audit_name, r.interval_start), ()
|
|
1164
|
+
),
|
|
1165
|
+
)
|
|
1166
|
+
for r in scoped
|
|
1167
|
+
]
|
|
1168
|
+
finally:
|
|
1169
|
+
adapter.close()
|
|
1170
|
+
|
|
1171
|
+
# Owner and columns for models that ran but whose snapshot is not in the environment.
|
|
1172
|
+
known = state_info.owners if state_info else {}
|
|
1173
|
+
wanted: t.Dict[str, str] = {}
|
|
1174
|
+
for model_name, run_list in runs.items():
|
|
1175
|
+
for run in run_list: # oldest first: the newest snapshot that ran wins
|
|
1176
|
+
if run.snapshot_id:
|
|
1177
|
+
wanted[model_name] = run.snapshot_id
|
|
1178
|
+
for record in hydrated:
|
|
1179
|
+
if record.snapshot_id and record.model_name not in wanted:
|
|
1180
|
+
wanted[record.model_name] = record.snapshot_id
|
|
1181
|
+
wanted = {name: sid for name, sid in wanted.items() if name not in known}
|
|
1182
|
+
extra_owners, extra_columns = _hydrate_snapshots(config, resolved_gateway, wanted)
|
|
1183
|
+
|
|
1184
|
+
return _build_report_data(
|
|
1185
|
+
hydrated,
|
|
1186
|
+
state_info=state_info,
|
|
1187
|
+
environment=environment,
|
|
1188
|
+
schema=resolved_schema,
|
|
1189
|
+
gateway=resolved_gateway,
|
|
1190
|
+
metrics=metric_series,
|
|
1191
|
+
schema_changes=changes,
|
|
1192
|
+
runs=runs,
|
|
1193
|
+
extra_owners=extra_owners,
|
|
1194
|
+
extra_columns=extra_columns,
|
|
1195
|
+
invocations=invocations,
|
|
1196
|
+
monitors=_configured_monitors(monitor_settings),
|
|
1197
|
+
)
|