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,180 @@
|
|
|
1
|
+
"""Deeper checks: null-rate drift, join fan-out, plan regression, key types, contracts."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import statistics
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
import sqlglot
|
|
8
|
+
from sqlglot import exp
|
|
9
|
+
from sqlglot.optimizer.scope import traverse_scope
|
|
10
|
+
|
|
11
|
+
from ..i18n import tr
|
|
12
|
+
from ..lineage import DIALECTS
|
|
13
|
+
from ..model import Finding
|
|
14
|
+
from . import Context, check
|
|
15
|
+
|
|
16
|
+
NUMERIC = ("INT", "BIGINT", "SMALLINT", "TINYINT", "HUGEINT", "DECIMAL", "NUMERIC", "DOUBLE", "FLOAT", "REAL", "NUMBER", "INTEGER", "LONG")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _family(t: str) -> str:
|
|
20
|
+
u = (t or "").upper()
|
|
21
|
+
if any(u.startswith(n) for n in NUMERIC):
|
|
22
|
+
return "number"
|
|
23
|
+
if u.startswith(("VARCHAR", "TEXT", "STRING", "CHAR")):
|
|
24
|
+
return "string"
|
|
25
|
+
if u.startswith(("DATE", "TIMESTAMP", "TIME")):
|
|
26
|
+
return "datetime"
|
|
27
|
+
return u or "?"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _join_equalities(ctx: Context, n):
|
|
31
|
+
"""Yield (left_uid, left_col, right_uid, right_col) of `a.x = b.y` joins between physical project relations."""
|
|
32
|
+
d = DIALECTS.get(ctx.project.adapter)
|
|
33
|
+
rel = ctx.project.by_relation()
|
|
34
|
+
schema = ctx.project.sqlglot_schema()
|
|
35
|
+
try:
|
|
36
|
+
from sqlglot.optimizer import qualify
|
|
37
|
+
tree = qualify.qualify(sqlglot.parse_one(n.compiled_code, read=d), dialect=d, schema=schema, validate_qualify_columns=False, identify=False)
|
|
38
|
+
scopes = traverse_scope(tree)
|
|
39
|
+
except Exception:
|
|
40
|
+
return
|
|
41
|
+
for sc in scopes:
|
|
42
|
+
phys = {}
|
|
43
|
+
for alias, src in sc.sources.items():
|
|
44
|
+
if isinstance(src, exp.Table):
|
|
45
|
+
u = rel.get((src.catalog.lower(), src.db.lower(), src.name.lower()))
|
|
46
|
+
if u:
|
|
47
|
+
phys[alias] = u
|
|
48
|
+
for j in sc.expression.args.get("joins", []) or []:
|
|
49
|
+
on = j.args.get("on")
|
|
50
|
+
if on is None:
|
|
51
|
+
continue
|
|
52
|
+
for eq in on.find_all(exp.EQ):
|
|
53
|
+
l, r = eq.left, eq.right
|
|
54
|
+
if isinstance(l, exp.Column) and isinstance(r, exp.Column) and l.table in phys and r.table in phys:
|
|
55
|
+
yield phys[l.table], l.name.lower(), phys[r.table], r.name.lower()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@check("SQL015", "Join key with incompatible types", stage="pre-merge", cost="static")
|
|
59
|
+
def join_type_mismatch(ctx: Context):
|
|
60
|
+
out = []
|
|
61
|
+
for uid, n in ctx.project.nodes.items():
|
|
62
|
+
if n.resource_type not in ("model", "snapshot") or n.language != "sql" or not n.compiled_code:
|
|
63
|
+
continue
|
|
64
|
+
for lu, lc, ru, rc in _join_equalities(ctx, n):
|
|
65
|
+
lt = ctx.project.nodes[lu].columns.get(lc)
|
|
66
|
+
rt = ctx.project.nodes[ru].columns.get(rc)
|
|
67
|
+
if lt and rt and lt.type and rt.type and _family(lt.type) != _family(rt.type):
|
|
68
|
+
out.append(Finding("SQL015", "medium", tr("{model}: join {left} ({left_type}) = {right} ({right_type})", model=n.name,
|
|
69
|
+
left=f"{ctx.project.nodes[lu].name}.{lc}", left_type=lt.type,
|
|
70
|
+
right=f"{ctx.project.nodes[ru].name}.{rc}", right_type=rt.type),
|
|
71
|
+
tr("Types of different families force an implicit conversion: it prevents hash/index use, can fail at runtime and match wrong values."),
|
|
72
|
+
[uid], "pre-merge", {"left": f"{lt.type}", "right": f"{rt.type}",
|
|
73
|
+
"recommendation": tr("align the types in the staging layer (one explicit cast)")}))
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@check("PRB004", "Join fan-out (non-unique key)", stage="pre-run", cost="probe")
|
|
78
|
+
def join_fanout(ctx: Context):
|
|
79
|
+
if ctx.warehouse is None:
|
|
80
|
+
return []
|
|
81
|
+
out, seen = [], set()
|
|
82
|
+
for uid, n in ctx.project.nodes.items():
|
|
83
|
+
if n.resource_type not in ("model", "snapshot") or n.language != "sql" or not n.compiled_code:
|
|
84
|
+
continue
|
|
85
|
+
for lu, lc, ru, rc in _join_equalities(ctx, n):
|
|
86
|
+
for side_uid, col in ((lu, lc), (ru, rc)):
|
|
87
|
+
key = (uid, side_uid, col)
|
|
88
|
+
node = ctx.project.nodes[side_uid]
|
|
89
|
+
if key in seen or not node.relation:
|
|
90
|
+
continue
|
|
91
|
+
seen.add(key)
|
|
92
|
+
try:
|
|
93
|
+
dup = int(ctx.warehouse.scalar(f'select count(*) - count(distinct "{col}") from {node.relation} where "{col}" is not null'))
|
|
94
|
+
tot = int(ctx.warehouse.scalar(f"select count(*) from {node.relation}"))
|
|
95
|
+
except Exception:
|
|
96
|
+
continue
|
|
97
|
+
other_dup_side_unique = any(t["name"] == "unique" and t.get("column") == col for t in node.tests)
|
|
98
|
+
if dup > 0 and not other_dup_side_unique:
|
|
99
|
+
out.append(Finding("PRB004", "high" if dup * 10 > tot else "medium",
|
|
100
|
+
tr("{model}: join on {key} multiplies rows ({dup} duplicated out of {total})", model=n.name,
|
|
101
|
+
key=f"{node.name}.{col}", dup=dup, total=tot),
|
|
102
|
+
tr("The join key is not unique on this side: each repeated value multiplies the rows of the other side (inflated metrics, memory)."),
|
|
103
|
+
[uid], "pre-run", {"duplicates": dup, "rows": tot, "side": f"{node.name}.{col}",
|
|
104
|
+
"recommendation": tr("aggregate before joining or join on a unique key")}))
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@check("PRB003", "Null-rate drift", stage="pre-run", cost="probe")
|
|
109
|
+
def null_rate_drift(ctx: Context):
|
|
110
|
+
if ctx.warehouse is None or ctx.store is None:
|
|
111
|
+
return []
|
|
112
|
+
out = []
|
|
113
|
+
for uid, n in ctx.project.nodes.items():
|
|
114
|
+
if n.resource_type not in ("model", "seed") or not n.relation:
|
|
115
|
+
continue
|
|
116
|
+
cols = list(ctx.project.actual_columns(uid))[:15]
|
|
117
|
+
if not cols:
|
|
118
|
+
continue
|
|
119
|
+
try:
|
|
120
|
+
sel = ", ".join(f'avg(case when "{c}" is null then 1.0 else 0.0 end)' for c in cols)
|
|
121
|
+
rates = ctx.warehouse.rows(f"select {sel} from {n.relation}")[0]
|
|
122
|
+
except Exception:
|
|
123
|
+
continue
|
|
124
|
+
for c, r in zip(cols, rates):
|
|
125
|
+
r = float(r or 0.0)
|
|
126
|
+
key = f"null:{uid}:{c}"
|
|
127
|
+
hist = [v for _, v in ctx.store.history(key)][-20:]
|
|
128
|
+
if ctx.record_probe_history:
|
|
129
|
+
ctx.store.add_history(key, time.time(), r)
|
|
130
|
+
if len(hist) >= 3:
|
|
131
|
+
med = statistics.median(hist)
|
|
132
|
+
if r - med >= 0.2 and r >= 2 * max(med, 0.01):
|
|
133
|
+
out.append(Finding("PRB003", "high" if r - med >= 0.5 else "medium",
|
|
134
|
+
tr("{column}: {rate} nulls (usually {median})", column=f"{n.name}.{c}", rate=f"{r:.0%}", median=f"{med:.0%}"),
|
|
135
|
+
tr("The null rate went up a lot; it usually means a broken upstream column, a join that does not match or a format change."),
|
|
136
|
+
[uid] + ctx.project.downstream(uid)[:10], "pre-run", {"rate": r, "median": med, "history": len(hist)}))
|
|
137
|
+
elif "PRB003" in ctx.required_checks:
|
|
138
|
+
ctx.failed_checks.add("PRB003")
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@check("SQL014", "Plan got worse in the PR", stage="pre-merge", cost="probe")
|
|
143
|
+
def plan_regression(ctx: Context):
|
|
144
|
+
"""Compare the estimated plan of the base and new version for models whose SQL changed."""
|
|
145
|
+
if ctx.warehouse is None or ctx.base_project is None:
|
|
146
|
+
return []
|
|
147
|
+
base_by_rel = {n.relation: n for n in ctx.base_project.nodes.values() if n.relation}
|
|
148
|
+
out = []
|
|
149
|
+
for uid, n in ctx.project.nodes.items():
|
|
150
|
+
b = base_by_rel.get(n.relation)
|
|
151
|
+
if not b or n.resource_type != "model" or n.language != "sql" or not n.compiled_code or b.compiled_code == n.compiled_code:
|
|
152
|
+
continue
|
|
153
|
+
try:
|
|
154
|
+
pb, ph = ctx.warehouse.plan(b.compiled_code), ctx.warehouse.plan(n.compiled_code)
|
|
155
|
+
except Exception:
|
|
156
|
+
continue
|
|
157
|
+
heavy = {"CROSS_PRODUCT", "NESTED_LOOP_JOIN", "BLOCKWISE_NL_JOIN", "Nested Loop"}
|
|
158
|
+
new_heavy = sorted((set(ph["operators"]) & heavy) - set(pb["operators"]))
|
|
159
|
+
metric = "cost" if ph.get("cost") and pb.get("cost") else "max_rows"
|
|
160
|
+
bv, hv = pb.get(metric), ph.get(metric)
|
|
161
|
+
grew = bv and hv and hv > 2 * bv and hv - bv > 1000
|
|
162
|
+
if new_heavy or grew:
|
|
163
|
+
title = (tr("{model}: plan got worse with the change (new operator {ops})", model=n.name, ops=", ".join(new_heavy)) if new_heavy
|
|
164
|
+
else tr("{model}: plan got worse with the change ({metric}: {old} → {new})", model=n.name, metric=metric, old=f"{bv:,.0f}", new=f"{hv:,.0f}"))
|
|
165
|
+
out.append(Finding("SQL014", "high" if new_heavy else "medium", title,
|
|
166
|
+
tr("The changed version has a worse estimated plan than the base: risk of slowness and of running out of memory."),
|
|
167
|
+
[uid], "pre-merge", {"base": pb, "head": ph, "new_heavy_operators": new_heavy}))
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@check("DBT005", "Exposed model without a contract", stage="pre-merge", cost="static")
|
|
172
|
+
def missing_contract(ctx: Context):
|
|
173
|
+
out = []
|
|
174
|
+
for uid, n in ctx.project.nodes.items():
|
|
175
|
+
down = len(ctx.project.downstream(uid))
|
|
176
|
+
if n.resource_type == "model" and down >= 3 and not n.contract_enforced:
|
|
177
|
+
out.append(Finding("DBT005", "low", tr("{model}: {n} consumers and no model contract", model=n.name, n=down),
|
|
178
|
+
tr("Without `contract: {enforced: true}`, type/column changes only show up when someone consumes them."),
|
|
179
|
+
[uid], "pre-merge", {"downstream": down, "recommendation": tr("turn on contract.enforced and declare columns and types")}))
|
|
180
|
+
return out
|
intentflow/checks/dq.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Findings from Great Expectations and Soda results, linked to the graph (downstream impact)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import N_, tr
|
|
5
|
+
from ..model import Finding
|
|
6
|
+
from . import Context, check
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _index(project):
|
|
10
|
+
idx: dict[str, list[str]] = {}
|
|
11
|
+
for uid, n in project.nodes.items():
|
|
12
|
+
keys = {n.name.lower()}
|
|
13
|
+
if n.relation:
|
|
14
|
+
parts = [p.strip('"`[]').lower() for p in n.relation.split(".")]
|
|
15
|
+
keys |= {parts[-1], ".".join(parts[-2:]), ".".join(parts)}
|
|
16
|
+
for k in keys:
|
|
17
|
+
idx.setdefault(k, []).append(uid)
|
|
18
|
+
return idx
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _match(idx, table: str, *, strict: bool = False) -> str | None:
|
|
22
|
+
t = (table or "").strip('"`[]').lower().replace('"', "")
|
|
23
|
+
if strict and "." in t:
|
|
24
|
+
hit = idx.get(t)
|
|
25
|
+
return hit[0] if hit and len(set(hit)) == 1 else None
|
|
26
|
+
for key in (t, t.split(".")[-1], ".".join(t.split(".")[-2:])):
|
|
27
|
+
hit = idx.get(key)
|
|
28
|
+
if hit and len(set(hit)) == 1:
|
|
29
|
+
return hit[0]
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@check("DQ001", "Quality check failed (Great Expectations / Soda)", stage="continuous", cost="statistical")
|
|
34
|
+
def dq_failures(ctx: Context):
|
|
35
|
+
if not ctx.dq_results or ctx.project is None:
|
|
36
|
+
return []
|
|
37
|
+
idx, out = _index(ctx.project), []
|
|
38
|
+
for r in ctx.dq_results:
|
|
39
|
+
if r.status == "pass":
|
|
40
|
+
continue
|
|
41
|
+
uid = _match(idx, r.table)
|
|
42
|
+
down = len(ctx.project.downstream(uid)) if uid else 0
|
|
43
|
+
where = f"{r.table}.{r.column}" if r.column else r.table or "?"
|
|
44
|
+
sev = "medium" if r.status == "warn" or r.severity in ("warning", "info") else ("critical" if down >= 3 or r.severity == "critical" else "high")
|
|
45
|
+
tool = "Great Expectations" if r.tool == "great_expectations" else "Soda"
|
|
46
|
+
verb = tr({"fail": N_("failed"), "warn": N_("is warning"), "error": N_("did not run")}[r.status])
|
|
47
|
+
out.append(Finding("DQ001", sev, tr("{where}: {tool} `{check}` {status}", where=where, tool=tool, check=r.check, status=verb),
|
|
48
|
+
(r.detail + (" " + tr("Observed: {value}.", value=r.observed) if r.observed else "")
|
|
49
|
+
+ (" " + tr("Affects {n} downstream model(s).", n=down) if down else "")).strip(),
|
|
50
|
+
[uid] if uid else [], "continuous",
|
|
51
|
+
{"tool": r.tool, "suite": r.suite, "status": r.status, "downstream": down, "observed": r.observed,
|
|
52
|
+
**({} if uid else {"unmapped_table": r.table})}))
|
|
53
|
+
return out
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Elementary results (dbt observability package) read from the warehouse: `<schema>.elementary_test_results`.
|
|
2
|
+
|
|
3
|
+
Config: `elementary.schema` (e.g. `analytics_elementary`). Reuses the anomaly tests (volume, freshness, distribution) that
|
|
4
|
+
Elementary already computes instead of reimplementing them; IntentFlow adds downstream impact, owner and grouped incidents.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from ..i18n import N_, tr
|
|
9
|
+
from ..model import Finding
|
|
10
|
+
from . import Context, check
|
|
11
|
+
|
|
12
|
+
COLS = ("test_unique_id", "model_unique_id", "table_name", "column_name", "test_name", "test_type", "test_sub_type",
|
|
13
|
+
"status", "test_results_description", "severity", "detected_at")
|
|
14
|
+
BAD = {"fail": N_("failed"), "warn": N_("is warning"), "error": N_("did not run")}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@check("ELM001", "Failing Elementary test/anomaly", stage="continuous", cost="statistical")
|
|
18
|
+
def elementary_failures(ctx: Context):
|
|
19
|
+
schema = ctx.store.get_setting("elementary.schema") if ctx.store is not None else None
|
|
20
|
+
if not schema or ctx.warehouse is None:
|
|
21
|
+
return []
|
|
22
|
+
schema = str(schema).replace('"', "").replace(";", "")
|
|
23
|
+
try:
|
|
24
|
+
rows = ctx.warehouse.rows(f"select {', '.join(COLS)} from {schema}.elementary_test_results order by detected_at desc limit 2000")
|
|
25
|
+
except Exception: # missing schema or no permission: do not take the run down
|
|
26
|
+
return []
|
|
27
|
+
latest: dict[str, dict] = {}
|
|
28
|
+
for r in rows: # only the latest result of each test
|
|
29
|
+
d = dict(zip(COLS, r))
|
|
30
|
+
latest.setdefault(str(d["test_unique_id"]), d)
|
|
31
|
+
by_uid = ctx.project.nodes if ctx.project is not None else {}
|
|
32
|
+
out = []
|
|
33
|
+
for d in latest.values():
|
|
34
|
+
st = str(d["status"]).lower()
|
|
35
|
+
if st not in BAD:
|
|
36
|
+
continue
|
|
37
|
+
uid = d["model_unique_id"] if d["model_unique_id"] in by_uid else next(
|
|
38
|
+
(u for u, n in by_uid.items() if n.name == d["table_name"] or n.name == str(d["model_unique_id"]).split(".")[-1]), None)
|
|
39
|
+
down = len(ctx.project.downstream(uid)) if uid else 0
|
|
40
|
+
where = f"{d['table_name']}.{d['column_name']}" if d.get("column_name") else str(d["table_name"])
|
|
41
|
+
anomaly = "anomaly" in str(d["test_type"]).lower() or "anomal" in str(d["test_name"]).lower()
|
|
42
|
+
sev = "medium" if st != "fail" or str(d.get("severity")).lower() == "warn" else ("critical" if down >= 3 else "high")
|
|
43
|
+
title = (tr("{where}: Elementary anomaly `{test}` {status}", where=where, test=d["test_name"], status=tr(BAD[st])) if anomaly
|
|
44
|
+
else tr("{where}: Elementary test `{test}` {status}", where=where, test=d["test_name"], status=tr(BAD[st])))
|
|
45
|
+
out.append(Finding("ELM001", sev, title,
|
|
46
|
+
(str(d.get("test_results_description") or "") + (" " + tr("Affects {n} downstream model(s).", n=down) if down else "")).strip(),
|
|
47
|
+
[uid] if uid else [], "continuous",
|
|
48
|
+
{"test": d["test_name"], "test_type": d["test_type"], "sub_type": d["test_sub_type"], "status": st,
|
|
49
|
+
"downstream": down, "detected_at": str(d["detected_at"]), **({} if uid else {"unmapped_table": d["table_name"]})}))
|
|
50
|
+
return out
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Jobs outside the project SQL (Spark, Python, notebooks): readers of a changed column, PII read, ambiguous datasets."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..i18n import cat, tr
|
|
5
|
+
from ..lineage_api import impact
|
|
6
|
+
from ..model import Finding
|
|
7
|
+
from . import Context, check
|
|
8
|
+
from .schema_drift import diff_columns
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@check("OL001", "External job reads a changed column", stage="pre-merge", emits=("OL002", "OL003", "OL004"))
|
|
12
|
+
def external_readers(ctx: Context):
|
|
13
|
+
if not ctx.external:
|
|
14
|
+
return []
|
|
15
|
+
out = _ambiguous(ctx) + _pii(ctx)
|
|
16
|
+
if ctx.base_project is None or ctx.base_lineage is None:
|
|
17
|
+
return out
|
|
18
|
+
for buid, _huid, removed, _added, changed in diff_columns(ctx.base_project, ctx.project):
|
|
19
|
+
bn = ctx.base_project.nodes[buid]
|
|
20
|
+
for col, what in [(c, tr("removed")) for c in removed] + [(c, tr("type {old} → {new}", old=t0, new=t1)) for c, (t0, t1) in changed.items()]:
|
|
21
|
+
try:
|
|
22
|
+
rows = impact(ctx.base_project, ctx.base_lineage, bn.name, col, external=ctx.external)["affected"]
|
|
23
|
+
except ValueError:
|
|
24
|
+
continue
|
|
25
|
+
removed_col = col in removed
|
|
26
|
+
for r in (x for x in rows if x.get("kind") == "job"):
|
|
27
|
+
out.append(Finding("OL001", "critical" if removed_col else "high",
|
|
28
|
+
_reads_title(r["name"], f"{bn.name}.{col}", what),
|
|
29
|
+
(tr("External job ({source}) reads the output of job {via}, which reads this column.", source=r["source"], via=r["via_job"])
|
|
30
|
+
if r.get("via_job") else
|
|
31
|
+
tr("External job ({source}) reads this column or something derived from it and is not validated by dbt/SQLMesh.", source=r["source"])),
|
|
32
|
+
[buid], "pre-merge",
|
|
33
|
+
{"job": r["name"], "model": bn.name, "column": col, "change": "removed" if removed_col else "type", "source": r["source"],
|
|
34
|
+
"reads": r["columns"], "writes": r["writes"], "owner": r["owner"], "via_job": r.get("via_job")}))
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _reads_title(job: str, column: str, what):
|
|
39
|
+
return cat(tr("{job} reads {column}", job=job, column=column), " (", what, ")")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _ambiguous(ctx: Context):
|
|
43
|
+
"""OL002: dataset read by a job that matches more than one model (the impact silently disappears); OL004: job without an application name."""
|
|
44
|
+
from .. import external
|
|
45
|
+
strict = bool(ctx.policies.get("external_warn_unmatched")) # opt-in: a dataset without a matching node also becomes a warning
|
|
46
|
+
out = []
|
|
47
|
+
for ds, v in external.unmatched(ctx.project, ctx.external).items():
|
|
48
|
+
ambiguous = v["reason"] == "ambiguous"
|
|
49
|
+
if not ambiguous and not strict:
|
|
50
|
+
continue
|
|
51
|
+
why = (tr("More than one model ends with this name; the impact on the jobs that read it is not computed.") if ambiguous
|
|
52
|
+
else tr("No model matches this name; project changes do not reach the jobs that read it."))
|
|
53
|
+
out.append(Finding("OL002", "medium" if ambiguous else "low",
|
|
54
|
+
tr("dataset '{dataset}' is ambiguous in the project", dataset=ds) if ambiguous else tr("dataset '{dataset}' is missing from the project", dataset=ds),
|
|
55
|
+
why + " " + tr("Declare an alias: `intentflow lineage --alias DATASET=MODEL`."), [], "pre-merge",
|
|
56
|
+
{"dataset": ds, "jobs": v["jobs"], "reason": v["reason"], "suggestions": external.suggest(ctx.project, ds)}))
|
|
57
|
+
for j in sorted({r.job for r in ctx.external if r.job.rsplit(".", 1)[-1].lower() in ("pyspark_shell", "spark-shell", "sparksession")}):
|
|
58
|
+
out.append(Finding("OL004", "low", tr("job '{job}' without an application name", job=j),
|
|
59
|
+
tr("Spark used the default name; different jobs get mixed up. Set `appName(...)` (or `spark.app.name`)."),
|
|
60
|
+
[], "pre-merge", {"job": j}))
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _pii(ctx: Context):
|
|
65
|
+
"""An external job reads a PII column (or an unmasked derivative) and writes elsewhere: its masking cannot be verified from here."""
|
|
66
|
+
from .. import external
|
|
67
|
+
from .dbt_quality import _pii_columns
|
|
68
|
+
if ctx.lineage is None:
|
|
69
|
+
return []
|
|
70
|
+
allowed = set(ctx.policies.get("pii_allowed_jobs", []))
|
|
71
|
+
pii: dict[tuple[str, str], tuple[str, str]] = {}
|
|
72
|
+
for u, c in _pii_columns(ctx.project):
|
|
73
|
+
origin, frontier = f"{ctx.project.nodes[u].name}.{c}", [(u, c)]
|
|
74
|
+
pii.setdefault((u, c), (origin, "direct"))
|
|
75
|
+
while frontier:
|
|
76
|
+
x = frontier.pop()
|
|
77
|
+
for e in ctx.lineage.downstream_of(*x):
|
|
78
|
+
if not e.masked and (e.dst, e.dst_col) not in pii:
|
|
79
|
+
pii[(e.dst, e.dst_col)] = (origin, "derived")
|
|
80
|
+
frontier.append((e.dst, e.dst_col))
|
|
81
|
+
out, seen = [], set()
|
|
82
|
+
for uid, col, r in external.resolve(ctx.project, ctx.external):
|
|
83
|
+
hit = pii.get((uid, col))
|
|
84
|
+
if not hit or r.job in allowed or (r.job, uid, col) in seen:
|
|
85
|
+
continue
|
|
86
|
+
seen.add((r.job, uid, col))
|
|
87
|
+
out.append(Finding("OL003", "high", tr("{job} reads PII {column}", job=r.job, column=f"{ctx.project.nodes[uid].name}.{col}"),
|
|
88
|
+
tr("A job outside the project reads an unmasked PII column; its masking cannot be verified. Confirm it or list it in `pii_allowed_jobs`."),
|
|
89
|
+
[uid], "pre-merge", {"job": r.job, "model": ctx.project.nodes[uid].name, "column": col, "origin": hit[0],
|
|
90
|
+
"pii": hit[1], "writes": list(r.writes), "owner": r.owner, "source": r.source}))
|
|
91
|
+
return out
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Health of Delta/Iceberg tables: small files (cost and latency) and schema evolving incompatibly."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .. import lakehouse
|
|
5
|
+
from ..i18n import tr
|
|
6
|
+
from ..model import Finding
|
|
7
|
+
from . import Context, check
|
|
8
|
+
|
|
9
|
+
SMALL_BYTES, SMALL_COUNT = 32 * 1024 * 1024, 100
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@check("LAKE001", "Lakehouse table with small files or a breaking schema", stage="continuous", cost="statistical")
|
|
13
|
+
def lakehouse_health(ctx: Context):
|
|
14
|
+
paths = lakehouse.tables(ctx.store.get_setting("lakehouse.tables") if ctx.store is not None else None)
|
|
15
|
+
if not paths:
|
|
16
|
+
return []
|
|
17
|
+
small_b = float(ctx.policies.get("small_file_bytes", SMALL_BYTES))
|
|
18
|
+
small_n = int(ctx.policies.get("small_file_count", SMALL_COUNT))
|
|
19
|
+
nodes = ctx.project.nodes if ctx.project is not None else {}
|
|
20
|
+
out = []
|
|
21
|
+
for p in paths:
|
|
22
|
+
try:
|
|
23
|
+
t = lakehouse.inspect(p)
|
|
24
|
+
except Exception as e:
|
|
25
|
+
out.append(Finding("LAKE001", "low", tr("{path}: unreadable table ({error})", path=p, error=type(e).__name__), str(e)[:200], [], "continuous",
|
|
26
|
+
{"path": p, "kind": "unreadable"}))
|
|
27
|
+
continue
|
|
28
|
+
uid = next((u for u, n in nodes.items() if n.name == t["name"]), None)
|
|
29
|
+
down = len(ctx.project.downstream(uid)) if uid else 0
|
|
30
|
+
ref = [uid] if uid else [f"lake:{t['name']}"]
|
|
31
|
+
if t["files"] >= small_n and t["avg_file_bytes"] < small_b:
|
|
32
|
+
out.append(Finding("LAKE001", "medium", tr("{table}: {n} files averaging {mb} MB", table=t["name"], n=t["files"], mb=f"{t['avg_file_bytes'] / 1e6:.1f}"),
|
|
33
|
+
tr("Many small files raise the listing/open cost and the query latency."), ref, "continuous",
|
|
34
|
+
{"kind": "small_files", "files": t["files"], "avg_bytes": t["avg_file_bytes"], "format": t["format"],
|
|
35
|
+
"recommendation": tr("compact (OPTIMIZE in Delta; rewrite_data_files in Iceberg) and tune the target write size")}))
|
|
36
|
+
old, new = t.get("prev_schema"), t["schema"]
|
|
37
|
+
if old:
|
|
38
|
+
removed = sorted(set(old) - set(new))
|
|
39
|
+
retyped = sorted(c for c in set(old) & set(new) if old[c] != new[c])
|
|
40
|
+
if removed or retyped:
|
|
41
|
+
what = [tr("`{column}` removed", column=c) for c in removed] + [f"`{c}`: {old[c]} → {new[c]}" for c in retyped]
|
|
42
|
+
out.append(Finding("LAKE001", "critical" if down else "high",
|
|
43
|
+
tr("{table}: schema changed incompatibly ({changes})", table=t["name"], changes="; ".join(what)),
|
|
44
|
+
tr("Consumers that read these columns break.") + (" " + tr("Affects {n} downstream model(s).", n=down) if down else ""), ref, "continuous",
|
|
45
|
+
{"kind": "schema_break", "removed": removed, "retyped": retyped, "downstream": down, "format": t["format"]}))
|
|
46
|
+
return out
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""SQL lint with SQLFluff over each model's compiled SQL (optional: `pip install intentdataflow[lint]`).
|
|
2
|
+
|
|
3
|
+
Only rules that point to correctness/performance risk, not style (layout and capitalization are left out). Customizable with
|
|
4
|
+
`policy.lint_rules` (list of codes, e.g. ["AM04","RF02"]). Results are cached by SQL hash.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
|
|
10
|
+
from ..i18n import N_, tr
|
|
11
|
+
from ..model import Finding
|
|
12
|
+
from . import Context, check
|
|
13
|
+
|
|
14
|
+
DEFAULT_RULES = ["AM01", "AM02", "AM03", "AM04", "AM06", "CV05", "CV08", "RF01", "RF02", "RF03", "ST03", "ST05", "ST07", "ST08"]
|
|
15
|
+
DIALECT = {"spark": "sparksql", "databricks": "databricks", "sqlserver": "tsql", "mysql": "mysql", "duckdb": "duckdb"}
|
|
16
|
+
SEVERITY = {"AM04": "medium", "AM02": "medium", "RF02": "medium", "CV05": "medium", "AM06": "low", "ST07": "low"}
|
|
17
|
+
WHY = {
|
|
18
|
+
"AM01": N_("DISTINCT with GROUP BY: the DISTINCT is redundant and costs an extra sort."),
|
|
19
|
+
"AM02": N_("UNION without ALL deduplicates (costs a sort/hash); use UNION ALL if you do not need to deduplicate."),
|
|
20
|
+
"AM03": N_("ORDER BY with an ambiguous direction across columns."),
|
|
21
|
+
"AM04": N_("`SELECT *`: the column set changes with the upstream and silently breaks consumers."),
|
|
22
|
+
"AM05": N_("JOIN without a qualifier (INNER/LEFT): the intent stays implicit."),
|
|
23
|
+
"AM06": N_("GROUP BY/ORDER BY by position and by name mixed: fragile to order changes."),
|
|
24
|
+
"CV05": N_("Comparison with NULL using `=`/`<>`: always unknown; use IS [NOT] NULL."),
|
|
25
|
+
"CV08": N_("RIGHT JOIN: use LEFT JOIN swapping the order; more readable and less error-prone."),
|
|
26
|
+
"RF01": N_("Reference to a table/alias that is not in the FROM."),
|
|
27
|
+
"RF02": N_("Unqualified column in a query with several tables: ambiguous, and it breaks when the upstream gains the column."),
|
|
28
|
+
"RF03": N_("Mix of qualified and unqualified columns."),
|
|
29
|
+
"ST03": N_("CTE defined and never used."),
|
|
30
|
+
"ST05": N_("Subquery in a JOIN/FROM that would be clearer and cheaper as a CTE."),
|
|
31
|
+
"ST07": N_("`USING` instead of an explicit `ON`: column ambiguity."),
|
|
32
|
+
"ST08": N_("`DISTINCT(col)` with parentheses is misleading: DISTINCT applies to the whole row."),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _linter(dialect: str, rules: list[str]):
|
|
37
|
+
from sqlfluff.core import FluffConfig, Linter
|
|
38
|
+
return Linter(config=FluffConfig(overrides={"dialect": dialect, "rules": ",".join(rules)}))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def lint_sql(sql: str, dialect: str, rules: list[str]) -> list[dict]:
|
|
42
|
+
res = _linter(dialect, rules).lint_string(sql)
|
|
43
|
+
# PRS/LXR/TMP = parse/template error of SQLFluff itself, not a problem in the SQL
|
|
44
|
+
return [{"rule": v.rule_code(), "line": v.line_no, "desc": v.desc()} for v in res.get_violations() if v.rule_code() not in ("PRS", "LXR", "TMP")]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@check("LINT001", "SQL problem reported by SQLFluff", stage="pre-merge", cost="static")
|
|
48
|
+
def sql_lint(ctx: Context):
|
|
49
|
+
# opt-in: SQLFluff takes seconds per model; `intentflow config set lint.enabled true` turns it on (results cached by SQL hash)
|
|
50
|
+
if ctx.project is None or ctx.store is None or not ctx.store.get_setting("lint.enabled"):
|
|
51
|
+
return []
|
|
52
|
+
try:
|
|
53
|
+
import sqlfluff # noqa: F401
|
|
54
|
+
except ImportError:
|
|
55
|
+
return []
|
|
56
|
+
rules = list(ctx.policies.get("lint_rules") or DEFAULT_RULES)
|
|
57
|
+
d = ctx.project.adapter or "ansi"
|
|
58
|
+
dialect = DIALECT.get(d, d)
|
|
59
|
+
out = []
|
|
60
|
+
for uid, n in ctx.project.nodes.items():
|
|
61
|
+
sql = n.compiled_code or ""
|
|
62
|
+
if n.resource_type not in ("model", "snapshot") or n.language != "sql" or not sql.strip():
|
|
63
|
+
continue
|
|
64
|
+
key = "lint:" + hashlib.sha1(f"{sql}|{dialect}|{','.join(rules)}|v1".encode()).hexdigest()
|
|
65
|
+
hit = ctx.store.get(key) if ctx.store is not None and hasattr(ctx.store, "get") else None
|
|
66
|
+
if hit is None:
|
|
67
|
+
try:
|
|
68
|
+
hit = {"v": lint_sql(sql, dialect, rules)}
|
|
69
|
+
except Exception: # unknown dialect or SQL the SQLFluff parser does not understand
|
|
70
|
+
hit = {"v": []}
|
|
71
|
+
if ctx.store is not None and hasattr(ctx.store, "set"):
|
|
72
|
+
ctx.store.set(key, hit)
|
|
73
|
+
by_rule: dict[str, list[int]] = {}
|
|
74
|
+
for v in hit["v"]:
|
|
75
|
+
by_rule.setdefault(v["rule"], []).append(v["line"])
|
|
76
|
+
for rule, lines in sorted(by_rule.items()):
|
|
77
|
+
why = tr(WHY[rule]) if rule in WHY else tr("SQLFluff rule.")
|
|
78
|
+
out.append(Finding("LINT001", SEVERITY.get(rule, "low"), f"{n.name}: {rule} ({len(lines)}x)", why, [uid],
|
|
79
|
+
"pre-merge", {"rule": rule, "lines": lines[:10], "count": len(lines), "file": n.path,
|
|
80
|
+
"recommendation": why if rule in WHY else ""}))
|
|
81
|
+
return out
|