intentdataflow 0.3.10__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.
- intentdataflow-0.3.10.dist-info/METADATA +191 -0
- intentdataflow-0.3.10.dist-info/RECORD +83 -0
- intentdataflow-0.3.10.dist-info/WHEEL +5 -0
- intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
- intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
- intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
- intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
- intentflow/__init__.py +2 -0
- intentflow/auth.py +30 -0
- intentflow/business_rules.py +77 -0
- intentflow/catalogs.py +100 -0
- intentflow/change_review.py +331 -0
- intentflow/checks/__init__.py +92 -0
- intentflow/checks/airflow3.py +174 -0
- intentflow/checks/business.py +27 -0
- intentflow/checks/catalog.py +43 -0
- intentflow/checks/cluster.py +81 -0
- intentflow/checks/contracts.py +79 -0
- intentflow/checks/cost.py +35 -0
- intentflow/checks/dbt_quality.py +90 -0
- intentflow/checks/dbt_run.py +83 -0
- intentflow/checks/deep.py +180 -0
- intentflow/checks/dq.py +53 -0
- intentflow/checks/elementary.py +50 -0
- intentflow/checks/external.py +91 -0
- intentflow/checks/lakehouse.py +46 -0
- intentflow/checks/lint.py +81 -0
- intentflow/checks/orchestration.py +148 -0
- intentflow/checks/probes.py +66 -0
- intentflow/checks/runtime_history.py +94 -0
- intentflow/checks/schema_drift.py +92 -0
- intentflow/checks/sql_quality.py +274 -0
- intentflow/checks/streaming.py +62 -0
- intentflow/cli.py +914 -0
- intentflow/contracts.py +107 -0
- intentflow/datadiff.py +172 -0
- intentflow/dbt_loader.py +194 -0
- intentflow/dbt_results.py +55 -0
- intentflow/dq_results.py +108 -0
- intentflow/extensions.py +51 -0
- intentflow/external.py +381 -0
- intentflow/http_utils.py +89 -0
- intentflow/i18n.py +76 -0
- intentflow/incidents.py +83 -0
- intentflow/integrations.py +139 -0
- intentflow/lakehouse.py +62 -0
- intentflow/lineage.py +336 -0
- intentflow/lineage_api.py +244 -0
- intentflow/lineage_oracle.py +374 -0
- intentflow/locale/pt.json +1300 -0
- intentflow/model.py +43 -0
- intentflow/monitoring.py +197 -0
- intentflow/notify.py +154 -0
- intentflow/ol_emit.py +93 -0
- intentflow/openlineage.py +168 -0
- intentflow/orchestrators/__init__.py +53 -0
- intentflow/orchestrators/airflow.py +69 -0
- intentflow/orchestrators/aws.py +93 -0
- intentflow/orchestrators/dagster.py +48 -0
- intentflow/orchestrators/dbtcloud.py +68 -0
- intentflow/orchestrators/extra.py +135 -0
- intentflow/orchestrators/ingestion.py +112 -0
- intentflow/orchestrators/kestra.py +27 -0
- intentflow/orchestrators/more.py +135 -0
- intentflow/orchestrators/prefect.py +53 -0
- intentflow/orchestrators/spark.py +118 -0
- intentflow/otel.py +53 -0
- intentflow/overview.py +123 -0
- intentflow/preflight.py +363 -0
- intentflow/promexport.py +39 -0
- intentflow/pyflow.py +554 -0
- intentflow/risks.py +178 -0
- intentflow/runner.py +264 -0
- intentflow/secrets_box.py +84 -0
- intentflow/sqlmesh_loader.py +134 -0
- intentflow/store.py +1006 -0
- intentflow/streaming.py +115 -0
- intentflow/totp.py +38 -0
- intentflow/warehouses/__init__.py +190 -0
- intentflow/warehouses/cloud.py +160 -0
- intentflow/warehouses/more.py +342 -0
- intentflow/web.html +878 -0
- intentflow/web.py +726 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Static lint of Airflow definitions (AST of DAG files) and Kestra definitions (flow YAML)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import ast
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from ..i18n import tr
|
|
12
|
+
from ..model import Finding
|
|
13
|
+
from . import Context, check
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _kw(call: ast.Call, name: str):
|
|
17
|
+
for k in call.keywords:
|
|
18
|
+
if k.arg == name:
|
|
19
|
+
return k.value
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _lit(node):
|
|
24
|
+
try:
|
|
25
|
+
return ast.literal_eval(node)
|
|
26
|
+
except Exception:
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _date_of(node):
|
|
31
|
+
if isinstance(node, ast.Call) and node.args and all(isinstance(a, ast.Constant) and isinstance(a.value, int) for a in node.args[:3]):
|
|
32
|
+
try:
|
|
33
|
+
return dt.date(*[a.value for a in node.args[:3]])
|
|
34
|
+
except Exception:
|
|
35
|
+
return None
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _airflow_file(path: Path):
|
|
40
|
+
src = path.read_text(errors="replace")
|
|
41
|
+
try:
|
|
42
|
+
tree = ast.parse(src)
|
|
43
|
+
except SyntaxError as e:
|
|
44
|
+
return [Finding("AF000", "high", tr("{file}: syntax error", file=path.name), str(e), [str(path)], "pre-merge")]
|
|
45
|
+
out = []
|
|
46
|
+
names = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)} | {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
|
|
47
|
+
kws = {k.arg for n in ast.walk(tree) if isinstance(n, ast.Call) for k in n.keywords}
|
|
48
|
+
dict_keys = {k.value for n in ast.walk(tree) if isinstance(n, ast.Dict) for k in n.keys if isinstance(k, ast.Constant)}
|
|
49
|
+
has = lambda k: k in kws or k in dict_keys # noqa: E731
|
|
50
|
+
dag_calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)
|
|
51
|
+
and (getattr(n.func, "id", "") in ("DAG", "dag") or getattr(n.func, "attr", "") in ("DAG", "dag"))]
|
|
52
|
+
if not dag_calls and "DAG" not in names and "dag" not in names:
|
|
53
|
+
return []
|
|
54
|
+
ref = [str(path)]
|
|
55
|
+
where = path.name
|
|
56
|
+
if not has("retries"):
|
|
57
|
+
out.append(Finding("AF001", "medium", tr("{file}: no retries", file=where), tr("A transient failure (network, throttling) brings the whole run down."), ref, "pre-merge",
|
|
58
|
+
{"recommendation": "default_args={'retries': 2, 'retry_delay': timedelta(minutes=5)}"}))
|
|
59
|
+
if not (has("execution_timeout") or has("dagrun_timeout")):
|
|
60
|
+
out.append(Finding("AF002", "medium", tr("{file}: no timeout", file=where),
|
|
61
|
+
tr("A stuck task holds a slot/worker forever and can exhaust memory and the pool."), ref, "pre-merge",
|
|
62
|
+
{"recommendation": tr("set execution_timeout on the tasks and dagrun_timeout on the DAG")}))
|
|
63
|
+
for c in dag_calls:
|
|
64
|
+
catchup = _kw(c, "catchup")
|
|
65
|
+
start = _date_of(_kw(c, "start_date"))
|
|
66
|
+
sched = _kw(c, "schedule") or _kw(c, "schedule_interval")
|
|
67
|
+
explicit_false = isinstance(catchup, ast.Constant) and catchup.value is False
|
|
68
|
+
if start and not explicit_false and sched is not None and (dt.date.today() - start).days > 30:
|
|
69
|
+
out.append(Finding("AF003", "high", tr("{file}: catchup on with start_date {date}", file=where, date=start),
|
|
70
|
+
tr("When unpaused, Airflow creates one run for each interval since start_date (backfill storm; memory and cost peak)."),
|
|
71
|
+
ref, "pre-merge", {"start_date": str(start), "recommendation": tr("catchup=False or a recent start_date + max_active_runs")}))
|
|
72
|
+
if _kw(c, "max_active_runs") is None:
|
|
73
|
+
out.append(Finding("AF004", "medium", tr("{file}: catchup without max_active_runs", file=where),
|
|
74
|
+
tr("Without a limit, the backfill runs execute in parallel."), ref, "pre-merge", {"recommendation": "max_active_runs=1..3"}))
|
|
75
|
+
if _kw(c, "schedule_interval") is not None:
|
|
76
|
+
out.append(Finding("AF006", "low", tr("{file}: `schedule_interval` is deprecated", file=where), tr("Removed in Airflow 3; use `schedule`."), ref, "pre-merge"))
|
|
77
|
+
if not (has("on_failure_callback") or has("email_on_failure") or has("email")):
|
|
78
|
+
out.append(Finding("AF005", "low", tr("{file}: no failure notification", file=where), tr("Failures are only seen when someone opens the UI."), ref, "continuous"))
|
|
79
|
+
for imp in ast.walk(tree):
|
|
80
|
+
mod = getattr(imp, "module", "") if isinstance(imp, ast.ImportFrom) else ""
|
|
81
|
+
if mod in ("airflow.operators.bash_operator", "airflow.operators.python_operator", "airflow.operators.dummy_operator") \
|
|
82
|
+
or (isinstance(imp, ast.ImportFrom) and any(a.name == "days_ago" for a in imp.names)):
|
|
83
|
+
out.append(Finding("AF006", "low", tr("{file}: deprecated import ({module})", file=where, module=mod or "days_ago"),
|
|
84
|
+
tr("It will be removed in newer Airflow versions."), ref, "pre-merge"))
|
|
85
|
+
break
|
|
86
|
+
for stmt in tree.body: # module-level code runs on every scheduler parse
|
|
87
|
+
for n in ast.walk(stmt) if not isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) else []:
|
|
88
|
+
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr == "get" \
|
|
89
|
+
and getattr(n.func.value, "id", "") == "Variable":
|
|
90
|
+
out.append(Finding("AF007", "medium", tr("{file}: Variable.get at module level", file=where),
|
|
91
|
+
tr("Runs on every DAG parse (every few seconds), querying the metadata database and slowing the scheduler down."),
|
|
92
|
+
ref, "pre-merge", {"recommendation": tr("use the Jinja template `{{ var.value.x }}` inside the tasks")}))
|
|
93
|
+
return out
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
SECRET = re.compile(r"(?i)[\w-]*(password|passwd|secret|token|api[_-]?key|access[_-]?key)\w*['\"]?\s*[:=]\s*['\"]?(?!\{\{)([^\s'\"{}]{6,})")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _kestra_file(path: Path):
|
|
101
|
+
try:
|
|
102
|
+
doc = yaml.safe_load(path.read_text())
|
|
103
|
+
except Exception as e:
|
|
104
|
+
return [Finding("KS000", "high", tr("{file}: invalid YAML", file=path.name), str(e)[:200], [str(path)], "pre-merge")]
|
|
105
|
+
if not isinstance(doc, dict) or "tasks" not in doc:
|
|
106
|
+
return []
|
|
107
|
+
fid = f"{doc.get('namespace', '?')}.{doc.get('id', path.stem)}"
|
|
108
|
+
ref = [fid]
|
|
109
|
+
out = []
|
|
110
|
+
tasks = doc.get("tasks") or []
|
|
111
|
+
if not doc.get("errors") and not doc.get("afterExecution"):
|
|
112
|
+
out.append(Finding("KS001", "medium", tr("{flow}: no error handling", flow=fid), tr("Without an `errors` block, failures raise no alert and do no cleanup."), ref, "pre-merge",
|
|
113
|
+
{"recommendation": tr("add `errors:` with a notification (Slack/e-mail)")}))
|
|
114
|
+
risky = [t for t in tasks if any(k in str(t.get("type", "")).lower() for k in ("http", "jdbc", "dbt", "script", "shell", "bigquery", "snowflake", "sql"))]
|
|
115
|
+
if risky and not any(t.get("retry") for t in risky):
|
|
116
|
+
out.append(Finding("KS002", "low", tr("{flow}: I/O tasks without retry", flow=fid), tr("Transient network/warehouse failures bring the flow down."), ref, "pre-merge"))
|
|
117
|
+
if tasks and not any(t.get("timeout") for t in tasks) and not doc.get("timeout"):
|
|
118
|
+
out.append(Finding("KS003", "low", tr("{flow}: no timeout", flow=fid), tr("A stuck execution keeps a worker busy."), ref, "pre-merge"))
|
|
119
|
+
scheduled = [t for t in (doc.get("triggers") or []) if "schedule" in str(t.get("type", "")).lower()]
|
|
120
|
+
if scheduled and not doc.get("concurrency"):
|
|
121
|
+
out.append(Finding("KS004", "medium", tr("{flow}: scheduled without a concurrency limit", flow=fid),
|
|
122
|
+
tr("If one execution runs late, the next ones pile up in parallel (memory and resource contention)."), ref, "pre-merge",
|
|
123
|
+
{"recommendation": "concurrency: {limit: 1, behavior: QUEUE|CANCEL}"}))
|
|
124
|
+
for t in scheduled:
|
|
125
|
+
bf = (t.get("backfill") or {}).get("start")
|
|
126
|
+
if bf and str(bf)[:4].isdigit() and int(str(bf)[:4]) < dt.date.today().year - 1:
|
|
127
|
+
out.append(Finding("KS006", "medium", tr("{flow}: backfill since {date}", flow=fid, date=bf), tr("Creates one execution per interval since the start date."), ref, "pre-merge"))
|
|
128
|
+
raw = path.read_text()
|
|
129
|
+
m = SECRET.search(raw)
|
|
130
|
+
if m:
|
|
131
|
+
out.append(Finding("KS005", "high", tr("{flow}: possible plain-text secret ({kind})", flow=fid, kind=m.group(1)),
|
|
132
|
+
tr("Credentials in the YAML leak through git and the UI."), ref, "pre-merge", {"recommendation": "use `{{ secret('NAME') }}`"}))
|
|
133
|
+
if doc.get("disabled") is True:
|
|
134
|
+
out.append(Finding("KS007", "info", tr("{flow}: flow disabled", flow=fid), "", ref, "continuous"))
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@check("ORC001", "Lint of Airflow/Kestra definitions", stage="pre-merge",
|
|
139
|
+
emits=tuple(f"AF00{i}" for i in range(8)) + tuple(f"KS00{i}" for i in range(8)))
|
|
140
|
+
def orchestration_lint(ctx: Context):
|
|
141
|
+
out = []
|
|
142
|
+
if ctx.airflow_dags_dir:
|
|
143
|
+
for p in sorted(Path(ctx.airflow_dags_dir).rglob("*.py")):
|
|
144
|
+
out.extend(_airflow_file(p))
|
|
145
|
+
if ctx.kestra_flows_dir:
|
|
146
|
+
for p in sorted(list(Path(ctx.kestra_flows_dir).rglob("*.yml")) + list(Path(ctx.kestra_flows_dir).rglob("*.yaml"))):
|
|
147
|
+
out.extend(_kestra_file(p))
|
|
148
|
+
return out
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Warehouse probes (read-only): duplicated keys and volume anomalies."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import statistics
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from ..i18n import tr
|
|
8
|
+
from ..model import Finding
|
|
9
|
+
from . import Context, check
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _rel(n):
|
|
13
|
+
return n.relation
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@check("PRB001", "Duplicated key (probe)", stage="pre-run", cost="probe")
|
|
17
|
+
def duplicate_keys(ctx: Context):
|
|
18
|
+
if ctx.warehouse is None:
|
|
19
|
+
return []
|
|
20
|
+
out = []
|
|
21
|
+
for uid, n in ctx.project.nodes.items():
|
|
22
|
+
if n.resource_type not in ("model", "seed") or not n.relation:
|
|
23
|
+
continue
|
|
24
|
+
for t in n.tests:
|
|
25
|
+
if t["name"] != "unique" or not t.get("column"):
|
|
26
|
+
continue
|
|
27
|
+
col = t["column"]
|
|
28
|
+
try:
|
|
29
|
+
d = ctx.warehouse.scalar(f'select count(*) - count(distinct "{col}") from {n.relation} where "{col}" is not null')
|
|
30
|
+
except Exception as e:
|
|
31
|
+
out.append(Finding("PRB001", "info", tr("{column}: probe failed", column=f"{n.name}.{col}"), str(e)[:160], [uid], "pre-run"))
|
|
32
|
+
continue
|
|
33
|
+
if d and int(d) > 0:
|
|
34
|
+
out.append(Finding("PRB001", "critical" if ctx.project.downstream(uid) else "high",
|
|
35
|
+
tr("{column}: {n} duplicated row(s) on the key", column=f"{n.name}.{col}", n=int(d)),
|
|
36
|
+
tr("The key should be unique; consumers that join on it will multiply rows."), [uid] + ctx.project.downstream(uid)[:10],
|
|
37
|
+
"pre-run", {"duplicates": int(d)}))
|
|
38
|
+
return out
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@check("PRB002", "Volume anomaly (probe)", stage="pre-run", cost="probe")
|
|
42
|
+
def volume_anomaly(ctx: Context):
|
|
43
|
+
if ctx.warehouse is None or ctx.store is None:
|
|
44
|
+
return []
|
|
45
|
+
out = []
|
|
46
|
+
for uid, n in ctx.project.nodes.items():
|
|
47
|
+
if n.resource_type not in ("model", "seed") or not n.relation:
|
|
48
|
+
continue
|
|
49
|
+
try:
|
|
50
|
+
now_rows = int(ctx.warehouse.scalar(f"select count(*) from {n.relation}"))
|
|
51
|
+
except Exception:
|
|
52
|
+
continue
|
|
53
|
+
hist = [v for _, v in ctx.store.history(f"rows:{uid}")][-20:]
|
|
54
|
+
if ctx.record_probe_history:
|
|
55
|
+
ctx.store.add_history(f"rows:{uid}", time.time(), now_rows)
|
|
56
|
+
if len(hist) < 3:
|
|
57
|
+
if "PRB002" in ctx.required_checks:
|
|
58
|
+
ctx.failed_checks.add("PRB002")
|
|
59
|
+
continue
|
|
60
|
+
med = statistics.median(hist)
|
|
61
|
+
if med > 0 and (now_rows < 0.5 * med or now_rows > 2 * med):
|
|
62
|
+
out.append(Finding("PRB002", "high" if now_rows < 0.5 * med else "medium",
|
|
63
|
+
tr("{model}: {rows} rows vs median {median}", model=n.name, rows=now_rows, median=int(med)),
|
|
64
|
+
tr("Volume outside the historical pattern; partial or duplicated load or a broken upstream filter."),
|
|
65
|
+
[uid] + ctx.project.downstream(uid)[:10], "pre-run", {"rows": now_rows, "median": med, "history": len(hist)}))
|
|
66
|
+
return out
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Checks over the orchestrators' run history (recurring failures, duration regression)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import statistics
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
|
|
7
|
+
from ..i18n import tr
|
|
8
|
+
from ..model import Finding
|
|
9
|
+
from . import Context, check
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@check("RUN001", "Recurring failures", stage="continuous", cost="statistical")
|
|
13
|
+
def recurring_failures(ctx: Context):
|
|
14
|
+
by = defaultdict(list)
|
|
15
|
+
for r in ctx.runs:
|
|
16
|
+
by[(r.system, r.pipeline)].append(r)
|
|
17
|
+
out = []
|
|
18
|
+
for (sys_, pipe), rs in by.items():
|
|
19
|
+
rs.sort(key=lambda r: r.start or 0)
|
|
20
|
+
last = [r.state for r in rs[-5:]]
|
|
21
|
+
if len(rs) >= 3 and last[-3:] == ["failed"] * 3:
|
|
22
|
+
out.append(Finding("RUN001", "high", tr("{pipeline} failed in the last 3 runs", pipeline=f"{sys_}:{pipe}"),
|
|
23
|
+
tr("Persistent failure; re-running does not fix it. Look at the first failure of the sequence."), [f"{sys_}:{pipe}"], "continuous",
|
|
24
|
+
{"states": last, "url": rs[-1].url}))
|
|
25
|
+
return out
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@check("RUN002", "Duration regression", stage="continuous", cost="statistical")
|
|
29
|
+
def duration_regression(ctx: Context):
|
|
30
|
+
by = defaultdict(list)
|
|
31
|
+
for r in ctx.runs:
|
|
32
|
+
if r.state == "success" and r.duration:
|
|
33
|
+
by[(r.system, r.pipeline)].append(r)
|
|
34
|
+
out = []
|
|
35
|
+
for (sys_, pipe), rs in by.items():
|
|
36
|
+
rs.sort(key=lambda r: r.start or 0)
|
|
37
|
+
if len(rs) < 6:
|
|
38
|
+
continue
|
|
39
|
+
base = statistics.median(r.duration for r in rs[:-1][-10:])
|
|
40
|
+
if base > 0 and rs[-1].duration > 2 * base:
|
|
41
|
+
out.append(Finding("RUN002", "medium", tr("{pipeline} became {x}× slower", pipeline=f"{sys_}:{pipe}", x=f"{rs[-1].duration/base:.1f}"),
|
|
42
|
+
tr("The last run took more than twice the median: risk of breaking the SLA and of piling up concurrent runs."),
|
|
43
|
+
[f"{sys_}:{pipe}"], "continuous", {"last_s": rs[-1].duration, "median_s": base}))
|
|
44
|
+
return out
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@check("RUN003", "SLA at risk", stage="continuous", cost="statistical")
|
|
48
|
+
def sla_risk(ctx: Context):
|
|
49
|
+
"""Policy `sla.<system>:<pipeline>` = {minutes}. Compares p90 and the last duration with the deadline."""
|
|
50
|
+
out = []
|
|
51
|
+
by = defaultdict(list)
|
|
52
|
+
for r in ctx.runs:
|
|
53
|
+
if r.duration and r.state in ("success", "failed"):
|
|
54
|
+
by[f"{r.system}:{r.pipeline}"].append(r)
|
|
55
|
+
for name, rs in by.items():
|
|
56
|
+
sla = (ctx.policies.get(f"sla.{name}") or {}).get("minutes")
|
|
57
|
+
if not sla:
|
|
58
|
+
continue
|
|
59
|
+
rs.sort(key=lambda r: r.start or 0)
|
|
60
|
+
limit = float(sla) * 60
|
|
61
|
+
ds = sorted(r.duration for r in rs[-20:])
|
|
62
|
+
p90 = ds[min(len(ds) - 1, int(0.9 * len(ds)))]
|
|
63
|
+
if rs[-1].duration > limit:
|
|
64
|
+
out.append(Finding("RUN003", "high", tr("{pipeline}: last run ({minutes} min) broke the {sla} min SLA", pipeline=name,
|
|
65
|
+
minutes=f"{rs[-1].duration/60:.1f}", sla=f"{sla:g}"),
|
|
66
|
+
tr("Deadline already missed."), [name], "continuous", {"last_s": rs[-1].duration, "sla_s": limit}))
|
|
67
|
+
elif p90 > 0.8 * limit:
|
|
68
|
+
out.append(Finding("RUN003", "medium", tr("{pipeline}: p90 of {minutes} min uses {ratio} of the {sla} min SLA", pipeline=name,
|
|
69
|
+
minutes=f"{p90/60:.1f}", ratio=f"{p90/limit:.0%}", sla=f"{sla:g}"),
|
|
70
|
+
tr("The margin is small; any upstream delay breaks the deadline."), [name], "continuous", {"p90_s": p90, "sla_s": limit}))
|
|
71
|
+
return out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@check("RUN004", "Pipeline without a recent run", stage="continuous", cost="statistical")
|
|
75
|
+
def stale(ctx: Context):
|
|
76
|
+
"""Policy `max_age_hours.<system>:<pipeline>` (number) — last successful run older than that."""
|
|
77
|
+
import time
|
|
78
|
+
out = []
|
|
79
|
+
now = time.time()
|
|
80
|
+
by = defaultdict(list)
|
|
81
|
+
for r in ctx.runs:
|
|
82
|
+
by[f"{r.system}:{r.pipeline}"].append(r)
|
|
83
|
+
for name, rs in by.items():
|
|
84
|
+
max_age = ctx.policies.get(f"max_age_hours.{name}")
|
|
85
|
+
if not max_age:
|
|
86
|
+
continue
|
|
87
|
+
ok = [r.end or r.start or 0 for r in rs if r.state == "success"]
|
|
88
|
+
age = (now - max(ok)) / 3600 if ok else None
|
|
89
|
+
if age is None or age > float(max_age):
|
|
90
|
+
title = (tr("{pipeline}: no success for more than {hours} h", pipeline=name, hours=format(max_age, "g")) if age is None
|
|
91
|
+
else tr("{pipeline}: no success for {hours} h", pipeline=name, hours=f"{age:.1f}"))
|
|
92
|
+
out.append(Finding("RUN004", "high", title,
|
|
93
|
+
tr("Downstream data is older than expected."), [name], "continuous", {"max_age_hours": max_age}))
|
|
94
|
+
return out
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Diff between two versions of the project/catalog: removed column, changed type, likely rename."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import difflib
|
|
5
|
+
|
|
6
|
+
from ..i18n import tr
|
|
7
|
+
from ..model import Finding
|
|
8
|
+
from . import Context, check
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def diff_columns(base, head):
|
|
12
|
+
"""Yield (uid, removed, added, changed) per node present in both versions (matched by relation name)."""
|
|
13
|
+
head_by_rel = {n.relation: u for u, n in head.nodes.items() if n.relation}
|
|
14
|
+
for buid, bn in base.nodes.items():
|
|
15
|
+
huid = head_by_rel.get(bn.relation)
|
|
16
|
+
if huid is None and buid in head.nodes:
|
|
17
|
+
# Homologation and production normally use different databases/schemas.
|
|
18
|
+
# Stable dbt identities still identify the same logical model.
|
|
19
|
+
huid = buid
|
|
20
|
+
if not huid:
|
|
21
|
+
continue
|
|
22
|
+
bc, hc = base.actual_columns(buid), head.actual_columns(huid)
|
|
23
|
+
if not bc or not hc:
|
|
24
|
+
continue # node without catalog in one of the versions: nothing to compare (avoids a false "removed")
|
|
25
|
+
b, h = set(bc), set(hc)
|
|
26
|
+
changed = {c: (bc[c].type, hc[c].type) for c in b & h
|
|
27
|
+
if bc[c].type and hc[c].type and bc[c].type.lower() != hc[c].type.lower()}
|
|
28
|
+
yield buid, huid, sorted(b - h), sorted(h - b), changed
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _rename_guess(old: str, candidates: list[str], bn, hn) -> tuple[str | None, float]:
|
|
32
|
+
best, score = None, 0.0
|
|
33
|
+
for c in candidates:
|
|
34
|
+
s = difflib.SequenceMatcher(None, old, c).ratio()
|
|
35
|
+
if bn.columns[old].type and bn.columns[old].type.lower() == hn.columns[c].type.lower():
|
|
36
|
+
s += 0.25 # same type strengthens the guess
|
|
37
|
+
if s > score:
|
|
38
|
+
best, score = c, s
|
|
39
|
+
return (best, min(score, 1.0)) if score >= 0.6 else (None, score)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@check("SCH001", "Schema change with impact", stage="pre-merge", emits=("SCH002", "SCH003"))
|
|
43
|
+
def schema_drift(ctx: Context):
|
|
44
|
+
if ctx.base_project is None or ctx.base_lineage is None:
|
|
45
|
+
return []
|
|
46
|
+
out = []
|
|
47
|
+
blind = [w for w, pr in (("base", ctx.base_project), ("head", ctx.project))
|
|
48
|
+
if pr.nodes and not any(pr.actual_columns(u) for u in pr.nodes)]
|
|
49
|
+
if blind: # without catalog.json the diff compares nothing: say so instead of passing silently
|
|
50
|
+
out.append(Finding("SCH003", "medium", tr("Schema diff is blind: no catalog in {side}", side="+".join(blind)),
|
|
51
|
+
tr("Run `dbt docs generate` in each version so target/catalog.json exists; without it removed or renamed columns are not detected."),
|
|
52
|
+
[], "pre-merge", {"missing_catalog": blind}))
|
|
53
|
+
for buid, huid, removed, added, changed in diff_columns(ctx.base_project, ctx.project):
|
|
54
|
+
bn, hn = ctx.base_project.nodes[buid], ctx.project.nodes[huid]
|
|
55
|
+
for col in removed:
|
|
56
|
+
consumers = ctx.base_lineage.downstream_of(buid, col)
|
|
57
|
+
indirect = ctx.base_lineage.indirect_of(buid, col) if hasattr(ctx.base_lineage, "indirect_of") else []
|
|
58
|
+
impacted = sorted({e.dst for e in consumers} | {d for d, _ in indirect})
|
|
59
|
+
guess, conf = _rename_guess(col, added, bn, hn)
|
|
60
|
+
if not impacted and not guess:
|
|
61
|
+
continue
|
|
62
|
+
fix = None
|
|
63
|
+
if guess:
|
|
64
|
+
fix = {"kind": "rename_column", "node": bn.name, "old": col, "new": guess,
|
|
65
|
+
"targets": [ctx.base_project.nodes[u].name for u in impacted]}
|
|
66
|
+
sev = "critical" if impacted else "low"
|
|
67
|
+
from ..lineage_api import impact # transitive blast radius (direct consumers break; the ones behind, in cascade)
|
|
68
|
+
blast = [r["name"] for r in impact(ctx.base_project, ctx.base_lineage, bn.name, col)["affected"] if r["name"] != bn.name] if impacted else []
|
|
69
|
+
if impacted:
|
|
70
|
+
detail = tr("{n} downstream model(s) read this column and will fail.", n=len(impacted))
|
|
71
|
+
if indirect:
|
|
72
|
+
detail += " " + tr("{n} only use it in JOIN/filter/grouping.", n=len(indirect))
|
|
73
|
+
if len(blast) > len(impacted):
|
|
74
|
+
detail += " " + tr("Transitive impact: {models}.", models=", ".join(blast))
|
|
75
|
+
else:
|
|
76
|
+
detail = tr("No known consumer.")
|
|
77
|
+
title = (tr("{column} removed (renamed to {new}?)", column=f"{bn.name}.{col}", new=guess) if guess
|
|
78
|
+
else tr("{column} removed", column=f"{bn.name}.{col}"))
|
|
79
|
+
out.append(Finding("SCH001", sev, title, detail, [huid] + [u for u in impacted],
|
|
80
|
+
"pre-merge", {"column": col, "rename_candidate": guess, "rename_confidence": round(conf, 2),
|
|
81
|
+
"consumers": [(ctx.base_project.nodes[e.dst].name, e.dst_col) for e in consumers],
|
|
82
|
+
"indirect_consumers": [(ctx.base_project.nodes[d].name, via) for d, via in indirect],
|
|
83
|
+
"downstream_total": blast},
|
|
84
|
+
fix, confidence=conf if guess else 1.0))
|
|
85
|
+
for col, (t0, t1) in changed.items():
|
|
86
|
+
consumers = ctx.base_lineage.downstream_of(buid, col)
|
|
87
|
+
ind = ctx.base_lineage.indirect_of(buid, col) if hasattr(ctx.base_lineage, "indirect_of") else []
|
|
88
|
+
out.append(Finding("SCH002", "high" if consumers or ind else "low", tr("{column}: type {old} → {new}", column=f"{bn.name}.{col}", old=t0, new=t1),
|
|
89
|
+
tr("A type change can truncate, lose precision or break casts and joins downstream."),
|
|
90
|
+
[huid] + sorted({e.dst for e in consumers} | {d for d, _ in ind}), "pre-merge",
|
|
91
|
+
{"column": col, "from": t0, "to": t1}))
|
|
92
|
+
return out
|