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,83 @@
1
+ """Groups findings by root cause: findings whose affected nodes share the same upstream origin
2
+ become a single incident (one alert instead of dozens)."""
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from .model import SEVERITIES
8
+ from .i18n import cat, tr
9
+
10
+
11
+ @dataclass
12
+ class Incident:
13
+ origin: str
14
+ title: str
15
+ severity: str
16
+ findings: list[dict] = field(default_factory=list)
17
+ impacted: list[str] = field(default_factory=list)
18
+ owners: list[str] = field(default_factory=list)
19
+
20
+ @property
21
+ def id(self) -> str:
22
+ return "inc-" + self.origin.replace("model.", "").replace("seed.", "").replace("source.", "").replace(".", "-")[:40]
23
+
24
+
25
+ def group(findings: list[dict], project=None) -> list[Incident]:
26
+ """`findings`: dicts (like `Store.findings`). `project`: dbt_loader.Project (for ancestry)."""
27
+ def ancestors(uid):
28
+ out, stack = set(), [uid]
29
+ while stack:
30
+ cur = stack.pop() # always drain the stack (an unknown node has no parents, but does not hang)
31
+ node = project.nodes.get(cur) if project else None
32
+ for d in (node.depends_on if node else []):
33
+ if d not in out:
34
+ out.add(d)
35
+ if d in project.nodes:
36
+ stack.append(d)
37
+ return out
38
+
39
+ by: dict[str, Incident] = {}
40
+ for f in findings:
41
+ nodes = f.get("nodes") or [f["id"]]
42
+ known = [n for n in nodes if project and n in project.nodes]
43
+ if known:
44
+ # origin = affected node without an affected ancestor; tie → the first (the finding itself names the node)
45
+ roots = [n for n in known if not (ancestors(n) & set(known))]
46
+ origin = (roots or known)[0]
47
+ else:
48
+ origin = nodes[0]
49
+ inc = by.setdefault(origin, Incident(origin, "", f["severity"]))
50
+ inc.findings.append(f)
51
+ inc.impacted = sorted(set(inc.impacted) | set(nodes))
52
+ if SEVERITIES.index(f["severity"]) < SEVERITIES.index(inc.severity):
53
+ inc.severity = f["severity"]
54
+ o = (f.get("evidence") or {}).get("owner")
55
+ if o and o not in inc.owners:
56
+ inc.owners.append(o)
57
+ # the same check on origin and descendant = the same root cause: merge into the ancestor
58
+ def checks(i):
59
+ return {(f.get("check_id") or f.get("check", "")) for f in i.findings}
60
+ if project:
61
+ merged = True
62
+ while merged:
63
+ merged = False
64
+ for a in list(by.values()):
65
+ for b in list(by.values()):
66
+ if a is not b and a.origin in by and b.origin in by and a.origin in ancestors(b.origin) and checks(a) & checks(b):
67
+ a.findings += b.findings
68
+ a.impacted = sorted(set(a.impacted) | set(b.impacted))
69
+ a.owners += [o for o in b.owners if o not in a.owners]
70
+ if SEVERITIES.index(b.severity) < SEVERITIES.index(a.severity):
71
+ a.severity = b.severity
72
+ del by[b.origin]
73
+ merged = True
74
+ break
75
+ if merged:
76
+ break
77
+ out = []
78
+ for inc in by.values():
79
+ top = min(inc.findings, key=lambda x: SEVERITIES.index(x["severity"]))
80
+ inc.title = cat(top["title"], " (" + tr("+{n} related", n=len(inc.findings) - 1) + ")") if len(inc.findings) > 1 else top["title"]
81
+ out.append(inc)
82
+ out.sort(key=lambda i: (SEVERITIES.index(i.severity), -len(i.findings), i.origin))
83
+ return out
@@ -0,0 +1,139 @@
1
+ """State of each integration for the UI: configured? has data? when was the last collection?
2
+
3
+ Only reads the store (settings, runs, samples): never opens a connection to any service.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import time
8
+
9
+ from . import extensions
10
+ from .i18n import N_, tr
11
+
12
+ RUN_SYSTEMS = [
13
+ ("airflow", "Airflow", "airflow.url"), ("kestra", "Kestra", "kestra.url"), ("prefect", "Prefect", "prefect.url"),
14
+ ("dagster", "Dagster", "dagster.url"), ("dbt_cloud", "dbt Cloud", "dbt_cloud.account_id"), ("airbyte", "Airbyte", "airbyte.url"),
15
+ ("fivetran", "Fivetran", "fivetran.url"), ("spark", "Spark", "spark.url"), ("databricks", "Databricks Jobs", "databricks.jobs_host"),
16
+ ("argo", "Argo Workflows", "argo.url"), ("mage", "Mage", "mage.url"), ("kafka_connect", "Kafka Connect", "kafka_connect.url"),
17
+ ("flink", "Flink", "flink.url"), ("luigi", "Luigi", "luigi.url"), ("mlflow", "MLflow", "mlflow.url"), ("rundeck", "Rundeck", "rundeck.url"),
18
+ ("glue", "AWS Glue", "aws.glue"), ("stepfunctions", "AWS Step Functions", "aws.stepfunctions"), ("athena", N_("AWS Athena (queries)"), "aws.athena"),
19
+ ("adf", "Azure Data Factory", "azure.data_factory"),
20
+ ("openlineage", N_("OpenLineage (received)"), None),
21
+ ]
22
+ SAMPLE_SOURCES = [
23
+ ("kubernetes", "Kubernetes", "kubernetes.enabled"), ("prometheus", "Prometheus", "prometheus.url"), ("kafka", N_("Kafka (lag)"), "kafka.bootstrap"),
24
+ ("spark", N_("Spark (memory)"), "spark.url"), ("docker", "Docker", None), ("host", N_("Local machine"), None), ("warehouse", N_("Warehouse (spill/OOM)"), None),
25
+ ]
26
+
27
+
28
+ def _ago(ts: float | None, now: float) -> str:
29
+ if not ts:
30
+ return "—"
31
+ d = max(0, now - ts)
32
+ return (tr("now") if d < 90 else tr("{n} min ago", n=int(d // 60)) if d < 5400 else tr("{n} h ago", n=int(d // 3600)) if d < 172800
33
+ else tr("{n} d ago", n=int(d // 86400)))
34
+
35
+
36
+ def build(store, now: float | None = None) -> dict:
37
+ now = now or time.time()
38
+ get = store.get_setting
39
+ cards: list[dict] = []
40
+
41
+ def card(group, id_, name, configured, state, summary, keys=(), detail=None):
42
+ cards.append({"group": group, "id": id_, "name": name, "configured": bool(configured), "state": state, "summary": summary,
43
+ "keys": list(keys), "detail": detail or {}})
44
+
45
+ # ---- runs
46
+ g_runs, g_mem, g_data = tr("Runs"), tr("Cluster and memory"), tr("Data and quality")
47
+ off = tr("Not configured")
48
+ runs = store.runs(2000)
49
+ by: dict[str, list[dict]] = {}
50
+ for r in runs:
51
+ by.setdefault(r["system"], []).append(r)
52
+ for sid, name, key in RUN_SYSTEMS:
53
+ rs = by.get(sid, [])
54
+ configured = bool(get(key)) if key else bool(rs)
55
+ if not configured and not rs:
56
+ card(g_runs, sid, tr(name), False, "off", off, [key] if key else [])
57
+ continue
58
+ failed = sum(r["state"] == "failed" for r in rs)
59
+ last = max([r.get("end") or r.get("start") or 0 for r in rs], default=0)
60
+ state = "warn" if (not rs or failed and failed == len(rs)) else "ok"
61
+ card(g_runs, sid, tr(name), True, state,
62
+ tr("{n} run(s), {failed} failed · last {ago}", n=len(rs), failed=failed, ago=_ago(last, now)) if rs else tr("Configured, no runs collected yet"),
63
+ [key] if key else [], {"runs": len(rs), "failed": failed, "last": last})
64
+
65
+ # ---- memory / resource samples
66
+ samples = store.recent_samples(now - 24 * 3600)
67
+ sb: dict[str, list] = {}
68
+ for s in samples:
69
+ sb.setdefault(s.source, []).append(s)
70
+ for sid, name, key in SAMPLE_SOURCES:
71
+ ss = sb.get(sid, [])
72
+ configured = bool(get(key)) if key else bool(ss)
73
+ if not configured and not ss:
74
+ card(g_mem, sid, tr(name), False, "off", off, [key] if key else [])
75
+ continue
76
+ oom = sum(1 for s in ss if s.metric == "oom_killed" and s.value > 0)
77
+ lag = max([s.value for s in ss if s.metric == "consumer_lag"], default=None)
78
+ parts = [tr("{n} sample(s) in the last 24 h", n=len(ss))] + ([f"{oom} OOM"] if oom else []) + ([tr("max lag {n}", n=int(lag))] if lag is not None else [])
79
+ card(g_mem, sid, tr(name), True, "warn" if oom or not ss else "ok",
80
+ " · ".join(parts) if ss else tr("Configured, no samples"), [key] if key else [], {"samples": len(ss), "oom": oom, "lag": lag})
81
+
82
+ # ---- warehouse
83
+ wt = get("warehouse.type") or ("duckdb" if get("warehouse.duckdb") else "postgres" if get("warehouse.postgres_env") else None)
84
+ card(g_data, "warehouse", tr("Warehouse (probes, plan, diff)"), bool(wt), "ok" if wt else "off",
85
+ tr("Type: {type}", type=wt) if wt else off, ["warehouse.type", "warehouse.duckdb", "warehouse.postgres_env"])
86
+ from . import contracts as _ct, dq_results as _dq, lakehouse as _lh
87
+ n_dq = len(_dq.load_all(get("dq.results"))) if get("dq.results") else 0
88
+ card(g_data, "dq", "Great Expectations / Soda", bool(get("dq.results")), "ok" if n_dq else ("warn" if get("dq.results") else "off"),
89
+ tr("{n} result(s) read", n=n_dq) if get("dq.results") else off, ["dq.results"])
90
+ n_ct = len(_ct.load_all(get("contracts.dir"))) if get("contracts.dir") else 0
91
+ card(g_data, "contracts", tr("Data contracts"), bool(get("contracts.dir")), "ok" if n_ct else ("warn" if get("contracts.dir") else "off"),
92
+ tr("{n} contract(s)", n=n_ct) if get("contracts.dir") else off, ["contracts.dir"])
93
+ card(g_data, "elementary", "Elementary", bool(get("elementary.schema")), "ok" if get("elementary.schema") else "off",
94
+ f"Schema: {get('elementary.schema')}" if get("elementary.schema") else off, ["elementary.schema"])
95
+ lk = _lh.tables(get("lakehouse.tables"))
96
+ card(g_data, "lakehouse", "Delta Lake / Iceberg", bool(lk), "ok" if lk else "off",
97
+ tr("{n} table(s)", n=len(lk)) if lk else off, ["lakehouse.tables"])
98
+ card(g_data, "lint", tr("SQL lint (SQLFluff)"), bool(get("lint.enabled")), "ok" if get("lint.enabled") else "off",
99
+ tr("On") if get("lint.enabled") else tr("Off (it is slow; turn it on in Settings)"), ["lint.enabled"])
100
+ nct = len(get("state.catalog.cur") or {})
101
+ card(g_data, "catalogs", tr("Catalogs (Glue / Unity)"), bool(get("catalog.glue") or get("catalog.unity")),
102
+ "ok" if nct else ("warn" if get("catalog.glue") or get("catalog.unity") else "off"),
103
+ tr("{n} table(s) observed", n=nct) if get("catalog.glue") or get("catalog.unity") else off, ["catalog.glue", "catalog.unity"])
104
+ card(g_data, "schema_registry", "Kafka Schema Registry", bool(get("kafka.schema_registry")),
105
+ "ok" if get("state.kafka_schemas") else ("warn" if get("kafka.schema_registry") else "off"),
106
+ tr("{n} subject(s) observed", n=len(get("state.kafka_schemas") or {})) if get("kafka.schema_registry") else off, ["kafka.schema_registry"])
107
+
108
+ extensions.each("integration_cards", store, card) # e.g. AI (Enterprise)
109
+
110
+ # ---- alerts
111
+ sinks = get("notify.sinks", []) or []
112
+ routes = get("notify.routes", []) or []
113
+ card(tr("Alerts"), "notify", tr("Alert outputs"), bool(sinks), "ok" if sinks and routes else ("warn" if sinks else "off"),
114
+ tr("{n} output(s): {names} · {routes} route(s)", n=len(sinks), names=", ".join(f"{s.get('name')} ({s.get('type')})" for s in sinks[:6]), routes=len(routes))
115
+ if sinks else tr("No output configured"),
116
+ ["notify.sinks", "notify.routes"], {"sinks": [{"name": s.get("name"), "type": s.get("type")} for s in sinks]})
117
+
118
+ # ---- project and security
119
+ tgt = get("dbt.target")
120
+ card(tr("Project"), "target", tr("Transformation project (dbt/SQLMesh)"), bool(tgt or get("dbt_cloud.job_id")), "ok" if tgt or get("dbt_cloud.job_id") else "off",
121
+ tr("Target: {target}", target=tgt) if tgt else (tr("dbt Cloud artifacts (job {job})", job=get("dbt_cloud.job_id")) if get("dbt_cloud.job_id") else off),
122
+ ["dbt.target", "dbt_cloud.job_id"])
123
+ bx = store.box.status()
124
+ g_sec = tr("Security")
125
+ card(g_sec, "secrets", tr("Secrets encrypted at rest"), bx["encrypted_at_rest"], "ok" if bx["encrypted_at_rest"] else "warn",
126
+ tr("Encrypted (key: {source})", source=bx["key_source"]) if bx["encrypted_at_rest"] else tr("TOTP/SSO secrets in plain text: set INTENTFLOW_SECRET_KEY"),
127
+ [tr("INTENTFLOW_SECRET_KEY (environment)")], bx)
128
+ users = store.users_admin() if store.has_users() else []
129
+ card(g_sec, "team", tr("Team and login"), bool(users), "ok" if users else "off",
130
+ tr("{n} person(s), {mfa} with MFA", n=len(users), mfa=sum(1 for u in users if u.get("mfa"))) + (" · " + tr("SSO configured") if get("sso.issuer") else "") if users
131
+ else tr("Local mode without login: add users before exposing it on a network"), [], {"sso": bool(get("sso.issuer"))})
132
+ card(g_sec, "store", tr("Store"), True, "ok", f"{store.backend} " + (tr("(production)") if store.backend == "postgres" else tr("(local file)")), [])
133
+
134
+ groups: dict[str, list[dict]] = {}
135
+ for c in cards:
136
+ groups.setdefault(c["group"], []).append(c)
137
+ on = sum(1 for c in cards if c["configured"])
138
+ return {"groups": [{"name": g, "cards": cs} for g, cs in groups.items()], "configured": on, "total": len(cards),
139
+ "warnings": sum(1 for c in cards if c["configured"] and c["state"] == "warn")}
@@ -0,0 +1,62 @@
1
+ """Delta Lake and Apache Iceberg tables: small files and schema evolution (optional: `pip install intentdataflow[lakehouse]`).
2
+
3
+ `lakehouse.tables`: list (or comma-separated text) of paths/URIs. Delta is detected by `_delta_log/`; Iceberg by a
4
+ `*.metadata.json` (pass the latest metadata file, or the table folder with `metadata/`).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from .i18n import tr
9
+
10
+ from pathlib import Path
11
+
12
+
13
+ def _delta(path: str) -> dict:
14
+ import pyarrow as pa
15
+ from deltalake import DeltaTable
16
+ dt = DeltaTable(path)
17
+ sizes = [int(x) for x in pa.table(dt.get_add_actions(flatten=True)).column("size_bytes").to_pylist()]
18
+ ver = dt.version()
19
+ prev = None
20
+ if ver > 0:
21
+ prev = {f.name: str(f.type.type if hasattr(f.type, "type") else f.type) for f in DeltaTable(path, version=ver - 1).schema().fields}
22
+ cur = {f.name: str(f.type.type if hasattr(f.type, "type") else f.type) for f in dt.schema().fields}
23
+ hist = dt.history(5)
24
+ return {"format": "delta", "path": path, "name": Path(path.rstrip("/")).name, "version": ver, "files": len(sizes), "bytes": sum(sizes),
25
+ "avg_file_bytes": (sum(sizes) / len(sizes)) if sizes else 0, "schema": cur, "prev_schema": prev,
26
+ "last_ops": [h.get("operation") for h in hist]}
27
+
28
+
29
+ def _iceberg(path: str) -> dict:
30
+ from pyiceberg.table import StaticTable
31
+ p = Path(path)
32
+ if p.is_dir():
33
+ cands = sorted((p / "metadata").glob("*.metadata.json"))
34
+ if not cands:
35
+ raise ValueError(f"sem metadata.json em {path}")
36
+ p = cands[-1]
37
+ t = StaticTable.from_metadata(str(p))
38
+ md = t.metadata
39
+ schemas = {s.schema_id: {f.name: str(f.field_type) for f in s.fields} for s in md.schemas}
40
+ ids = sorted(schemas)
41
+ cur_id = md.current_schema_id
42
+ prev_id = max([i for i in ids if i < cur_id], default=None)
43
+ files = [f.file.file_size_in_bytes for f in t.scan().plan_files()] if md.current_snapshot_id else []
44
+ return {"format": "iceberg", "path": str(p), "name": p.parent.parent.name if p.parent.name == "metadata" else p.stem, "version": md.current_snapshot_id,
45
+ "files": len(files), "bytes": sum(files), "avg_file_bytes": (sum(files) / len(files)) if files else 0,
46
+ "schema": schemas[cur_id], "prev_schema": schemas[prev_id] if prev_id is not None else None,
47
+ "last_ops": [s.summary.operation.value if s.summary else None for s in (md.snapshots or [])[-5:]]}
48
+
49
+
50
+ def inspect(path: str) -> dict:
51
+ p = Path(path)
52
+ if (p / "_delta_log").exists():
53
+ return _delta(path)
54
+ if p.suffix == ".json" or (p / "metadata").exists():
55
+ return _iceberg(path)
56
+ raise ValueError(tr("{path}: not a recognized Delta or Iceberg table", path=path))
57
+
58
+
59
+ def tables(spec) -> list[str]:
60
+ if isinstance(spec, str):
61
+ spec = [x.strip() for x in spec.split(",")]
62
+ return [str(x) for x in (spec or []) if str(x).strip()]
intentflow/lineage.py ADDED
@@ -0,0 +1,336 @@
1
+ """Column lineage from the compiled SQL (SQLGlot).
2
+
3
+ Resolved: goes through CTEs, joins, aliases, aggregations, `select *` (with the catalog schema).
4
+ Unresolved (recorded, never invented): SQL without a catalog, opaque UDFs, unsupported dialect.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import threading
14
+ import logging
15
+
16
+ import sqlglot
17
+ from sqlglot import exp
18
+ from sqlglot.lineage import lineage
19
+ from sqlglot.optimizer import qualify as _qualify
20
+ from sqlglot.optimizer.scope import Scope, build_scope, traverse_scope
21
+ from sqlglot.schema import MappingSchema
22
+
23
+ from .dbt_loader import Project
24
+ from .model import Edge
25
+ from .i18n import N_
26
+
27
+ logging.getLogger("sqlglot").setLevel(logging.ERROR) # optimizer noise on real SQL
28
+ DIALECTS = {"duckdb": "duckdb", "postgres": "postgres", "snowflake": "snowflake", "bigquery": "bigquery",
29
+ "databricks": "databricks", "spark": "spark", "redshift": "redshift", "trino": "trino", "clickhouse": "clickhouse",
30
+ "athena": "athena", "starrocks": "starrocks", "doris": "doris", "mysql": "mysql", "sqlserver": "tsql", "oracle": "oracle"}
31
+ MASK_FUNCS = {"MD5", "SHA", "SHA1", "SHA2", "SHA256", "SHA512", "HASH", "FARM_FINGERPRINT", "XXHASH64"}
32
+
33
+
34
+ @dataclass
35
+ class LineageResult:
36
+ cache_hits: int = 0
37
+ edges: list[Edge] = field(default_factory=list)
38
+ unresolved: list[tuple[str, str, str]] = field(default_factory=list) # (node, col, motivo)
39
+ columns_total: int = 0
40
+ # INDIRECT dependencies (model level): a column used in JOIN/WHERE/GROUP BY/ORDER BY/window/CASE affects the whole model
41
+ indirect: list[tuple[str, str, str, str]] = field(default_factory=list) # (src_uid, src_col, dst_uid, via)
42
+
43
+ @property
44
+ def precision_report(self) -> dict:
45
+ ok = self.columns_total - len(self.unresolved)
46
+ return {"columns": self.columns_total, "resolved": ok,
47
+ "unresolved": len(self.unresolved),
48
+ "resolved_ratio": round(ok / self.columns_total, 3) if self.columns_total else 1.0}
49
+
50
+ def upstream_of(self, uid: str, col: str) -> list[Edge]:
51
+ return [e for e in self.edges if e.dst == uid and e.dst_col == col]
52
+
53
+ def downstream_of(self, uid: str, col: str) -> list[Edge]:
54
+ return [e for e in self.edges if e.src == uid and e.src_col == col]
55
+
56
+ def indirect_of(self, uid: str, col: str) -> list[tuple[str, str]]:
57
+ """[(model, via)] that depend on `uid.col` only through JOIN/filter/grouping/ordering/window/CASE."""
58
+ return [(d, via) for s, c, d, via in self.indirect if s == uid and c in (col, "*")]
59
+
60
+
61
+ def _flags(path: list) -> tuple[str, bool]:
62
+ kind, masked = "direct", False
63
+ for nd in path:
64
+ e = nd.expression
65
+ inner = e.this if isinstance(e, exp.Alias) else e
66
+ if isinstance(inner, exp.Table):
67
+ continue
68
+ # `select *` expands into columns; any other expression is derived
69
+ if not isinstance(inner, (exp.Column, exp.Table, exp.Star)):
70
+ kind = "derived"
71
+ for f in inner.find_all(exp.Func):
72
+ if f.sql_name().upper() in MASK_FUNCS or type(f).__name__.upper() in MASK_FUNCS:
73
+ masked = True
74
+ return kind, masked
75
+
76
+
77
+ def _leaves(node, path=None):
78
+ path = (path or []) + [node]
79
+ if not node.downstream:
80
+ yield node, path
81
+ for d in node.downstream:
82
+ yield from _leaves(d, path)
83
+
84
+
85
+ def _walk(node):
86
+ yield node
87
+ for d in node.downstream:
88
+ yield from _walk(d)
89
+
90
+
91
+ # ------------------------------------------------------------ indirect dependencies
92
+ def _set_branches(scope) -> list:
93
+ """SELECT branches of a UNION/INTERSECT/EXCEPT (nested ones flattened). `set_operation_scopes` in sqlglot ≥ 28; `union_scopes` before."""
94
+ kids = getattr(scope, "set_operation_scopes", None)
95
+ if kids is None:
96
+ kids = getattr(scope, "union_scopes", None)
97
+ out = []
98
+ for k in kids or []:
99
+ if isinstance(k.expression, exp.Select):
100
+ out.append(k)
101
+ else:
102
+ out.extend(_set_branches(k))
103
+ return out
104
+
105
+
106
+ def _provenance(source, name: str, rel: dict, depth: int = 0) -> set[tuple[str, str]]:
107
+ """Physical columns (uid, column) that column `name` of a scope (CTE/subquery) derives from."""
108
+ if depth > 12 or not isinstance(source, Scope):
109
+ return set()
110
+ sel = source.expression
111
+ branches = [source] if isinstance(sel, exp.Select) else _set_branches(source)
112
+ out: set[tuple[str, str]] = set()
113
+ for br in branches:
114
+ s = br.expression
115
+ if not isinstance(s, exp.Select):
116
+ continue
117
+ names = [p.alias_or_name for p in s.expressions]
118
+ if name not in names:
119
+ if len(branches) > 1 and names: # UNION: match by position with the first branch
120
+ first = [p.alias_or_name for p in branches[0].expression.expressions]
121
+ idx = first.index(name) if name in first else -1
122
+ if idx < 0 or idx >= len(names):
123
+ continue
124
+ proj = s.expressions[idx]
125
+ else:
126
+ continue
127
+ else:
128
+ proj = s.expressions[names.index(name)]
129
+ for c in proj.find_all(exp.Column):
130
+ out |= _resolve_column(c, br, rel, depth + 1)
131
+ return out
132
+
133
+
134
+ def _resolve_column(c: exp.Column, scope: Scope, rel: dict, depth: int = 0) -> set[tuple[str, str]]:
135
+ src = scope.sources.get(c.table) if c.table else None
136
+ if isinstance(src, exp.Table):
137
+ uid = rel.get((src.catalog.lower(), src.db.lower(), src.name.lower()))
138
+ return {(uid, c.name.lower())} if uid else set()
139
+ if isinstance(src, Scope):
140
+ return _provenance(src, c.name, rel, depth)
141
+ return set()
142
+
143
+
144
+ def _indirect_refs(expression, rel: dict) -> set[tuple[str, str, str]]:
145
+ """(uid, column, via) of physical columns read only as a condition: JOIN/WHERE/GROUP BY/HAVING/ORDER BY/QUALIFY/window/CASE."""
146
+ out: set[tuple[str, str, str]] = set()
147
+
148
+ def add(nodes, scope, via):
149
+ for n in nodes:
150
+ if n is None:
151
+ continue
152
+ for c in n.find_all(exp.Column):
153
+ for uid, col in _resolve_column(c, scope, rel):
154
+ out.add((uid, col, via))
155
+ for scope in traverse_scope(expression):
156
+ s = scope.expression
157
+ if not isinstance(s, exp.Select):
158
+ continue
159
+ for j in s.args.get("joins") or []:
160
+ add([j.args.get("on")] + list(j.args.get("using") or []), scope, "join")
161
+ add([(s.args.get("where") or exp.Null()).this if s.args.get("where") else None], scope, "filter")
162
+ add([s.args.get("having").this] if s.args.get("having") else [], scope, "filter")
163
+ add([s.args.get("qualify").this] if s.args.get("qualify") else [], scope, "filter")
164
+ add(list((s.args.get("group").expressions if s.args.get("group") else []) or []), scope, "group")
165
+ add(list((s.args.get("order").expressions if s.args.get("order") else []) or []), scope, "sort")
166
+ for w in s.find_all(exp.Window):
167
+ add(list(w.args.get("partition_by") or []) + ([w.args["order"]] if w.args.get("order") else []), scope, "window")
168
+ for case in s.find_all(exp.Case):
169
+ add([i.this for i in case.args.get("ifs") or []], scope, "conditional")
170
+ return out
171
+
172
+
173
+ def _model_key(project: Project, uid: str, dialect) -> str:
174
+ """Changes if the SQL, the dialect or the parents' schema change — only then is the model's lineage recomputed."""
175
+ n = project.nodes[uid]
176
+ parents = sorted(
177
+ (project.nodes[d].relation, tuple(sorted((c.name, c.type) for c in project.nodes[d].columns.values())))
178
+ for d in n.depends_on if d in project.nodes)
179
+ cols = tuple(sorted((c.name, c.actual) for c in n.columns.values()))
180
+ raw = json.dumps([n.compiled_code, dialect, parents, cols, "v9"], default=str)
181
+ return hashlib.sha256(raw.encode()).hexdigest()
182
+
183
+
184
+ def _model_edges(project: Project, uid: str, schema: dict, rel: dict, dialect) -> tuple[list[Edge], list[tuple], int, list[tuple]]:
185
+ n = project.nodes[uid]
186
+ edges: list[Edge] = []
187
+ unresolved: list[tuple] = []
188
+ total = 0
189
+ has_catalog = bool(project.actual_columns(uid))
190
+ try: # qualify and build the scope ONCE per model (it was the dominant cost)
191
+ expression = _qualify.qualify(sqlglot.parse_one(n.compiled_code, read=dialect), dialect=dialect, schema=schema,
192
+ validate_qualify_columns=False, identify=False)
193
+ scope = build_scope(expression)
194
+ except Exception as ex:
195
+ expression = scope = None
196
+ prep_err = f"{type(ex).__name__}: {str(ex)[:80]}"
197
+ indirect: list[tuple] = []
198
+ if expression is not None:
199
+ try:
200
+ indirect = [(su, sc, uid, via) for su, sc, via in sorted(_indirect_refs(expression, rel))]
201
+ except Exception: # direct lineage is computed anyway; indirect is best-effort
202
+ indirect = []
203
+ seen: set[Edge] = set()
204
+ declared = {c: col for c, col in n.columns.items() if not (has_catalog and not col.actual)}
205
+ inferred: list[str] = []
206
+ if scope is not None: # without YAML/catalog: the output columns come from the compiled SELECT itself
207
+ try:
208
+ for nm in expression.named_selects:
209
+ if nm == "*":
210
+ unresolved.append((uid, "*", N_("select * without the upstream schema")))
211
+ total += 1
212
+ elif nm and nm not in declared and nm.lower() not in {d.lower() for d in declared}:
213
+ inferred.append(nm)
214
+ except Exception:
215
+ pass
216
+ for cname in list(declared) + inferred:
217
+ total += 1
218
+ if scope is None:
219
+ unresolved.append((uid, cname, prep_err))
220
+ continue
221
+ try:
222
+ # trim_selects/copy=False: sqlglot deep-copied the tree for every column (92 % of the time); identical result, ~19x faster
223
+ root = lineage(cname, expression, schema=schema, dialect=dialect, scope=scope, trim_selects=False, copy=False)
224
+ except Exception as ex:
225
+ unresolved.append((uid, cname, f"{type(ex).__name__}: {str(ex)[:80]}"))
226
+ continue
227
+ found = False
228
+ for leaf, path in _leaves(root):
229
+ t = leaf.expression
230
+ if not isinstance(t, exp.Table):
231
+ continue
232
+ src = rel.get((t.catalog.lower(), t.db.lower(), t.name.lower()))
233
+ if not src:
234
+ continue
235
+ kind, masked = _flags(path)
236
+ e = Edge(src, leaf.name.split(".")[-1].strip('"`[]').lower(), uid, cname, kind, masked)
237
+ if e not in seen:
238
+ seen.add(e)
239
+ edges.append(e)
240
+ found = True
241
+ if not found and any(not isinstance(lf.expression, exp.Table) and lf.expression.find(exp.Column) is not None
242
+ for lf, _ in _leaves(root)):
243
+ unresolved.append((uid, cname, "no upstream table resolved"))
244
+ # a declared parent without any column edge (unknown schema, `select *`, SQL generated without introspection):
245
+ # the impact falls back to a model dependency, never to "nothing"
246
+ linked = {e.src for e in edges} | {i[0] for i in indirect}
247
+ indirect += [(d, "*", uid, "opaque") for d in sorted(n.depends_on) if d in project.nodes and d not in linked]
248
+ return edges, unresolved, total, indirect
249
+
250
+
251
+ def _rel_for(project: Project, uid: str, rel: dict) -> dict:
252
+ """The same table can be a seed AND a source (two nodes, one relation): the model links to what it declares in depends_on."""
253
+ parents = [d for d in project.nodes[uid].depends_on if d in project.nodes and project.nodes[d].relation]
254
+ if not parents:
255
+ return rel
256
+ rel_m = dict(rel)
257
+ for d in parents:
258
+ parts = tuple(p.strip('"`[]').lower() for p in project.nodes[d].relation.split("."))
259
+ if len(parts) == 3:
260
+ rel_m[parts] = d
261
+ return rel_m
262
+
263
+
264
+ _CTX: tuple | None = None # context initialized once in each child process
265
+
266
+
267
+ def _init_worker(project, schema, rel, dialect):
268
+ global _CTX
269
+ _CTX = (project, schema, rel, dialect)
270
+
271
+
272
+ def _worker(uid: str):
273
+ project, schema, rel, dialect = _CTX
274
+ return uid, _model_edges(project, uid, schema, _rel_for(project, uid, rel), dialect)
275
+
276
+
277
+ def _compute(project, todo: list[str], schema, rel, dialect, workers: int) -> dict:
278
+ """Spawned processes: the context is sent once per worker, without inheriting native thread locks."""
279
+ # The server keeps the serial path + cache so it does not open a pool per request.
280
+ import multiprocessing as mp
281
+ # a child process (e.g. a script without `if __name__ == "__main__"` re-imported by spawn) never opens another pool: avoids a cascade
282
+ if workers > 1 and len(todo) >= 2 * workers and threading.active_count() == 1 and mp.parent_process() is None:
283
+ try:
284
+ ctx = mp.get_context("spawn")
285
+ with ctx.Pool(workers, initializer=_init_worker, initargs=(project, schema, rel, dialect)) as pool:
286
+ return dict(pool.imap_unordered(_worker, todo, chunksize=max(1, len(todo) // (workers * 8))))
287
+ except Exception: # process/pickle failure: recompute everything serially
288
+ pass
289
+ return {u: _model_edges(project, u, schema, _rel_for(project, u, rel), dialect) for u in todo}
290
+
291
+
292
+ def default_workers() -> int:
293
+ try:
294
+ return max(1, int(os.environ.get("INTENTFLOW_WORKERS", "")))
295
+ except ValueError:
296
+ return min(4, os.cpu_count() or 1) # measured: 8 processes were worse than 4 (serialization/pool dominate)
297
+
298
+
299
+ def cache_keys(project: Project) -> set[str]:
300
+ """Lineage cache keys the current project uses (everything else in the cache is stale)."""
301
+ dialect = DIALECTS.get(project.adapter)
302
+ return {_model_key(project, u, dialect) for u, n in project.nodes.items() if n.resource_type in ("model", "snapshot") and n.compiled_code}
303
+
304
+
305
+ def build(project: Project, cache=None, workers: int | None = None) -> LineageResult:
306
+ """`cache`: object with `get(key)`/`set(key, value)` (e.g. the SQLite store) to reuse unchanged models.
307
+ `workers`: processes for the models not in the cache (default: cores, max 4; `INTENTFLOW_WORKERS` overrides)."""
308
+ res = LineageResult()
309
+ # MappingSchema built ONCE: passing the dict makes sqlglot renormalize everything for every column
310
+ dialect = DIALECTS.get(project.adapter)
311
+ schema = MappingSchema(project.sqlglot_schema(), dialect=dialect)
312
+ rel = project.by_relation()
313
+ res.cache_hits = 0
314
+ uids = [u for u, n in project.nodes.items() if n.resource_type in ("model", "snapshot") and n.compiled_code]
315
+ keys = {u: (_model_key(project, u, dialect) if cache is not None else None) for u in uids}
316
+ hits = {u: cache.get(keys[u]) for u in uids} if cache is not None else {}
317
+ todo = [u for u in uids if hits.get(u) is None]
318
+ done = _compute(project, todo, schema, rel, dialect, workers or default_workers()) if todo else {}
319
+ for uid in uids: # stable order = the project's, regardless of who finished first
320
+ hit = hits.get(uid)
321
+ if hit is not None:
322
+ edges = [Edge(**e) for e in hit["edges"]]
323
+ unres, total = [tuple(x) for x in hit["unresolved"]], hit["total"]
324
+ indirect = [tuple(x) for x in hit.get("indirect", [])]
325
+ res.cache_hits += 1
326
+ else:
327
+ edges, unres, total, indirect = done[uid]
328
+ if cache is not None:
329
+ cache.set(keys[uid], {"edges": [{"src": e.src, "src_col": e.src_col, "dst": e.dst, "dst_col": e.dst_col,
330
+ "kind": e.kind, "masked": e.masked} for e in edges],
331
+ "unresolved": unres, "total": total, "indirect": indirect})
332
+ res.edges.extend(edges)
333
+ res.indirect.extend(indirect)
334
+ res.unresolved.extend(unres)
335
+ res.columns_total += total
336
+ return res