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,363 @@
1
+ """Evidence required before promoting a dbt build; never executes project code.
2
+
3
+ This checks a *full* build, not a selected sandbox build. Artifacts must be
4
+ generated by trusted CI in the candidate checkout. They are not signed proof.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import math
10
+ import time
11
+ from collections import Counter
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+
15
+ from .i18n import tr
16
+ from .model import SEVERITIES
17
+
18
+ DEFAULT_REQUIRED = ("SQL001", "SQL002", "DBT002", "DBT003", "DBT004", "SCH001", "SCH002", "SCH003", "DBTR001", "DBTR002", "DBTR003", "BIZ001", "BIZ002")
19
+ SUPPORTED_REQUIRED = set(DEFAULT_REQUIRED) | {f"SQL{i:03}" for i in range(1, 16)} | {f"DBT{i:03}" for i in range(1, 6)} | {f"PRB{i:03}" for i in range(1, 5)} | {"CTR001", "DQ001"}
20
+ EXECUTABLE = {"model", "seed", "snapshot", "test", "unit_test"}
21
+
22
+
23
+ def inspect_artifacts(target, base, root, *, max_age_hours=24, warnings_as_errors=False, revision=None, require_freshness=False, now=None):
24
+ """Return explicit gaps; missing, malformed and partial evidence cannot pass."""
25
+ now = time.time() if now is None else now
26
+ if not math.isfinite(max_age_hours) or max_age_hours <= 0:
27
+ raise ValueError(tr("maximum artifact age must be a positive finite number"))
28
+ if revision is not None and (not isinstance(revision, str) or not revision.strip()):
29
+ raise ValueError(tr("expected artifact revision must not be empty"))
30
+ report = {"errors": [], "warnings": [], "build_counts": {}, "expected_resources": 0, "revision": revision}
31
+
32
+ def gap(code, message, nodes=()):
33
+ report["errors"].append({"code": code, "message": str(message), "nodes": list(nodes)[:20], "total": len(nodes)})
34
+
35
+ def read(folder, name, side):
36
+ try:
37
+ doc = json.loads((Path(folder) / name).read_text())
38
+ if not isinstance(doc, dict) or not isinstance(doc.get("metadata"), dict):
39
+ raise ValueError("expected an artifact object with metadata")
40
+ return doc
41
+ except (OSError, ValueError, UnicodeError) as e:
42
+ gap("artifact_unavailable", tr("{side}/{name}: artifact unavailable or invalid ({error})", side=side, name=name, error=type(e).__name__))
43
+ return None
44
+
45
+ def nodes(man):
46
+ sections = [man.get("nodes"), man.get("unit_tests", {})]
47
+ if not all(isinstance(section, dict) and all(isinstance(n, dict) and isinstance(n.get("config", {}), dict)
48
+ for n in section.values()) for section in sections):
49
+ raise ValueError("invalid manifest nodes")
50
+ return {uid: n for section in sections for uid, n in section.items()
51
+ if n.get("resource_type") in EXECUTABLE and (n.get("config") or {}).get("enabled", True)
52
+ and (n.get("config") or {}).get("materialized") != "ephemeral"}
53
+
54
+ documents = {}
55
+ expected = {}
56
+ def check_revision(doc, name):
57
+ env = doc["metadata"].get("env")
58
+ if revision and (not isinstance(env, dict) or env.get("INTENTFLOW_REVISION") != revision):
59
+ gap("revision_mismatch", tr("{name}: artifact revision does not match the candidate", name=name))
60
+ for side, folder in (("head", target), ("base", base)):
61
+ man = read(folder, "manifest.json", side)
62
+ cat = read(folder, "catalog.json", side)
63
+ documents[side] = man
64
+ if man:
65
+ try:
66
+ expected[side] = nodes(man)
67
+ except (ValueError, TypeError, AttributeError):
68
+ gap("manifest_invalid", tr("{side}: manifest resource definitions are invalid", side=side))
69
+ if cat:
70
+ if cat.get("errors"):
71
+ gap("catalog_errors", tr("{side}: catalog generation reported errors", side=side))
72
+ catalog_nodes = cat.get("nodes")
73
+ if not isinstance(catalog_nodes, dict):
74
+ gap("catalog_invalid", tr("{side}: catalog nodes are invalid", side=side))
75
+ elif side in expected:
76
+ missing = [uid for uid, n in expected[side].items() if n.get("resource_type") in {"model", "seed", "snapshot"}
77
+ and not (isinstance(catalog_nodes.get(uid), dict) and catalog_nodes[uid].get("columns"))]
78
+ if missing:
79
+ gap("catalog_incomplete", tr("{side}: built relations are missing catalog columns", side=side), missing)
80
+ if side == "head":
81
+ for name, doc in (("manifest.json", man), ("catalog.json", cat)):
82
+ if doc:
83
+ check_age(doc, name, now, max_age_hours, gap)
84
+ check_revision(doc, name)
85
+
86
+ head, previous = documents.get("head"), documents.get("base")
87
+ if report["errors"]:
88
+ return report
89
+ if head and previous:
90
+ for key in ("project_name", "adapter_type"):
91
+ h, b = head["metadata"].get(key), previous["metadata"].get(key)
92
+ if not h or h != b:
93
+ gap("baseline_mismatch", tr("base/head metadata differs or is absent: {key}", key=key))
94
+ uncompiled = [uid for uid, n in expected.get("head", {}).items() if n.get("resource_type") in ("model", "snapshot")
95
+ and (n.get("language") or "sql") == "sql" and not n.get("compiled_code")]
96
+ if uncompiled:
97
+ gap("sql_not_compiled", tr("SQL models lack compiled code for required analysis"), uncompiled)
98
+
99
+ built = read(target, "run_results.json", "head")
100
+ if built:
101
+ check_age(built, "run_results.json", now, max_age_hours, gap)
102
+ check_revision(built, "run_results.json")
103
+ if not isinstance(built.get("args"), dict) or built["args"].get("which") != "build":
104
+ gap("build_required", tr("run_results must come from dbt build, not docs/parse/run/test"))
105
+ rows = built.get("results")
106
+ if not isinstance(rows, list) or not rows or any(not isinstance(r, dict) or not isinstance(r.get("unique_id"), str) for r in rows):
107
+ gap("results_invalid", tr("build results are missing, empty or invalid"))
108
+ else:
109
+ ids = [r["unique_id"] for r in rows]
110
+ counts = Counter(ids)
111
+ repeated = [uid for uid, count in counts.items() if count > 1]
112
+ if repeated:
113
+ gap("results_duplicate", tr("build results repeat resource identifiers"), repeated)
114
+ if "head" in expected:
115
+ wanted = expected["head"]
116
+ report["expected_resources"] = len(wanted)
117
+ missing, extra = sorted(set(wanted) - set(ids)), sorted(set(ids) - set(wanted))
118
+ if missing:
119
+ gap("build_incomplete", tr("full build evidence is missing resources"), missing)
120
+ if extra:
121
+ gap("results_mismatch", tr("build results contain resources absent from the manifest"), extra)
122
+ if not any(n.get("resource_type") in {"test", "unit_test"} for n in wanted.values()):
123
+ gap("tests_missing", tr("the manifest has no enabled tests"))
124
+ statuses = Counter(str(r.get("status")) for r in rows)
125
+ report["build_counts"] = dict(statuses)
126
+ bad = [r["unique_id"] for r in rows if r.get("status") not in ("success", "pass", "warn")]
127
+ if bad:
128
+ gap("build_unsuccessful", tr("build contains failures, skipped resources or unknown statuses"), bad)
129
+ warned = [r["unique_id"] for r in rows if r.get("status") == "warn"]
130
+ if warned:
131
+ if warnings_as_errors:
132
+ gap("build_warnings", tr("build warnings are blocking by policy"), warned)
133
+ else:
134
+ report["warnings"].append({"code": "build_warnings", "nodes": warned[:20], "total": len(warned)})
135
+ # dbt docs generates another invocation. Compare compiled content instead
136
+ # of requiring invocation ids to match across those two commands.
137
+ if head:
138
+ all_nodes = head.get("nodes", {})
139
+ drift = [r["unique_id"] for r in rows if isinstance(r.get("compiled_code"), str) and
140
+ isinstance(all_nodes.get(r["unique_id"], {}).get("compiled_code"), str) and
141
+ r["compiled_code"].strip() != all_nodes[r["unique_id"]]["compiled_code"].strip()]
142
+ if drift:
143
+ gap("compiled_code_mismatch", tr("build and manifest compiled SQL differ"), drift)
144
+
145
+ if head and require_freshness:
146
+ sources = head.get("sources", {})
147
+ freshness = read(target, "sources.json", "head")
148
+ if freshness:
149
+ check_age(freshness, "sources.json", now, max_age_hours, gap)
150
+ check_revision(freshness, "sources.json")
151
+ inspect_freshness(sources, freshness, now, warnings_as_errors, report, gap)
152
+
153
+ if head:
154
+ package = head["metadata"].get("project_name")
155
+ changed = []
156
+ for uid, n in head.get("nodes", {}).items() if isinstance(head.get("nodes"), dict) else []:
157
+ if not isinstance(n, dict) or n.get("package_name") != package or not isinstance(n.get("raw_code"), str) or not n["raw_code"]:
158
+ continue
159
+ path = n.get("original_file_path", "")
160
+ if Path(path).suffix.lower() not in {".sql", ".py"}:
161
+ continue
162
+ try:
163
+ source = (Path(root) / path).resolve()
164
+ if not source.is_relative_to(Path(root).resolve()) or source.read_text().strip() != n["raw_code"].strip():
165
+ changed.append(uid)
166
+ except (OSError, UnicodeError):
167
+ changed.append(uid)
168
+ if changed:
169
+ gap("source_changed", tr("current SQL/Python sources differ from the candidate manifest"), changed)
170
+ return report
171
+
172
+
173
+ def inspect_freshness(sources, freshness, now, warnings_as_errors, report, gap):
174
+ """Check all declared source SLAs; re-evaluate age at promotion time."""
175
+ if not isinstance(sources, dict) or not sources or any(not isinstance(n, dict) for n in sources.values()):
176
+ gap("source_freshness_missing", tr("source freshness requires declared sources and SLAs"))
177
+ return
178
+ rows = freshness.get("results")
179
+ if not isinstance(rows, list) or any(not isinstance(r, dict) or not isinstance(r.get("unique_id"), str) for r in rows):
180
+ gap("source_freshness_invalid", tr("source freshness results are invalid"))
181
+ return
182
+ by_id = {r["unique_id"]: r for r in rows}
183
+ if len(by_id) != len(rows) or set(by_id) != set(sources):
184
+ gap("source_freshness_incomplete", tr("source freshness did not evaluate exactly the declared sources"))
185
+ periods = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
186
+ for uid, source in sources.items():
187
+ cfg = source.get("config") or {}
188
+ if not isinstance(cfg, dict):
189
+ gap("source_freshness_invalid", tr("source freshness timestamps or thresholds are invalid"), [uid])
190
+ continue
191
+ limits = cfg.get("freshness") if "freshness" in cfg else source.get("freshness")
192
+ r = by_id.get(uid)
193
+ if not isinstance(limits, dict) or not any(isinstance(limits.get(key), dict) and limits[key].get("count") is not None and limits[key].get("period") for key in ("warn_after", "error_after")):
194
+ gap("source_sla_missing", tr("source has no freshness SLA"), [uid])
195
+ continue
196
+ if not r:
197
+ continue
198
+ if r.get("status") not in ("pass", "warn"):
199
+ gap("source_freshness_failed", tr("source freshness failed or could not execute"), [uid])
200
+ continue
201
+ try:
202
+ loaded = datetime.fromisoformat(r["max_loaded_at"].replace("Z", "+00:00"))
203
+ snapshot = datetime.fromisoformat(r["snapshotted_at"].replace("Z", "+00:00"))
204
+ if loaded.tzinfo is None or snapshot.tzinfo is None or snapshot.timestamp() > now + 300 or loaded.timestamp() > snapshot.timestamp() + 300:
205
+ raise ValueError("invalid timezone/clock")
206
+ age = now - loaded.timestamp()
207
+ if age < -300:
208
+ raise ValueError("future loaded timestamp")
209
+ warned = r["status"] == "warn"
210
+ for key in ("warn_after", "error_after"):
211
+ limit = limits.get(key)
212
+ if not limit or (isinstance(limit, dict) and limit.get("count") is None and limit.get("period") is None):
213
+ continue
214
+ count, unit = float(limit["count"]), limit["period"]
215
+ if not math.isfinite(count) or count < 0 or unit not in periods:
216
+ raise ValueError("invalid threshold")
217
+ if age > count * periods[unit]:
218
+ if key == "error_after":
219
+ gap("source_stale", tr("source data exceeds its freshness SLA at promotion time"), [uid])
220
+ else:
221
+ warned = True
222
+ if warned:
223
+ if warnings_as_errors:
224
+ gap("source_freshness_warning", tr("source freshness warning blocks by policy"), [uid])
225
+ else:
226
+ report["warnings"].append({"code": "source_freshness_warning", "nodes": [uid]})
227
+ except (KeyError, TypeError, ValueError, AttributeError, OverflowError):
228
+ gap("source_freshness_invalid", tr("source freshness timestamps or thresholds are invalid"), [uid])
229
+
230
+
231
+ def inspect_quality(spec, project, now, hours, warnings_as_errors, report):
232
+ """Require recognized, current and mapped GX/Soda results for every input."""
233
+ from . import dq_results
234
+ from .checks.dq import _index, _match
235
+ def gap(code, message):
236
+ report["errors"].append({"code": code, "message": str(message)})
237
+ parts = [part.strip() for part in (spec or "").split(",") if part.strip()]
238
+ if not parts:
239
+ gap("quality_required", tr("required external quality results are not configured"))
240
+ index = _index(project)
241
+ def payloads(doc):
242
+ if isinstance(doc, list):
243
+ for item in doc:
244
+ yield from payloads(item)
245
+ elif isinstance(doc, dict) and "run_results" in doc:
246
+ for item in doc["run_results"].values():
247
+ yield from payloads(item.get("validation_result", item))
248
+ else:
249
+ yield doc
250
+ for part in parts:
251
+ files = dq_results.expand(part)
252
+ if not files:
253
+ gap("quality_required", tr("required external quality input is missing: {path}", path=part))
254
+ for file in files:
255
+ try:
256
+ doc = json.loads(file.read_text())
257
+ items = list(payloads(doc))
258
+ if not items:
259
+ raise ValueError("empty results")
260
+ for item in items:
261
+ parsed = dq_results.parse(item)
262
+ if not parsed or item.get("hasErrors") or any(r.status == "error" for r in parsed):
263
+ raise ValueError("unrecognized or incomplete results")
264
+ meta = item.get("meta") or {}
265
+ stamp = item.get("scanStartTimestamp") or meta.get("validation_time") or (meta.get("run_id") or {}).get("run_time")
266
+ check_age({"metadata": {"generated_at": stamp}}, str(file), now, hours,
267
+ lambda code, message: gap(code, message))
268
+ if any(_match(index, r.table, strict=True) is None for r in parsed):
269
+ gap("quality_unmapped", tr("external quality results do not map unambiguously to project models"))
270
+ if warnings_as_errors and any(r.status == "warn" for r in parsed):
271
+ gap("quality_warning", tr("external quality warnings block by policy"))
272
+ except (OSError, ValueError, KeyError, TypeError, AttributeError, UnicodeError):
273
+ gap("quality_required", tr("external quality input is invalid or incomplete: {path}", path=file))
274
+
275
+
276
+ def check_age(doc, name, now, hours, gap):
277
+ try:
278
+ stamp = datetime.fromisoformat(doc["metadata"]["generated_at"].replace("Z", "+00:00"))
279
+ if stamp.tzinfo is None:
280
+ raise ValueError("missing timezone")
281
+ age = now - stamp.timestamp()
282
+ if age < -300 or age > hours * 3600:
283
+ gap("artifact_stale", tr("{name}: timestamp is stale or in the future", name=name))
284
+ except (KeyError, TypeError, ValueError, AttributeError, OverflowError):
285
+ gap("artifact_timestamp", tr("{name}: generated_at must include a valid timezone", name=name))
286
+
287
+
288
+ def run(store, options, *, required=(), max_age_hours=24, warnings_as_errors=False, fail_on="high", revision=None, require_freshness=False, accepted_changes=(), review_model_logic=False, baseline_revision=None):
289
+ from . import runner
290
+ from .checks import REGISTRY, load_all
291
+
292
+ o = runner.resolve_options(store, options)
293
+ if not all(o.get(k) for k in ("target", "base", "root")):
294
+ raise ValueError(tr("preflight requires target, base and root"))
295
+ if Path(o["target"]).resolve() == Path(o["base"]).resolve():
296
+ raise ValueError(tr("candidate and baseline must be different artifact locations"))
297
+ evidence = inspect_artifacts(o["target"], o["base"], o["root"], max_age_hours=max_age_hours, warnings_as_errors=warnings_as_errors, revision=revision, require_freshness=require_freshness)
298
+ evidence.update({"ok": False, "findings": [], "completed_checks": [], "failed_checks": [], "required_checks": sorted(set(DEFAULT_REQUIRED) | set(required))})
299
+ if not evidence["errors"]:
300
+ from . import change_review
301
+ try:
302
+ changes = change_review.load(o["target"], o["base"], review_model_logic=review_model_logic, baseline_revision=baseline_revision)
303
+ except ValueError as e:
304
+ evidence["errors"].append({"code": "change_comparison_unavailable", "message": str(e)})
305
+ else:
306
+ evidence["change_review"] = change_review.acknowledge(changes, accepted_changes)
307
+ if changes["gaps"]:
308
+ evidence["errors"].append({"code": "change_comparison_incomplete", "message": str(tr("Catalog columns unavailable for change comparison.")), "gaps": changes["gaps"]})
309
+ if changes["unreviewed"]:
310
+ evidence["errors"].append({"code": "changes_require_review", "message": str(tr("Existing controls or interfaces changed; review the identified changes before promotion.")), "changes": changes["unreviewed"]})
311
+ if accepted_changes:
312
+ store.audit("cli", "change_acknowledged", {"changes": [{"id": c["id"], "reason": c["reason"]} for c in changes["changes"] if c["acknowledged"]]})
313
+ load_all()
314
+ known = {code for c in REGISTRY.values() for code in (c.id, *c.emits)}
315
+ unknown = set(evidence["required_checks"]) - known
316
+ if unknown:
317
+ evidence["errors"].append({"code": "unknown_checks", "message": str(tr("unknown required checks")), "nodes": sorted(unknown)})
318
+ unsupported = set(required) & known - SUPPORTED_REQUIRED
319
+ if unsupported:
320
+ evidence["errors"].append({"code": "unsupported_required_evidence", "message": str(tr("mandatory input evidence is not supported for these checks")), "nodes": sorted(unsupported)})
321
+ if "DQ001" in required and not evidence["errors"]:
322
+ from . import dbt_loader
323
+ inspect_quality(store.get_setting("dq.results"), dbt_loader.load(o["target"], o["root"]), time.time(), max_age_hours, warnings_as_errors, evidence)
324
+ if "CTR001" in required:
325
+ from . import contracts
326
+ try:
327
+ contracts.load_all(store.get_setting("contracts.dir"), strict=True)
328
+ except Exception:
329
+ evidence["errors"].append({"code": "contracts_required", "message": str(tr("required contracts must be configured and readable"))})
330
+ warehouse_required = {"PRB001", "PRB002", "PRB003", "PRB004", "SQL012", "SQL013", "SQL014"} & set(required)
331
+ if warehouse_required:
332
+ from . import warehouses
333
+ wh = None
334
+ try:
335
+ wh = warehouses.connect(lambda key: o.get("duckdb") or store.get_setting(key) if key == "warehouse.duckdb" else
336
+ o.get("postgres_env") or store.get_setting(key) if key == "warehouse.postgres_env" else store.get_setting(key))
337
+ if wh is None:
338
+ raise ValueError("warehouse not configured")
339
+ except Exception:
340
+ evidence["errors"].append({"code": "warehouse_required", "message": str(tr("required warehouse checks need an available connection")), "nodes": sorted(warehouse_required)})
341
+ finally:
342
+ if wh is not None:
343
+ wh.close()
344
+ # Do not load malformed or partial artifacts into the normal runner/store.
345
+ if evidence["errors"]:
346
+ return evidence
347
+ try:
348
+ result = runner.run_check(store, o, required_checks=set(evidence["required_checks"]))
349
+ except Exception as e:
350
+ evidence["errors"].append({"code": "checks_unavailable", "message": str(tr("preflight checks unavailable ({error})", error=type(e).__name__))})
351
+ return evidence
352
+ evidence["completed_checks"] = result["completed_checks"]
353
+ evidence["failed_checks"] = result["failed_checks"]
354
+ missing = sorted(set(evidence["required_checks"]) - set(result["completed_checks"]))
355
+ if missing or result["failed_checks"]:
356
+ evidence["errors"].append({"code": "checks_incomplete", "message": str(tr("required checks did not complete or a check failed")),
357
+ "nodes": sorted(set(missing) | set(result["failed_checks"]))})
358
+ evidence["findings"] = [f.to_dict() for f in result["findings"]]
359
+ evidence["lineage"] = result["lineage"]
360
+ levels = SEVERITIES[:SEVERITIES.index(fail_on) + 1]
361
+ evidence["blocking_findings"] = [f.id for f in result["findings"] if f.severity in levels]
362
+ evidence["ok"] = not evidence["errors"] and not evidence["blocking_findings"]
363
+ return evidence
@@ -0,0 +1,39 @@
1
+ """IntentFlow metrics in the Prometheus exposition format (`GET /metrics`, with a Bearer token like the rest of the API)."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+
7
+ def _esc(v) -> str:
8
+ return re.sub(r'(["\\])', r"\\\1", str(v)).replace("\n", " ")
9
+
10
+
11
+ def render(store) -> str:
12
+ lines: list[str] = []
13
+
14
+ def metric(name: str, help_: str, kind: str, rows: list[tuple[dict, float]]):
15
+ lines.append(f"# HELP {name} {help_}")
16
+ lines.append(f"# TYPE {name} {kind}")
17
+ for lab, v in rows:
18
+ body = ",".join(f'{k}="{_esc(x)}"' for k, x in lab.items())
19
+ lines.append(f"{name}{{{body}}} {v:g}" if body else f"{name} {v:g}")
20
+
21
+ sev: dict[str, int] = {}
22
+ by_check: dict[str, int] = {}
23
+ for f in store.findings("open"):
24
+ sev[f["severity"]] = sev.get(f["severity"], 0) + 1
25
+ c = f.get("check_id") or f.get("check") or "?"
26
+ by_check[c] = by_check.get(c, 0) + 1
27
+ metric("intentflow_findings_open", "Open findings by severity", "gauge",
28
+ [({"severity": s}, n) for s, n in sorted(sev.items())] or [({"severity": "none"}, 0)])
29
+ metric("intentflow_findings_open_by_check", "Open findings by check", "gauge", [({"check": c}, n) for c, n in sorted(by_check.items())])
30
+ runs: dict[tuple, int] = {}
31
+ for r in store.runs(1000):
32
+ k = (r["system"], r["state"])
33
+ runs[k] = runs.get(k, 0) + 1
34
+ metric("intentflow_runs", "Recent collected runs by system and state", "gauge",
35
+ [({"system": s, "state": st}, n) for (s, st), n in sorted(runs.items())])
36
+ last = store.get_setting("state.last_check") or {}
37
+ metric("intentflow_check_last_run_timestamp_seconds", "When the last check finished", "gauge", [({}, float(last.get("ts", 0)))])
38
+ metric("intentflow_check_last_findings", "Findings of the last check", "gauge", [({}, float(last.get("findings", 0)))])
39
+ return "\n".join(lines) + "\n"