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.
Files changed (83) hide show
  1. intentdataflow-0.3.10.dist-info/METADATA +191 -0
  2. intentdataflow-0.3.10.dist-info/RECORD +83 -0
  3. intentdataflow-0.3.10.dist-info/WHEEL +5 -0
  4. intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
  5. intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
  6. intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
  7. intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
  8. intentflow/__init__.py +2 -0
  9. intentflow/auth.py +30 -0
  10. intentflow/business_rules.py +77 -0
  11. intentflow/catalogs.py +100 -0
  12. intentflow/change_review.py +331 -0
  13. intentflow/checks/__init__.py +92 -0
  14. intentflow/checks/airflow3.py +174 -0
  15. intentflow/checks/business.py +27 -0
  16. intentflow/checks/catalog.py +43 -0
  17. intentflow/checks/cluster.py +81 -0
  18. intentflow/checks/contracts.py +79 -0
  19. intentflow/checks/cost.py +35 -0
  20. intentflow/checks/dbt_quality.py +90 -0
  21. intentflow/checks/dbt_run.py +83 -0
  22. intentflow/checks/deep.py +180 -0
  23. intentflow/checks/dq.py +53 -0
  24. intentflow/checks/elementary.py +50 -0
  25. intentflow/checks/external.py +91 -0
  26. intentflow/checks/lakehouse.py +46 -0
  27. intentflow/checks/lint.py +81 -0
  28. intentflow/checks/orchestration.py +148 -0
  29. intentflow/checks/probes.py +66 -0
  30. intentflow/checks/runtime_history.py +94 -0
  31. intentflow/checks/schema_drift.py +92 -0
  32. intentflow/checks/sql_quality.py +274 -0
  33. intentflow/checks/streaming.py +62 -0
  34. intentflow/cli.py +914 -0
  35. intentflow/contracts.py +107 -0
  36. intentflow/datadiff.py +172 -0
  37. intentflow/dbt_loader.py +194 -0
  38. intentflow/dbt_results.py +55 -0
  39. intentflow/dq_results.py +108 -0
  40. intentflow/extensions.py +51 -0
  41. intentflow/external.py +381 -0
  42. intentflow/http_utils.py +89 -0
  43. intentflow/i18n.py +76 -0
  44. intentflow/incidents.py +83 -0
  45. intentflow/integrations.py +139 -0
  46. intentflow/lakehouse.py +62 -0
  47. intentflow/lineage.py +336 -0
  48. intentflow/lineage_api.py +244 -0
  49. intentflow/lineage_oracle.py +374 -0
  50. intentflow/locale/pt.json +1300 -0
  51. intentflow/model.py +43 -0
  52. intentflow/monitoring.py +197 -0
  53. intentflow/notify.py +154 -0
  54. intentflow/ol_emit.py +93 -0
  55. intentflow/openlineage.py +168 -0
  56. intentflow/orchestrators/__init__.py +53 -0
  57. intentflow/orchestrators/airflow.py +69 -0
  58. intentflow/orchestrators/aws.py +93 -0
  59. intentflow/orchestrators/dagster.py +48 -0
  60. intentflow/orchestrators/dbtcloud.py +68 -0
  61. intentflow/orchestrators/extra.py +135 -0
  62. intentflow/orchestrators/ingestion.py +112 -0
  63. intentflow/orchestrators/kestra.py +27 -0
  64. intentflow/orchestrators/more.py +135 -0
  65. intentflow/orchestrators/prefect.py +53 -0
  66. intentflow/orchestrators/spark.py +118 -0
  67. intentflow/otel.py +53 -0
  68. intentflow/overview.py +123 -0
  69. intentflow/preflight.py +363 -0
  70. intentflow/promexport.py +39 -0
  71. intentflow/pyflow.py +554 -0
  72. intentflow/risks.py +178 -0
  73. intentflow/runner.py +264 -0
  74. intentflow/secrets_box.py +84 -0
  75. intentflow/sqlmesh_loader.py +134 -0
  76. intentflow/store.py +1006 -0
  77. intentflow/streaming.py +115 -0
  78. intentflow/totp.py +38 -0
  79. intentflow/warehouses/__init__.py +190 -0
  80. intentflow/warehouses/cloud.py +160 -0
  81. intentflow/warehouses/more.py +342 -0
  82. intentflow/web.html +878 -0
  83. intentflow/web.py +726 -0
