-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics_quality.py
More file actions
96 lines (76 loc) · 2.95 KB
/
analytics_quality.py
File metadata and controls
96 lines (76 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from __future__ import annotations
import sqlite3
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
DB_PATH = Path("autoops.db")
def get_conn(db_path: str | Path = DB_PATH) -> sqlite3.Connection:
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
return conn
def _table_exists(conn: sqlite3.Connection, name: str) -> bool:
row = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
(name,),
).fetchone()
return row is not None
def _load_rows(conn: sqlite3.Connection) -> tuple[str | None, list[sqlite3.Row]]:
for table in ["analyses", "incident_history", "analysis_history", "history", "incidents"]:
if _table_exists(conn, table):
return table, conn.execute(f"SELECT * FROM {table} ORDER BY id DESC").fetchall()
return None, []
def validate_data_quality(db_path: str | Path = DB_PATH) -> dict[str, Any]:
conn = get_conn(db_path)
table, rows = _load_rows(conn)
if not table:
conn.close()
return {"error": "no source history table found"}
actual_cols = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
required_cols = {"id"}
missing_cols = sorted(required_cols - actual_cols)
missing_required = 0
duplicates = 0
stale_rows = 0
outlier_flags = 0
seen = set()
now = datetime.now(timezone.utc)
for row in rows:
row_id = row["id"] if "id" in row.keys() else None
if row_id is None:
missing_required += 1
signature = tuple((k, row[k]) for k in row.keys() if k in {"id", "timestamp", "created_at", "event_type", "failure_family"})
if signature in seen:
duplicates += 1
seen.add(signature)
timestamp = None
for key in ["timestamp", "created_at", "event_time"]:
if key in row.keys() and row[key]:
timestamp = str(row[key])
break
if timestamp:
try:
ts = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
if now - ts > timedelta(days=7):
stale_rows += 1
except Exception:
stale_rows += 1
if "confidence" in row.keys() and row["confidence"] is not None:
try:
c = float(row["confidence"])
if c < 0.0 or c > 1.0:
outlier_flags += 1
except Exception:
outlier_flags += 1
conn.close()
return {
"table": table,
"rows_checked": len(rows),
"missing_required": missing_required,
"duplicates": duplicates,
"stale_rows": stale_rows,
"outlier_flags": outlier_flags,
"schema_issues": {"missing_columns": missing_cols},
"anomaly_summary": {
"has_issues": bool(missing_required or duplicates or stale_rows or outlier_flags or missing_cols)
},
}