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
intentflow/catalogs.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Data catalogs (AWS Glue Data Catalog, Databricks Unity Catalog): a snapshot of table schemas, without going through dbt.
|
|
2
|
+
|
|
3
|
+
`collect(store)` writes `state.catalog.cur` and, when the snapshot changes, moves the previous one to `state.catalog.prev`; check CAT001 compares both.
|
|
4
|
+
Config: `catalog.glue` (true; uses `aws.region`), `catalog.unity` (workspace host; token in DATABRICKS_TOKEN),
|
|
5
|
+
`catalog.unity_catalogs` (list/text with the catalogs; empty = all), `catalog.include` (`db.` / `catalog.schema.` prefixes to watch).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from .orchestrators import http_json
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GlueCatalog:
|
|
17
|
+
def __init__(self, region=None, endpoint_url=None, boto=None):
|
|
18
|
+
if boto is None:
|
|
19
|
+
from .orchestrators.aws import client
|
|
20
|
+
boto = client("glue", region, endpoint_url)
|
|
21
|
+
self.c = boto
|
|
22
|
+
|
|
23
|
+
def snapshot(self, include: list[str] | None = None) -> dict[str, dict[str, str]]:
|
|
24
|
+
out: dict[str, dict[str, str]] = {}
|
|
25
|
+
for dbs in self.c.get_paginator("get_databases").paginate():
|
|
26
|
+
for d in dbs.get("DatabaseList", []):
|
|
27
|
+
if include and not any(f"{d['Name']}.".startswith(i) or i.startswith(d["Name"] + ".") for i in include):
|
|
28
|
+
continue
|
|
29
|
+
for ts in self.c.get_paginator("get_tables").paginate(DatabaseName=d["Name"]):
|
|
30
|
+
for t in ts.get("TableList", []):
|
|
31
|
+
cols = (t.get("StorageDescriptor") or {}).get("Columns", []) + t.get("PartitionKeys", [])
|
|
32
|
+
out[f"{d['Name']}.{t['Name']}".lower()] = {c["Name"].lower(): c.get("Type", "") for c in cols}
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class UnityCatalog:
|
|
37
|
+
def __init__(self, host: str, fetch=http_json):
|
|
38
|
+
h = host.rstrip("/")
|
|
39
|
+
self.base = h if "://" in h else f"https://{h}"
|
|
40
|
+
self.fetch = fetch
|
|
41
|
+
|
|
42
|
+
def _h(self) -> dict:
|
|
43
|
+
t = os.environ.get("DATABRICKS_TOKEN")
|
|
44
|
+
return {"Authorization": f"Bearer {t}"} if t else {}
|
|
45
|
+
|
|
46
|
+
def _get(self, path: str):
|
|
47
|
+
return self.fetch(f"{self.base}/api/2.1/unity-catalog{path}", self._h()) or {}
|
|
48
|
+
|
|
49
|
+
def snapshot(self, catalogs: list[str] | None = None, include: list[str] | None = None) -> dict[str, dict[str, str]]:
|
|
50
|
+
out: dict[str, dict[str, str]] = {}
|
|
51
|
+
cats = catalogs or [c["name"] for c in self._get("/catalogs").get("catalogs", [])]
|
|
52
|
+
for c in cats:
|
|
53
|
+
for s in self._get(f"/schemas?catalog_name={c}").get("schemas", []):
|
|
54
|
+
prefix = f"{c}.{s['name']}."
|
|
55
|
+
if include and not any(prefix.startswith(i) or i.startswith(prefix) for i in include):
|
|
56
|
+
continue
|
|
57
|
+
token = None
|
|
58
|
+
while True:
|
|
59
|
+
d = self._get(f"/tables?catalog_name={c}&schema_name={s['name']}" + (f"&page_token={token}" if token else ""))
|
|
60
|
+
for t in d.get("tables", []):
|
|
61
|
+
out[f"{c}.{s['name']}.{t['name']}".lower()] = {x["name"].lower(): x.get("type_text") or x.get("type_name", "")
|
|
62
|
+
for x in t.get("columns", [])}
|
|
63
|
+
token = d.get("next_page_token")
|
|
64
|
+
if not token:
|
|
65
|
+
break
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _list(v) -> list[str]:
|
|
70
|
+
if isinstance(v, str):
|
|
71
|
+
v = [x.strip() for x in v.split(",")]
|
|
72
|
+
return [str(x) for x in (v or []) if str(x).strip()]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def collect(store, glue=None, unity=None, now: float | None = None) -> dict:
|
|
76
|
+
res = {"tables": 0, "changed": False, "errors": []}
|
|
77
|
+
snap: dict[str, dict[str, str]] = {}
|
|
78
|
+
include = _list(store.get_setting("catalog.include")) or None
|
|
79
|
+
if store.get_setting("catalog.glue"):
|
|
80
|
+
try:
|
|
81
|
+
g = glue or GlueCatalog(store.get_setting("aws.region"), store.get_setting("aws.endpoint_url"))
|
|
82
|
+
snap.update({f"glue:{k}": v for k, v in g.snapshot(include).items()})
|
|
83
|
+
except Exception as e:
|
|
84
|
+
res["errors"].append(f"glue: {str(e)[:150]}")
|
|
85
|
+
if store.get_setting("catalog.unity"):
|
|
86
|
+
try:
|
|
87
|
+
u = unity or UnityCatalog(store.get_setting("catalog.unity"))
|
|
88
|
+
snap.update({f"unity:{k}": v for k, v in u.snapshot(_list(store.get_setting("catalog.unity_catalogs")) or None, include).items()})
|
|
89
|
+
except Exception as e:
|
|
90
|
+
res["errors"].append(f"unity: {str(e)[:150]}")
|
|
91
|
+
if not snap:
|
|
92
|
+
return res
|
|
93
|
+
cur = store.get_setting("state.catalog.cur")
|
|
94
|
+
if cur is not None and cur != snap: # changed: the current snapshot becomes the previous one
|
|
95
|
+
store.set_setting("state.catalog.prev", cur)
|
|
96
|
+
res["changed"] = True
|
|
97
|
+
store.set_setting("state.catalog.cur", snap)
|
|
98
|
+
store.set_setting("state.catalog.ts", now or time.time())
|
|
99
|
+
res["tables"] = len(snap)
|
|
100
|
+
return res
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""Compare declared controls/interfaces before deployment; never execute project code.
|
|
2
|
+
|
|
3
|
+
Changed test SQL needs review: arbitrary SQL cannot reliably be classified as
|
|
4
|
+
stronger or weaker. Digests bind an acknowledgement to the exact change, while
|
|
5
|
+
the public report deliberately omits raw SQL and arbitrary custom metadata.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
from collections import Counter, defaultdict
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import sqlglot
|
|
15
|
+
|
|
16
|
+
from .i18n import tr
|
|
17
|
+
|
|
18
|
+
RELATIONS = {"model", "seed", "snapshot", "source"}
|
|
19
|
+
TESTS = {"test", "unit_test"}
|
|
20
|
+
MAX_IMPACT_PREVIEW = 100
|
|
21
|
+
# dbt build records these runtime helpers on test nodes; docs/parse may omit
|
|
22
|
+
# those edges. Include them consistently, still comparing their actual bodies.
|
|
23
|
+
DBT_TEST_EXECUTION_MACROS = ("macro.dbt.get_limit_subquery_sql", "macro.dbt.should_store_failures", "macro.dbt.statement")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _hash(value):
|
|
27
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _sql(value):
|
|
31
|
+
"""Ignore layout/comments and pure dbt config calls, preserving literal values."""
|
|
32
|
+
if not value:
|
|
33
|
+
return []
|
|
34
|
+
try:
|
|
35
|
+
tokens = sqlglot.tokenize(value)
|
|
36
|
+
out, i = [], 0
|
|
37
|
+
while i < len(tokens):
|
|
38
|
+
if [t.token_type.name for t in tokens[i:i+4]] == ["L_BRACE", "L_BRACE", "VAR", "L_PAREN"] and tokens[i+2].text == "config":
|
|
39
|
+
depth, j = 1, i + 4
|
|
40
|
+
while j < len(tokens) and depth:
|
|
41
|
+
depth += (tokens[j].token_type.name == "L_PAREN") - (tokens[j].token_type.name == "R_PAREN")
|
|
42
|
+
j += 1
|
|
43
|
+
if not depth and [t.token_type.name for t in tokens[j:j+2]] == ["R_BRACE", "R_BRACE"]:
|
|
44
|
+
i = j + 2
|
|
45
|
+
continue
|
|
46
|
+
token = tokens[i]
|
|
47
|
+
kind = token.token_type.name
|
|
48
|
+
text = token.text if kind in {"VAR", "IDENTIFIER"} or "STRING" in kind else token.text.upper()
|
|
49
|
+
out.append((kind, text))
|
|
50
|
+
i += 1
|
|
51
|
+
return out
|
|
52
|
+
except Exception:
|
|
53
|
+
# Unsupported syntax remains significant; never discard an unknown body.
|
|
54
|
+
return {"unparsed": value.replace("\r\n", "\n").strip()}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _nodes(manifest):
|
|
58
|
+
out = {}
|
|
59
|
+
for key in ("nodes", "sources", "exposures", "semantic_models", "metrics", "saved_queries", "unit_tests"):
|
|
60
|
+
section = manifest.get(key) or {}
|
|
61
|
+
if not isinstance(section, dict) or any(not isinstance(n, dict) for n in section.values()):
|
|
62
|
+
raise ValueError(tr("change comparison requires valid manifest resources"))
|
|
63
|
+
for uid, node in section.items():
|
|
64
|
+
if not isinstance(node.get("config") or {}, dict) or not isinstance(node.get("depends_on") or {}, dict):
|
|
65
|
+
raise ValueError(tr("change comparison requires valid manifest resources"))
|
|
66
|
+
if (node.get("config") or {}).get("enabled", True):
|
|
67
|
+
out[uid] = node
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _code(node):
|
|
72
|
+
raw = node.get("raw_code") or node.get("raw_sql") or ""
|
|
73
|
+
if (node.get("language") or "sql").lower() != "sql":
|
|
74
|
+
return raw.replace("\r\n", "\n") # Python indentation is significant.
|
|
75
|
+
return _sql(raw)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _tags(node):
|
|
79
|
+
return set(node.get("tags") or []) | set((node.get("config") or {}).get("tags") or [])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _anchor(node):
|
|
83
|
+
metadata = node.get("test_metadata") or {}
|
|
84
|
+
deps = sorted((node.get("depends_on") or {}).get("nodes") or [])
|
|
85
|
+
if metadata:
|
|
86
|
+
return _hash(["generic", node.get("package_name"), metadata.get("namespace"), metadata.get("name"),
|
|
87
|
+
node.get("attached_node") or deps,
|
|
88
|
+
node.get("column_name") or (metadata.get("kwargs") or {}).get("column_name")])
|
|
89
|
+
return _hash([node.get("resource_type"), node.get("package_name"), node.get("name")])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _macros(manifest):
|
|
93
|
+
definitions = manifest.get("macros") or {}
|
|
94
|
+
if not isinstance(definitions, dict):
|
|
95
|
+
raise ValueError(tr("change comparison requires valid macro definitions"))
|
|
96
|
+
cache = {}
|
|
97
|
+
def dependencies(node, *, test=False):
|
|
98
|
+
found, stack = {}, list((node.get("depends_on") or {}).get("macros") or [])
|
|
99
|
+
if test:
|
|
100
|
+
stack.extend(DBT_TEST_EXECUTION_MACROS)
|
|
101
|
+
while stack:
|
|
102
|
+
uid = stack.pop()
|
|
103
|
+
if uid in found:
|
|
104
|
+
continue
|
|
105
|
+
macro = definitions.get(uid)
|
|
106
|
+
if not isinstance(macro, dict):
|
|
107
|
+
found[uid] = "missing"
|
|
108
|
+
continue
|
|
109
|
+
if uid not in cache:
|
|
110
|
+
cache[uid] = _hash(_sql(macro.get("macro_sql")))
|
|
111
|
+
found[uid] = cache[uid]
|
|
112
|
+
stack.extend((macro.get("depends_on") or {}).get("macros") or [])
|
|
113
|
+
return sorted(found.items())
|
|
114
|
+
return dependencies
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _test_parts(node, macros):
|
|
118
|
+
cfg = node.get("config") or {}
|
|
119
|
+
policy = {key: cfg.get(key) for key in ("where", "limit")}
|
|
120
|
+
# Runtime partition dates are data context, not necessarily a changed rule.
|
|
121
|
+
unrendered = node.get("unrendered_config") or {}
|
|
122
|
+
if "where" in unrendered:
|
|
123
|
+
policy["where"] = unrendered["where"]
|
|
124
|
+
policy.update(severity=str(cfg.get("severity") or "error").lower(),
|
|
125
|
+
error_if=cfg.get("error_if") or "!= 0", warn_if=cfg.get("warn_if") or "!= 0",
|
|
126
|
+
fail_calc=cfg.get("fail_calc") or "count(*)")
|
|
127
|
+
descriptive = {"tags", "meta", "description", "docs", "group", "alias", "schema", "database", "store_failures", "store_failures_as", "grants", "persist_docs", "enabled"}
|
|
128
|
+
policy["additional_config"] = {key: value for key, value in cfg.items() if key not in descriptive and key not in policy
|
|
129
|
+
and value is not None and value != [] and value != {}}
|
|
130
|
+
return {"sql": _sql(node.get("raw_code") or node.get("raw_sql")),
|
|
131
|
+
"arguments": (node.get("test_metadata") or {}).get("kwargs") or {},
|
|
132
|
+
"inputs": sorted((node.get("depends_on") or {}).get("nodes") or []),
|
|
133
|
+
"policy": policy, "macros": macros(node, test=True),
|
|
134
|
+
"unit_fixtures": {key: node.get(key) for key in ("given", "expect", "overrides", "model")}}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def compare(base, head, base_catalog, head_catalog, *, review_model_logic=False):
|
|
138
|
+
for key in ("project_name", "adapter_type"):
|
|
139
|
+
old, new = (base.get("metadata") or {}).get(key), (head.get("metadata") or {}).get(key)
|
|
140
|
+
if not old or old != new:
|
|
141
|
+
raise ValueError(tr("base/head metadata differs or is absent: {key}", key=key))
|
|
142
|
+
old_nodes, new_nodes = _nodes(base), _nodes(head)
|
|
143
|
+
gaps = []
|
|
144
|
+
for side, graph, catalog in (("base", old_nodes, base_catalog), ("head", new_nodes, head_catalog)):
|
|
145
|
+
for uid, node in graph.items():
|
|
146
|
+
if node.get("resource_type") not in RELATIONS or (node.get("config") or {}).get("materialized") == "ephemeral":
|
|
147
|
+
continue
|
|
148
|
+
section = catalog.get("sources" if node.get("resource_type") == "source" else "nodes") or {}
|
|
149
|
+
if not isinstance(section, dict) or not isinstance(section.get(uid), dict) or not section[uid].get("columns"):
|
|
150
|
+
gaps.append({"side": side, "resource": uid, "message": str(tr("Catalog columns unavailable for change comparison."))})
|
|
151
|
+
all_nodes = {**old_nodes, **new_nodes}
|
|
152
|
+
children = defaultdict(set)
|
|
153
|
+
for graph in (old_nodes, new_nodes):
|
|
154
|
+
for uid, node in graph.items():
|
|
155
|
+
if node.get("resource_type") in TESTS:
|
|
156
|
+
continue
|
|
157
|
+
for parent in (node.get("depends_on") or {}).get("nodes") or []:
|
|
158
|
+
children[parent].add(uid)
|
|
159
|
+
def impact(roots):
|
|
160
|
+
seen, stack = set(roots), sorted(roots)
|
|
161
|
+
truncated = len(seen) > MAX_IMPACT_PREVIEW
|
|
162
|
+
while stack and not truncated:
|
|
163
|
+
for uid in sorted(children[stack.pop()]):
|
|
164
|
+
if uid not in seen:
|
|
165
|
+
seen.add(uid)
|
|
166
|
+
stack.append(uid)
|
|
167
|
+
if len(seen) > MAX_IMPACT_PREVIEW:
|
|
168
|
+
truncated = True
|
|
169
|
+
break
|
|
170
|
+
return ([{"id": uid, "name": all_nodes[uid].get("name", uid), "type": all_nodes[uid].get("resource_type")}
|
|
171
|
+
for uid in sorted(seen)[:MAX_IMPACT_PREVIEW] if uid in all_nodes], truncated)
|
|
172
|
+
changes = []
|
|
173
|
+
def add(kind, resource, before, after, message, *, review=True, roots=None, fields=()):
|
|
174
|
+
identity = {"kind": kind, "resource": resource, "before": before, "after": after}
|
|
175
|
+
node = new_nodes.get(resource) or old_nodes.get(resource) or {}
|
|
176
|
+
meta = {**(node.get("meta") or {}), **((node.get("config") or {}).get("meta") or {})}
|
|
177
|
+
owner = meta.get("owner") or meta.get("team")
|
|
178
|
+
affected, truncated = impact([resource] if roots is None else roots)
|
|
179
|
+
changes.append({"id": "CHG-" + _hash(identity)[:24], "kind": kind, "resource": resource,
|
|
180
|
+
"name": node.get("name", resource), "requires_review": review, "message": str(message),
|
|
181
|
+
"before": before, "after": after, "changed_fields": list(fields),
|
|
182
|
+
"owner": owner if isinstance(owner, str) else None, "impact": affected, "impact_truncated": truncated})
|
|
183
|
+
old_macros, new_macros = _macros(base), _macros(head)
|
|
184
|
+
for uid, node in old_nodes.items():
|
|
185
|
+
if node.get("resource_type") not in RELATIONS:
|
|
186
|
+
continue
|
|
187
|
+
other = new_nodes.get(uid)
|
|
188
|
+
if other is None:
|
|
189
|
+
add("resource_removed", uid, _hash(node), None, tr("Existing model or source removed; verify its consumers."))
|
|
190
|
+
continue
|
|
191
|
+
a, b = node.get("config") or {}, other.get("config") or {}
|
|
192
|
+
old_alias = node.get("alias") or node.get("identifier") or a.get("alias") or node.get("name")
|
|
193
|
+
new_alias = other.get("alias") or other.get("identifier") or b.get("alias") or other.get("name")
|
|
194
|
+
if old_alias != new_alias:
|
|
195
|
+
add("relation_alias_changed", uid, {"alias": old_alias}, {"alias": new_alias}, tr("Physical table/view name changed; verify consumers outside dbt."))
|
|
196
|
+
if (a.get("contract") or {}).get("enforced") and not (b.get("contract") or {}).get("enforced"):
|
|
197
|
+
add("model_contract_disabled", uid, True, False, tr("Model contract enforcement was disabled."))
|
|
198
|
+
def constraints(n):
|
|
199
|
+
values = list(n.get("constraints") or [])
|
|
200
|
+
values += [{"column": col, "constraint": item} for col, value in (n.get("columns") or {}).items() for item in value.get("constraints") or []]
|
|
201
|
+
return Counter(_hash(value) for value in values)
|
|
202
|
+
old_constraints, new_constraints = constraints(node), constraints(other)
|
|
203
|
+
dropped = old_constraints - new_constraints
|
|
204
|
+
if dropped:
|
|
205
|
+
add("constraints_removed", uid, sorted(old_constraints.elements()), sorted(new_constraints.elements()), tr("Declared model/column constraints were removed or replaced."))
|
|
206
|
+
if "incremental" in (a.get("materialized"), b.get("materialized")):
|
|
207
|
+
old_key = {k: a.get(k) for k in ("materialized", "unique_key", "incremental_strategy")}
|
|
208
|
+
new_key = {k: b.get(k) for k in old_key}
|
|
209
|
+
if old_key != new_key:
|
|
210
|
+
add("incremental_changed", uid, _hash(old_key), _hash(new_key), tr("Incremental materialization, key or strategy changed; verify retry and backfill behavior."), fields=[k for k in old_key if old_key[k] != new_key[k]])
|
|
211
|
+
if node.get("resource_type") == "source":
|
|
212
|
+
def freshness(n):
|
|
213
|
+
cfg = n.get("config") or {}
|
|
214
|
+
effective = cfg.get("freshness", n.get("freshness"))
|
|
215
|
+
effective = dict(effective) if isinstance(effective, dict) else effective
|
|
216
|
+
raw = ((n.get("unrendered_config") or {}).get("freshness") or {})
|
|
217
|
+
if isinstance(effective, dict) and "filter" in raw:
|
|
218
|
+
effective["filter"] = raw["filter"]
|
|
219
|
+
return {"freshness": effective,
|
|
220
|
+
"loaded_at_field": cfg.get("loaded_at_field", n.get("loaded_at_field")),
|
|
221
|
+
"loaded_at_query": cfg.get("loaded_at_query", n.get("loaded_at_query"))}
|
|
222
|
+
f0, f1 = freshness(node), freshness(other)
|
|
223
|
+
if f0 != f1 and any(isinstance((f0["freshness"] or {}).get(k), dict) and f0["freshness"][k].get("count") is not None for k in ("error_after", "warn_after")):
|
|
224
|
+
add("source_freshness_changed", uid, _hash(f0), _hash(f1), tr("Source freshness policy changed; verify thresholds, filters and the reference clock."))
|
|
225
|
+
p0 = {"code": _code(node), "macros": old_macros(node)}
|
|
226
|
+
p1 = {"code": _code(other), "macros": new_macros(other)}
|
|
227
|
+
if p0 != p1:
|
|
228
|
+
add("model_logic_changed", uid, _hash(p0), _hash(p1), tr("Model SQL or a declared macro dependency changed; compare data results."), review=review_model_logic)
|
|
229
|
+
for uid, node in new_nodes.items():
|
|
230
|
+
if uid not in old_nodes and node.get("resource_type") in RELATIONS:
|
|
231
|
+
add("resource_added", uid, None, _hash(node), tr("Model or source added; validate its data and consumers."), review=False)
|
|
232
|
+
for uid in sorted(set(old_nodes) & set(new_nodes)):
|
|
233
|
+
if old_nodes[uid].get("resource_type") not in RELATIONS:
|
|
234
|
+
continue
|
|
235
|
+
old_cols = ((base_catalog.get("sources") if old_nodes[uid].get("resource_type") == "source" else base_catalog.get("nodes")) or {}).get(uid, {}).get("columns") or {}
|
|
236
|
+
new_cols = ((head_catalog.get("sources") if new_nodes[uid].get("resource_type") == "source" else head_catalog.get("nodes")) or {}).get(uid, {}).get("columns") or {}
|
|
237
|
+
for col in sorted(set(old_cols) - set(new_cols)):
|
|
238
|
+
add("column_removed", uid, {"column": col, "type": old_cols[col].get("type")}, None, tr("Column removed; absence of declared consumers does not prove it is unused."))
|
|
239
|
+
for col in sorted(set(new_cols) - set(old_cols)):
|
|
240
|
+
add("column_added", uid, None, {"column": col, "type": new_cols[col].get("type")}, tr("Column added; strict-schema consumers may still need validation."), review=False)
|
|
241
|
+
for col in sorted(set(old_cols) & set(new_cols)):
|
|
242
|
+
a, b = old_cols[col].get("type"), new_cols[col].get("type")
|
|
243
|
+
if str(a).lower() != str(b).lower():
|
|
244
|
+
add("column_type_changed", uid, {"column": col, "type": a}, {"column": col, "type": b}, tr("Column type changed; verify casts, precision and consumers."))
|
|
245
|
+
|
|
246
|
+
before = {u:n for u,n in old_nodes.items() if n.get("resource_type") in TESTS}
|
|
247
|
+
after = {u:n for u,n in new_nodes.items() if n.get("resource_type") in TESTS}
|
|
248
|
+
old_parts = {u:_test_parts(n, old_macros) for u,n in before.items()}
|
|
249
|
+
new_parts = {u:_test_parts(n, new_macros) for u,n in after.items()}
|
|
250
|
+
def pair(left, right):
|
|
251
|
+
n0, n1 = before[left], after[right]
|
|
252
|
+
roots = sorted(set((old_parts[left]["inputs"] or []) + (new_parts[right]["inputs"] or [])))
|
|
253
|
+
changed = [key for key in old_parts[left] if old_parts[left][key] != new_parts[right][key]]
|
|
254
|
+
if changed:
|
|
255
|
+
add("test_definition_changed", right, _hash(old_parts[left]), _hash(new_parts[right]),
|
|
256
|
+
tr("An existing test definition changed; arbitrary SQL cannot be assumed to be stronger."), roots=roots, fields=changed)
|
|
257
|
+
if "business_rule" in _tags(n0) and "business_rule" not in _tags(n1):
|
|
258
|
+
add("business_tracking_removed", right, True, False, tr("Business-rule tracking was removed from an existing test."), roots=roots)
|
|
259
|
+
for uid in sorted(set(before) & set(after)):
|
|
260
|
+
pair(uid, uid)
|
|
261
|
+
left, right = defaultdict(list), defaultdict(list)
|
|
262
|
+
for uid in sorted(set(before) - set(after)):
|
|
263
|
+
left[_anchor(before[uid])].append(uid)
|
|
264
|
+
for uid in sorted(set(after) - set(before)):
|
|
265
|
+
right[_anchor(after[uid])].append(uid)
|
|
266
|
+
for anchor in sorted(set(left) | set(right)):
|
|
267
|
+
remaining_old, remaining_new = list(left[anchor]), list(right[anchor])
|
|
268
|
+
for uid in list(remaining_old):
|
|
269
|
+
matches = [v for v in remaining_new if old_parts[uid] == new_parts[v]]
|
|
270
|
+
if matches:
|
|
271
|
+
match = min(matches, key=lambda v:(('business_rule' in _tags(before[uid])) != ('business_rule' in _tags(after[v])), v))
|
|
272
|
+
pair(uid, match)
|
|
273
|
+
remaining_old.remove(uid)
|
|
274
|
+
remaining_new.remove(match)
|
|
275
|
+
if len(remaining_old) == len(remaining_new) == 1:
|
|
276
|
+
pair(remaining_old[0], remaining_new[0])
|
|
277
|
+
elif remaining_old and remaining_new:
|
|
278
|
+
roots = sorted({v for u in remaining_old for v in old_parts[u]["inputs"]} | {v for u in remaining_new for v in new_parts[u]["inputs"]})
|
|
279
|
+
add("test_set_changed", remaining_new[0], sorted(_hash(old_parts[u]) for u in remaining_old),
|
|
280
|
+
sorted(_hash(new_parts[u]) for u in remaining_new), tr("Several tests share an identity; review the changed set without assuming a match."), roots=roots)
|
|
281
|
+
else:
|
|
282
|
+
for uid in remaining_old:
|
|
283
|
+
add("test_removed", uid, _hash(old_parts[uid]), None, tr("An existing test was removed or disabled, even if other tests still pass."), roots=old_parts[uid]["inputs"])
|
|
284
|
+
for uid in remaining_new:
|
|
285
|
+
add("test_added", uid, None, _hash(new_parts[uid]), tr("Test added; confirm that it exercises the intended expectation."), review=False, roots=new_parts[uid]["inputs"])
|
|
286
|
+
changes.sort(key=lambda c:(not c["requires_review"], c["resource"], c["kind"], c["id"]))
|
|
287
|
+
return {"changes": changes, "gaps": gaps, "summary": {"total": len(changes), "review_required": sum(c["requires_review"] for c in changes),
|
|
288
|
+
"by_kind": dict(Counter(c["kind"] for c in changes))},
|
|
289
|
+
"baseline_revision": ((base.get("metadata") or {}).get("env") or {}).get("INTENTFLOW_REVISION"),
|
|
290
|
+
"candidate_revision": ((head.get("metadata") or {}).get("env") or {}).get("INTENTFLOW_REVISION"),
|
|
291
|
+
"note": str(tr("Impact includes declared baseline/candidate dependencies, not every external consumer. Review acknowledgements are not verified approvals."))}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def load(target, base, *, review_model_logic=False, baseline_revision=None):
|
|
295
|
+
if Path(target).resolve() == Path(base).resolve():
|
|
296
|
+
raise ValueError(tr("candidate and baseline must be different artifact locations"))
|
|
297
|
+
def read(folder, name):
|
|
298
|
+
try:
|
|
299
|
+
doc = json.loads((Path(folder) / name).read_text())
|
|
300
|
+
if not isinstance(doc, dict):
|
|
301
|
+
raise ValueError("expected object")
|
|
302
|
+
return doc
|
|
303
|
+
except (OSError, ValueError, UnicodeError) as e:
|
|
304
|
+
raise ValueError(tr("change comparison artifact unavailable or invalid: {name}", name=name)) from e
|
|
305
|
+
try:
|
|
306
|
+
old, old_catalog = read(base, "manifest.json"), read(base, "catalog.json")
|
|
307
|
+
if baseline_revision is not None:
|
|
308
|
+
if not baseline_revision.strip():
|
|
309
|
+
raise ValueError(tr("expected artifact revision must not be empty"))
|
|
310
|
+
for doc in (old, old_catalog):
|
|
311
|
+
if ((doc.get("metadata") or {}).get("env") or {}).get("INTENTFLOW_REVISION") != baseline_revision:
|
|
312
|
+
raise ValueError(tr("baseline artifacts do not match the expected deployed revision"))
|
|
313
|
+
return compare(old, read(target, "manifest.json"), old_catalog, read(target, "catalog.json"), review_model_logic=review_model_logic)
|
|
314
|
+
except (TypeError, KeyError, AttributeError) as e:
|
|
315
|
+
raise ValueError(tr("change comparison requires valid manifest resources")) from e
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def acknowledge(report, acknowledgements=()):
|
|
319
|
+
reasons = {}
|
|
320
|
+
available = {c["id"] for c in report["changes"] if c["requires_review"]}
|
|
321
|
+
for item in acknowledgements:
|
|
322
|
+
identity, separator, reason = item.partition("=")
|
|
323
|
+
if not separator or not reason.strip() or identity not in available or identity in reasons:
|
|
324
|
+
raise ValueError(tr("accept-change requires an exact current change id and a nonempty reason"))
|
|
325
|
+
reasons[identity] = reason.strip()
|
|
326
|
+
for change in report["changes"]:
|
|
327
|
+
change["acknowledged"] = change["id"] in reasons
|
|
328
|
+
if change["acknowledged"]:
|
|
329
|
+
change["reason"] = reasons[change["id"]]
|
|
330
|
+
report["unreviewed"] = [c["id"] for c in report["changes"] if c["requires_review"] and not c["acknowledged"]]
|
|
331
|
+
return report
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Pluggable check registry.
|
|
2
|
+
|
|
3
|
+
A check is a function `(ctx) -> list[Finding]` registered with `@check(id, title, stage, cost)`.
|
|
4
|
+
`cost`: static (metadata/code only) | probe (warehouse query) | statistical (history).
|
|
5
|
+
Titles are English; display them with `tr(check.title)`.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
from ..i18n import tr
|
|
13
|
+
from ..model import Finding
|
|
14
|
+
|
|
15
|
+
REGISTRY: dict[str, Check] = {}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Check:
|
|
20
|
+
id: str
|
|
21
|
+
title: str
|
|
22
|
+
stage: str
|
|
23
|
+
cost: str
|
|
24
|
+
fn: Callable
|
|
25
|
+
emits: tuple = () # secondary ids this check also produces (they must resolve on their own when the problem goes away)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def check(id: str, title: str, stage: str = "pre-merge", cost: str = "static", emits: tuple = ()):
|
|
29
|
+
def deco(fn):
|
|
30
|
+
REGISTRY[id] = Check(id, title, stage, cost, fn, tuple(emits))
|
|
31
|
+
return fn
|
|
32
|
+
return deco
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Context:
|
|
37
|
+
project: object = None # dbt_loader.Project
|
|
38
|
+
lineage: object = None # lineage.LineageResult
|
|
39
|
+
base_project: object = None # previous version (schema diff)
|
|
40
|
+
base_lineage: object = None
|
|
41
|
+
policies: dict = field(default_factory=dict)
|
|
42
|
+
airflow_dags_dir: str | None = None
|
|
43
|
+
kestra_flows_dir: str | None = None
|
|
44
|
+
store: object = None
|
|
45
|
+
warehouse: object = None
|
|
46
|
+
runs: list = field(default_factory=list) # orchestrators.Run
|
|
47
|
+
samples: list = field(default_factory=list) # monitoring.Sample
|
|
48
|
+
dbt_results: dict | None = None # dbt_results.load()
|
|
49
|
+
dq_results: list = field(default_factory=list) # dq_results.DQResult (GX/Soda)
|
|
50
|
+
contracts: list = field(default_factory=list) # contracts.ModelContract
|
|
51
|
+
external: list = field(default_factory=list) # external.ExtRead: jobs outside the SQL (OpenLineage + declared)
|
|
52
|
+
completed_checks: set[str] = field(default_factory=set) # only checks completed in this run
|
|
53
|
+
failed_checks: set[str] = field(default_factory=set)
|
|
54
|
+
required_checks: set[str] = field(default_factory=set)
|
|
55
|
+
active_check: str | None = None
|
|
56
|
+
record_probe_history: bool = True
|
|
57
|
+
parsed_sql: dict = field(default_factory=dict) # ASTs shared only within one run
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_all() -> None:
|
|
61
|
+
from . import dbt_quality, schema_drift, sql_quality, orchestration, airflow3, dq, contracts, streaming, lint, elementary, lakehouse, catalog, probes, cluster, runtime_history, cost, dbt_run, deep, external, business # noqa: F401
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def run_checks(ctx: Context, only: list[str] | None = None, costs: set[str] | None = None, stages: set[str] | None = None) -> list[Finding]:
|
|
65
|
+
load_all()
|
|
66
|
+
out: list[Finding] = []
|
|
67
|
+
ctx.completed_checks.clear()
|
|
68
|
+
ctx.failed_checks.clear()
|
|
69
|
+
ctx.parsed_sql.clear()
|
|
70
|
+
disabled = set(ctx.policies.get("disabled_checks", []) or [])
|
|
71
|
+
for c in REGISTRY.values():
|
|
72
|
+
if c.id in disabled:
|
|
73
|
+
continue
|
|
74
|
+
if only and not any(code.startswith(o) for o in only for code in (c.id, *c.emits)):
|
|
75
|
+
continue
|
|
76
|
+
if costs and c.cost not in costs:
|
|
77
|
+
continue
|
|
78
|
+
if stages and c.stage not in stages:
|
|
79
|
+
continue
|
|
80
|
+
try:
|
|
81
|
+
ctx.active_check = c.id
|
|
82
|
+
out.extend(c.fn(ctx) or [])
|
|
83
|
+
if c.id not in ctx.failed_checks:
|
|
84
|
+
ctx.completed_checks.update((c.id, *c.emits))
|
|
85
|
+
else:
|
|
86
|
+
ctx.failed_checks.update(c.emits)
|
|
87
|
+
except Exception as e: # a broken check does not take the others down
|
|
88
|
+
ctx.failed_checks.update((c.id, *c.emits))
|
|
89
|
+
out.append(Finding(c.id, "info", tr("check {id} failed to run", id=c.id), f"{type(e).__name__}: {e}", stage=c.stage))
|
|
90
|
+
finally:
|
|
91
|
+
ctx.active_check = None
|
|
92
|
+
return out
|