@@ -0,0 +1,107 @@
1
+ """Data contracts (Data Contract Specification `models:` and ODCS v3 `schema:`) → {model: {column: rules}}.
2
+
3
+ We read the contract the team already maintains; IntentFlow defines no format of its own. Configuration: `contracts.dir` (folder or file).
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from .i18n import tr
8
+
9
+ import os
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+
13
+ import yaml
14
+
15
+ FAMILIES = {
16
+ "string": {"string", "text", "varchar", "char", "character varying", "str", "uuid"},
17
+ "integer": {"int", "integer", "bigint", "long", "smallint", "tinyint", "int32", "int64", "hugeint"},
18
+ "number": {"float", "double", "decimal", "numeric", "number", "real", "float32", "float64", "money"},
19
+ "boolean": {"boolean", "bool"},
20
+ "date": {"date"},
21
+ "timestamp": {"timestamp", "timestamp_ntz", "timestamp_tz", "timestamptz", "datetime", "timestamp without time zone", "timestamp with time zone"},
22
+ }
23
+
24
+
25
+ def family(t: str | None) -> str | None:
26
+ if not t:
27
+ return None
28
+ base = str(t).lower().split("(")[0].strip()
29
+ for fam, names in FAMILIES.items():
30
+ if base in names or (fam == "timestamp" and base.startswith("timestamp")):
31
+ return fam
32
+ return None
33
+
34
+
35
+ @dataclass
36
+ class ColumnRule:
37
+ name: str
38
+ type: str | None = None
39
+ required: bool = False
40
+ unique: bool = False
41
+ pii: bool = False
42
+ description: str = ""
43
+
44
+
45
+ @dataclass
46
+ class ModelContract:
47
+ name: str
48
+ columns: dict[str, ColumnRule] = field(default_factory=dict)
49
+ source: str = ""
50
+ owner: str = ""
51
+
52
+
53
+ def _truthy(x) -> bool:
54
+ return bool(x) and str(x).lower() not in ("false", "0", "no")
55
+
56
+
57
+ def _from_spec(doc: dict, src: str) -> list[ModelContract]:
58
+ out = []
59
+ owner = str((doc.get("info") or {}).get("owner") or "")
60
+ for mname, m in (doc.get("models") or {}).items(): # Data Contract Specification
61
+ mc = ModelContract(str(mname), source=src, owner=owner)
62
+ for cname, c in ((m or {}).get("fields") or {}).items():
63
+ c = c or {}
64
+ mc.columns[str(cname).lower()] = ColumnRule(str(cname).lower(), c.get("type"), _truthy(c.get("required")),
65
+ _truthy(c.get("unique")) or _truthy(c.get("primary") or c.get("primaryKey")),
66
+ _truthy(c.get("pii")) or "pii" in [str(t).lower() for t in c.get("tags", [])],
67
+ c.get("description", "") or "")
68
+ out.append(mc)
69
+ for t in doc.get("schema") or []: # ODCS v3
70
+ if not isinstance(t, dict):
71
+ continue
72
+ mc = ModelContract(str(t.get("name") or t.get("physicalName")), source=src, owner=owner)
73
+ for p in t.get("properties") or []:
74
+ mc.columns[str(p["name"]).lower()] = ColumnRule(
75
+ str(p["name"]).lower(), p.get("physicalType") or p.get("logicalType"), _truthy(p.get("required")),
76
+ _truthy(p.get("unique")) or _truthy(p.get("primaryKey")), _truthy(p.get("pii")) or "pii" in [str(c).lower() for c in p.get("classification", [])] if isinstance(p.get("classification"), list) else _truthy(p.get("pii")),
77
+ p.get("description", "") or "")
78
+ out.append(mc)
79
+ return out
80
+
81
+
82
+ def load_all(spec: str | None, *, strict: bool = False) -> list[ModelContract]:
83
+ files: list[Path] = []
84
+ for part in [x.strip() for x in (spec or "").split(",") if x.strip()]:
85
+ p = Path(os.path.expanduser(part))
86
+ matched = sorted([*p.rglob("*.yaml"), *p.rglob("*.yml")]) if p.is_dir() else [p]
87
+ if strict and not matched:
88
+ raise ValueError(tr("no contract files found: {path}", path=p))
89
+ files += matched
90
+ res: list[ModelContract] = []
91
+ for f in files:
92
+ try:
93
+ doc = yaml.safe_load(f.read_text())
94
+ except (OSError, yaml.YAMLError, UnicodeError) as e:
95
+ if strict:
96
+ raise ValueError(tr("contract unavailable or invalid: {path}", path=f)) from e
97
+ continue
98
+ if isinstance(doc, dict):
99
+ parsed = _from_spec(doc, str(f))
100
+ if strict and not parsed:
101
+ raise ValueError(tr("no supported contract definitions: {path}", path=f))
102
+ res += parsed
103
+ elif strict:
104
+ raise ValueError(tr("contract unavailable or invalid: {path}", path=f))
105
+ if strict and not res:
106
+ raise ValueError(tr("no contract definitions configured"))
107
+ return res
intentflow/datadiff.py ADDED
@@ -0,0 +1,172 @@
1
+ """Data diff between two relations (base version × changed version), run in the warehouse itself.
2
+
3
+ No data leaves the warehouse: only counts, statistics and a small sample of changed rows.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import math
8
+
9
+ import sqlglot
10
+ from sqlglot import exp
11
+ from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
12
+
13
+ from .warehouses import Warehouse
14
+ from .i18n import tr
15
+
16
+
17
+ def q(c: str) -> str: # ANSI default; `diff_relations` uses the engine's quote when it differs
18
+ return '"' + c.replace('"', '""') + '"'
19
+
20
+
21
+ def _relation(value: str, dialect: str) -> str:
22
+ """Accept a table identifier, never an arbitrary FROM clause or extra statement."""
23
+ try:
24
+ trees = sqlglot.parse("select * from " + value, read=dialect)
25
+ except (sqlglot.errors.ParseError, ValueError, TypeError):
26
+ raise ValueError(tr("invalid relation: pass only the qualified table name")) from None
27
+ if len(trees) != 1 or not isinstance(trees[0], exp.Select):
28
+ raise ValueError(tr("invalid relation: SQL statements are not allowed"))
29
+ tree = trees[0]
30
+ if any(v for k, v in tree.args.items() if k not in ("expressions", "from_", "from")):
31
+ raise ValueError(tr("invalid relation: SQL clauses are not allowed"))
32
+ frm = tree.args.get("from_") or tree.args.get("from")
33
+ table = frm.this if frm is not None else None
34
+ if (not isinstance(table, exp.Table)
35
+ or any(v for k, v in table.args.items() if k not in ("this", "db", "catalog"))
36
+ or not table.parts or not all(isinstance(p, exp.Identifier) for p in table.parts)):
37
+ raise ValueError(tr("invalid relation: functions, aliases and subqueries are not allowed"))
38
+ table = normalize_identifiers(table, dialect=dialect)
39
+ clean = exp.Table(**{k: exp.Identifier(this=v.name, quoted=True)
40
+ for k, v in table.args.items() if k in ("this", "db", "catalog") and v is not None})
41
+ return clean.sql(dialect=dialect)
42
+
43
+
44
+ def diff_relations(wh: Warehouse, base: str, head: str, key: list[str], sample: int = 5, columns: list[str] | None = None,
45
+ sample_pct: float | None = None) -> dict:
46
+ """`sample_pct` (0 < p < 100): compare only ~p % of the keys (hash of the key, the same in both relations). For huge tables;
47
+ the numbers become the sample's and `out["sampled"]` carries the estimate for the total."""
48
+ if not key or len(set(key)) != len(key) or not all(isinstance(k, str) and k for k in key):
49
+ raise ValueError(tr("pass a non-empty key without repeated columns"))
50
+ if not isinstance(sample, int) or not 0 <= sample <= 1000:
51
+ raise ValueError(tr("sample must be between 0 and 1000"))
52
+ if sample_pct is not None and (not math.isfinite(sample_pct) or not 0 < sample_pct <= 100):
53
+ raise ValueError(tr("sample_pct must be greater than 0 and at most 100"))
54
+ base, head = _relation(base, wh.dialect), _relation(head, wh.dialect)
55
+ q = wh.quote # noqa: F811 — aspas/crases e IS DISTINCT FROM variam por motor
56
+ bcols, hcols = dict(wh.describe(base)), dict(wh.describe(head))
57
+ shared = [c for c in (columns or list(bcols)) if c in hcols and c not in key]
58
+ for k in key:
59
+ if k not in bcols or k not in hcols:
60
+ raise ValueError(tr("key '{key}' does not exist in both relations", key=k))
61
+ on = " and ".join(f"b.{q(k)} = h.{q(k)}" for k in key)
62
+ out: dict = {"base": base, "head": head, "key": key}
63
+ pred = None
64
+ if sample_pct is not None and 0 < sample_pct < 100:
65
+ pred = wh.sample_pred([q(k) for k in key], sample_pct)
66
+ out["sampled"] = {"pct": sample_pct}
67
+
68
+ def S(rel: str, alias: str) -> str: # the relation, filtered by the key hash when sampling
69
+ return f"(select * from {rel} where {pred}) {alias}" if pred else f"{rel} {alias}"
70
+ out["schema"] = {"added": sorted(set(hcols) - set(bcols)), "removed": sorted(set(bcols) - set(hcols)),
71
+ "type_changed": [(c, bcols[c], hcols[c]) for c in bcols if c in hcols and str(bcols[c]) != str(hcols[c])]}
72
+ kexpr = ", ".join(q(k) for k in key)
73
+ # Scans (independent of the number of columns): 1 per relation for count+statistics (columns in batches), 1 per relation
74
+ # for duplicated keys, 1 aggregated join per batch of columns, 2 anti-joins. Before: ~11 + 3 per column.
75
+ batch = 40
76
+ chunks = [shared[i:i + batch] for i in range(0, len(shared), batch)] or [[]]
77
+ rows_n, col_stats = {}, {}
78
+ for side, rel in (("base", base), ("head", head)):
79
+ n_rows = None
80
+ for ch in chunks:
81
+ sel = "count(*)" + "".join(f", count({q(c)}), min({q(c)}), max({q(c)})" for c in ch)
82
+ try:
83
+ r = wh.rows(f"select {sel} from {S(rel, 't')}")[0]
84
+ except Exception: # type without min/max (JSON, array...): fall back to column by column, skipping the unsupported ones
85
+ r = None
86
+ one = {}
87
+ for c in ch:
88
+ try:
89
+ x = wh.rows(f"select count(*), count({q(c)}), min({q(c)}), max({q(c)}) from {S(rel, 't')}")[0]
90
+ n_rows = int(x[0]) if n_rows is None else n_rows
91
+ one[c] = (int(x[0]) - int(x[1]), x[2], x[3])
92
+ except Exception:
93
+ continue
94
+ col_stats.setdefault(side, {}).update(one)
95
+ if n_rows is None:
96
+ n_rows = int(wh.scalar(f"select count(*) from {S(rel, 't')}"))
97
+ continue
98
+ n_rows = int(r[0]) if n_rows is None else n_rows
99
+ for i, c in enumerate(ch):
100
+ cnt, mn, mx = r[1 + 3 * i: 4 + 3 * i]
101
+ col_stats.setdefault(side, {})[c] = (int(r[0]) - int(cnt), mn, mx)
102
+ rows_n[side] = n_rows or 0
103
+ out["rows"] = rows_n
104
+ out["duplicate_keys"] = {
105
+ "base": int(wh.scalar(f"select count(*) from (select {kexpr} from {S(base, 's')} group by {kexpr} having count(*) > 1) t")),
106
+ "head": int(wh.scalar(f"select count(*) from (select {kexpr} from {S(head, 's')} group by {kexpr} having count(*) > 1) t")),
107
+ }
108
+ k0 = key[0] # anti-join: portable (ClickHouse does not accept a correlated NOT EXISTS)
109
+ out["only_in_base"] = int(wh.scalar(f"select count(*) from {S(base, 'b')} left join {S(head, 'h')} on {on} where h.{q(k0)} is null"))
110
+ out["only_in_head"] = int(wh.scalar(f"select count(*) from {S(head, 'h')} left join {S(base, 'b')} on {on} where b.{q(k0)} is null"))
111
+ changed, total_changed_rows = {}, 0
112
+ flag = lambda c: f"sum(case when {wh.differs(f'b.{q(c)}', f'h.{q(c)}')} then 1 else 0 end)"
113
+ for i, ch in enumerate(chunks):
114
+ if not ch:
115
+ continue
116
+ extra = ""
117
+ if i == 0: # rows with any difference: a single expression, in the same scan as the first batch
118
+ any_diff = " or ".join(wh.differs(f"b.{q(c)}", f"h.{q(c)}") for c in shared)
119
+ extra = f", sum(case when {any_diff} then 1 else 0 end)"
120
+ r = wh.rows(f"select {', '.join(flag(c) for c in ch)}{extra} from {S(base, 'b')} join {S(head, 'h')} on {on}")[0]
121
+ for c, n in zip(ch, r):
122
+ if n:
123
+ changed[c] = int(n)
124
+ if i == 0:
125
+ total_changed_rows = int(r[len(ch)] or 0)
126
+ out["changed_rows"] = total_changed_rows
127
+ out["changed_by_column"] = changed
128
+ samples = []
129
+ if changed and sample:
130
+ cols = list(changed)[:4]
131
+ sel = ", ".join([f"b.{q(k)}" for k in key] + [f"b.{q(c)} as {q('base_' + c)}, h.{q(c)} as {q('head_' + c)}" for c in cols])
132
+ cond = " or ".join(wh.differs(f"b.{q(c)}", f"h.{q(c)}") for c in cols)
133
+ names = key + [x for c in cols for x in (f"base_{c}", f"head_{c}")]
134
+ for r in wh.rows(f"select {sel} from {S(base, 'b')} join {S(head, 'h')} on {on} where {cond} order by 1 limit {int(sample)}"):
135
+ samples.append(dict(zip(names, r)))
136
+ out["samples"] = samples
137
+ stats = {}
138
+ for c in shared:
139
+ sb, sh = col_stats.get("base", {}).get(c), col_stats.get("head", {}).get(c)
140
+ if sb is None or sh is None:
141
+ continue
142
+ if tuple(sb) != tuple(sh):
143
+ stats[c] = {"base": {"nulls": sb[0], "min": str(sb[1]), "max": str(sb[2])}, "head": {"nulls": sh[0], "min": str(sh[1]), "max": str(sh[2])}}
144
+ out["column_stats_changed"] = stats
145
+ if pred:
146
+ f = 100.0 / sample_pct
147
+ out["sampled"].update({k: int(out[k] * f) for k in ("only_in_base", "only_in_head", "changed_rows")} | {"rows": {k: int(v * f) for k, v in rows_n.items()}})
148
+ out["identical"] = not (out["schema"]["added"] or out["schema"]["removed"] or out["schema"]["type_changed"] or out["only_in_base"] or out["only_in_head"] or total_changed_rows
149
+ or out["rows"]["base"] != out["rows"]["head"])
150
+ return out
151
+
152
+
153
+ def to_markdown(d: dict) -> str:
154
+ L = ["### " + tr("Data diff: `{base}` → `{head}`", base=d["base"], head=d["head"]), ""]
155
+ if d["identical"]:
156
+ return "\n".join(L + [tr("No differences in the sample ({pct} % of the keys).", pct=d["sampled"]["pct"]) if d.get("sampled") else tr("No differences.")])
157
+ if d.get("sampled"):
158
+ sm = d["sampled"]
159
+ L.append("- " + tr("**Sample of {pct} % of the keys** (hash); estimate for the total: changed ≈ {changed}, only in base ≈ {base}, only in new ≈ {head}",
160
+ pct=sm["pct"], changed=sm["changed_rows"], base=sm["only_in_base"], head=sm["only_in_head"]))
161
+ L.append("- " + tr("Rows: {base} → {head} | only in base: {only_base} | only in new: {only_head}", base=d["rows"]["base"], head=d["rows"]["head"],
162
+ only_base=d["only_in_base"], only_head=d["only_in_head"]))
163
+ L.append("- " + tr("Changed rows: {n} | duplicated keys (base/new): {base}/{head}", n=d["changed_rows"], base=d["duplicate_keys"]["base"],
164
+ head=d["duplicate_keys"]["head"]))
165
+ s = d["schema"]
166
+ if s["added"] or s["removed"] or s["type_changed"]:
167
+ L.append("- " + tr("Schema: +{added} −{removed} type: {changed}", added=s["added"], removed=s["removed"], changed=[(c, a, b) for c, a, b in s["type_changed"]]))
168
+ if d["changed_by_column"]:
169
+ L += ["", tr("| column | changed rows |"), "|---|---:|"] + [f"| {c} | {n} |" for c, n in d["changed_by_column"].items()]
170
+ for smp in d["samples"]:
171
+ L.append(" - " + ", ".join(f"{k}={v}" for k, v in smp.items()))
172
+ return "\n".join(L)
@@ -0,0 +1,194 @@
1
+ """Reads dbt artifacts (manifest.json, catalog.json) into a simple graph."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from .i18n import tr
9
+
10
+
11
+ @dataclass
12
+ class Col:
13
+ name: str
14
+ type: str = ""
15
+ description: str = ""
16
+ meta: dict = field(default_factory=dict)
17
+ tags: list[str] = field(default_factory=list)
18
+ actual: bool = True # came from the catalog (exists in the warehouse), not only declared in YAML
19
+
20
+
21
+ @dataclass
22
+ class DbtNode:
23
+ unique_id: str
24
+ name: str
25
+ resource_type: str # model | seed | source | snapshot
26
+ relation: str = "" # "db"."schema"."table"
27
+ path: str = ""
28
+ raw_code: str = ""
29
+ compiled_code: str = ""
30
+ materialized: str = ""
31
+ unique_key: object = None
32
+ incremental_strategy: str | None = None
33
+ contract_enforced: bool = False
34
+ meta: dict = field(default_factory=dict)
35
+ tags: list[str] = field(default_factory=list)
36
+ description: str = ""
37
+ columns: dict[str, Col] = field(default_factory=dict)
38
+ depends_on: list[str] = field(default_factory=list)
39
+ tests: list[dict] = field(default_factory=list) # {name, column, kwargs}
40
+ language: str = "sql"
41
+
42
+
43
+ @dataclass
44
+ class Project:
45
+ nodes: dict[str, DbtNode]
46
+ tests_by_id: dict[str, tuple] = field(default_factory=dict) # test unique_id → (attached node, name, column)
47
+ adapter: str = "duckdb"
48
+ root: Path | None = None
49
+ root_package: str | None = None # name of the root dbt project; models of installed packages (dbt_utils, evaluator...) are not the team's
50
+ test_definitions: dict[str, dict] = field(default_factory=dict)
51
+
52
+ def in_root_package(self, uid: str) -> bool:
53
+ """True for nodes of the root project (or when there is no notion of package, e.g. SQLMesh)."""
54
+ if not self.root_package or uid not in self.nodes:
55
+ return True
56
+ parts = uid.split(".")
57
+ return len(parts) < 3 or parts[1] == self.root_package
58
+
59
+ def actual_columns(self, uid: str) -> dict[str, Col]:
60
+ """Columns confirmed by the catalog; empty if the node was not cataloged."""
61
+ return {k: c for k, c in self.nodes[uid].columns.items() if c.actual}
62
+
63
+ def children(self) -> dict[str, list[str]]:
64
+ # The graph is fixed once loaded (loaders finish depends_on before building the Project); node count guards additions.
65
+ sig = len(self.nodes)
66
+ cached = getattr(self, "_children", None)
67
+ if cached is not None and cached[0] == sig:
68
+ return cached[1]
69
+ out: dict[str, list[str]] = {u: [] for u in self.nodes}
70
+ for u, n in self.nodes.items():
71
+ for d in n.depends_on:
72
+ out.setdefault(d, []).append(u)
73
+ self._children = (sig, out)
74
+ return out
75
+
76
+ def downstream(self, uid: str) -> list[str]:
77
+ ch, seen, out, stack = self.children(), {uid}, [], [uid]
78
+ while stack:
79
+ for c in ch.get(stack.pop(), []):
80
+ if c not in seen:
81
+ seen.add(c)
82
+ out.append(c)
83
+ stack.append(c)
84
+ return out
85
+
86
+ def by_relation(self) -> dict[tuple[str, str, str], str]:
87
+ out = {}
88
+ for u, n in self.nodes.items():
89
+ if n.relation:
90
+ parts = [p.strip('"`[]').lower() for p in n.relation.split(".")]
91
+ if len(parts) == 3:
92
+ out[tuple(parts)] = u
93
+ return out
94
+
95
+ def sqlglot_schema(self) -> dict:
96
+ s: dict = {}
97
+ for n in self.nodes.values():
98
+ parts = [p.strip('"`[]').lower() for p in n.relation.split(".")] if n.relation else []
99
+ if len(parts) == 3 and n.columns:
100
+ s.setdefault(parts[0], {}).setdefault(parts[1], {})[parts[2]] = {
101
+ c.name.lower(): (c.type or "VARCHAR") for c in n.columns.values()
102
+ }
103
+ return s
104
+
105
+
106
+ def load(target_dir: str | Path, root: str | Path | None = None) -> Project:
107
+ t = Path(target_dir)
108
+ from . import sqlmesh_loader # a SQLMesh project (or exported snapshot) becomes the same Project
109
+ if not (t / "manifest.json").exists() and (sqlmesh_loader.is_project(t) or sqlmesh_loader.is_snapshot(t)):
110
+ if sqlmesh_loader.is_project(t) and not sqlmesh_loader.is_snapshot(t) and os.environ.get("INTENTFLOW_SQLMESH_ALLOW_EXEC") != "1":
111
+ raise ValueError(tr(
112
+ "{dir} is a SQLMesh project: reading it runs its config.py and Python models. Run `intentflow sqlmesh-export {dir}` "
113
+ "in a trusted environment and use the JSON as --target, or set INTENTFLOW_SQLMESH_ALLOW_EXEC=1 if you trust the code.", dir=t))
114
+ return sqlmesh_loader.load(t, root)
115
+ man = json.loads((t / "manifest.json").read_text())
116
+ cat = {}
117
+ if (t / "catalog.json").exists():
118
+ c = json.loads((t / "catalog.json").read_text())
119
+ cat = {**c.get("nodes", {}), **c.get("sources", {})}
120
+ adapter = man.get("metadata", {}).get("adapter_type", "duckdb")
121
+ nodes: dict[str, DbtNode] = {}
122
+ tests: list[dict] = []
123
+ tests_by_id: dict[str, tuple] = {}
124
+ semantic = {**(man.get("semantic_models") or {}), **(man.get("metrics") or {}), **(man.get("saved_queries") or {})}
125
+ for uid, n in {**man["nodes"], **man.get("sources", {}), **man.get("exposures", {}), **semantic}.items():
126
+ rt = n["resource_type"]
127
+ if rt == "test":
128
+ tests.append(n)
129
+ continue
130
+ if rt not in ("model", "seed", "source", "snapshot", "exposure", "semantic_model", "metric", "saved_query"):
131
+ continue
132
+ cfg = n.get("config", {}) or {}
133
+ if rt in ("semantic_model", "metric", "saved_query"): # semantic layer: metrics depend on models through semantic models
134
+ nodes[uid] = DbtNode(unique_id=uid, name=n["name"], resource_type=rt, path=n.get("original_file_path", ""),
135
+ meta={**(n.get("meta") or {}), **(cfg.get("meta") or {}), **({"label": n["label"]} if n.get("label") else {}),
136
+ **({"metric_type": n["type"]} if n.get("type") and rt == "metric" else {})},
137
+ description=n.get("description", "") or "", tags=list(n.get("tags") or []),
138
+ depends_on=[d for d in (n.get("depends_on") or {}).get("nodes", [])])
139
+ continue
140
+ if rt == "exposure": # dashboards/applications that consume models: the impact must reach them
141
+ ow = n.get("owner") or {}
142
+ nodes[uid] = DbtNode(unique_id=uid, name=n["name"], resource_type="exposure", path=n.get("original_file_path", ""),
143
+ meta={k: v for k, v in {"owner": ow.get("name") or ow.get("email"), "exposure_type": n.get("type"),
144
+ "url": n.get("url"), "maturity": n.get("maturity")}.items() if v},
145
+ description=n.get("description", "") or "", tags=list(n.get("tags") or []),
146
+ depends_on=[d for d in (n.get("depends_on") or {}).get("nodes", [])])
147
+ continue
148
+ node = DbtNode(
149
+ unique_id=uid, name=n["name"], resource_type=rt,
150
+ relation=n.get("relation_name") or "", path=n.get("original_file_path", ""),
151
+ raw_code=n.get("raw_code", "") or "", compiled_code=n.get("compiled_code", "") or "",
152
+ language=n.get("language") or "sql",
153
+ materialized=cfg.get("materialized", ""), unique_key=cfg.get("unique_key"),
154
+ incremental_strategy=cfg.get("incremental_strategy"),
155
+ contract_enforced=bool((cfg.get("contract") or {}).get("enforced")),
156
+ meta={**(n.get("meta") or {}), **(cfg.get("meta") or {})}, tags=list(n.get("tags") or []),
157
+ description=n.get("description", "") or "",
158
+ depends_on=[d for d in (n.get("depends_on") or {}).get("nodes", [])],
159
+ )
160
+ declared = n.get("columns", {}) or {}
161
+ actual = (cat.get(uid) or {}).get("columns", {}) or {}
162
+ for cn, ci in actual.items():
163
+ d = declared.get(cn.lower(), declared.get(cn, {})) or {}
164
+ node.columns[cn.lower()] = Col(cn.lower(), ci.get("type", ""), d.get("description", ""),
165
+ {**(d.get("meta") or {}), **((d.get("config") or {}).get("meta") or {})},
166
+ list(d.get("tags") or []), True)
167
+ for cn, d in declared.items():
168
+ if cn.lower() not in node.columns:
169
+ node.columns[cn.lower()] = Col(cn.lower(), d.get("data_type") or "", d.get("description", ""),
170
+ {**(d.get("meta") or {}), **((d.get("config") or {}).get("meta") or {})},
171
+ list(d.get("tags") or []), False)
172
+ nodes[uid] = node
173
+ test_definitions = {}
174
+ for t_ in [*tests, *(man.get("unit_tests") or {}).values()]:
175
+ cfg = t_.get("config") or {}
176
+ if cfg.get("enabled", True) is False:
177
+ continue
178
+ deps = [uid for uid in (t_.get("depends_on") or {}).get("nodes", []) if uid in nodes]
179
+ test_definitions[t_["unique_id"]] = {
180
+ "id": t_["unique_id"], "name": t_["name"], "models": deps,
181
+ "tags": list(dict.fromkeys([*(t_.get("tags") or []), *(cfg.get("tags") or [])])),
182
+ "meta": {**(t_.get("meta") or {}), **(cfg.get("meta") or {})},
183
+ "description": t_.get("description") or "", "severity": cfg.get("severity", "error"),
184
+ "file": t_.get("original_file_path") or "", "resource_type": t_.get("resource_type", "test"),
185
+ }
186
+ att = t_.get("attached_node")
187
+ md = t_.get("test_metadata") or {}
188
+ if att in nodes:
189
+ kw = md.get("kwargs") or {}
190
+ nodes[att].tests.append({"name": md.get("name", t_["name"]), "column": kw.get("column_name") or t_.get("column_name"),
191
+ "kwargs": kw})
192
+ tests_by_id[t_["unique_id"]] = (att, md.get("name", t_["name"]), kw.get("column_name") or t_.get("column_name"))
193
+ return Project(nodes=nodes, tests_by_id=tests_by_id, adapter=adapter, root=Path(root) if root else None,
194
+ root_package=(man.get("metadata") or {}).get("project_name"), test_definitions=test_definitions)
@@ -0,0 +1,55 @@
1
+ """Result of the last dbt run (`target/run_results.json`): tests, failures, warnings, timings and skipped nodes."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import statistics
6
+ from pathlib import Path
7
+
8
+
9
+ def load(target: str | Path) -> dict | None:
10
+ f = Path(target) / "run_results.json"
11
+ if not f.exists():
12
+ return None
13
+ try:
14
+ d = json.loads(f.read_text())
15
+ except ValueError:
16
+ return None
17
+ meta = d.get("metadata", {})
18
+ return {
19
+ "invocation_id": meta.get("invocation_id"), "generated_at": meta.get("generated_at"),
20
+ "command": (d.get("args") or {}).get("which"), "elapsed": d.get("elapsed_time"),
21
+ "results": [{"unique_id": r["unique_id"], "status": r.get("status"), "time": r.get("execution_time") or 0.0,
22
+ "message": r.get("message"), "failures": r.get("failures")} for r in d.get("results", [])],
23
+ }
24
+
25
+
26
+ def summary(res: dict, project=None) -> dict:
27
+ out = {"invocation_id": res["invocation_id"], "command": res["command"], "elapsed": res["elapsed"],
28
+ "counts": {}, "slowest": [], "failing": []}
29
+ for r in res["results"]:
30
+ out["counts"][r["status"]] = out["counts"].get(r["status"], 0) + 1
31
+ name = lambda u: (project.nodes[u].name if project and u in project.nodes else u.split(".")[-1]) # noqa: E731
32
+ out["slowest"] = [{"name": name(r["unique_id"]), "time": round(r["time"], 2)}
33
+ for r in sorted(res["results"], key=lambda r: -r["time"]) if not r["unique_id"].startswith(("test.", "unit_test."))][:5]
34
+ for r in res["results"]:
35
+ if r["status"] in ("fail", "error", "warn"):
36
+ definition = project.test_definitions.get(r["unique_id"], {}) if project else {}
37
+ label = definition.get("name") or r["unique_id"].split(".")[-1]
38
+ out["failing"].append({"name": label, "status": r["status"], "failures": r["failures"], "message": (r["message"] or "")[:160]})
39
+ return out
40
+
41
+
42
+ def record(store, res: dict) -> bool:
43
+ """Record per-node timings in the history (once per invocation). Returns False if already recorded."""
44
+ if store.get_setting("state.dbt_invocation") == res["invocation_id"]:
45
+ return False
46
+ for r in res["results"]:
47
+ if not r["unique_id"].startswith(("test.", "unit_test.")) and r["status"] in ("success", "pass"):
48
+ store.add_history(f"dbt_time:{r['unique_id']}", __import__("time").time(), r["time"])
49
+ store.set_setting("state.dbt_invocation", res["invocation_id"])
50
+ return True
51
+
52
+
53
+ def median_history(store, uid: str, last: int = 20) -> tuple[float | None, int]:
54
+ h = [v for _, v in store.history(f"dbt_time:{uid}")][-last:]
55
+ return (statistics.median(h) if h else None), len(h)
@@ -0,0 +1,108 @@
1
+ """Results of quality tools (Great Expectations, Soda) → common records.
2
+
3
+ Input: JSON files the tools themselves write (the tool is never run here):
4
+ - Great Expectations: validation/checkpoint result (`result.to_json_dict()`, or `uncommitted/validations/**/*.json`).
5
+ - Soda Core/Cloud scan: `soda scan ... -srf results.json`.
6
+ Configuration: `intentflow config set dq.results 'path/or/glob[,another]'` (folders work; only `.json`).
7
+ """
8
+ from __future__ import annotations
9
+
10
+
11
+ import glob
12
+ import json
13
+ import os
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+
18
+ @dataclass
19
+ class DQResult:
20
+ tool: str # great_expectations | soda
21
+ table: str # dataset/table name as the tool knows it
22
+ column: str | None
23
+ check: str # expect_column_values_to_not_be_null | row_count > 0 ...
24
+ status: str # pass | fail | warn | error
25
+ detail: str = ""
26
+ observed: dict = field(default_factory=dict)
27
+ suite: str = ""
28
+ severity: str = "" # declared in the tool (GX 1.x: critical|warning|info), if any
29
+
30
+
31
+ def _gx_table(v: dict) -> str:
32
+ meta = v.get("meta") or {}
33
+ bd = meta.get("active_batch_definition") or {}
34
+ spec = meta.get("batch_spec") or {}
35
+ for c in (bd.get("data_asset_name"), spec.get("table_name"), spec.get("data_asset_name"), (v.get("batch_spec") or {}).get("table_name"),
36
+ meta.get("asset_name"), (meta.get("batch_markers") or {}).get("table_name")):
37
+ if c:
38
+ return str(c)
39
+ ids = meta.get("batch_id") or (v.get("batch_id") if isinstance(v.get("batch_id"), str) else "") or ""
40
+ return str(ids).split("-")[-1] if ids else "" # batch_id: "<datasource>-<asset>"
41
+
42
+
43
+ def _gx_validation(v: dict) -> list[DQResult]:
44
+ table = _gx_table(v)
45
+ suite = v.get("suite_name") or (v.get("meta") or {}).get("expectation_suite_name") or ""
46
+ out = []
47
+ for r in v.get("results", []):
48
+ cfg = r.get("expectation_config") or {}
49
+ kw = {k: x for k, x in (cfg.get("kwargs") or {}).items() if k != "batch_id"}
50
+ res = r.get("result") or {}
51
+ exc = r.get("exception_info") or {}
52
+ raised = exc.get("raised_exception") if isinstance(exc, dict) and "raised_exception" in exc else bool(exc and any(
53
+ isinstance(x, dict) and x.get("raised_exception") for x in exc.values()))
54
+ name = cfg.get("type") or cfg.get("expectation_type") or "expectation"
55
+ status = "error" if raised else ("pass" if r.get("success") else "fail")
56
+ obs = {k: res[k] for k in ("element_count", "unexpected_count", "unexpected_percent", "observed_value") if k in res}
57
+ out.append(DQResult("great_expectations", table, kw.get("column"), name, status,
58
+ "" if status == "pass" else f"{name}({', '.join(f'{k}={v!r}' for k, v in kw.items() if k != 'column')})", obs, suite,
59
+ str(cfg.get("severity") or "")))
60
+ return out
61
+
62
+
63
+ def _soda(doc: dict) -> list[DQResult]:
64
+ out = []
65
+ for c in doc.get("checks", []):
66
+ o = str(c.get("outcome") or "").lower()
67
+ status = {"pass": "pass", "fail": "fail", "warn": "warn"}.get(o, "error")
68
+ diag = c.get("diagnostics") or {}
69
+ obs = {k: v for k, v in diag.items() if isinstance(v, (int, float, str)) and k in ("value", "fail", "warn")}
70
+ out.append(DQResult("soda", c.get("table") or c.get("tableName") or "", c.get("column"), c.get("name") or str(c.get("definition") or "check").strip().splitlines()[-1].strip(" -"),
71
+ status, "", obs, c.get("definitionName") or ""))
72
+ return out
73
+
74
+
75
+ def parse(doc) -> list[DQResult]:
76
+ """Detect the format from the content. Unknown → []."""
77
+ if isinstance(doc, list):
78
+ return [r for d in doc for r in parse(d)]
79
+ if not isinstance(doc, dict):
80
+ return []
81
+ if "checks" in doc and ("hasFailures" in doc or "defaultDataSource" in doc or "definitionName" in doc):
82
+ return _soda(doc)
83
+ if "run_results" in doc: # GX 0.x/1.x checkpoint
84
+ return [r for v in doc["run_results"].values() for r in parse(v.get("validation_result", v))]
85
+ if "results" in doc and ("suite_name" in doc or "expectation_suite_name" in (doc.get("meta") or {}) or "statistics" in doc):
86
+ return _gx_validation(doc)
87
+ return []
88
+
89
+
90
+ def expand(spec: str | None) -> list[Path]:
91
+ out: list[Path] = []
92
+ for part in [x.strip() for x in (spec or "").split(",") if x.strip()]:
93
+ p = Path(os.path.expanduser(part))
94
+ if p.is_dir():
95
+ out += sorted(p.rglob("*.json"))
96
+ else:
97
+ out += [Path(x) for x in sorted(glob.glob(str(p)))]
98
+ return out
99
+
100
+
101
+ def load_all(spec: str | None) -> list[DQResult]:
102
+ res: list[DQResult] = []
103
+ for f in expand(spec):
104
+ try:
105
+ res += parse(json.loads(f.read_text()))
106
+ except (OSError, ValueError):
107
+ continue
108
+ return res