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
intentflow/model.py ADDED
@@ -0,0 +1,43 @@
1
+ """Core types: findings, lineage nodes and edges."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ from dataclasses import asdict, dataclass, field
7
+
8
+ SEVERITIES = ["critical", "high", "medium", "low", "info"]
9
+ STAGES = ["pre-merge", "pre-run", "continuous"]
10
+
11
+
12
+ @dataclass
13
+ class Finding:
14
+ check: str # e.g. DBT002
15
+ severity: str # critical|high|medium|low|info
16
+ title: str
17
+ detail: str = ""
18
+ nodes: list[str] = field(default_factory=list) # affected unique_ids
19
+ stage: str = "pre-merge"
20
+ evidence: dict = field(default_factory=dict)
21
+ fix: dict | None = None # fix proposal data (used by IntentFlow Enterprise)
22
+ confidence: float = 1.0
23
+
24
+ @property
25
+ def id(self) -> str:
26
+ title = getattr(self.title, "en", self.title) # English rendering: the id must not depend on the language
27
+ key = json.dumps([self.check, sorted(self.nodes), title], sort_keys=True)
28
+ return self.check + "-" + hashlib.sha1(key.encode()).hexdigest()[:8]
29
+
30
+ def to_dict(self) -> dict:
31
+ d = asdict(self)
32
+ d["id"] = self.id
33
+ return d
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Edge:
38
+ src: str # unique_id
39
+ src_col: str
40
+ dst: str
41
+ dst_col: str
42
+ kind: str # direct | derived
43
+ masked: bool = False # went through a hash/mask function
@@ -0,0 +1,197 @@
1
+ """Sampling of cluster memory/resources (local and orchestrators) and exhaustion forecast."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ import subprocess
7
+ import time
8
+ from dataclasses import dataclass
9
+ from .i18n import tr
10
+
11
+ UNITS = {"B": 1, "KB": 1e3, "MB": 1e6, "GB": 1e9, "KIB": 1024, "MIB": 1024**2, "GIB": 1024**3, "TIB": 1024**4}
12
+
13
+
14
+ @dataclass
15
+ class Sample:
16
+ ts: float
17
+ source: str # host | docker | duckdb | airflow | warehouse
18
+ scope: str # container/pool/query name
19
+ metric: str # memory_bytes | oom_killed | queued | spilled_bytes
20
+ value: float
21
+ limit: float | None = None
22
+
23
+
24
+ def parse_size(s: str) -> float:
25
+ m = re.match(r"\s*([\d.]+)\s*([A-Za-z]+)", s)
26
+ return float(m.group(1)) * UNITS.get(m.group(2).upper(), 1) if m else 0.0
27
+
28
+
29
+ def host_memory(now=None) -> list[Sample]:
30
+ now = now or time.time()
31
+ try:
32
+ with open("/proc/meminfo") as f:
33
+ kv = {l.split(":")[0]: int(l.split()[1]) * 1024 for l in f if ":" in l}
34
+ except OSError:
35
+ return []
36
+ total, avail = kv.get("MemTotal", 0), kv.get("MemAvailable", 0)
37
+ return [Sample(now, "host", "host", "memory_bytes", float(total - avail), float(total))]
38
+
39
+
40
+ def docker_containers(now=None, run=subprocess.run) -> list[Sample]:
41
+ now = now or time.time()
42
+ out: list[Sample] = []
43
+ try:
44
+ r = run(["docker", "stats", "--no-stream", "--format", "{{json .}}"], capture_output=True, text=True, timeout=30)
45
+ except (OSError, subprocess.TimeoutExpired):
46
+ return out
47
+ for line in (r.stdout or "").splitlines():
48
+ try:
49
+ d = json.loads(line)
50
+ used, _, lim = d["MemUsage"].partition("/")
51
+ out.append(Sample(now, "docker", d["Name"], "memory_bytes", parse_size(used), parse_size(lim) or None))
52
+ except (ValueError, KeyError):
53
+ continue
54
+ try:
55
+ ids = run(["docker", "ps", "-aq"], capture_output=True, text=True, timeout=15).stdout.split()
56
+ if ids:
57
+ r = run(["docker", "inspect", "-f", "{{.Name}} {{.State.OOMKilled}}", *ids], capture_output=True, text=True, timeout=15)
58
+ for line in r.stdout.splitlines():
59
+ name, _, killed = line.strip().partition(" ")
60
+ if killed == "true":
61
+ out.append(Sample(now, "docker", name.lstrip("/"), "oom_killed", 1.0))
62
+ except (OSError, subprocess.TimeoutExpired):
63
+ pass
64
+ return out
65
+
66
+
67
+ def airflow_pools(client, now=None) -> list[Sample]:
68
+ now = now or time.time()
69
+ out = []
70
+ for p in client.pools():
71
+ slots = float(p.get("slots", 0) or 0)
72
+ used = float(p.get("running_slots", p.get("occupied_slots", 0)) or 0)
73
+ out.append(Sample(now, "airflow", p.get("name", "pool"), "pool_slots_used", used, slots or None))
74
+ out.append(Sample(now, "airflow", p.get("name", "pool"), "queued", float(p.get("queued_slots", 0) or 0), slots or None))
75
+ return out
76
+
77
+
78
+ def warehouse_spill(wh, hours=24, now=None) -> list[Sample]:
79
+ now = now or time.time()
80
+ return [Sample(now, "warehouse", f"{r['source']}:{r['scope']}", "spilled_bytes", float(r["spilled_bytes"])) for r in wh.spill_report(hours)]
81
+
82
+
83
+ def warehouse_memory_failures(wh, hours=24, now=None) -> list[Sample]:
84
+ now = now or time.time()
85
+ return [Sample(now, "warehouse", f"{r['source']}:{r['scope']}", "oom_killed", 1.0) for r in wh.memory_failures(hours)]
86
+
87
+
88
+ def time_to_exhaustion(points: list[tuple[float, float]], limit: float) -> float | None:
89
+ """Simple linear regression; returns the seconds until `limit` is reached, or None if it is not growing."""
90
+ if len(points) < 4 or limit <= 0:
91
+ return None
92
+ n = len(points)
93
+ mt = sum(t for t, _ in points) / n
94
+ mv = sum(v for _, v in points) / n
95
+ den = sum((t - mt) ** 2 for t, _ in points)
96
+ if den == 0:
97
+ return None
98
+ slope = sum((t - mt) * (v - mv) for t, v in points) / den
99
+ if slope <= 0:
100
+ return None
101
+ last_t, last_v = points[-1]
102
+ return max(0.0, (limit - last_v) / slope)
103
+
104
+
105
+ # ---------------------------------------------------------------- Kubernetes and Prometheus
106
+ _K8S = {"Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4, "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "k": 1e3, "m": 1e-3}
107
+
108
+
109
+ def k8s_quantity(q) -> float | None:
110
+ """'512Mi' / '1G' / '123456' / '129e6' → bytes."""
111
+ m = re.fullmatch(r"\s*([\d.]+(?:[eE][+-]?\d+)?)\s*([A-Za-z]{0,2})\s*", str(q or ""))
112
+ if not m:
113
+ return None
114
+ return float(m.group(1)) * (_K8S.get(m.group(2), 1) if m.group(2) else 1)
115
+
116
+
117
+ def kubernetes_pods(now=None, run=subprocess.run, context: str | None = None, namespace: str | None = None) -> list[Sample]:
118
+ """Pods through `kubectl`: OOMKilled (the container's last state) and memory use vs limit (`kubectl top`, needs the metrics-server)."""
119
+ now = now or time.time()
120
+ base = ["kubectl"] + (["--context", context] if context else [])
121
+ ns = ["-n", namespace] if namespace else ["-A"]
122
+ out: list[Sample] = []
123
+ try:
124
+ r = run([*base, "get", "pods", *ns, "-o", "json"], capture_output=True, text=True, timeout=60)
125
+ pods = json.loads(r.stdout or "{}").get("items", []) if r.returncode == 0 else []
126
+ except (OSError, subprocess.TimeoutExpired, ValueError):
127
+ return out
128
+ limits: dict[tuple, float | None] = {}
129
+ for p in pods:
130
+ md, spec, st = p.get("metadata", {}), p.get("spec", {}), p.get("status", {})
131
+ for c in spec.get("containers", []):
132
+ lim = ((c.get("resources") or {}).get("limits") or {}).get("memory")
133
+ limits[(md.get("namespace"), md.get("name"), c.get("name"))] = k8s_quantity(lim)
134
+ for cs in st.get("containerStatuses", []) or []:
135
+ scope = f"{md.get('namespace')}/{md.get('name')}/{cs.get('name')}"
136
+ for state in (cs.get("lastState") or {}, cs.get("state") or {}):
137
+ if (state.get("terminated") or {}).get("reason") == "OOMKilled":
138
+ out.append(Sample(now, "kubernetes", scope, "oom_killed", 1.0))
139
+ break
140
+ try:
141
+ r = run([*base, "top", "pods", *ns, "--containers", "--no-headers"], capture_output=True, text=True, timeout=60)
142
+ if r.returncode == 0:
143
+ for line in r.stdout.splitlines():
144
+ cols = line.split()
145
+ if len(cols) < (4 if namespace else 5): # with -n there is no NAMESPACE column
146
+ continue
147
+ # with -A: NAMESPACE POD NAME CPU MEM ; with -n: POD NAME CPU MEM
148
+ nsn, pod, cont, mem = (cols[0], cols[1], cols[2], cols[4]) if namespace is None else (namespace, cols[0], cols[1], cols[3])
149
+ used = k8s_quantity(mem)
150
+ if used is not None:
151
+ out.append(Sample(now, "kubernetes", f"{nsn}/{pod}/{cont}", "memory_bytes", used, limits.get((nsn, pod, cont))))
152
+ except (OSError, subprocess.TimeoutExpired):
153
+ pass
154
+ return out
155
+
156
+
157
+ DEFAULT_PROM_QUERIES = [
158
+ {"query": 'container_memory_working_set_bytes{container!="",container!="POD"}', "labels": ["namespace", "pod", "container"],
159
+ "limit_query": 'container_spec_memory_limit_bytes{container!="",container!="POD"} > 0', "metric": "memory_bytes", "source": "prometheus"},
160
+ {"query": "node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes", "labels": ["instance"],
161
+ "limit_query": "node_memory_MemTotal_bytes", "metric": "memory_bytes", "source": "prometheus-node"},
162
+ ]
163
+
164
+
165
+ def prometheus_samples(url: str, queries=None, now=None, fetch=None) -> list[Sample]:
166
+ """Instant queries (`/api/v1/query`). Each series becomes a sample; `limit_query` matches the series by the same labels."""
167
+ from urllib.parse import quote
168
+ from .orchestrators import http_json
169
+ fetch = fetch or http_json
170
+ now = now or time.time()
171
+ base = url.rstrip("/")
172
+
173
+ def vec(q: str) -> list[dict]:
174
+ d = fetch(f"{base}/api/v1/query?query={quote(q)}", {})
175
+ if not isinstance(d, dict) or d.get("status") != "success":
176
+ raise RuntimeError(tr("Prometheus refused the query: {error}", error=str((d or {}).get("error", ""))[:100]))
177
+ return d["data"].get("result", [])
178
+ out: list[Sample] = []
179
+ for spec in queries or DEFAULT_PROM_QUERIES:
180
+ labels = spec.get("labels") or []
181
+ lim = {}
182
+ if spec.get("limit_query"):
183
+ try:
184
+ lim = {tuple(s["metric"].get(k, "") for k in labels): float(s["value"][1]) for s in vec(spec["limit_query"])}
185
+ except (RuntimeError, KeyError, ValueError):
186
+ lim = {}
187
+ for s in vec(spec["query"]):
188
+ key = tuple(s["metric"].get(k, "") for k in labels)
189
+ try:
190
+ v = float(s["value"][1])
191
+ except (KeyError, ValueError, IndexError):
192
+ continue
193
+ if v != v: # NaN
194
+ continue
195
+ scope = "/".join(x for x in key if x) or s["metric"].get("__name__", "series")
196
+ out.append(Sample(now, spec.get("source", "prometheus"), scope, spec.get("metric", "memory_bytes"), v, lim.get(key)))
197
+ return out
intentflow/notify.py ADDED
@@ -0,0 +1,154 @@
1
+ """Outputs: Slack/webhook, e-mail (SMTP) and pull request comment (GitHub). Secrets only through environment variables.
2
+ Extensions add other sink types (`notify_deliver` hook).
3
+
4
+ Configuration (in the store): `notify.sinks` = list of {name, type, url_env|..., min_severity} and
5
+ `notify.routes` = list of {sink, owner?, check_prefix?, min_severity?}. Managed through the CLI/UI.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import smtplib
13
+ import time
14
+ import urllib.request
15
+ from email.message import EmailMessage
16
+
17
+ from . import extensions
18
+ from .i18n import tr
19
+ from .model import SEVERITIES
20
+ from .store import Store
21
+
22
+ COOLDOWN_S = 24 * 3600
23
+ CORE_TYPES = ("slack", "webhook", "email", "github")
24
+ ENTERPRISE_TYPES = ("gitlab", "bitbucket", "azure_devops", "pagerduty", "opsgenie", "jira", "teams")
25
+
26
+
27
+ def sink_types() -> list[str]:
28
+ return list(CORE_TYPES) + [t for m in extensions.loaded() for t in getattr(m, "SINK_TYPES", ())]
29
+
30
+
31
+ def render_markdown(incidents, title: str | None = None, limit: int = 15) -> str:
32
+ title = title or tr("IntentFlow: problems found before production")
33
+ if not incidents:
34
+ return f"### {title}\n\n" + tr("No open problems.") + " ✅"
35
+ L = [f"### {title}", "", tr("{n} incident(s) grouped by root cause:", n=len(incidents)), ""]
36
+ icon = {"critical": "🔴", "high": "🟠", "medium": "🟡", "low": "⚪", "info": "ℹ️"}
37
+ for inc in incidents[:limit]:
38
+ L.append(f"- {icon.get(inc.severity, '')} **{inc.severity}** — {inc.title}")
39
+ for f in inc.findings[:5]:
40
+ L.append(f" - `{f['check_id'] if 'check_id' in f else f.get('check')}` {f['title']}")
41
+ if len(inc.findings) > 5:
42
+ L.append(" - " + tr("… and {n} more", n=len(inc.findings) - 5))
43
+ if inc.owners:
44
+ L.append(" - " + tr("owner: {owners}", owners=", ".join(inc.owners)))
45
+ if len(incidents) > limit:
46
+ L.append("\n" + tr("… and {n} more incident(s).", n=len(incidents) - limit))
47
+ return "\n".join(L)
48
+
49
+
50
+ def post_json(url: str, payload: dict, headers: dict | None = None, timeout: float = 10.0) -> int:
51
+ if not url.lower().startswith(("https://", "http://")): # urllib would also open file:// and ftp://
52
+ raise ValueError(tr("only http(s) URLs are allowed"))
53
+ req = urllib.request.Request(url, data=json.dumps(payload).encode(), method="POST",
54
+ headers={"Content-Type": "application/json", **(headers or {})})
55
+ with urllib.request.urlopen(req, timeout=timeout) as r:
56
+ return r.status
57
+
58
+
59
+ def env(sink: dict, key: str, default: str) -> str:
60
+ v = os.environ.get(sink.get(key, default))
61
+ if not v:
62
+ raise RuntimeError(tr("variable {name} is not set", name=sink.get(key, default)))
63
+ return v
64
+
65
+
66
+ def _send_mail(sink: dict, host: str, port: int, m: EmailMessage) -> None:
67
+ """SMTP with opportunistic STARTTLS (`tls`: auto|starttls|ssl|none), login with SMTP_USER/SMTP_PASSWORD and certificate checks.
68
+ Refuses to authenticate over an unencrypted channel unless `allow_insecure_auth: true` (development only)."""
69
+ import ssl
70
+ mode = sink.get("tls", "auto")
71
+ ctx = ssl.create_default_context()
72
+ if sink.get("tls_verify") is False:
73
+ ctx.check_hostname, ctx.verify_mode = False, ssl.CERT_NONE
74
+ user, pw = os.environ.get(sink.get("user_env", "SMTP_USER")), os.environ.get(sink.get("password_env", "SMTP_PASSWORD"))
75
+ cls = smtplib.SMTP_SSL if mode == "ssl" else smtplib.SMTP
76
+ kw = {"context": ctx} if mode == "ssl" else {}
77
+ with cls(host, port, timeout=10, **kw) as s:
78
+ s.ehlo()
79
+ encrypted = mode == "ssl"
80
+ if mode in ("auto", "starttls") and s.has_extn("starttls"):
81
+ s.starttls(context=ctx)
82
+ s.ehlo()
83
+ encrypted = True
84
+ elif mode == "starttls":
85
+ raise RuntimeError(tr("SMTP server does not offer STARTTLS"))
86
+ if user and pw:
87
+ if not encrypted and not sink.get("allow_insecure_auth"):
88
+ raise RuntimeError(tr("SMTP login refused: channel without TLS (use tls: starttls/ssl or allow_insecure_auth)"))
89
+ s.login(user, pw)
90
+ s.send_message(m)
91
+
92
+
93
+ def deliver(sink: dict, subject: str, body: str, meta: dict | None = None) -> None:
94
+ """`meta` (optional): {id, severity, title} of the incident, used by sinks that deduplicate or prioritize."""
95
+ meta = meta or {}
96
+ t = sink["type"]
97
+ if t in ("slack", "webhook"):
98
+ url = os.environ.get(sink["url_env"])
99
+ if not url:
100
+ raise RuntimeError(tr("variable {name} is not set", name=sink["url_env"]))
101
+ post_json(url, {"text": f"*{subject}*\n{body}"} if t == "slack" else {"subject": subject, "body": body})
102
+ elif t == "email":
103
+ host, port = os.environ.get(sink.get("host_env", "SMTP_HOST"), "localhost"), int(os.environ.get(sink.get("port_env", "SMTP_PORT"), "25"))
104
+ m = EmailMessage()
105
+ m["Subject"], m["From"], m["To"] = subject, sink.get("from", "intentflow@localhost"), sink["to"]
106
+ m.set_content(body)
107
+ _send_mail(sink, host, port, m)
108
+ elif t == "github":
109
+ tok = os.environ.get(sink.get("token_env", "GITHUB_TOKEN"))
110
+ if not tok:
111
+ raise RuntimeError(tr("GITHUB_TOKEN is not set"))
112
+ api = sink.get("api", "https://api.github.com").rstrip("/")
113
+ post_json(f"{api}/repos/{sink['repo']}/issues/{sink['pr']}/comments", {"body": body},
114
+ {"Authorization": f"Bearer {tok}", "Accept": "application/vnd.github+json"})
115
+ elif not extensions.first("notify_deliver", sink, subject, body, meta):
116
+ raise ValueError(tr("sink type {type} needs IntentFlow Enterprise", type=t) if t in ENTERPRISE_TYPES else
117
+ tr("unknown sink type: {type}", type=t))
118
+
119
+
120
+ def _matches(route: dict, inc) -> bool:
121
+ if route.get("owner") and route["owner"] not in inc.owners:
122
+ return False
123
+ if route.get("check_prefix") and not any((f.get("check_id") or f.get("check", "")).startswith(route["check_prefix"]) for f in inc.findings):
124
+ return False
125
+ ms = route.get("min_severity")
126
+ return not ms or SEVERITIES.index(inc.severity) <= SEVERITIES.index(ms)
127
+
128
+
129
+ def send(store: Store, incidents, dry_run: bool = False, now: float | None = None) -> list[dict]:
130
+ """Send incidents through the routes. Anti-spam: the same incident with the same severity is only resent after 24 h."""
131
+ now = now or time.time()
132
+ sinks = {s["name"]: s for s in store.get_setting("notify.sinks", [])}
133
+ routes = store.get_setting("notify.routes", [])
134
+ log = []
135
+ for inc in incidents:
136
+ sig = hashlib.sha1(f"{inc.id}|{inc.severity}|{len(inc.findings)}".encode()).hexdigest()[:12]
137
+ targets = {r["sink"] for r in routes if _matches(r, inc) and r["sink"] in sinks}
138
+ for name in sorted(targets):
139
+ key = f"state.notified.{name}.{sig}"
140
+ last = store.get_setting(key)
141
+ if last and now - last < COOLDOWN_S:
142
+ log.append({"incident": inc.id, "sink": name, "status": "suppressed"})
143
+ continue
144
+ if dry_run:
145
+ log.append({"incident": inc.id, "sink": name, "status": "dry-run"})
146
+ continue
147
+ try:
148
+ deliver(sinks[name], f"[{inc.severity}] {inc.title}", render_markdown([inc]), {"id": inc.id, "severity": inc.severity, "title": inc.title})
149
+ store.set_setting(key, now)
150
+ store.audit("system", "notified", {"incident": inc.id, "sink": name})
151
+ log.append({"incident": inc.id, "sink": name, "status": "sent"})
152
+ except Exception as e:
153
+ log.append({"incident": inc.id, "sink": name, "status": f"error: {str(e)[:120]}"})
154
+ return log
intentflow/ol_emit.py ADDED
@@ -0,0 +1,93 @@
1
+ """OpenLineage emitter: IntentFlow column lineage → RunEvents (DataHub, OpenMetadata, Marquez, Atlan… ingest OpenLineage).
2
+
3
+ One COMPLETE event per model, with `schema` and `columnLineage` facets (spec 1.x). Idempotent: deterministic runId per model + SQL hash.
4
+ """
5
+ from __future__ import annotations
6
+
7
+
8
+ import json
9
+ import time
10
+ import urllib.error
11
+ import urllib.request
12
+ import uuid
13
+ from datetime import datetime, UTC
14
+
15
+ PRODUCER = "https://github.com/intentflow/intentflow"
16
+ _SCHEMA = "https://openlineage.io/spec/facets/1-0-0/"
17
+
18
+
19
+ def _ds(project, uid: str) -> dict:
20
+ n = project.nodes[uid]
21
+ name = ".".join(p.strip('"`[]') for p in n.relation.split(".")) if n.relation else n.name
22
+ return {"namespace": project.adapter or "unknown", "name": name}
23
+
24
+
25
+ def _facet(kind: str, version: str, body: dict) -> dict:
26
+ return {"_producer": PRODUCER, "_schemaURL": f"https://openlineage.io/spec/facets/{version}/{kind}Facet.json", **body}
27
+
28
+
29
+ def build_events(project, lineage_result, namespace: str = "intentflow", now: float | None = None) -> list[dict]:
30
+ when = datetime.fromtimestamp(now or time.time(), UTC).isoformat().replace("+00:00", "Z")
31
+ by_dst: dict[str, list] = {}
32
+ for e in lineage_result.edges:
33
+ by_dst.setdefault(e.dst, []).append(e)
34
+ events = []
35
+ for uid, n in project.nodes.items():
36
+ if n.resource_type not in ("model", "snapshot") or not n.depends_on:
37
+ continue
38
+ ins = []
39
+ for d in n.depends_on:
40
+ if d not in project.nodes:
41
+ continue
42
+ ds = _ds(project, d)
43
+ cols = project.nodes[d].columns
44
+ if cols:
45
+ ds["facets"] = {"schema": _facet("SchemaDataset", "1-1-1", {"fields": [{"name": c.name, "type": c.type or ""} for c in cols.values()]})}
46
+ ins.append(ds)
47
+ out = _ds(project, uid)
48
+ fields: dict[str, dict] = {}
49
+ for e in by_dst.get(uid, []):
50
+ src = _ds(project, e.src)
51
+ xform = {"type": "DIRECT", "subtype": "IDENTITY" if e.kind == "direct" else "TRANSFORMATION", "masking": bool(e.masked)}
52
+ fields.setdefault(e.dst_col, {"inputFields": [], "transformationType": "IDENTITY" if e.kind == "direct" else "TRANSFORMATION"})
53
+ fields[e.dst_col]["inputFields"].append({**src, "field": e.src_col, "transformations": [xform]})
54
+ facets = {}
55
+ if n.columns:
56
+ facets["schema"] = _facet("SchemaDataset", "1-1-1", {"fields": [{"name": c.name, "type": c.type or "", **({"description": c.description} if c.description else {})}
57
+ for c in n.columns.values()]})
58
+ if fields:
59
+ facets["columnLineage"] = _facet("ColumnLineageDataset", "1-2-0", {"fields": fields})
60
+ out["facets"] = facets
61
+ sql_id = (n.compiled_code or n.raw_code or "")
62
+ run_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f"intentflow:{uid}:{hash_sql(sql_id)}"))
63
+ events.append({"eventType": "COMPLETE", "eventTime": when, "producer": PRODUCER, "schemaURL": "https://openlineage.io/spec/2-0-2/OpenLineage.json#/$defs/RunEvent",
64
+ "run": {"runId": run_id}, "job": {"namespace": namespace, "name": n.name,
65
+ "facets": {"sourceCode": {"_producer": PRODUCER, "_schemaURL": _SCHEMA.replace("facets/1-0-0/", "facets/1-0-1/") + "SourceCodeJobFacet.json",
66
+ "language": "sql", "sourceCode": sql_id}} if sql_id else {}},
67
+ "inputs": ins, "outputs": [out]})
68
+ return events
69
+
70
+
71
+ def hash_sql(s: str) -> str:
72
+ import hashlib
73
+ return hashlib.sha1(s.encode()).hexdigest()[:12]
74
+
75
+
76
+ def emit(url: str, events: list[dict], headers: dict | None = None, timeout: float = 15.0) -> dict:
77
+ """POST de cada evento em `{url}/api/v1/lineage` (Marquez/DataHub/OpenMetadata). Retorna contagem e erros."""
78
+ target = url.rstrip("/")
79
+ if not target.endswith("/api/v1/lineage"):
80
+ target += "/api/v1/lineage"
81
+ sent, errors = 0, []
82
+ for ev in events:
83
+ req = urllib.request.Request(target, data=json.dumps(ev).encode(), method="POST",
84
+ headers={"Content-Type": "application/json", **(headers or {})})
85
+ try:
86
+ urllib.request.urlopen(req, timeout=timeout).read()
87
+ sent += 1
88
+ except urllib.error.HTTPError as e:
89
+ errors.append(f"{ev['job']['name']}: HTTP {e.code}")
90
+ except urllib.error.URLError as e:
91
+ errors.append(f"{ev['job']['name']}: {e.reason}")
92
+ break
93
+ return {"sent": sent, "errors": errors}
@@ -0,0 +1,168 @@
1
+ """OpenLineage input (RunEvent, spec 1.x): runs + inputs/outputs + column lineage.
2
+
3
+ Covers every OpenLineage emitter (Airflow, Spark, dbt, Flink, Dagster, Kestra) without one connector per tool.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ from datetime import datetime
9
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
10
+
11
+ from .orchestrators import Run
12
+ from .store import Store
13
+ from .http_utils import RequestError, read_body
14
+ from .i18n import tr
15
+
16
+ STATE = {"START": "running", "RUNNING": "running", "COMPLETE": "success", "FAIL": "failed", "ABORT": "failed", "OTHER": "other"}
17
+
18
+
19
+ def _ts(s):
20
+ try:
21
+ return datetime.fromisoformat(str(s).replace("Z", "+00:00")).timestamp()
22
+ except ValueError:
23
+ return None
24
+
25
+
26
+ def ingest_events(store: Store, events: list[dict]) -> dict:
27
+ runs: dict[tuple[str, str], dict] = {}
28
+ n_edges = 0
29
+ for ev in sorted((e for e in events if isinstance(e, dict) and "run" in e and "job" in e), key=lambda e: e.get("eventTime", "")):
30
+ rid = ev["run"]["runId"]
31
+ job = f"{ev['job'].get('namespace', '')}.{ev['job']['name']}"
32
+ rf = (ev.get("run") or {}).get("facets") or {}
33
+ grouped = False
34
+ by_parent = str(store.get_setting("openlineage.group_by_parent") or "").lower() in ("1", "true", "yes", "sim")
35
+ if ((rf.get("processing_engine") or {}).get("name") == "spark" or by_parent) and isinstance(rf.get("parent"), dict):
36
+ pj = rf["parent"].get("job") or {} # each Spark action becomes a "job"; what the team recognizes is the application (other engines: opt-in)
37
+ if pj.get("name"):
38
+ job, grouped = f"{pj.get('namespace', '')}.{pj['name']}", True
39
+ t = _ts(ev.get("eventTime"))
40
+ st = STATE.get(ev.get("eventType", "OTHER"), "other")
41
+ key = (job, rid)
42
+ if key not in runs:
43
+ previous = store.con.execute("select start, \"end\", state from runs where system=? and pipeline=? and run_id=?",
44
+ ("openlineage", job, rid)).fetchone()
45
+ runs[key] = {"job": job, "start": previous["start"] if previous else None,
46
+ "end": previous["end"] if previous else None, "state": previous["state"] if previous else st}
47
+ r = runs[key]
48
+ if st == "running" and t is not None:
49
+ r["start"] = min(r["start"], t) if r["start"] is not None else t
50
+ terminal = r["state"] in ("success", "failed")
51
+ if st in ("success", "failed") and (r["end"] is None or (t is not None and t >= r["end"])):
52
+ r["end"], r["state"] = t, st
53
+ elif not terminal:
54
+ r["state"] = st
55
+ # dbt (and IntentFlow's own emitter) is already in the project: storing it as an "external job" would only duplicate the impact
56
+ prod = str(ev.get("producer") or "").lower()
57
+ own = ("/integration/dbt" in prod or "openlineage-dbt" in prod or "github.com/intentflow/" in prod) \
58
+ and str(store.get_setting("openlineage.keep_project_lineage") or "").lower() not in ("1", "true", "yes", "sim")
59
+ ins = [f"{d.get('namespace','')}:{d['name']}" for d in ([] if own else ev.get("inputs", []))]
60
+ outs = [f"{d.get('namespace','')}:{d['name']}" for d in ([] if own else ev.get("outputs", []))]
61
+ if grouped and (ins or outs): # the application adds up what all its actions read and write
62
+ row = store.con.execute("select inputs, outputs from ol_jobs where job=?", (job,)).fetchone()
63
+ if row:
64
+ ins = sorted(set(ins) | set(json.loads(row["inputs"])))
65
+ outs = sorted(set(outs) | set(json.loads(row["outputs"])))
66
+ if ins or outs:
67
+ store.upsert_ol_job(job, ins, outs, t or 0)
68
+ edges = []
69
+ for o in ([] if own else ev.get("outputs", [])):
70
+ cl = (o.get("facets") or {}).get("columnLineage") or {}
71
+ for col, spec in (cl.get("fields") or {}).items():
72
+ for f in spec.get("inputFields", []):
73
+ edges.append((f"{f.get('namespace','')}:{f['name']}", f["field"], f"{o.get('namespace','')}:{o['name']}", col))
74
+ if edges:
75
+ store.add_ol_edges(job, edges)
76
+ n_edges += len(edges)
77
+ out = [Run("openlineage", r["job"], rid, r["state"], r["start"], r["end"],
78
+ (r["end"] - r["start"]) if r["end"] is not None and r["start"] is not None else None) for (_, rid), r in runs.items()]
79
+ store.upsert_runs(out)
80
+ return {"runs": len(out), "column_edges": n_edges}
81
+
82
+
83
+ def ingest_file(store: Store, path: str) -> dict:
84
+ with open(path) as source:
85
+ text = source.read().strip()
86
+ try:
87
+ data = json.loads(text)
88
+ events = data if isinstance(data, list) else [data]
89
+ except ValueError: # NDJSON
90
+ events = [json.loads(l) for l in text.splitlines() if l.strip()]
91
+ return ingest_events(store, events)
92
+
93
+
94
+ def make_handler(store_path: str, token: str | None = None):
95
+ """`token` (or INTENTFLOW_OL_TOKEN): required as `Authorization: Bearer` when set; mandatory outside loopback."""
96
+ import hmac
97
+ import os
98
+ token = token if token is not None else os.environ.get("INTENTFLOW_OL_TOKEN") or None
99
+
100
+ class H(BaseHTTPRequestHandler):
101
+ def setup(self):
102
+ self.request.settimeout(15)
103
+ if hasattr(self.request, "do_handshake"): # TLS handshake in the worker thread, bounded by the timeout: never in accept()
104
+ self.request.do_handshake()
105
+ super().setup()
106
+
107
+ def log_message(self, *a):
108
+ pass
109
+
110
+ def log_request(self, code="-", size="-"):
111
+ from .http_utils import access_log
112
+ access_log(self, code)
113
+
114
+ def do_POST(self):
115
+ if self.path.rstrip("/") != "/api/v1/lineage": # Marquez-compatible path
116
+ self.send_response(404)
117
+ self.end_headers()
118
+ return
119
+ if self.headers.get("Origin") is not None:
120
+ self.send_response(403)
121
+ self.end_headers()
122
+ return
123
+ if token:
124
+ auth = self.headers.get("Authorization") or ""
125
+ if not hmac.compare_digest(auth.encode(), f"Bearer {token}".encode()):
126
+ self.close_connection = True
127
+ self.send_response(401)
128
+ self.end_headers()
129
+ return
130
+ try:
131
+ event = json.loads(read_body(self, limit=4 * 1024 * 1024))
132
+ if not isinstance(event, dict) or not isinstance(event.get("run"), dict) or not isinstance(event.get("job"), dict):
133
+ raise ValueError(tr("invalid OpenLineage event"))
134
+ with Store(store_path) as store:
135
+ res = ingest_events(store, [event])
136
+ code, body = 200, json.dumps(res)
137
+ except (ValueError, KeyError, TypeError, AttributeError) as e: # malformed facets/datasets: 400, never a dropped connection
138
+ self.close_connection = True
139
+ code = e.status if isinstance(e, RequestError) else 400
140
+ body = json.dumps({"error": str(e)})
141
+ self.send_response(code)
142
+ self.send_header("Content-Type", "application/json")
143
+ self.end_headers()
144
+ self.wfile.write(body.encode())
145
+ return H
146
+
147
+
148
+ def serve(store_path: str, port: int = 5000, host: str = "127.0.0.1", token: str | None = None,
149
+ tls_cert: str | None = None, tls_key: str | None = None, behind_proxy: bool = False):
150
+ """Outside loopback: a token AND transport encryption (own TLS or a declared TLS proxy), so the Bearer never travels in clear."""
151
+ import os
152
+ token = token or os.environ.get("INTENTFLOW_OL_TOKEN") or None
153
+ if host not in ("127.0.0.1", "localhost", "::1"):
154
+ if not token:
155
+ raise SystemExit(tr("refused: to listen outside loopback set INTENTFLOW_OL_TOKEN (emitters send it as Bearer)"))
156
+ if not (tls_cert and tls_key) and not behind_proxy:
157
+ raise SystemExit(tr("refused: outside loopback use HTTPS (--tls-cert/--tls-key) or declare --behind-proxy (reverse proxy with TLS)"))
158
+ srv = ThreadingHTTPServer((host, port), make_handler(store_path, token))
159
+ scheme = "http"
160
+ if tls_cert and tls_key:
161
+ from .http_utils import tls_context
162
+ srv.socket = tls_context(tls_cert, tls_key).wrap_socket(srv.socket, server_side=True, do_handshake_on_connect=False)
163
+ scheme = "https"
164
+ print(tr("OpenLineage receiver: {url}", url=f"{scheme}://{host}:{srv.server_address[1]}/api/v1/lineage"))
165
+ try:
166
+ srv.serve_forever()
167
+ finally:
168
+ srv.server_close()