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,463 @@
1
+ """Turns SQLMesh execution observations into plain per-invocation records.
2
+
3
+ The collector never touches the warehouse. Observer callbacks copy plain values and return; a
4
+ finished :class:`Invocation` is handed to the writer that ``install()`` configured, which writes it
5
+ to the warehouse (``writer.py``). Tests may also keep finished invocations in memory.
6
+
7
+ Invocation boundaries:
8
+
9
+ * ``arm`` is called from the notification target's ``*_start`` hook with the environment and plan
10
+ id SQLMesh reports. A new ``arm`` replaces a stale slot (``Context.run`` sends no end hook when
11
+ there is nothing to do) and hands off any invocation still open as ``unfinished``.
12
+ * ``begin`` is called once per observer resolution, which SQLMesh does once per outer plan or run.
13
+ The first resolution under an armed slot mints the invocation; later ones under the same slot
14
+ reuse it (``Context.run`` restarting after ``CircuitBreakerError``).
15
+ * ``end`` is called from ``*_end`` / ``*_failure`` and hands the invocation off.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextvars
21
+ import dataclasses
22
+ import datetime
23
+ import json
24
+ import logging
25
+ import threading
26
+ import typing as t
27
+ import uuid
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ Status = t.Literal["success", "failure", "unfinished"]
32
+
33
+
34
+ @dataclasses.dataclass
35
+ class ModelRun:
36
+ """One model interval batch, from a ``model`` observation."""
37
+
38
+ invocation_id: str
39
+ model_name: str
40
+ snapshot_id: str
41
+ version: str
42
+ interval_start: t.Optional[int]
43
+ interval_end: t.Optional[int]
44
+ batch_index: t.Optional[int]
45
+ execution_time: t.Optional[int]
46
+ audit_only: bool
47
+ environment: t.Optional[str]
48
+ started_at: datetime.datetime
49
+ physical_table: t.Optional[str] = None
50
+ finished_at: t.Optional[datetime.datetime] = None
51
+ duration_ms: t.Optional[int] = None
52
+ status: t.Optional[str] = None
53
+ error_type: t.Optional[str] = None
54
+ error_message: t.Optional[str] = None
55
+ # Plain model metadata for passive monitors .
56
+ kind: t.Optional[str] = None
57
+ columns: t.Tuple[t.Tuple[str, str], ...] = ()
58
+ time_column: t.Optional[str] = None
59
+ time_column_format: t.Optional[str] = None
60
+ model_dialect: t.Optional[str] = None
61
+
62
+
63
+ @dataclasses.dataclass
64
+ class SchemaCapture:
65
+ """Declared columns of one snapshot, from a ``physical`` create or schema migration."""
66
+
67
+ invocation_id: str
68
+ model_name: str
69
+ snapshot_id: str
70
+ version: str
71
+ action: str
72
+ # Identifiers of the snapshots this one descends from, oldest first.
73
+ previous_snapshot_ids: t.Tuple[str, ...]
74
+ columns: t.Tuple[t.Tuple[str, str], ...]
75
+ recorded_at: datetime.datetime
76
+
77
+
78
+ @dataclasses.dataclass
79
+ class AuditRun:
80
+ """One audit of one model run, from an ``audit`` observation nested in a ``model`` one."""
81
+
82
+ invocation_id: str
83
+ audit_name: str
84
+ model_name: t.Optional[str]
85
+ snapshot_id: t.Optional[str]
86
+ version: t.Optional[str]
87
+ physical_table: t.Optional[str]
88
+ interval_start: t.Optional[int]
89
+ interval_end: t.Optional[int]
90
+ environment: t.Optional[str]
91
+ finished_at: datetime.datetime
92
+ status: str = "pass"
93
+ violation_count: t.Optional[int] = None
94
+ skipped: bool = False
95
+ blocking: t.Optional[bool] = None
96
+ args_json: t.Optional[str] = None
97
+ query_sql: t.Optional[str] = None
98
+ error_type: t.Optional[str] = None
99
+ error_message: t.Optional[str] = None
100
+
101
+
102
+ @dataclasses.dataclass
103
+ class Invocation:
104
+ """One outer SQLMesh plan application or scheduler run."""
105
+
106
+ invocation_id: str
107
+ command: t.Optional[str]
108
+ environment: t.Optional[str]
109
+ plan_id: t.Optional[str]
110
+ started_at: datetime.datetime
111
+ finished_at: t.Optional[datetime.datetime] = None
112
+ status: t.Optional[Status] = None
113
+ models: t.List[ModelRun] = dataclasses.field(default_factory=list)
114
+ audits: t.List[AuditRun] = dataclasses.field(default_factory=list)
115
+ schemas: t.List[SchemaCapture] = dataclasses.field(default_factory=list)
116
+
117
+
118
+ @dataclasses.dataclass
119
+ class _Slot:
120
+ command: str
121
+ environment: t.Optional[str]
122
+ plan_id: t.Optional[str]
123
+ invocation_id: t.Optional[str] = None
124
+
125
+
126
+ @dataclasses.dataclass
127
+ class _OpenModel:
128
+ record: ModelRun
129
+ token: t.Optional[contextvars.Token]
130
+
131
+
132
+ # The model run currently executing on this worker. SQLMesh calls the observer synchronously in the
133
+ # worker's context, so nested physical/audit observations see the value set at model start.
134
+ _current_model: contextvars.ContextVar[t.Optional[ModelRun]] = contextvars.ContextVar(
135
+ "sqlmesh_observability_current_model", default=None
136
+ )
137
+
138
+
139
+ def _now() -> datetime.datetime:
140
+ return datetime.datetime.now(datetime.timezone.utc)
141
+
142
+
143
+ def _error_fields(error: t.Optional[BaseException]) -> t.Tuple[t.Optional[str], t.Optional[str]]:
144
+ if error is None:
145
+ return None, None
146
+ return type(error).__name__, str(error)
147
+
148
+
149
+ def _to_ms(value: t.Any) -> t.Optional[int]:
150
+ if value is None:
151
+ return None
152
+ from sqlmesh.utils.date import to_timestamp
153
+
154
+ return int(to_timestamp(value))
155
+
156
+
157
+ class Collector:
158
+ """Process-wide collector shared by every wrapped console and notification target."""
159
+
160
+ def __init__(self) -> None:
161
+ self._lock = threading.RLock()
162
+ self._slot: t.Optional[_Slot] = None
163
+ self._open: t.Dict[str, Invocation] = {}
164
+ self._open_models: t.Dict[int, _OpenModel] = {}
165
+ self.finished: t.List[Invocation] = []
166
+ self.record_finished = False # test-only; a long-lived process must not grow this list
167
+ self.writer: t.Optional[t.Any] = None # sqlmesh_observability.writer.Writer
168
+ self.dialect: t.Optional[str] = None # dialect of the project's default gateway
169
+ self.settings: t.Dict[str, t.Any] = {}
170
+
171
+ # --- Boundaries (notification target and console wrap) --------------------------------------
172
+
173
+ def arm(self, command: str, environment: t.Optional[str], plan_id: t.Optional[str]) -> None:
174
+ with self._lock:
175
+ stale = list(self._open)
176
+ self._slot = _Slot(command=command, environment=environment, plan_id=plan_id)
177
+ for invocation_id in stale:
178
+ self._hand_off(invocation_id, "unfinished")
179
+
180
+ def begin(self) -> str:
181
+ with self._lock:
182
+ slot = self._slot
183
+ if slot is not None and slot.invocation_id in self._open:
184
+ return slot.invocation_id # type: ignore[return-value]
185
+ stale = list(self._open)
186
+ invocation = Invocation(
187
+ invocation_id=uuid.uuid4().hex,
188
+ command=slot.command if slot else None,
189
+ environment=slot.environment if slot else None,
190
+ plan_id=slot.plan_id if slot else None,
191
+ started_at=_now(),
192
+ )
193
+ self._open[invocation.invocation_id] = invocation
194
+ if slot is not None:
195
+ slot.invocation_id = invocation.invocation_id
196
+ for invocation_id in stale:
197
+ self._hand_off(invocation_id, "unfinished")
198
+ return invocation.invocation_id
199
+
200
+ def end(self, status: Status) -> None:
201
+ with self._lock:
202
+ slot, self._slot = self._slot, None
203
+ if slot is not None and slot.invocation_id is not None:
204
+ self._hand_off(slot.invocation_id, status)
205
+
206
+ def _hand_off(self, invocation_id: str, status: Status) -> None:
207
+ with self._lock:
208
+ invocation = self._open.pop(invocation_id, None)
209
+ if invocation is None:
210
+ return
211
+ invocation.status = status
212
+ invocation.finished_at = _now()
213
+ if self.record_finished:
214
+ self.finished.append(invocation)
215
+ writer = self.writer
216
+ if writer is not None:
217
+ try:
218
+ writer.submit_and_wait(invocation)
219
+ except Exception:
220
+ logger.debug("sqlmesh-observability writer hand-off failed", exc_info=True)
221
+
222
+ # --- Observations -----------------------------------------------------------------------------
223
+
224
+ def handle(
225
+ self,
226
+ invocation_id: str,
227
+ phase: str,
228
+ facts: t.Mapping[str, t.Any],
229
+ error: t.Optional[BaseException],
230
+ ) -> None:
231
+ kind = facts.get("kind")
232
+ if kind == "model":
233
+ if phase == "start":
234
+ self._model_start(invocation_id, facts)
235
+ else:
236
+ self._model_finish(facts, error)
237
+ elif phase != "finish":
238
+ return
239
+ elif kind == "physical":
240
+ physical_action = facts.get("action")
241
+ if physical_action == "materialize":
242
+ current = _current_model.get()
243
+ if current is not None and current.invocation_id == invocation_id:
244
+ target = facts.get("target")
245
+ current.physical_table = None if target is None else str(target)
246
+ if error is None and (
247
+ physical_action in ("create", "schema_migration")
248
+ or (physical_action == "materialize" and facts.get("creating"))
249
+ ):
250
+ self._capture_schema(invocation_id, str(physical_action), facts.get("snapshot"))
251
+ elif kind == "audit":
252
+ self._audit_finish(invocation_id, facts, error)
253
+ elif kind == "stage":
254
+ self._stage_finish(invocation_id, facts)
255
+
256
+ def _invocation(self, invocation_id: str) -> t.Optional[Invocation]:
257
+ with self._lock:
258
+ return self._open.get(invocation_id)
259
+
260
+ def _model_start(self, invocation_id: str, facts: t.Mapping[str, t.Any]) -> None:
261
+ invocation = self._invocation(invocation_id)
262
+ snapshot = facts.get("snapshot")
263
+ interval = facts.get("interval") or (None, None)
264
+ record = ModelRun(
265
+ invocation_id=invocation_id,
266
+ model_name=str(getattr(snapshot, "name", "")),
267
+ snapshot_id=str(getattr(snapshot, "identifier", "")),
268
+ version=str(getattr(snapshot, "version", "")),
269
+ interval_start=_to_ms(interval[0]),
270
+ interval_end=_to_ms(interval[1]),
271
+ batch_index=facts.get("batch_index"),
272
+ execution_time=_to_ms(facts.get("execution_time")),
273
+ audit_only=bool(facts.get("audit_only", False)),
274
+ environment=invocation.environment if invocation else None,
275
+ started_at=_now(),
276
+ )
277
+ self._copy_model_metadata(record, getattr(snapshot, "model", None))
278
+ token = _current_model.set(record)
279
+ with self._lock:
280
+ self._open_models[id(facts)] = _OpenModel(record=record, token=token)
281
+
282
+ def _columns(self, model: t.Any) -> t.Tuple[t.Tuple[str, str], ...]:
283
+ try:
284
+ columns = model.columns_to_types
285
+ except Exception:
286
+ return ()
287
+ if not columns:
288
+ return ()
289
+ return tuple(
290
+ (str(name), kind.sql(dialect=self.dialect) if hasattr(kind, "sql") else str(kind))
291
+ for name, kind in columns.items()
292
+ )
293
+
294
+ def _copy_model_metadata(self, record: ModelRun, model: t.Any) -> None:
295
+ """Copy plain strings the writer needs for passive monitors; ``model`` is not kept."""
296
+ if model is None:
297
+ return
298
+ try:
299
+ record.kind = str(model.kind.name.value)
300
+ record.columns = self._columns(model)
301
+ record.model_dialect = str(model.dialect) if model.dialect is not None else None
302
+ time_column = getattr(model, "time_column", None)
303
+ if time_column is not None:
304
+ record.time_column = str(time_column.column.name)
305
+ record.time_column_format = (
306
+ None if time_column.format is None else str(time_column.format)
307
+ )
308
+ except Exception:
309
+ logger.debug("sqlmesh-observability: could not copy model metadata", exc_info=True)
310
+
311
+ def _capture_schema(self, invocation_id: str, action: str, snapshot: t.Any) -> None:
312
+ invocation = self._invocation(invocation_id)
313
+ model = getattr(snapshot, "model", None)
314
+ if invocation is None or model is None:
315
+ return
316
+ try:
317
+ if getattr(snapshot, "is_symbolic", False):
318
+ return
319
+ columns = self._columns(model)
320
+ if not columns:
321
+ return
322
+ capture = SchemaCapture(
323
+ invocation_id=invocation_id,
324
+ model_name=str(snapshot.name),
325
+ snapshot_id=str(snapshot.identifier),
326
+ version=str(snapshot.version),
327
+ action=action,
328
+ previous_snapshot_ids=tuple(
329
+ str(v.fingerprint.to_identifier()) for v in snapshot.previous_versions
330
+ ),
331
+ columns=columns,
332
+ recorded_at=_now(),
333
+ )
334
+ except Exception:
335
+ logger.debug("sqlmesh-observability: could not capture schema", exc_info=True)
336
+ return
337
+ with self._lock:
338
+ invocation.schemas[:] = [
339
+ s for s in invocation.schemas if s.snapshot_id != capture.snapshot_id
340
+ ]
341
+ invocation.schemas.append(capture)
342
+
343
+ def _model_finish(self, facts: t.Mapping[str, t.Any], error: t.Optional[BaseException]) -> None:
344
+ with self._lock:
345
+ opened = self._open_models.pop(id(facts), None)
346
+ if opened is None:
347
+ return
348
+ record = opened.record
349
+ if opened.token is not None:
350
+ try:
351
+ _current_model.reset(opened.token)
352
+ except ValueError: # token from another context; never leave this worker pointing at it
353
+ _current_model.set(None)
354
+ record.finished_at = _now()
355
+ record.duration_ms = int((record.finished_at - record.started_at).total_seconds() * 1000)
356
+ record.status = "failure" if error is not None else "success"
357
+ record.error_type, record.error_message = _error_fields(error)
358
+ invocation = self._invocation(record.invocation_id)
359
+ if invocation is not None:
360
+ with self._lock:
361
+ invocation.models.append(record)
362
+
363
+ def _audit_finish(
364
+ self, invocation_id: str, facts: t.Mapping[str, t.Any], error: t.Optional[BaseException]
365
+ ) -> None:
366
+ invocation = self._invocation(invocation_id)
367
+ if invocation is None:
368
+ return
369
+ model = _current_model.get()
370
+ if model is not None and model.invocation_id != invocation_id:
371
+ model = None
372
+ error_type, error_message = _error_fields(error)
373
+ result = facts.get("audit_result")
374
+ if error is None and result is None:
375
+ error_type, error_message = "MissingAuditResult", "audit finished without a result"
376
+ record = AuditRun(
377
+ invocation_id=invocation_id,
378
+ audit_name=str(facts.get("audit_name", "")),
379
+ model_name=model.model_name if model else None,
380
+ snapshot_id=model.snapshot_id if model else None,
381
+ version=model.version if model else None,
382
+ physical_table=model.physical_table if model else None,
383
+ interval_start=model.interval_start if model else None,
384
+ interval_end=model.interval_end if model else None,
385
+ environment=invocation.environment,
386
+ finished_at=_now(),
387
+ error_type=error_type,
388
+ error_message=error_message,
389
+ )
390
+ if result is not None:
391
+ self._copy_audit_result(record, result)
392
+ record.status = _audit_status(record)
393
+ with self._lock:
394
+ invocation.audits.append(record)
395
+
396
+ def _copy_audit_result(self, record: AuditRun, result: t.Any) -> None:
397
+ """Copy plain values from a SQLMesh ``AuditResult``; the object itself is not kept."""
398
+ count = getattr(result, "count", None)
399
+ record.violation_count = None if count is None else int(count)
400
+ record.skipped = bool(getattr(result, "skipped", False))
401
+ blocking = getattr(result, "blocking", None)
402
+ record.blocking = None if blocking is None else bool(blocking)
403
+ record.args_json = _args_json(getattr(result, "audit_args", None) or {}, self.dialect)
404
+ query = getattr(result, "query", None)
405
+ if query is not None:
406
+ try:
407
+ record.query_sql = query.sql(dialect=self.dialect)
408
+ except Exception:
409
+ logger.debug("sqlmesh-observability: could not render audit SQL", exc_info=True)
410
+
411
+ def _stage_finish(self, invocation_id: str, facts: t.Mapping[str, t.Any]) -> None:
412
+ invocation = self._invocation(invocation_id)
413
+ if invocation is None:
414
+ return
415
+ with self._lock:
416
+ if invocation.command is None:
417
+ invocation.command = "plan"
418
+ if invocation.plan_id is None and facts.get("native_plan_id") is not None:
419
+ invocation.plan_id = str(facts["native_plan_id"])
420
+
421
+
422
+ def _audit_status(record: AuditRun) -> str:
423
+ """Worst status of an audit's results: error, then skip, then fail, otherwise pass."""
424
+ if record.error_type is not None:
425
+ return "error"
426
+ if record.skipped:
427
+ return "skip"
428
+ if record.violation_count:
429
+ return "fail"
430
+ return "pass"
431
+
432
+
433
+ def _args_json(args: t.Mapping[t.Any, t.Any], dialect: t.Optional[str]) -> str:
434
+ def text(value: t.Any) -> str:
435
+ sql = getattr(value, "sql", None)
436
+ if callable(sql):
437
+ try:
438
+ return str(sql(dialect=dialect))
439
+ except Exception:
440
+ pass
441
+ return str(value)
442
+
443
+ return json.dumps({str(k): text(v) for k, v in args.items()}, sort_keys=True)
444
+
445
+
446
+ _COLLECTOR = Collector()
447
+
448
+
449
+ def get_collector() -> Collector:
450
+ return _COLLECTOR
451
+
452
+
453
+ def _reset_for_tests() -> None:
454
+ """Drop all collector state and keep finished invocations in memory. Test-only."""
455
+ global _COLLECTOR
456
+ previous = _COLLECTOR
457
+ if previous.writer is not None:
458
+ try:
459
+ previous.writer.stop()
460
+ except Exception:
461
+ pass
462
+ _COLLECTOR = Collector()
463
+ _COLLECTOR.record_finished = True