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,174 @@
|
|
|
1
|
+
"""Airflow 2 → 3 migration: finds in DAG files what breaks when moving to Airflow 3 and rewrites what is mechanical.
|
|
2
|
+
|
|
3
|
+
The rules (AF3xx) come from the documented Airflow 3 breaking changes and were checked against a real Airflow 3.1
|
|
4
|
+
(operator imports moved to the `standard` provider, `airflow.sdk`, removal of `execution_date`, `Table` → `Asset`...).
|
|
5
|
+
Only exact module swaps are rewritten; everything else becomes a finding with the recommendation.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ..i18n import N_, cat, tr
|
|
14
|
+
from ..model import Finding
|
|
15
|
+
from . import Context, check
|
|
16
|
+
|
|
17
|
+
# old module → new module (exact swap, imported names do not change)
|
|
18
|
+
MODULE_MOVES = {
|
|
19
|
+
"airflow.operators.bash": "airflow.providers.standard.operators.bash",
|
|
20
|
+
"airflow.operators.bash_operator": "airflow.providers.standard.operators.bash",
|
|
21
|
+
"airflow.operators.python": "airflow.providers.standard.operators.python",
|
|
22
|
+
"airflow.operators.python_operator": "airflow.providers.standard.operators.python",
|
|
23
|
+
"airflow.operators.empty": "airflow.providers.standard.operators.empty",
|
|
24
|
+
"airflow.operators.trigger_dagrun": "airflow.providers.standard.operators.trigger_dagrun",
|
|
25
|
+
"airflow.operators.latest_only": "airflow.providers.standard.operators.latest_only",
|
|
26
|
+
"airflow.operators.datetime": "airflow.providers.standard.operators.datetime",
|
|
27
|
+
"airflow.sensors.filesystem": "airflow.providers.standard.sensors.filesystem",
|
|
28
|
+
"airflow.sensors.time_sensor": "airflow.providers.standard.sensors.time",
|
|
29
|
+
"airflow.sensors.date_time": "airflow.providers.standard.sensors.date_time",
|
|
30
|
+
"airflow.sensors.external_task": "airflow.providers.standard.sensors.external_task",
|
|
31
|
+
}
|
|
32
|
+
# `from <mod> import names` → `from airflow.sdk import names` when ALL names exist in the SDK
|
|
33
|
+
SDK_MODULES = {"airflow": {"DAG"}, "airflow.models": {"DAG", "Variable", "Connection", "BaseOperator", "XComArg", "Param"},
|
|
34
|
+
"airflow.decorators": {"dag", "task", "task_group", "setup", "teardown"},
|
|
35
|
+
"airflow.models.baseoperator": {"BaseOperator", "chain", "cross_downstream"},
|
|
36
|
+
"airflow.models.dag": {"DAG", "dag"}}
|
|
37
|
+
RENAMED = {"DummyOperator": "EmptyOperator", "Dataset": "Asset"}
|
|
38
|
+
REMOVED_IMPORTS = {"days_ago": N_("use pendulum.today('UTC').add(days=-N) or datetime(...)"),
|
|
39
|
+
"SubDagOperator": N_("replace it with a TaskGroup"),
|
|
40
|
+
"provide_session": N_("workers do not access the metadata database; use the API/Task SDK"),
|
|
41
|
+
"create_session": N_("workers do not access the metadata database; use the API/Task SDK")}
|
|
42
|
+
REMOVED_ARGS = {"provide_context": ("AF304", N_("removed: the context is always passed; declare **context or the kwargs you use")),
|
|
43
|
+
"schedule_interval": ("AF302", N_("removed in Airflow 3: use `schedule`")),
|
|
44
|
+
"timetable": ("AF302", N_("removed as a DAG argument: use `schedule=`"))}
|
|
45
|
+
TEMPLATE_VARS = {"execution_date": "logical_date", "next_execution_date": "data_interval_end", "prev_execution_date": N_("(no direct equivalent; use data_interval_start)"),
|
|
46
|
+
"tomorrow_ds": "macros/pendulum", "yesterday_ds": "macros/pendulum", "next_ds": "data_interval_end | ds",
|
|
47
|
+
"prev_ds": "data_interval_start | ds", "conf": "params / dag_run.conf"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def scan_source(src: str) -> list[dict]:
|
|
51
|
+
"""Return problems: {rule, severity, line, message, recommendation, fixable}."""
|
|
52
|
+
try:
|
|
53
|
+
tree = ast.parse(src)
|
|
54
|
+
except SyntaxError:
|
|
55
|
+
return []
|
|
56
|
+
out: list[dict] = []
|
|
57
|
+
|
|
58
|
+
def add(rule, sev, line, msg, rec, fixable=False):
|
|
59
|
+
out.append({"rule": rule, "severity": sev, "line": line, "message": msg, "recommendation": rec, "fixable": fixable})
|
|
60
|
+
|
|
61
|
+
dag_calls = []
|
|
62
|
+
for n in ast.walk(tree):
|
|
63
|
+
if isinstance(n, ast.ImportFrom) and n.module:
|
|
64
|
+
names = {a.name for a in n.names}
|
|
65
|
+
if n.module in MODULE_MOVES:
|
|
66
|
+
add("AF301", "high", n.lineno, tr("`{module}` left the core in Airflow 3", module=n.module),
|
|
67
|
+
tr("`from {module} import …` (package apache-airflow-providers-standard)", module=MODULE_MOVES[n.module]), True)
|
|
68
|
+
elif n.module in SDK_MODULES and names <= SDK_MODULES[n.module]:
|
|
69
|
+
add("AF301", "high", n.lineno, tr("`from {module} import {names}` moved to the SDK", module=n.module, names=", ".join(sorted(names))),
|
|
70
|
+
"`from airflow.sdk import …`", True)
|
|
71
|
+
if n.module in ("airflow.datasets", "airflow.dataset") or "Dataset" in names:
|
|
72
|
+
add("AF310", "medium", n.lineno, tr("`Dataset` became `Asset` (and `airflow.datasets` was removed)"),
|
|
73
|
+
tr("`from airflow.sdk import Asset`; `inlets`/`outlets`/`schedule` use Asset"))
|
|
74
|
+
if n.module == "airflow.lineage.entities":
|
|
75
|
+
add("AF310", "medium", n.lineno, tr("`airflow.lineage.entities.Table/File` was removed (checked on 3.1)"),
|
|
76
|
+
tr("use `Asset(uri)` (e.g. `Asset('postgres://host:5432/db/schema/table')`)"))
|
|
77
|
+
if n.module == "airflow.settings" and "Session" in names:
|
|
78
|
+
add("AF308", "high", n.lineno, tr("direct access to the metadata database does not work in tasks in Airflow 3"), tr(REMOVED_IMPORTS["provide_session"]))
|
|
79
|
+
for nm in names & set(REMOVED_IMPORTS):
|
|
80
|
+
add("AF306" if nm == "days_ago" else ("AF305" if nm == "SubDagOperator" else "AF308"), "high", n.lineno,
|
|
81
|
+
tr("`{name}` was removed in Airflow 3", name=nm), tr(REMOVED_IMPORTS[nm]))
|
|
82
|
+
for nm in names & set(RENAMED):
|
|
83
|
+
if nm == "DummyOperator":
|
|
84
|
+
add("AF301", "medium", n.lineno, tr("`DummyOperator` was removed"), tr("use `EmptyOperator` (airflow.providers.standard.operators.empty)"))
|
|
85
|
+
if isinstance(n, ast.Call):
|
|
86
|
+
fn = getattr(n.func, "id", getattr(n.func, "attr", ""))
|
|
87
|
+
if fn in ("DAG", "dag"):
|
|
88
|
+
dag_calls.append(n)
|
|
89
|
+
for k in n.keywords:
|
|
90
|
+
if k.arg in REMOVED_ARGS and (fn in ("DAG", "dag") or k.arg == "provide_context"):
|
|
91
|
+
rule, msg = REMOVED_ARGS[k.arg]
|
|
92
|
+
add(rule, "high", n.lineno, cat(f"`{k.arg}`: ", tr(msg)), tr(msg))
|
|
93
|
+
if fn == "SubDagOperator":
|
|
94
|
+
add("AF305", "high", n.lineno, tr("`SubDagOperator` was removed"), tr(REMOVED_IMPORTS["SubDagOperator"]))
|
|
95
|
+
if isinstance(n, ast.Attribute) and n.attr == "NONE_FAILED_OR_SKIPPED":
|
|
96
|
+
add("AF309", "medium", n.lineno, tr("`TriggerRule.NONE_FAILED_OR_SKIPPED` was removed"), "`TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS`")
|
|
97
|
+
if isinstance(n, ast.Subscript) and isinstance(n.slice, ast.Constant) and n.slice.value in ("execution_date", "next_execution_date", "prev_execution_date"):
|
|
98
|
+
add("AF303", "high", n.lineno, tr("context[`{key}`] was removed", key=n.slice.value),
|
|
99
|
+
tr("use `logical_date`/`data_interval_*` ({hint})", hint=tr(TEMPLATE_VARS[n.slice.value])))
|
|
100
|
+
for c in dag_calls:
|
|
101
|
+
kw = {k.arg for k in c.keywords}
|
|
102
|
+
has_sched = ("schedule" in kw or "schedule_interval" in kw) and not any(
|
|
103
|
+
k.arg in ("schedule", "schedule_interval") and isinstance(k.value, ast.Constant) and k.value.value is None for k in c.keywords)
|
|
104
|
+
if has_sched and "catchup" not in kw:
|
|
105
|
+
add("AF307", "medium", c.lineno, tr("`catchup` not declared: the default changed from True (2.x) to False (3.x)"),
|
|
106
|
+
tr("declare `catchup=` explicitly so the behavior does not change silently"))
|
|
107
|
+
for i, line in enumerate(src.splitlines(), 1):
|
|
108
|
+
if "{{" in line:
|
|
109
|
+
for m in re.finditer(r"\{\{[^}]*\b(execution_date|next_execution_date|prev_execution_date|tomorrow_ds|yesterday_ds|next_ds|prev_ds)\b", line):
|
|
110
|
+
v = m.group(1)
|
|
111
|
+
add("AF303", "high", i, tr("template variable `{name}` was removed", name=v),
|
|
112
|
+
tr("use `{replacement}` (e.g. `{example}`)", replacement=tr(TEMPLATE_VARS[v]), example="{{ logical_date }}"))
|
|
113
|
+
if re.search(r"/api/v1/", line) and "airflow" in src.lower():
|
|
114
|
+
add("AF311", "medium", i, tr("call to the REST `/api/v1`, removed in Airflow 3"), tr("use `/api/v2` with a JWT token (`POST /auth/token`)"))
|
|
115
|
+
seen, uniq = set(), []
|
|
116
|
+
for p in out:
|
|
117
|
+
k = (p["rule"], p["line"], p["message"])
|
|
118
|
+
if k not in seen:
|
|
119
|
+
seen.add(k)
|
|
120
|
+
uniq.append(p)
|
|
121
|
+
return sorted(uniq, key=lambda p: (p["line"], p["rule"]))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def rewrite_source(src: str) -> tuple[str, int]:
|
|
125
|
+
"""Apply only exact import swaps. Return (new_text, count)."""
|
|
126
|
+
n = 0
|
|
127
|
+
|
|
128
|
+
def sub(m):
|
|
129
|
+
nonlocal n
|
|
130
|
+
indent, mod, rest = m.group(1), m.group(2), m.group(3)
|
|
131
|
+
names = {x.strip().split(" as ")[0].strip("() ") for x in rest.split(",") if x.strip().strip("()")}
|
|
132
|
+
if mod in MODULE_MOVES:
|
|
133
|
+
n += 1
|
|
134
|
+
new = MODULE_MOVES[mod]
|
|
135
|
+
elif mod in SDK_MODULES and names and names <= SDK_MODULES[mod]:
|
|
136
|
+
n += 1
|
|
137
|
+
new = "airflow.sdk"
|
|
138
|
+
else:
|
|
139
|
+
return m.group(0)
|
|
140
|
+
return f"{indent}from {new} import {rest}"
|
|
141
|
+
return re.sub(r"^([ \t]*)from\s+([\w.]+)\s+import\s+(.+)$", sub, src, flags=re.M), n
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def migrate_dir(path: str | Path, write: bool = False) -> list[dict]:
|
|
145
|
+
"""Scan a DAG folder. With write=True rewrite the mechanical imports (keeps a .af2.bak next to each file)."""
|
|
146
|
+
res = []
|
|
147
|
+
for p in sorted(Path(path).rglob("*.py")):
|
|
148
|
+
src = p.read_text(errors="replace")
|
|
149
|
+
if "airflow" not in src:
|
|
150
|
+
continue
|
|
151
|
+
issues = scan_source(src)
|
|
152
|
+
new, n = rewrite_source(src)
|
|
153
|
+
if write and n and new != src:
|
|
154
|
+
p.with_suffix(p.suffix + ".af2.bak").write_text(src)
|
|
155
|
+
p.write_text(new)
|
|
156
|
+
if issues or n:
|
|
157
|
+
remaining = scan_source(new) if write and n else issues
|
|
158
|
+
res.append({"file": str(p), "issues": issues, "rewritable": n, "remaining": remaining if write else None, "written": bool(write and n)})
|
|
159
|
+
return res
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@check("AF3", "Airflow 3 compatibility (2 → 3 migration)", stage="pre-merge")
|
|
163
|
+
def airflow3_compat(ctx: Context):
|
|
164
|
+
# opt-in: teams still on Airflow 2 must not see hundreds of "high" findings. `intentflow policy airflow-target 3` turns it on.
|
|
165
|
+
if not ctx.airflow_dags_dir or int(ctx.policies.get("airflow_target_major", 0) or 0) < 3:
|
|
166
|
+
return []
|
|
167
|
+
out = []
|
|
168
|
+
for r in migrate_dir(ctx.airflow_dags_dir):
|
|
169
|
+
name = Path(r["file"]).name
|
|
170
|
+
for p in r["issues"]:
|
|
171
|
+
out.append(Finding(p["rule"], p["severity"], cat(f"{name}:{p['line']} ", p["message"]),
|
|
172
|
+
tr("Breaks when migrating to Airflow 3 (checked against Airflow 3.1)."), [r["file"]], "pre-merge",
|
|
173
|
+
{"line": p["line"], "recommendation": p["recommendation"], "auto_fixable": p["fixable"]}))
|
|
174
|
+
return out
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Visibility and accountability for business rules declared in dbt."""
|
|
2
|
+
from .. import business_rules
|
|
3
|
+
from ..i18n import tr
|
|
4
|
+
from ..model import Finding
|
|
5
|
+
from . import check
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@check("BIZ001", "Business rule result unavailable", stage="continuous", emits=("BIZ002",))
|
|
9
|
+
def business_rule_coverage(ctx):
|
|
10
|
+
if ctx.project is None:
|
|
11
|
+
return []
|
|
12
|
+
catalog = business_rules.build(ctx.project, ctx.dbt_results, ctx.store,
|
|
13
|
+
max_age_hours=float(ctx.policies.get("max_rule_age_hours", 24)))
|
|
14
|
+
out = []
|
|
15
|
+
for rule in catalog["rules"]:
|
|
16
|
+
evidence = {"test_id": rule["id"], "business_rule": True, "file": rule["file"], "status": rule["status"]}
|
|
17
|
+
if rule["owner"]:
|
|
18
|
+
evidence["owner"] = rule["owner"]
|
|
19
|
+
if not rule["fresh"] or rule["status"] in ("skipped", "not_run"):
|
|
20
|
+
out.append(Finding("BIZ001", "high", tr("{rule}: business rule has no current execution", rule=rule["name"]),
|
|
21
|
+
tr("Run the declared dbt test and preserve run_results; an absent, skipped or outdated result is not a pass."),
|
|
22
|
+
rule["model_ids"], "continuous", evidence))
|
|
23
|
+
if not rule["owner"]:
|
|
24
|
+
out.append(Finding("BIZ002", "medium", tr("{rule}: business rule has no owner", rule=rule["name"]),
|
|
25
|
+
tr("Set meta.owner on the dbt test or one unambiguous owner on its input models."),
|
|
26
|
+
rule["model_ids"], "continuous", evidence))
|
|
27
|
+
return out
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Schema change in catalogs (Glue/Unity) between two collections: removed column, changed type, dropped table."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import tr
|
|
5
|
+
from ..model import Finding
|
|
6
|
+
from . import Context, check
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@check("CAT001", "Schema changed in the data catalog", stage="continuous", cost="static")
|
|
10
|
+
def catalog_changes(ctx: Context):
|
|
11
|
+
if ctx.store is None:
|
|
12
|
+
return []
|
|
13
|
+
cur, prev = ctx.store.get_setting("state.catalog.cur"), ctx.store.get_setting("state.catalog.prev")
|
|
14
|
+
if not cur or not prev:
|
|
15
|
+
return []
|
|
16
|
+
names: dict[str, str] = {}
|
|
17
|
+
if ctx.project is not None:
|
|
18
|
+
for uid, n in ctx.project.nodes.items():
|
|
19
|
+
if n.relation:
|
|
20
|
+
parts = [p.strip('"`[]').lower() for p in n.relation.split(".")]
|
|
21
|
+
names[".".join(parts[-2:])] = uid
|
|
22
|
+
names[parts[-1]] = names.get(parts[-1], uid)
|
|
23
|
+
out = []
|
|
24
|
+
for fqn, old in prev.items():
|
|
25
|
+
kind, _, name = fqn.partition(":")
|
|
26
|
+
short = ".".join(name.split(".")[-2:])
|
|
27
|
+
uid = names.get(short) or names.get(name.split(".")[-1])
|
|
28
|
+
down = len(ctx.project.downstream(uid)) if uid and ctx.project else 0
|
|
29
|
+
ref = [uid] if uid else [f"catalog:{fqn}"]
|
|
30
|
+
new = cur.get(fqn)
|
|
31
|
+
if new is None:
|
|
32
|
+
out.append(Finding("CAT001", "critical" if down else "high", tr("{table}: table disappeared from the catalog ({catalog})", table=name, catalog=kind),
|
|
33
|
+
tr("Consumers of this table will fail.") + (" " + tr("Affects {n} downstream model(s).", n=down) if down else ""),
|
|
34
|
+
ref, "continuous", {"kind": "table_dropped", "catalog": kind, "downstream": down}))
|
|
35
|
+
continue
|
|
36
|
+
removed = sorted(set(old) - set(new))
|
|
37
|
+
retyped = sorted(c for c in set(old) & set(new) if old[c] != new[c])
|
|
38
|
+
if removed or retyped:
|
|
39
|
+
what = [tr("`{column}` removed", column=c) for c in removed] + [f"`{c}`: {old[c]} → {new[c]}" for c in retyped]
|
|
40
|
+
out.append(Finding("CAT001", "critical" if down else "high", tr("{table}: schema changed ({changes})", table=name, changes="; ".join(what)),
|
|
41
|
+
tr("Incompatible change observed in the catalog.") + (" " + tr("Affects {n} downstream model(s).", n=down) if down else ""),
|
|
42
|
+
ref, "continuous", {"kind": "schema_break", "catalog": kind, "removed": removed, "retyped": retyped, "downstream": down}))
|
|
43
|
+
return out
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Memory pressure and resource saturation (samples from the cluster, orchestrators and warehouse)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
|
|
6
|
+
from ..i18n import tr
|
|
7
|
+
from ..model import Finding
|
|
8
|
+
from ..monitoring import time_to_exhaustion
|
|
9
|
+
from . import Context, check
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _series(ctx: Context):
|
|
13
|
+
s = defaultdict(list)
|
|
14
|
+
for x in ctx.samples:
|
|
15
|
+
s[(x.source, x.scope, x.metric)].append(x)
|
|
16
|
+
for v in s.values():
|
|
17
|
+
v.sort(key=lambda x: x.ts)
|
|
18
|
+
return s
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@check("CLU001", "High memory use", stage="continuous", cost="statistical")
|
|
22
|
+
def memory_high(ctx: Context):
|
|
23
|
+
out = []
|
|
24
|
+
for (src, scope, metric), v in _series(ctx).items():
|
|
25
|
+
if metric != "memory_bytes" or not v[-1].limit:
|
|
26
|
+
continue
|
|
27
|
+
ratio = v[-1].value / v[-1].limit
|
|
28
|
+
if ratio >= 0.7:
|
|
29
|
+
sev = "critical" if ratio >= 0.9 else "high" if ratio >= 0.8 else "medium"
|
|
30
|
+
out.append(Finding("CLU001", sev, tr("{where} uses {ratio} of its memory", where=f"{src}:{scope}", ratio=f"{ratio:.0%}"),
|
|
31
|
+
tr("Above 70% the chance of an OOM kill goes up (aggregation/join peaks)."), [f"{src}:{scope}"], "continuous",
|
|
32
|
+
{"used_bytes": v[-1].value, "limit_bytes": v[-1].limit,
|
|
33
|
+
"recommendation": tr("raise the limit, reduce parallelism/pool or optimize the queries that use the most")}))
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@check("CLU002", "Memory exhaustion trend", stage="continuous", cost="statistical")
|
|
38
|
+
def memory_trend(ctx: Context):
|
|
39
|
+
out = []
|
|
40
|
+
for (src, scope, metric), v in _series(ctx).items():
|
|
41
|
+
if metric != "memory_bytes" or not v[-1].limit or len(v) < 4:
|
|
42
|
+
continue
|
|
43
|
+
eta = time_to_exhaustion([(x.ts, x.value) for x in v], v[-1].limit)
|
|
44
|
+
if eta is not None and eta < 24 * 3600 and v[-1].value / v[-1].limit < 0.9:
|
|
45
|
+
out.append(Finding("CLU002", "high" if eta < 3600 else "medium",
|
|
46
|
+
tr("{where} runs out of memory in ~{hours} h", where=f"{src}:{scope}", hours=f"{eta/3600:.1f}"),
|
|
47
|
+
tr("Continuous growth (leak or runs piling up). Linear projection over the recent samples."),
|
|
48
|
+
[f"{src}:{scope}"], "continuous", {"eta_seconds": round(eta), "samples": len(v)}))
|
|
49
|
+
return out
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@check("CLU003", "Process killed for lack of memory", stage="continuous", cost="statistical")
|
|
53
|
+
def oom_killed(ctx: Context):
|
|
54
|
+
return [Finding("CLU003", "critical", tr("{where} was killed by OOM", where=f"{src}:{scope}"),
|
|
55
|
+
tr("The kernel/container killed the process (OOMKilled). Running tasks were lost."), [f"{src}:{scope}"], "continuous",
|
|
56
|
+
{"recommendation": tr("raise the container memory limit or reduce the concurrent load")})
|
|
57
|
+
for (src, scope, metric), v in _series(ctx).items() if metric == "oom_killed" and v[-1].value > 0]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@check("CLU004", "Queries spilling to disk", stage="continuous", cost="statistical")
|
|
61
|
+
def spill(ctx: Context):
|
|
62
|
+
out = []
|
|
63
|
+
for (_src, scope, metric), v in _series(ctx).items():
|
|
64
|
+
if metric == "spilled_bytes" and v[-1].value > 0:
|
|
65
|
+
gb = v[-1].value / 1e9
|
|
66
|
+
out.append(Finding("CLU004", "high" if gb >= 10 else "medium", tr("query {query} spilled {gb} GB to disk", query=scope, gb=f"{gb:.1f}"),
|
|
67
|
+
tr("Spill means the query did not fit in the warehouse/cluster memory: slow and an OOM candidate."),
|
|
68
|
+
[scope], "continuous", {"spilled_bytes": v[-1].value,
|
|
69
|
+
"recommendation": tr("filter before joining, aggregate first, read fewer columns or grow the warehouse")}))
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@check("CLU005", "Saturated pool/worker", stage="continuous", cost="statistical")
|
|
74
|
+
def saturation(ctx: Context):
|
|
75
|
+
out = []
|
|
76
|
+
for (src, scope, metric), v in _series(ctx).items():
|
|
77
|
+
if metric == "queued" and len(v) >= 2 and all(x.value > 0 for x in v[-3:]):
|
|
78
|
+
out.append(Finding("CLU005", "medium", tr("{where} has tasks queued continuously", where=f"{src}:{scope}"),
|
|
79
|
+
tr("Tasks wait for a slot across several samples in a row: SLA at risk and backfills piling up."), [f"{src}:{scope}"], "continuous",
|
|
80
|
+
{"queued": v[-1].value}))
|
|
81
|
+
return out
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Data contract × reality (project catalog/tests): what the consumer agreed to and what actually exists."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..contracts import family
|
|
5
|
+
from ..i18n import tr
|
|
6
|
+
from ..model import Finding
|
|
7
|
+
from . import Context, check
|
|
8
|
+
|
|
9
|
+
UNIQUE_TESTS = {"unique", "unique_combination_of_columns", "dbt_utils.unique_combination_of_columns"}
|
|
10
|
+
NOT_NULL_TESTS = {"not_null"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@check("CTR001", "Data contract violated or not covered", stage="pre-merge")
|
|
14
|
+
def contract_checks(ctx: Context):
|
|
15
|
+
if not ctx.contracts or ctx.project is None:
|
|
16
|
+
return []
|
|
17
|
+
def normalize(name):
|
|
18
|
+
return ".".join(part.strip('"`[]').lower() for part in name.split("."))
|
|
19
|
+
by_name = {}
|
|
20
|
+
for uid, n in ctx.project.nodes.items():
|
|
21
|
+
if n.resource_type in ("model", "seed", "snapshot"):
|
|
22
|
+
aliases = {n.name, uid}
|
|
23
|
+
parts = uid.split(".")
|
|
24
|
+
if len(parts) >= 3 and parts[0] in ("model", "seed", "snapshot"):
|
|
25
|
+
aliases.add(f"{parts[1]}.{n.name}")
|
|
26
|
+
if n.relation:
|
|
27
|
+
aliases.add(n.relation)
|
|
28
|
+
for alias in aliases:
|
|
29
|
+
by_name.setdefault(normalize(alias), set()).add(uid)
|
|
30
|
+
out = []
|
|
31
|
+
for c in ctx.contracts:
|
|
32
|
+
candidates = sorted(by_name.get(normalize(c.name), set()))
|
|
33
|
+
if not candidates:
|
|
34
|
+
out.append(Finding("CTR001", "high", tr("contract `{name}`: the model does not exist in the project", name=c.name),
|
|
35
|
+
tr("Declared in {source}; consumers expect a table that is not produced.", source=c.source), [], "pre-merge",
|
|
36
|
+
{"contract": c.source, "kind": "missing_model"}))
|
|
37
|
+
continue
|
|
38
|
+
if len(candidates) > 1:
|
|
39
|
+
if "CTR001" in ctx.required_checks:
|
|
40
|
+
ctx.failed_checks.add("CTR001")
|
|
41
|
+
out.append(Finding("CTR001", "high", tr("contract `{name}`: model name is ambiguous", name=c.name),
|
|
42
|
+
tr("Qualify the contract model with its package, full dbt id or relation; no arbitrary match is accepted."),
|
|
43
|
+
candidates, "pre-merge", {"contract": c.source, "kind": "ambiguous_model", "candidates": candidates}))
|
|
44
|
+
continue
|
|
45
|
+
uid = candidates[0]
|
|
46
|
+
n = ctx.project.nodes[uid]
|
|
47
|
+
down = len(ctx.project.downstream(uid))
|
|
48
|
+
have = ctx.project.actual_columns(uid) or n.columns
|
|
49
|
+
tested = {(t.get("column") or "").lower(): set() for t in n.tests}
|
|
50
|
+
for t in n.tests:
|
|
51
|
+
tested.setdefault((t.get("column") or "").lower(), set()).add(str(t.get("name")))
|
|
52
|
+
affects = " " + tr("Affects {n} downstream model(s).", n=down) if down else ""
|
|
53
|
+
for col, rule in c.columns.items():
|
|
54
|
+
actual = have.get(col)
|
|
55
|
+
if actual is None:
|
|
56
|
+
out.append(Finding("CTR001", "critical" if down else "high", tr("{column}: contract column does not exist", column=f"{n.name}.{col}"),
|
|
57
|
+
tr("{source} promises the column; the model does not produce it.", source=c.source) + affects,
|
|
58
|
+
[uid], "pre-merge", {"contract": c.source, "kind": "missing_column", "downstream": down}))
|
|
59
|
+
continue
|
|
60
|
+
want, got = family(rule.type), family(actual.type)
|
|
61
|
+
if want and got and want != got:
|
|
62
|
+
out.append(Finding("CTR001", "high", tr("{column}: type {actual} differs from the contract ({expected})", column=f"{n.name}.{col}",
|
|
63
|
+
actual=actual.type, expected=rule.type),
|
|
64
|
+
tr("Contract in {source}.", source=c.source), [uid], "pre-merge",
|
|
65
|
+
{"contract": c.source, "kind": "type_mismatch", "expected": rule.type, "actual": actual.type}))
|
|
66
|
+
ts = tested.get(col, set())
|
|
67
|
+
# A configured incremental key/grain is not a uniqueness assertion.
|
|
68
|
+
# Likewise uniqueness of (a,b) does not prove that a alone is unique.
|
|
69
|
+
single_column_unique = any(t.get("name") in UNIQUE_TESTS and
|
|
70
|
+
[str(c).lower() for c in (t.get("kwargs", {}).get("combination_of_columns") or [])] == [col]
|
|
71
|
+
for t in n.tests)
|
|
72
|
+
enforcement_severity = "high" if "CTR001" in ctx.required_checks else "medium"
|
|
73
|
+
if rule.unique and not ("unique" in ts or single_column_unique):
|
|
74
|
+
out.append(Finding("CTR001", enforcement_severity, tr("{column}: the contract requires uniqueness but no test enforces it", column=f"{n.name}.{col}"),
|
|
75
|
+
tr("Nothing guarantees the contract's promise."), [uid], "pre-merge", {"contract": c.source, "kind": "unenforced_unique"}))
|
|
76
|
+
if rule.required and not (ts & NOT_NULL_TESTS):
|
|
77
|
+
out.append(Finding("CTR001", enforcement_severity, tr("{column}: the contract requires a value but there is no `not_null` test", column=f"{n.name}.{col}"),
|
|
78
|
+
tr("Nothing guarantees the contract's promise."), [uid], "pre-merge", {"contract": c.source, "kind": "unenforced_required"}))
|
|
79
|
+
return out
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Estimated cost before running: the warehouse plan (EXPLAIN), without running the query."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import tr
|
|
5
|
+
from ..model import Finding
|
|
6
|
+
from . import Context, check
|
|
7
|
+
|
|
8
|
+
HEAVY = {"CROSS_PRODUCT", "NESTED_LOOP_JOIN", "BLOCKWISE_NL_JOIN", "Nested Loop"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@check("SQL013", "Expensive plan (estimate)", stage="pre-run", cost="probe")
|
|
12
|
+
def expensive_plan(ctx: Context):
|
|
13
|
+
if ctx.warehouse is None:
|
|
14
|
+
return []
|
|
15
|
+
limit = int(ctx.policies.get("max_estimated_rows", 10_000_000))
|
|
16
|
+
out = []
|
|
17
|
+
for uid, n in ctx.project.nodes.items():
|
|
18
|
+
if n.resource_type not in ("model", "snapshot") or n.language != "sql" or not n.compiled_code:
|
|
19
|
+
continue
|
|
20
|
+
try:
|
|
21
|
+
plan = ctx.warehouse.plan(n.compiled_code)
|
|
22
|
+
except Exception:
|
|
23
|
+
continue # the relation may not exist yet (new model in the PR): no plan, no finding
|
|
24
|
+
heavy = sorted(set(plan["operators"]) & HEAVY)
|
|
25
|
+
big = plan["max_rows"] is not None and plan["max_rows"] > limit
|
|
26
|
+
if heavy and (big or plan["max_rows"] is None or any("CROSS" in h for h in heavy)):
|
|
27
|
+
out.append(Finding("SQL013", "high", tr("{model}: plan uses {ops}", model=n.name, ops=", ".join(heavy)),
|
|
28
|
+
tr("The planner chose a join without hash/merge (nested loop or cartesian product): the cost grows quadratically with volume."),
|
|
29
|
+
[uid], "pre-run", {"operators": heavy, "estimated_max_rows": plan["max_rows"],
|
|
30
|
+
"recommendation": tr("make the join condition an equality or aggregate first")}))
|
|
31
|
+
elif big:
|
|
32
|
+
out.append(Finding("SQL013", "medium", tr("{model}: estimate of {rows} rows in one operator", model=n.name, rows=f"{plan['max_rows']:,}"),
|
|
33
|
+
tr("Above the policy limit ({limit}); memory and time risk.", limit=f"{limit:,}"), [uid], "pre-run",
|
|
34
|
+
{"estimated_max_rows": plan["max_rows"], "limit": limit}))
|
|
35
|
+
return out
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Checks on the dbt project: tests, idempotency, owner, PII propagation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import tr
|
|
5
|
+
from ..model import Finding
|
|
6
|
+
from . import Context, check
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _sev_by_impact(n_down: int, base: str = "medium") -> str:
|
|
10
|
+
return "high" if n_down >= 3 else base
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@check("DBT001", "Key without a uniqueness test")
|
|
14
|
+
def missing_key_tests(ctx: Context):
|
|
15
|
+
out = []
|
|
16
|
+
for uid, n in ctx.project.nodes.items():
|
|
17
|
+
if n.resource_type != "model" or not ctx.project.downstream(uid):
|
|
18
|
+
continue # without consumers the risk is lower
|
|
19
|
+
has_unique = any(t["name"] in ("unique", "unique_combination_of_columns") for t in n.tests)
|
|
20
|
+
if not has_unique:
|
|
21
|
+
out.append(Finding("DBT001", _sev_by_impact(len(ctx.project.downstream(uid))),
|
|
22
|
+
tr("{model}: no uniqueness test", model=n.name),
|
|
23
|
+
tr("A model consumed by others declares no `unique` test; a duplicated key spreads through joins and inflates metrics."),
|
|
24
|
+
[uid], "pre-merge", {"downstream": len(ctx.project.downstream(uid)),
|
|
25
|
+
"recommendation": tr("add `unique` and `not_null` on the primary key")}))
|
|
26
|
+
return out
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@check("DBT002", "Incremental without unique_key")
|
|
30
|
+
def incremental_idempotency(ctx: Context):
|
|
31
|
+
out = []
|
|
32
|
+
for uid, n in ctx.project.nodes.items():
|
|
33
|
+
if n.resource_type == "model" and n.materialized == "incremental" and not n.unique_key \
|
|
34
|
+
and n.incremental_strategy != "microbatch":
|
|
35
|
+
out.append(Finding("DBT002", "high", tr("{model}: incremental without unique_key", model=n.name),
|
|
36
|
+
tr("Reprocessing a window (retry, backfill) inserts the same rows again: the result stops being idempotent."),
|
|
37
|
+
[uid], "pre-merge", {"recommendation": tr("set `unique_key` and the `merge`/`delete+insert` strategy"),
|
|
38
|
+
"key_candidates": [c for c in n.columns if c.lower() == "id" or c.lower().endswith("_id")][:6]}))
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@check("DBT003", "Model without owner")
|
|
43
|
+
def missing_owner(ctx: Context):
|
|
44
|
+
out = []
|
|
45
|
+
for uid, n in ctx.project.nodes.items():
|
|
46
|
+
if n.resource_type == "model" and not (n.meta.get("owner") or n.meta.get("team")):
|
|
47
|
+
down = len(ctx.project.downstream(uid))
|
|
48
|
+
out.append(Finding("DBT003", "medium" if down else "low", tr("{model}: no owner", model=n.name),
|
|
49
|
+
tr("Without `meta.owner`, alerts and fix proposals have no one to be routed to."),
|
|
50
|
+
[uid], "continuous", {"downstream": down}))
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _pii_columns(project):
|
|
55
|
+
for uid, n in project.nodes.items():
|
|
56
|
+
for c in n.columns.values():
|
|
57
|
+
if c.meta.get("pii") or "pii" in c.tags:
|
|
58
|
+
yield uid, c.name
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@check("DBT004", "PII propagated without masking")
|
|
62
|
+
def pii_propagation(ctx: Context):
|
|
63
|
+
"""Propagate PII columns through the lineage; report arrival at a non-authorized model without hash/mask."""
|
|
64
|
+
if ctx.lineage is None:
|
|
65
|
+
return []
|
|
66
|
+
allowed = set(ctx.policies.get("pii_allowed_models", []))
|
|
67
|
+
out, reported = [], set()
|
|
68
|
+
for src_uid, src_col in _pii_columns(ctx.project):
|
|
69
|
+
frontier = [(src_uid, src_col, False)]
|
|
70
|
+
seen = set()
|
|
71
|
+
while frontier:
|
|
72
|
+
uid, col, masked = frontier.pop()
|
|
73
|
+
for e in ctx.lineage.downstream_of(uid, col):
|
|
74
|
+
m = masked or e.masked
|
|
75
|
+
key = (e.dst, e.dst_col, m)
|
|
76
|
+
if key in seen:
|
|
77
|
+
continue
|
|
78
|
+
seen.add(key)
|
|
79
|
+
dst = ctx.project.nodes[e.dst]
|
|
80
|
+
ok = dst.name in allowed or dst.meta.get("contains_pii") is True
|
|
81
|
+
if not m and not ok and (e.dst, e.dst_col) not in reported:
|
|
82
|
+
reported.add((e.dst, e.dst_col))
|
|
83
|
+
origin = f"{ctx.project.nodes[src_uid].name}.{src_col}"
|
|
84
|
+
out.append(Finding("DBT004", "high", tr("{column}: PII from {origin} without masking", column=f"{dst.name}.{e.dst_col}", origin=origin),
|
|
85
|
+
tr("A column marked as PII reaches a model that neither declares `contains_pii: true` nor goes through a hash/mask."),
|
|
86
|
+
[e.dst], "pre-merge",
|
|
87
|
+
{"origin": origin,
|
|
88
|
+
"recommendation": tr("apply md5/sha256 or drop the column; or list the model in `pii_allowed_models`")}))
|
|
89
|
+
frontier.append((e.dst, e.dst_col, m))
|
|
90
|
+
return out
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Findings from the actual result of the last dbt run (run_results.json)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..dbt_results import median_history
|
|
5
|
+
from ..business_rules import rule_owner
|
|
6
|
+
from ..i18n import cat, tr
|
|
7
|
+
from ..model import Finding
|
|
8
|
+
from . import Context, check
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _node(ctx, uid):
|
|
12
|
+
return ctx.project.nodes.get(uid)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@check("DBTR001", "Failing dbt test", stage="continuous", cost="statistical")
|
|
16
|
+
def failing_tests(ctx: Context):
|
|
17
|
+
r = ctx.dbt_results
|
|
18
|
+
if not r:
|
|
19
|
+
return []
|
|
20
|
+
out = []
|
|
21
|
+
for x in r["results"]:
|
|
22
|
+
if not x["unique_id"].startswith(("test.", "unit_test.")) or x["status"] not in ("fail", "error", "warn"):
|
|
23
|
+
continue
|
|
24
|
+
att, tname, col = ctx.project.tests_by_id.get(x["unique_id"], (None, x["unique_id"].split(".")[2], None))
|
|
25
|
+
definition = ctx.project.test_definitions.get(x["unique_id"], {})
|
|
26
|
+
dependencies = definition.get("models") or ([att] if att else [])
|
|
27
|
+
if att is None and dependencies:
|
|
28
|
+
att = dependencies[0]
|
|
29
|
+
n = _node(ctx, att)
|
|
30
|
+
downstream = {v for u in dependencies for v in ctx.project.downstream(u)} - set(dependencies)
|
|
31
|
+
down = len(downstream)
|
|
32
|
+
where = f"{n.name}.{col}" if n and col else (n.name if n else x["unique_id"])
|
|
33
|
+
warn = x["status"] == "warn"
|
|
34
|
+
title = tr("{where}: test `{test}` is warning", where=where, test=tname) if warn else tr("{where}: test `{test}` failed", where=where, test=tname)
|
|
35
|
+
if x["failures"]:
|
|
36
|
+
title = cat(title, " (", tr("{n} row(s)", n=x["failures"]), ")")
|
|
37
|
+
out.append(Finding("DBTR001", "medium" if warn else ("critical" if down >= 3 else "high"), title,
|
|
38
|
+
(x["message"] or "") + (" " + tr("Affects {n} downstream model(s).", n=down) if down else ""),
|
|
39
|
+
dependencies, "continuous",
|
|
40
|
+
{"test": tname, "test_id": x["unique_id"], "status": x["status"], "failures": x["failures"], "downstream": down,
|
|
41
|
+
**({"owner": rule_owner(ctx.project, definition)} if definition else {}),
|
|
42
|
+
**({"business_rule": True} if "business_rule" in definition.get("tags", []) else {})}))
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@check("DBTR002", "Model with a run error", stage="continuous", cost="statistical", emits=("DBTR003",))
|
|
47
|
+
def failed_models(ctx: Context):
|
|
48
|
+
r = ctx.dbt_results
|
|
49
|
+
if not r:
|
|
50
|
+
return []
|
|
51
|
+
out = []
|
|
52
|
+
skipped = [x["unique_id"] for x in r["results"] if x["status"] == "skipped" and not x["unique_id"].startswith(("test.", "unit_test."))]
|
|
53
|
+
for x in r["results"]:
|
|
54
|
+
if x["unique_id"].startswith(("test.", "unit_test.")) or x["status"] != "error":
|
|
55
|
+
continue
|
|
56
|
+
n = _node(ctx, x["unique_id"])
|
|
57
|
+
out.append(Finding("DBTR002", "high", tr("{model}: run error", model=n.name if n else x["unique_id"]),
|
|
58
|
+
(x["message"] or "")[:300], [x["unique_id"]], "continuous", {"skipped_downstream": len(skipped)}))
|
|
59
|
+
# A failing test can block descendants even when every executed model succeeded.
|
|
60
|
+
if skipped and any(x["status"] in ("fail", "error") for x in r["results"]):
|
|
61
|
+
out.append(Finding("DBTR003", "medium", tr("{n} model(s) did not run because of an upstream failure", n=len(skipped)),
|
|
62
|
+
tr("dbt skipped them; their data is out of date."), skipped[:20], "continuous", {}))
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@check("DBTR004", "Model got slower", stage="continuous", cost="statistical")
|
|
67
|
+
def slow_models(ctx: Context):
|
|
68
|
+
r = ctx.dbt_results
|
|
69
|
+
if not r or ctx.store is None:
|
|
70
|
+
return []
|
|
71
|
+
out = []
|
|
72
|
+
for x in r["results"]:
|
|
73
|
+
if x["unique_id"].startswith(("test.", "unit_test.")) or x["status"] not in ("success", "pass"):
|
|
74
|
+
continue
|
|
75
|
+
med, n = median_history(ctx.store, x["unique_id"])
|
|
76
|
+
# the history already includes this run when recorded first; require a sample and a clear slowdown
|
|
77
|
+
if med and n >= 5 and x["time"] > 2 * med and x["time"] - med > 5:
|
|
78
|
+
node = _node(ctx, x["unique_id"])
|
|
79
|
+
out.append(Finding("DBTR004", "medium", tr("{model}: {s}s (median {median}s)", model=node.name if node else x["unique_id"],
|
|
80
|
+
s=f"{x['time']:.0f}", median=f"{med:.0f}"),
|
|
81
|
+
tr("More than twice the usual time; risk of missing the window and of using more memory."),
|
|
82
|
+
[x["unique_id"]], "continuous", {"time": x["time"], "median": med}))
|
|
83
|
+
return out
|