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,103 @@
1
+ """Macros used by the shipped anomaly audits.
2
+
3
+ ``sqlmesh-observe init-audits`` copies this file verbatim to
4
+ ``<project>/macros/observability_audits.py``, so it must stay self-contained: it imports only
5
+ SQLMesh and sqlglot.
6
+
7
+ Why macros: no single SQL spelling of "date plus N days" or "date difference in days" parses the
8
+ same way across DuckDB, Snowflake, BigQuery, Postgres, Trino, and others. The audit's interval
9
+ bounds and execution time are literals at render time, so the date arithmetic is done here and the
10
+ audit SQL only sees ``CAST('YYYY-MM-DD' AS DATE)`` / ``CAST('YYYY-MM-DD HH:MM:SS' AS TIMESTAMP)``
11
+ literals, which every engine accepts.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import datetime
17
+ import functools
18
+ import typing as t
19
+
20
+ from sqlglot import exp
21
+ from sqlmesh import macro
22
+
23
+ OBS_MAX_SPINE_DAYS = 10_000
24
+
25
+
26
+ def _obs_text(value: t.Any) -> str:
27
+ return value.name if isinstance(value, exp.Expression) else str(value)
28
+
29
+
30
+ def _obs_date(value: t.Any) -> datetime.date:
31
+ from sqlmesh.utils.date import to_datetime
32
+
33
+ return to_datetime(_obs_text(value)).date()
34
+
35
+
36
+ def _obs_int(value: t.Any) -> int:
37
+ return int(float(_obs_text(value)))
38
+
39
+
40
+ def _obs_date_literal(day: datetime.date) -> exp.Expression:
41
+ return exp.cast(exp.Literal.string(day.isoformat()), exp.DataType.build("DATE"))
42
+
43
+
44
+ @macro()
45
+ def obs_days_before(evaluator: t.Any, day: t.Any, days: t.Any) -> exp.Expression:
46
+ """``@obs_days_before(@start_ds, 14)`` -> ``CAST('<start_ds - 14 days>' AS DATE)``."""
47
+ return _obs_date_literal(_obs_date(day) - datetime.timedelta(days=_obs_int(days)))
48
+
49
+
50
+ @macro()
51
+ def obs_day_spine(
52
+ evaluator: t.Any, start_ds: t.Any, end_ds: t.Any, training_days: t.Any
53
+ ) -> exp.Query:
54
+ """One row per day, column ``bucket``, from ``start_ds - training_days`` to ``end_ds``."""
55
+ first = _obs_date(start_ds) - datetime.timedelta(days=_obs_int(training_days))
56
+ last = _obs_date(end_ds)
57
+ count = (last - first).days + 1
58
+ if count < 1 or count > OBS_MAX_SPINE_DAYS:
59
+ raise ValueError(
60
+ f"obs_day_spine: {count} days from {first} to {last}; "
61
+ f"expected 1..{OBS_MAX_SPINE_DAYS}. Use a smaller batch_size or training_days."
62
+ )
63
+ selects: t.List[exp.Query] = [
64
+ exp.select(_obs_date_literal(first + datetime.timedelta(days=offset)).as_("bucket"))
65
+ for offset in range(count)
66
+ ]
67
+ return functools.reduce(lambda left, right: exp.union(left, right, distinct=False), selects)
68
+
69
+
70
+ @macro()
71
+ def obs_freshness_cutoff(
72
+ evaluator: t.Any, execution_ts: t.Any, end_ts: t.Any, hours: t.Any
73
+ ) -> exp.Expression:
74
+ """``min(execution_ts, end_ts) - hours`` as a ``CAST('…' AS TIMESTAMP)`` literal."""
75
+ from sqlmesh.utils.date import to_datetime
76
+
77
+ reference = min(to_datetime(_obs_text(execution_ts)), to_datetime(_obs_text(end_ts)))
78
+ cutoff = reference - datetime.timedelta(hours=_obs_int(hours))
79
+ text = cutoff.replace(tzinfo=None).isoformat(sep=" ", timespec="microseconds")
80
+ return exp.cast(exp.Literal.string(text), exp.DataType.build("TIMESTAMP"))
81
+
82
+
83
+ OBS_COLUMN_METRICS = ("null_rate", "mean")
84
+
85
+
86
+ @macro()
87
+ def obs_column_metric(evaluator: t.Any, column: t.Any, metric: t.Any) -> exp.Expr:
88
+ """Per-bucket aggregate for ``column_anomaly``.
89
+
90
+ ``null_rate`` -> share of rows where the column is null (0 to 1).
91
+ ``mean`` -> average of the non-null values (``NULL`` when all are null).
92
+ """
93
+ name = _obs_text(metric).lower()
94
+ double = exp.DataType.build("DOUBLE")
95
+ target = column if isinstance(column, exp.Expression) else exp.column(str(column))
96
+ if name == "null_rate":
97
+ nulls = exp.Sub(this=exp.func("COUNT", exp.Star()), expression=exp.func("COUNT", target))
98
+ return exp.Div(this=exp.cast(nulls, double), expression=exp.func("COUNT", exp.Star()))
99
+ if name == "mean":
100
+ return exp.func("AVG", exp.cast(target, double))
101
+ raise ValueError(
102
+ f"column_anomaly: unknown metric {name!r}; use one of {', '.join(OBS_COLUMN_METRICS)}"
103
+ )
@@ -0,0 +1,96 @@
1
+ /*
2
+ volume_anomaly: flags days whose row count deviates from recent history.
3
+
4
+ Shipped by sqlmesh-observability; copy with `sqlmesh-observe init-audits`, which also copies the
5
+ macros it uses (macros/observability_audits.py).
6
+
7
+ audits (volume_anomaly(time_column := ds, source := analytics.orders))
8
+
9
+ time_column column whose date defines the daily bucket
10
+ source the audited model itself. A named model resolves to the same version's physical
11
+ table, unfiltered; @this_model would only contain the processed interval.
12
+ training_days days before the processed interval used as history (default 14)
13
+ min_buckets minimum days of real history, counted from the first day present in source;
14
+ with fewer, nothing is flagged (default 7)
15
+ threshold flag when |count - mean| > threshold * sample stddev (default 3). With
16
+ zero-variance history, any change is flagged.
17
+ spike_failure_percent_threshold
18
+ ignore spikes smaller than this percent of the training mean: a day above the
19
+ mean is flagged only if count > (1 + pct / 100) * mean (default NULL, off)
20
+ drop_failure_percent_threshold
21
+ ignore drops smaller than this percent: a day below the mean is flagged only if
22
+ count < (1 - pct / 100) * mean (default NULL, off)
23
+ These two match Elementary's ignore_small_changes. Each applies only in its own
24
+ direction.
25
+
26
+ Returns one row per flagged day in the processed interval. Days with no rows count as 0.
27
+ No dialect is set: the query parses in the project's dialect, and all date arithmetic is done by
28
+ the macros at render time, so the SQL is portable.
29
+ */
30
+ AUDIT (
31
+ name volume_anomaly,
32
+ blocking false,
33
+ defaults (
34
+ training_days = 14,
35
+ min_buckets = 7,
36
+ threshold = 3,
37
+ spike_failure_percent_threshold = NULL,
38
+ drop_failure_percent_threshold = NULL
39
+ )
40
+ );
41
+
42
+ WITH spine AS (
43
+ SELECT bucket
44
+ FROM (@obs_day_spine(@start_ds, @end_ds, @training_days)) AS days
45
+ ), history AS (
46
+ SELECT MIN(CAST(@time_column AS DATE)) AS first_bucket
47
+ FROM @source
48
+ ), counts AS (
49
+ SELECT CAST(@time_column AS DATE) AS bucket, COUNT(*) AS row_count
50
+ FROM @source
51
+ WHERE CAST(@time_column AS DATE) BETWEEN @obs_days_before(@start_ds, @training_days)
52
+ AND CAST(@end_ds AS DATE)
53
+ GROUP BY CAST(@time_column AS DATE)
54
+ ), series AS (
55
+ SELECT spine.bucket, COALESCE(counts.row_count, 0) AS row_count
56
+ FROM spine
57
+ LEFT JOIN counts
58
+ ON spine.bucket = counts.bucket
59
+ ), training AS (
60
+ SELECT
61
+ COUNT(*) AS training_buckets,
62
+ AVG(series.row_count) AS mean_row_count,
63
+ COALESCE(STDDEV_SAMP(series.row_count), 0) AS stddev_row_count
64
+ FROM series
65
+ CROSS JOIN history
66
+ WHERE series.bucket < CAST(@start_ds AS DATE)
67
+ AND series.bucket >= history.first_bucket
68
+ )
69
+ SELECT
70
+ series.bucket,
71
+ series.row_count,
72
+ training.mean_row_count,
73
+ training.stddev_row_count,
74
+ (series.row_count - training.mean_row_count) / NULLIF(training.stddev_row_count, 0) AS z_score,
75
+ training.training_buckets
76
+ FROM series
77
+ CROSS JOIN training
78
+ WHERE series.bucket >= CAST(@start_ds AS DATE)
79
+ AND training.training_buckets >= @min_buckets
80
+ AND ABS(series.row_count - training.mean_row_count) > @threshold * training.stddev_row_count
81
+ AND (
82
+ (
83
+ series.row_count >= training.mean_row_count
84
+ AND (
85
+ @spike_failure_percent_threshold IS NULL
86
+ OR series.row_count > (1 + @spike_failure_percent_threshold / 100.0) * training.mean_row_count
87
+ )
88
+ )
89
+ OR (
90
+ series.row_count < training.mean_row_count
91
+ AND (
92
+ @drop_failure_percent_threshold IS NULL
93
+ OR series.row_count < (1 - @drop_failure_percent_threshold / 100.0) * training.mean_row_count
94
+ )
95
+ )
96
+ )
@@ -0,0 +1,173 @@
1
+ """``sqlmesh-observe`` command line entry point.
2
+
3
+ Commands: ``init-audits``, ``report``, ``serve``, and ``monitor``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import sys
10
+ import typing as t
11
+
12
+
13
+ def _init_audits(args: argparse.Namespace) -> int:
14
+ from sqlmesh_observability.audits import copy_audits
15
+
16
+ try:
17
+ written = copy_audits(args.path, force=args.force)
18
+ except FileExistsError as error:
19
+ print(f"sqlmesh-observe: {error}", file=sys.stderr)
20
+ return 1
21
+ for path in written:
22
+ print(f"wrote {path}")
23
+ if not written:
24
+ print("audits are up to date")
25
+ return 0
26
+
27
+
28
+ def _report(args: argparse.Namespace) -> int:
29
+ from sqlmesh_observability.reader import MissingAuditTableError, load_report_data
30
+ from sqlmesh_observability.report import write_report
31
+
32
+ try:
33
+ data = load_report_data(
34
+ path=args.path,
35
+ gateway=args.gateway,
36
+ schema=args.schema,
37
+ environment=args.environment,
38
+ )
39
+ except MissingAuditTableError as error:
40
+ print(f"sqlmesh-observe: {error}", file=sys.stderr)
41
+ return 1
42
+
43
+ if not data.state_available:
44
+ print(
45
+ f"sqlmesh-observe: SQLMesh state for environment '{data.environment}' could not be "
46
+ "read; the report shows only the latest invocation that targeted it.",
47
+ file=sys.stderr,
48
+ )
49
+ written = write_report(data, args.output, history=args.history)
50
+ print(f"wrote {written}")
51
+ return 0
52
+
53
+
54
+ def _serve(args: argparse.Namespace) -> int:
55
+ from sqlmesh_observability.app import SERVE_EXTRA_HINT, create_app
56
+
57
+ try:
58
+ import uvicorn
59
+
60
+ app = create_app(
61
+ path=args.path,
62
+ gateway=args.gateway,
63
+ schema=args.schema,
64
+ environment=args.environment,
65
+ history=args.history,
66
+ )
67
+ except ImportError:
68
+ print(f"sqlmesh-observe: {SERVE_EXTRA_HINT}", file=sys.stderr)
69
+ return 1
70
+ uvicorn.run(app, host=args.host, port=args.port)
71
+ return 0
72
+
73
+
74
+ def _monitor(args: argparse.Namespace) -> int:
75
+ from sqlmesh_observability.alerts import run_monitor
76
+ from sqlmesh_observability.reader import MissingAuditTableError
77
+
78
+ try:
79
+ return run_monitor(
80
+ path=args.path,
81
+ gateway=args.gateway,
82
+ schema=args.schema,
83
+ environment=args.environment,
84
+ )
85
+ except MissingAuditTableError as error:
86
+ print(f"sqlmesh-observe: {error}", file=sys.stderr)
87
+ return 1
88
+
89
+
90
+ def _add_source_options(command: argparse.ArgumentParser) -> None:
91
+ """The options every read-side command shares: where the log is and which environment."""
92
+ command.add_argument(
93
+ "--path", default=".", help="Directory containing config.py (model files are not required)."
94
+ )
95
+ command.add_argument(
96
+ "--gateway",
97
+ default=None,
98
+ help="Gateway holding observability tables (defaults to install() or default_gateway).",
99
+ )
100
+ command.add_argument(
101
+ "--schema",
102
+ default=None,
103
+ help="Observability schema (defaults to install() schema or 'observability').",
104
+ )
105
+ command.add_argument(
106
+ "--environment",
107
+ default="prod",
108
+ help="Target environment to scope to (default: prod).",
109
+ )
110
+
111
+
112
+ def _add_history_option(command: argparse.ArgumentParser) -> None:
113
+ from sqlmesh_observability.payload import DEFAULT_HISTORY
114
+
115
+ command.add_argument(
116
+ "--history",
117
+ type=int,
118
+ default=DEFAULT_HISTORY,
119
+ help=f"Intervals of history to keep per model and metric (default: {DEFAULT_HISTORY}).",
120
+ )
121
+
122
+
123
+ def _parser() -> argparse.ArgumentParser:
124
+ parser = argparse.ArgumentParser(prog="sqlmesh-observe")
125
+ commands = parser.add_subparsers(dest="command", required=True)
126
+
127
+ init_audits = commands.add_parser(
128
+ "init-audits", help="Copy the package audits into the project's audits/ directory."
129
+ )
130
+ init_audits.add_argument("--path", default=".", help="SQLMesh project directory.")
131
+ init_audits.add_argument(
132
+ "--force", action="store_true", help="Overwrite audit files that differ."
133
+ )
134
+ init_audits.set_defaults(handler=_init_audits)
135
+
136
+ report = commands.add_parser(
137
+ "report", help="Generate a self-contained static HTML observability report."
138
+ )
139
+ _add_source_options(report)
140
+ _add_history_option(report)
141
+ report.add_argument(
142
+ "-o",
143
+ "--output",
144
+ default="report.html",
145
+ help="Output HTML file path (default: report.html).",
146
+ )
147
+ report.set_defaults(handler=_report)
148
+
149
+ serve = commands.add_parser(
150
+ "serve", help="Serve the report as a read-only web app (needs the [serve] extra)."
151
+ )
152
+ _add_source_options(serve)
153
+ _add_history_option(serve)
154
+ serve.add_argument("--host", default="127.0.0.1", help="Bind address (default: 127.0.0.1).")
155
+ serve.add_argument("--port", type=int, default=8000, help="Port (default: 8000).")
156
+ serve.set_defaults(handler=_serve)
157
+
158
+ monitor = commands.add_parser(
159
+ "monitor",
160
+ help="Send one grouped message per owner for new prod audit failures and anomalies.",
161
+ )
162
+ _add_source_options(monitor)
163
+ monitor.set_defaults(handler=_monitor)
164
+ return parser
165
+
166
+
167
+ def main(argv: t.Optional[t.Sequence[str]] = None) -> int:
168
+ args = _parser().parse_args(argv)
169
+ return int(args.handler(args))
170
+
171
+
172
+ def entrypoint() -> None:
173
+ sys.exit(main())