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,244 @@
1
+ """Lineage/impact queries for the UI. Loads the project once per artifact version (mtime)."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import threading
6
+ from collections import deque
7
+ from pathlib import Path
8
+
9
+ from . import dbt_loader, lineage as lin
10
+ from .i18n import tr
11
+
12
+ _cache: dict = {}
13
+ _lock = threading.Lock()
14
+
15
+
16
+ def _sig(target: str):
17
+ return tuple(os.path.getmtime(Path(target) / f) if (Path(target) / f).exists() else 0 for f in ("manifest.json", "catalog.json"))
18
+
19
+
20
+ def load(target: str, root: str | None = None, cache=None):
21
+ """(project, lineage_result); recomputed only when manifest/catalog change. `cache` (store): only changed models are re-read."""
22
+ target = str(Path(target).resolve())
23
+ root = str(Path(root).resolve()) if root else str(Path(target).parent)
24
+ key = (target, root, _sig(target))
25
+ with _lock:
26
+ hit = _cache.get((target, root))
27
+ if hit and hit[0] == key:
28
+ return hit[1], hit[2]
29
+ proj = dbt_loader.load(target, root or Path(target).parent)
30
+ res = lin.build(proj, cache=cache)
31
+ if cache is not None and hasattr(cache, "flush"):
32
+ cache.flush()
33
+ with _lock:
34
+ _cache[(target, root)] = (key, proj, res)
35
+ while len(_cache) > 16:
36
+ del _cache[next(iter(_cache))]
37
+ return proj, res
38
+
39
+
40
+ def _resolve(proj, model: str) -> str | None:
41
+ return next((u for u, n in proj.nodes.items() if n.name == model or u == model), None)
42
+
43
+
44
+ def models(proj, findings: list[dict] | None = None, include_packages: bool = False) -> list[dict]:
45
+ by_node: dict[str, list[str]] = {}
46
+ for f in findings or []:
47
+ for n in f.get("nodes", []):
48
+ by_node.setdefault(n, []).append(f["severity"])
49
+ order = ["critical", "high", "medium", "low", "info"]
50
+ out = []
51
+ for uid, n in proj.nodes.items():
52
+ if not include_packages and not proj.in_root_package(uid):
53
+ continue # installed packages (dbt_utils, project-evaluator...) are not the team's; `scan.include_packages` shows them
54
+ sv = by_node.get(uid, [])
55
+ out.append({"id": uid, "name": n.name, "type": n.resource_type, "materialized": n.materialized,
56
+ "columns": len(proj.actual_columns(uid)) or len(n.columns), "upstream": len(n.depends_on),
57
+ "downstream": len(proj.downstream(uid)), "owner": n.meta.get("owner") or n.meta.get("team"),
58
+ "tests": len(n.tests), "findings": len(sv), "worst": min(sv, key=order.index) if sv else None,
59
+ "pii": any(c.meta.get("pii") or "pii" in c.tags for c in n.columns.values())})
60
+ out.sort(key=lambda m: (m["type"] != "model", -m["downstream"], m["name"]))
61
+ return out
62
+
63
+
64
+ def model_detail(proj, model: str) -> dict | None:
65
+ uid = _resolve(proj, model)
66
+ if not uid:
67
+ return None
68
+ n = proj.nodes[uid]
69
+ cols = proj.actual_columns(uid) or n.columns
70
+ return {"id": uid, "name": n.name, "type": n.resource_type, "materialized": n.materialized, "path": n.path,
71
+ "owner": n.meta.get("owner"), "description": n.description,
72
+ "columns": [{"name": c.name, "type": c.type, "pii": bool(c.meta.get("pii") or "pii" in c.tags),
73
+ "tests": sorted({t["name"] for t in n.tests if t.get("column") == c.name})} for c in cols.values()],
74
+ "tests": [t["name"] for t in n.tests if not t.get("column")]}
75
+
76
+
77
+ def model_graph(proj, model: str, depth: int = 2) -> dict:
78
+ uid = _resolve(proj, model)
79
+ if not uid:
80
+ raise ValueError(tr("model '{model}' not found", model=model))
81
+ nodes, edges = {uid: 0}, set()
82
+ q = deque([(uid, 0)])
83
+ visited = {(uid, "up"), (uid, "down")}
84
+ ch = proj.children()
85
+ while q:
86
+ cur, d = q.popleft()
87
+ if abs(d) >= depth:
88
+ continue
89
+ for p in proj.nodes[cur].depends_on:
90
+ if p in proj.nodes and d <= 0:
91
+ nodes.setdefault(p, d - 1)
92
+ edges.add((p, cur))
93
+ if (p, "up") not in visited:
94
+ visited.add((p, "up"))
95
+ q.append((p, d - 1))
96
+ for c in ch.get(cur, []):
97
+ if d >= 0:
98
+ nodes.setdefault(c, d + 1)
99
+ edges.add((cur, c))
100
+ if (c, "down") not in visited:
101
+ visited.add((c, "down"))
102
+ q.append((c, d + 1))
103
+ return {"center": uid, "nodes": [{"id": u, "name": proj.nodes[u].name, "type": proj.nodes[u].resource_type, "level": lv,
104
+ "owner": proj.nodes[u].meta.get("owner")} for u, lv in nodes.items()],
105
+ "edges": [{"src": a, "dst": b} for a, b in sorted(edges)]}
106
+
107
+
108
+ def column_graph(proj, res, model: str, column: str, depth: int = 3) -> dict:
109
+ uid = _resolve(proj, model)
110
+ if not uid:
111
+ raise ValueError(tr("model '{model}' not found", model=model))
112
+ column = column.lower()
113
+ if column not in proj.nodes[uid].columns:
114
+ raise ValueError(tr("column '{column}' does not exist in {model}", column=column, model=model))
115
+ nodes = {(uid, column): 0}
116
+ edges = []
117
+ for direction in ("up", "down"):
118
+ q = deque([((uid, column), 0)])
119
+ seen = {(uid, column)}
120
+ while q:
121
+ (u, c), d = q.popleft()
122
+ if d >= depth:
123
+ continue
124
+ es = res.upstream_of(u, c) if direction == "up" else res.downstream_of(u, c)
125
+ for e in es:
126
+ nxt = (e.src, e.src_col) if direction == "up" else (e.dst, e.dst_col)
127
+ lvl = -(d + 1) if direction == "up" else d + 1
128
+ nodes.setdefault(nxt, lvl)
129
+ edges.append({"src": f"{e.src}.{e.src_col}", "dst": f"{e.dst}.{e.dst_col}", "kind": e.kind, "masked": e.masked})
130
+ if nxt not in seen:
131
+ seen.add(nxt)
132
+ q.append((nxt, d + 1))
133
+ seen_e, uniq = set(), []
134
+ for e in edges:
135
+ k = (e["src"], e["dst"])
136
+ if k not in seen_e:
137
+ seen_e.add(k)
138
+ uniq.append(e)
139
+ out_nodes = []
140
+ for (u, c), lv in nodes.items():
141
+ n = proj.nodes[u]
142
+ col = n.columns.get(c)
143
+ out_nodes.append({"id": f"{u}.{c}", "model": n.name, "column": c, "type": col.type if col else "", "level": lv,
144
+ "pii": bool(col and (col.meta.get("pii") or "pii" in col.tags)), "owner": n.meta.get("owner")})
145
+ return {"center": f"{uid}.{column}", "nodes": out_nodes, "edges": uniq}
146
+
147
+
148
+ def impact(proj, res, model: str, column: str | None = None, external: list | None = None) -> dict:
149
+ uid = _resolve(proj, model)
150
+ if not uid:
151
+ raise ValueError(tr("model '{model}' not found", model=model))
152
+ if column:
153
+ affected: dict[str, dict] = {}
154
+ via_map: dict[str, set[str]] = {}
155
+ frontier = [(uid, column.lower(), 0)]
156
+ seen = set()
157
+ while frontier:
158
+ u, c, d = frontier.pop()
159
+ for dst, via in res.indirect_of(u, c): # JOIN/filter/grouping...: the whole model is affected
160
+ via_map.setdefault(dst, set()).add(via)
161
+ a = affected.setdefault(dst, {"distance": d + 1, "columns": set()})
162
+ a["distance"] = min(a["distance"], d + 1)
163
+ for col in proj.nodes[dst].columns:
164
+ if (dst, col) not in seen:
165
+ seen.add((dst, col))
166
+ frontier.append((dst, col, d + 1))
167
+ for e in res.downstream_of(u, c):
168
+ if (e.dst, e.dst_col) in seen:
169
+ continue
170
+ seen.add((e.dst, e.dst_col))
171
+ a = affected.setdefault(e.dst, {"distance": d + 1, "columns": set()})
172
+ a["distance"] = min(a["distance"], d + 1)
173
+ a["columns"].add(e.dst_col)
174
+ frontier.append((e.dst, e.dst_col, d + 1))
175
+ rows = [{"name": proj.nodes[u].name, "id": u, "distance": a["distance"], "columns": sorted(a["columns"]),
176
+ "owner": proj.nodes[u].meta.get("owner"), "tests": len(proj.nodes[u].tests),
177
+ **({"indirect_via": sorted(via_map[u])} if u in via_map else {})} for u, a in affected.items()]
178
+ hit = {uid, *affected}
179
+ consumers: dict[str, int] = {} # dashboards, semantic models, metrics: reached through the graph, without column lineage
180
+ for h in hit:
181
+ base = affected[h]["distance"] if h in affected else 0
182
+ for d in proj.downstream(h):
183
+ if proj.nodes[d].resource_type in ("exposure", "semantic_model", "metric", "saved_query"):
184
+ consumers[d] = min(consumers.get(d, 99), base + 1)
185
+ if external: # jobs outside the project (Spark/Python/...) that read the column or something derived from it, and the chain of outputs
186
+ from . import external as ext
187
+ touched = {(uid, column.lower())} | {(u, c) for u, a in affected.items() for c in a["columns"]}
188
+ hits = ext.readers(proj, external, touched, set(affected) | {uid})
189
+ jdist: dict[str, int] = {}
190
+ for job, h in hits.items(): # `hits` comes in discovery order: the previous job already has a distance
191
+ rs = h["reads"]
192
+ base_d = min((affected[u]["distance"] for u, _, r in ext.resolve(proj, rs) if u in affected), default=0)
193
+ jdist[job] = jdist[h["via"]] + 1 if h["via"] in jdist else base_d + h["depth"]
194
+ rows.append({"name": job, "id": "job:" + job, "distance": jdist[job], "columns": sorted({r.column for r in rs if r.column != "*"}),
195
+ "owner": rs[0].owner, "tests": 0, "kind": "job", "source": rs[0].source,
196
+ "writes": sorted({w for r in rs for w in r.writes}), "via_job": h["via"]})
197
+ known = {r["id"] for r in rows}
198
+ outs = {f for r in rs for f in (r.feeds or tuple((w, "*") for w in r.writes))}
199
+ for w, wcol in outs: # a job output that is a project node: per column when known, otherwise the whole node
200
+ wu = ext.match_dataset(proj, w)
201
+ if not wu or wu == uid:
202
+ continue
203
+ wn = proj.nodes[wu]
204
+ sub = ([r2 for r2 in impact(proj, res, wn.name, wcol)["affected"] if r2.get("kind") is None]
205
+ if wcol != "*" and wcol in wn.columns else
206
+ [{"id": du, "name": proj.nodes[du].name, "distance": 1, "columns": [], "owner": proj.nodes[du].meta.get("owner"),
207
+ "tests": len(proj.nodes[du].tests)} for du in proj.downstream(wu)])
208
+ for du, name, dist, cols, own, ntests in [(wu, wn.name, 0, [wcol] if wcol != "*" else [], wn.meta.get("owner"), len(wn.tests))] + \
209
+ [(x["id"], x["name"], x["distance"] or 1, x["columns"], x["owner"], x["tests"]) for x in sub]:
210
+ if du in known or du in affected or du == uid:
211
+ continue
212
+ known.add(du)
213
+ rows.append({"name": name, "id": du, "distance": jdist[job] + 1 + dist, "columns": cols, "owner": own, "tests": ntests,
214
+ "via_job": job})
215
+ for xu, dist in consumers.items():
216
+ xn = proj.nodes[xu]
217
+ rows.append({"name": xn.name, "id": xu, "distance": dist, "columns": [], "owner": xn.meta.get("owner"), "tests": 0,
218
+ "kind": xn.resource_type, "exposure_type": xn.meta.get("exposure_type"), "url": xn.meta.get("url")})
219
+ else:
220
+ down = proj.downstream(uid)
221
+ rows = [{"name": proj.nodes[u].name, "id": u, "distance": None, "columns": [], "owner": proj.nodes[u].meta.get("owner"),
222
+ "tests": len(proj.nodes[u].tests)} for u in down]
223
+ rows.sort(key=lambda r: (r["distance"] or 99, r["name"]))
224
+ return {"model": proj.nodes[uid].name, "column": column, "affected": rows, "owners": sorted({r["owner"] for r in rows if r["owner"]}),
225
+ "count": len(rows)}
226
+
227
+
228
+ def _edges(proj, res) -> dict:
229
+ def name(u):
230
+ return proj.nodes[u].name if u in proj.nodes else u
231
+ return {(f"{name(e.src)}.{e.src_col}", f"{name(e.dst)}.{e.dst_col}"): e.kind for e in res.edges}
232
+
233
+
234
+ def diff(base, head) -> dict:
235
+ """Column-lineage changes between two (project, result) pairs, keyed by model name (stable across builds).
236
+ `changed`: same edge, different kind (e.g. direct → derived)."""
237
+ (bp, br), (hp, hr) = base, head
238
+ b, h = _edges(bp, br), _edges(hp, hr)
239
+ row = lambda k, kind: {"src": k[0], "dst": k[1], "kind": kind}
240
+ bm, hm = {n.name for n in bp.nodes.values()}, {n.name for n in hp.nodes.values()}
241
+ return {"added": [row(k, h[k]) for k in sorted(h.keys() - b.keys())],
242
+ "removed": [row(k, b[k]) for k in sorted(b.keys() - h.keys())],
243
+ "changed": [{"src": k[0], "dst": k[1], "from": b[k], "to": h[k]} for k in sorted(b.keys() & h.keys()) if b[k] != h[k]],
244
+ "models_added": sorted(hm - bm), "models_removed": sorted(bm - hm)}
@@ -0,0 +1,374 @@
1
+ """Dynamic oracle to measure column lineage on real projects (DuckDB), without a hand-made answer key.
2
+
3
+ For each source column (seed/source) the oracle perturbs the data (NULL and value shift), rebuilds the project models from
4
+ the compiled SQL, and sees which output columns changed. It compares that with the closure of the static lineage (SQLGlot):
5
+
6
+ * TP = the lineage claims the dependency and the data changed;
7
+ * FN = the data changed and the lineage does not claim it (recall drops);
8
+ * FP? = the lineage claims it, the model kept its row count and the column did not change under any perturbation ("suspect": it can be a
9
+ real dependency the perturbation does not reveal, e.g. a COALESCE that never takes the branch; hence an upper bound of false positives);
10
+ * undetermined = the model's row count changed under both perturbations (filter/join): indirect dependency, left out of the count.
11
+
12
+ It is a measured approximation, not an answer key. See docs/BENCHMARKS.md for the method and the numbers.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import shutil
18
+ import tempfile
19
+ import time
20
+ from collections import defaultdict
21
+ from pathlib import Path
22
+
23
+ NUMERIC = re.compile(r"(?i)^(tinyint|smallint|integer|int|bigint|hugeint|ubigint|float|double|real|decimal|numeric)")
24
+
25
+
26
+ def _q(n: str) -> str:
27
+ return '"' + n.replace('"', '""') + '"'
28
+
29
+
30
+ def _rel(node) -> str:
31
+ return ".".join(_q(p.strip('"`[]')) for p in node.relation.split("."))
32
+
33
+
34
+ def _order(project, models: list[str]) -> list[str]:
35
+ deps = {u: [d for d in project.nodes[u].depends_on if d in set(models)] for u in models}
36
+ out, seen = [], set()
37
+
38
+ def visit(u):
39
+ if u in seen:
40
+ return
41
+ seen.add(u)
42
+ for d in deps[u]:
43
+ visit(d)
44
+ out.append(u)
45
+ for u in models:
46
+ visit(u)
47
+ return out
48
+
49
+
50
+ def _sample_bases(con, project, bases: list[str], cap: int) -> dict[str, list[int]]:
51
+ """Shrink each source above `cap` rows by key hash (the same key falls in the same bucket in every table, so joins
52
+ survive). Key = the first column whose name appears in 2+ sources, otherwise the first column. Works on the temporary copy."""
53
+ cols: dict[str, list[str]] = {}
54
+ for b in bases:
55
+ try:
56
+ cols[b] = [r[0] for r in con.execute(f"describe select * from {_rel(project.nodes[b])}").fetchall()]
57
+ except Exception:
58
+ continue
59
+ seen: dict[str, int] = defaultdict(int)
60
+ for cs in cols.values():
61
+ for c in set(x.lower() for x in cs):
62
+ seen[c] += 1
63
+ out: dict[str, list[int]] = {}
64
+ for b, cs in cols.items():
65
+ r = _rel(project.nodes[b])
66
+ try:
67
+ n = con.execute(f"select count(*) from {r}").fetchone()[0]
68
+ if n <= cap or not cs:
69
+ continue
70
+ key = next((c for c in cs if seen[c.lower()] > 1), cs[0])
71
+ con.execute(f"create or replace temp table _smp as select * from {r} where hash({_q(key)}) % 10000 < {max(1, int(cap / n * 10000))}")
72
+ con.execute(f"delete from {r}")
73
+ con.execute(f"insert into {r} select * from _smp")
74
+ con.execute("drop table _smp")
75
+ out[project.nodes[b].name] = [n, con.execute(f"select count(*) from {r}").fetchone()[0]]
76
+ except Exception:
77
+ continue
78
+ return out
79
+
80
+
81
+ def static_closure(edges, start: tuple[str, str], indirect=(), model_columns: dict | None = None, include_indirect: bool = True) -> set[tuple[str, str]]:
82
+ """Columns reached by direct lineage and, with `include_indirect`, by indirect dependency (affects every column of the model)."""
83
+ by: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
84
+ for e in edges:
85
+ by[(e.src, e.src_col.strip('"`[]').lower())].append((e.dst, e.dst_col.strip('"`[]').lower()))
86
+ if include_indirect:
87
+ for src, col, dst, _via in indirect:
88
+ for c in (model_columns or {}).get(dst, []):
89
+ by[(src, col.lower())].append((dst, c.lower()))
90
+ seen, stack = set(), [start]
91
+ while stack:
92
+ for nxt in by.get(stack.pop(), []):
93
+ if nxt not in seen:
94
+ seen.add(nxt)
95
+ stack.append(nxt)
96
+ return seen
97
+
98
+
99
+ def run(project, lineage_result, duckdb_path: str, package: str | None = None, max_columns: int | None = None,
100
+ only_models: list[str] | None = None, progress=None, only_used: bool = False,
101
+ only_sources: list[str] | None = None, sample_rows: int | None = None) -> dict:
102
+ import duckdb
103
+ models = [u for u, n in project.nodes.items() if n.resource_type == "model" and n.compiled_code and n.relation
104
+ and (not package or u.startswith(f"model.{package}."))]
105
+ if only_models:
106
+ models = [u for u in models if project.nodes[u].name in only_models]
107
+ models = _order(project, models)
108
+ bases_all = [u for u, n in project.nodes.items() if n.resource_type in ("seed", "source") and n.relation]
109
+ same: dict[str, list[str]] = {} # a seed and a source can be the same physical table: test once, add up both nodes' lineage
110
+ for u in bases_all:
111
+ same.setdefault(project.nodes[u].relation.lower(), []).append(u)
112
+ bases = [us[0] for us in same.values()]
113
+ tmpdir = tempfile.mkdtemp(prefix="intentflow-oracle-")
114
+ tmp = Path(tmpdir) / Path(duckdb_path).name # the file name is the catalog name in the relations
115
+ shutil.copy(duckdb_path, tmp)
116
+ con = duckdb.connect(str(tmp))
117
+ try: # the copy holds real data: always closed and deleted
118
+ return _run(project, lineage_result, con, models, bases, same, max_columns, progress, only_used, only_sources, sample_rows)
119
+ finally:
120
+ con.close()
121
+ shutil.rmtree(tmpdir, ignore_errors=True)
122
+
123
+
124
+ def _run(project, lineage_result, con, models, bases, same, max_columns, progress, only_used, only_sources, sample_rows) -> dict:
125
+
126
+ def tab_cols(u):
127
+ try:
128
+ return [r[0] for r in con.execute(f"describe select * from {_rel(project.nodes[u])}").fetchall()]
129
+ except Exception:
130
+ return []
131
+
132
+ def rebuild(ms=None):
133
+ for u in (models if ms is None else ms):
134
+ kind = "view" if project.nodes[u].materialized == "view" else "table" # keep the original object type
135
+ con.execute(f"create or replace {kind} {_rel(project.nodes[u])} as {project.nodes[u].compiled_code}")
136
+
137
+ keys: dict[str, str | None] = {}
138
+
139
+ def pick_key(u):
140
+ """First unique, non-null column of the model (aligns rows across runs); None if there is none."""
141
+ n = project.nodes[u]
142
+ for c in tab_cols(u):
143
+ r, d, nn = con.execute(f"select count(*), count(distinct {_q(c)}), count({_q(c)}) from {_rel(n)}").fetchone()
144
+ if r > 1 and r == d == nn:
145
+ return c
146
+ return None
147
+
148
+ def signature(ms=None):
149
+ sig = {}
150
+ txt = lambda c: f"coalesce(cast({_q(c)} as varchar), '<null>')"
151
+ for u in (models if ms is None else ms):
152
+ n = project.nodes[u]
153
+ cols = [c for c in tab_cols(u)]
154
+ rows = con.execute(f"select count(*) from {_rel(n)}").fetchone()[0]
155
+ if u not in keys:
156
+ keys[u] = pick_key(u)
157
+ k = keys[u]
158
+ hs = {}
159
+ for c in cols:
160
+ # with a key: pair (key, value) and see changes in WHICH row gets which value (ROW_NUMBER/RANK), which a multiset hides
161
+ pair = f"{txt(k)} || '#' || {txt(c)}" if k and c != k else txt(c)
162
+ hs[c.lower()] = con.execute(f"select md5(string_agg({pair}, '|' order by {pair})) from {_rel(n)}").fetchone()[0]
163
+ sig[u] = (rows, hs)
164
+ return sig
165
+
166
+ t0 = time.time()
167
+ unbuildable: dict[str, str] = {} # SQL invalid/incompatible with DuckDB, or depends on such a model: out of the test, but reported
168
+ built = []
169
+ def _exists(u):
170
+ try:
171
+ con.execute(f"select 1 from {_rel(project.nodes[u])} limit 0")
172
+ return True
173
+ except Exception:
174
+ return False
175
+ # a model without parents that already exists in the file: its data is the source; rebuilding it (e.g. empty `graph` outside dbt) would wipe it
176
+ keep = {u for u in models if not any(d in project.nodes for d in project.nodes[u].depends_on) and _exists(u)}
177
+ for u in models:
178
+ if u in keep:
179
+ built.append(u)
180
+ continue
181
+ parts = [x.strip('"`[]') for x in project.nodes[u].relation.split(".")]
182
+ if len(parts) == 3: # the model's target schema may not exist in the data file
183
+ con.execute(f'create schema if not exists {_q(parts[0])}.{_q(parts[1])}')
184
+ kind = "view" if project.nodes[u].materialized == "view" else "table"
185
+ try:
186
+ con.execute(f"create or replace {kind} {_rel(project.nodes[u])} as {project.nodes[u].compiled_code}")
187
+ built.append(u)
188
+ except Exception as ex:
189
+ unbuildable[u] = str(ex).strip().splitlines()[0][:160]
190
+ models = built
191
+ # a model without any parent (data from literals/`graph`) is the "source" of that project: its table is perturbed
192
+ roots = [u for u in models if not any(d in project.nodes for d in project.nodes[u].depends_on)]
193
+ models = [u for u in models if u not in roots]
194
+ for u in roots:
195
+ r_ = _rel(project.nodes[u]) # the root becomes a physical table (a view does not accept UPDATE) and is no longer rebuilt
196
+ con.execute(f"create or replace temp table _root_copy as select * from {r_}")
197
+ for drop in ("view", "table"):
198
+ try:
199
+ con.execute(f"drop {drop} if exists {r_}")
200
+ except Exception:
201
+ pass
202
+ con.execute(f"create table {r_} as select * from _root_copy")
203
+ con.execute("drop table _root_copy")
204
+ same.setdefault(project.nodes[u].relation.lower(), []).append(u)
205
+ if project.nodes[u].relation.lower() not in {project.nodes[b].relation.lower() for b in bases}:
206
+ bases.append(u)
207
+ sampled: dict[str, list[int]] = {}
208
+ if sample_rows:
209
+ sampled = _sample_bases(con, project, bases, sample_rows)
210
+ rebuild()
211
+ base_sig = signature()
212
+ rebuild()
213
+ again = signature() # two builds without perturbation: what changes on its own (now(), random()) cannot count as an effect
214
+ unstable_rows = {u for u in models if again[u][0] != base_sig[u][0]}
215
+ unstable = {(u, c) for u in models for c, h in base_sig[u][1].items() if again[u][1].get(c) != h}
216
+ mcols = {u: list(base_sig[u][1]) for u in models}
217
+ targets = []
218
+ for b in bases:
219
+ n = project.nodes[b]
220
+ try: # a seed/source missing from the given DuckDB is not testable: skip it (its lineage stays unverified)
221
+ desc = con.execute(f"describe select * from {_rel(n)}").fetchall()
222
+ except Exception:
223
+ continue
224
+ for col, typ in [(r[0], str(r[1])) for r in desc]:
225
+ targets.append((b, col, typ))
226
+ used = {(e.src, e.src_col.strip('"`[]').lower()) for e in lineage_result.edges} | {(s_, c_.lower()) for s_, c_, *_ in lineage_result.indirect}
227
+ unused = [(b, c) for b, c, _ in targets if not any((t, c.lower()) in used for t in same[project.nodes[b].relation.lower()])]
228
+ if only_used: # faster, but hides false negatives: columns the lineage thinks nobody reads are not tested
229
+ targets = [t for t in targets if any((x, t[1].lower()) in used for x in same[project.nodes[t[0]].relation.lower()])]
230
+ if only_sources: # `name` (all columns) or `name.column`
231
+ wanted = set(only_sources)
232
+ targets = [t for t in targets if project.nodes[t[0]].name in wanted or f"{project.nodes[t[0]].name}.{t[1]}" in wanted]
233
+ if max_columns:
234
+ targets = targets[:max_columns]
235
+
236
+ # real values per column name (all sources): "swap for another valid value" passes through filters like `= 'model'`,
237
+ # which `value || '_x'` never passes
238
+ vals_by_col: dict[str, list[str]] = {}
239
+ for b in bases:
240
+ try:
241
+ for cname, ctype, *_ in con.execute(f"describe select * from {_rel(project.nodes[b])}").fetchall():
242
+ if str(ctype).upper().startswith("VARCHAR"):
243
+ got = [r[0] for r in con.execute(f"select {_q(cname)} from {_rel(project.nodes[b])} where {_q(cname)} is not null "
244
+ f"group by 1 order by count(*) desc limit 8").fetchall()]
245
+ for v in got:
246
+ if v not in vals_by_col.setdefault(cname.lower(), []) and len(vals_by_col[cname.lower()]) < 12:
247
+ vals_by_col[cname.lower()].append(v)
248
+ except Exception:
249
+ pass
250
+
251
+ rel_of = {u: _rel(project.nodes[u]).lower() for u in models}
252
+ code_of = {u: (project.nodes[u].compiled_code or "").lower() for u in models}
253
+ affected_cache: dict[str, list[str]] = {}
254
+
255
+ def affected_by(b: str) -> list[str]:
256
+ """Models that can see a perturbation in `b` (in topological order); the others are not rebuilt."""
257
+ key = project.nodes[b].relation.lower()
258
+ if key not in affected_cache:
259
+ rels = {_rel(project.nodes[t]).lower() for t in same[key]}
260
+ uids = set(same[key])
261
+ out = []
262
+ for u in models:
263
+ if u in uids:
264
+ continue
265
+ if any(d in uids for d in project.nodes[u].depends_on) or any(r in code_of[u] for r in rels):
266
+ out.append(u)
267
+ uids.add(u)
268
+ rels.add(rel_of[u])
269
+ affected_cache[key] = out
270
+ return affected_cache[key]
271
+
272
+ tp = fn = fp_susp = indet = explained_n = 0
273
+ mtp = mfp = mfn = 0
274
+ mset = set(models)
275
+ rows_out, fn_list, fp_list, skipped, all_null = [], [], [], [], []
276
+ for i, (b, col, typ) in enumerate(targets):
277
+ node = project.nodes[b]
278
+ rel, cq = _rel(node), _q(col)
279
+ perturbs = {"null": f"update {rel} set {cq} = NULL"}
280
+ tu = typ.upper()
281
+ if NUMERIC.match(typ):
282
+ perturbs["shift"] = f"update {rel} set {cq} = {cq} + 1000003"
283
+ perturbs["reverse"] = f"update {rel} set {cq} = -{cq}" # inverte a ordem relativa (revela ORDER BY / janelas)
284
+ elif tu.startswith("DATE") or tu.startswith("TIMESTAMP"):
285
+ perturbs["shift"] = f"update {rel} set {cq} = {cq} + INTERVAL 1 DAY"
286
+ perturbs["reverse"] = f"update {rel} set {cq} = DATE '2100-01-01' - ({cq}::DATE - DATE '1970-01-01')"
287
+ elif tu.startswith("BOOL"):
288
+ perturbs["shift"] = f"update {rel} set {cq} = not {cq}"
289
+ else:
290
+ perturbs["shift"] = f"update {rel} set {cq} = {cq} || '_x'"
291
+ perturbs["reverse"] = f"update {rel} set {cq} = reverse(cast({cq} as varchar))"
292
+ if tu.startswith("VARCHAR"):
293
+ own = {r[0] for r in con.execute(f"select distinct {cq} from {rel} limit 50").fetchall()}
294
+ for i_, v in enumerate([v for v in vals_by_col.get(col.lower(), []) if v not in own][:3]):
295
+ perturbs[f"swap{i_}"] = "update " + rel + " set " + cq + " = '" + v.replace("'", "''") + "' where " + cq + " is not null"
296
+ try: # a column without any value: every perturbation is a no-op (NULL+1 = NULL), so it cannot be tested
297
+ if con.execute(f"select count({cq}) from {rel}").fetchone()[0] == 0:
298
+ all_null.append(f"{node.name}.{col}")
299
+ continue
300
+ except Exception:
301
+ pass
302
+ aff = affected_by(b)
303
+ applied = 0
304
+ row_changed: set[str] = set()
305
+ changed: dict[tuple[str, str], bool] = {}
306
+ stable_rows: dict[str, bool] = {}
307
+ for _pname, sql in perturbs.items():
308
+ con.execute("begin")
309
+ try:
310
+ con.execute(sql)
311
+ except Exception: # perturbation not applicable (type/object): never counts as a "hit" or a "false positive"
312
+ con.execute("rollback")
313
+ continue
314
+ applied += 1
315
+ try:
316
+ rebuild(aff)
317
+ sig = signature(aff)
318
+ except Exception:
319
+ con.execute("rollback")
320
+ continue
321
+ con.execute("rollback")
322
+ for u in models:
323
+ if u not in sig: # does not depend on the perturbed source: same output by construction
324
+ stable_rows[u] = True
325
+ continue
326
+ brows, bh = base_sig[u]
327
+ prows, ph = sig[u]
328
+ if u in unstable_rows:
329
+ continue # non-deterministic row count: no verdict
330
+ if prows != brows:
331
+ row_changed.add(u) # rows changed: affected (indirect); out of the column-by-column metric
332
+ continue
333
+ stable_rows[u] = True
334
+ for c, h in ph.items():
335
+ if (u, c) not in unstable and bh.get(c) != h:
336
+ changed[(u, c)] = True
337
+ if not applied:
338
+ skipped.append(f"{node.name}.{col}")
339
+ continue
340
+ dyn = set(changed)
341
+ twins = same[node.relation.lower()]
342
+ stat_direct = {(u, c) for t in twins for (u, c) in static_closure(lineage_result.edges, (t, col.lower())) if u in mset}
343
+ stat_all = {(u, c) for t in twins for (u, c) in static_closure(lineage_result.edges, (t, col.lower()), lineage_result.indirect, mcols) if u in mset}
344
+ dyn_models, stat_models = {u for u, _ in dyn} | row_changed, {u for u, _ in stat_all}
345
+ # column by column, direct lineage only
346
+ d_tp = dyn & stat_direct
347
+ d_susp = {(u, c) for (u, c) in stat_direct if stable_rows.get(u)} - dyn
348
+ # what changed and direct lineage does not cover: explained by indirect dependency (model ∈ indirect closure) or truly lost
349
+ d_miss = dyn - stat_direct
350
+ explained = {k for k in d_miss if k[0] in stat_models}
351
+ lost = d_miss - explained
352
+ # model level (direct ∪ indirect)
353
+ m_tp = dyn_models & stat_models
354
+ m_susp = {u for u in stat_models if stable_rows.get(u)} - dyn_models
355
+ m_miss = dyn_models - stat_models
356
+ tp += len(d_tp); fp_susp += len(d_susp); fn += len(lost); explained_n += len(explained)
357
+ mtp += len(m_tp); mfp += len(m_susp); mfn += len(m_miss)
358
+ indet += len({(u, c) for (u, c) in stat_direct if not stable_rows.get(u)})
359
+ name = lambda k: f"{project.nodes[k[0]].name}.{k[1]}"
360
+ rows_out.append({"source": f"{node.name}.{col}", "static_direct": len(stat_direct), "static_with_indirect": len(stat_all), "dynamic": len(dyn),
361
+ "tp": len(d_tp), "fn_lost": len(lost), "explained_by_indirect": len(explained), "fp_suspect": len(d_susp),
362
+ "model_tp": len(m_tp), "model_fp_suspect": len(m_susp), "model_fn": len(m_miss)})
363
+ fn_list += [f"{node.name}.{col} → {name(k)}" for k in sorted(lost)]
364
+ fp_list += [f"{node.name}.{col} → {name(k)}" for k in sorted(d_susp)]
365
+ if progress:
366
+ progress(i + 1, len(targets), f"{node.name}.{col}")
367
+ rate = lambda a, b: (a / (a + b)) if a + b else None
368
+ prec, rec = rate(tp, fp_susp), rate(tp, fn + explained_n) # recall direto: o que mudou e a direta cobre
369
+ mprec, mrec = rate(mtp, mfp), rate(mtp, mfn)
370
+ return {"models": len(models), "unbuildable": {project.nodes[u].name: r for u, r in unbuildable.items()}, "root_models_as_sources": [project.nodes[u].name for u in roots], "sampled_sources": sampled, "nondeterministic_columns": len(unstable), "perturbation_not_applicable": skipped, "untestable_all_null": all_null, "source_columns_tested": len(targets), "source_columns_unused": len(unused), "seconds": round(time.time() - t0, 1),
371
+ "direct": {"tp": tp, "fp_suspect": fp_susp, "precision_lower_bound": prec, "recall_of_value_changes": rec,
372
+ "changed_but_only_indirect": explained_n, "lost": fn},
373
+ "model_level": {"tp": mtp, "fp_suspect": mfp, "fn": mfn, "precision_lower_bound": mprec, "recall": mrec},
374
+ "indeterminate": indet, "per_source": rows_out, "false_negatives": fn_list, "suspect_false_positives": fp_list}