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,115 @@
1
+ """Kafka: consumer lag (Admin API through kafka-python) and Schema Registry (REST, compatible with Confluent/Redpanda).
2
+
3
+ `collect(store)` records `consumer_lag` samples and a snapshot of the schema versions; the KAF* checks only read the store.
4
+ Config: `kafka.bootstrap` (host:port[,..]) and `kafka.schema_registry` (URL). SASL credentials: KAFKA_USER/KAFKA_PASSWORD (SASL_PLAIN).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import time
11
+
12
+ from .monitoring import Sample
13
+ from .orchestrators import http_json
14
+ from .i18n import tr
15
+
16
+
17
+ class SchemaRegistry:
18
+ def __init__(self, url: str, fetch=http_json):
19
+ self.base, self.fetch = url.rstrip("/"), fetch
20
+
21
+ def _h(self) -> dict:
22
+ from .orchestrators import basic
23
+ return basic("SCHEMA_REGISTRY_USER", "SCHEMA_REGISTRY_PASSWORD")
24
+
25
+ def subjects(self) -> list[str]:
26
+ return self.fetch(f"{self.base}/subjects", self._h()) or []
27
+
28
+ def versions(self, subject: str) -> list[int]:
29
+ return self.fetch(f"{self.base}/subjects/{subject}/versions", self._h()) or []
30
+
31
+ def version(self, subject: str, v: int | str) -> dict:
32
+ return self.fetch(f"{self.base}/subjects/{subject}/versions/{v}", self._h())
33
+
34
+ def snapshot(self, keep: int = 5) -> dict[str, list[dict]]:
35
+ out = {}
36
+ for s in self.subjects():
37
+ vs = sorted(self.versions(s))[-keep:]
38
+ out[s] = [{"version": v, "fields": avro_fields(self.version(s, v).get("schema")),
39
+ "type": self.version(s, v).get("schemaType", "AVRO")} for v in vs]
40
+ return out
41
+
42
+
43
+ def avro_fields(schema) -> dict[str, str]:
44
+ """{field: type} of a top-level Avro schema (record). Other formats → {}."""
45
+ try:
46
+ doc = json.loads(schema) if isinstance(schema, str) else schema
47
+ except (TypeError, ValueError):
48
+ return {}
49
+ if not isinstance(doc, dict) or doc.get("type") != "record":
50
+ return {}
51
+ out = {}
52
+ for f in doc.get("fields", []):
53
+ t = f.get("type")
54
+ if isinstance(t, list): # union: ["null","string"]
55
+ t = "|".join(sorted(str(x if not isinstance(x, dict) else x.get("type", "complex")) for x in t))
56
+ elif isinstance(t, dict):
57
+ t = t.get("logicalType") or t.get("type", "complex")
58
+ out[f["name"]] = str(t)
59
+ return out
60
+
61
+
62
+ def consumer_lag(bootstrap: str, groups: list[str] | None = None) -> list[tuple[str, str, int]]:
63
+ """[(group, topic, lag)] summing the partitions. Requires `kafka-python-ng`."""
64
+ try:
65
+ from kafka import KafkaAdminClient, KafkaConsumer
66
+ except ImportError as e:
67
+ raise RuntimeError(tr("install `kafka-python-ng` (pip install intentdataflow[kafka]) to measure lag")) from e
68
+ cfg: dict = {"bootstrap_servers": bootstrap.split(","), "request_timeout_ms": 15000}
69
+ if os.environ.get("KAFKA_USER"):
70
+ cfg.update(security_protocol="SASL_PLAINTEXT", sasl_mechanism="PLAIN", sasl_plain_username=os.environ["KAFKA_USER"],
71
+ sasl_plain_password=os.environ.get("KAFKA_PASSWORD", ""))
72
+ admin = KafkaAdminClient(**cfg)
73
+ try:
74
+ names = groups or [g[0] for g in admin.list_consumer_groups()]
75
+ out = []
76
+ consumer = KafkaConsumer(**cfg)
77
+ try:
78
+ for g in names:
79
+ offs = admin.list_consumer_group_offsets(g)
80
+ if not offs:
81
+ continue
82
+ ends = consumer.end_offsets(list(offs))
83
+ per_topic: dict[str, int] = {}
84
+ for tp, om in offs.items():
85
+ per_topic[tp.topic] = per_topic.get(tp.topic, 0) + max(0, ends[tp] - om.offset)
86
+ out += [(g, t, lag) for t, lag in per_topic.items()]
87
+ finally:
88
+ consumer.close()
89
+ return out
90
+ finally:
91
+ admin.close()
92
+
93
+
94
+ def collect(store, now: float | None = None, lag_fn=consumer_lag, registry=SchemaRegistry) -> dict:
95
+ now = now or time.time()
96
+ res = {"lag": 0, "subjects": 0, "errors": []}
97
+ boot, reg = store.get_setting("kafka.bootstrap"), store.get_setting("kafka.schema_registry")
98
+ if boot:
99
+ try:
100
+ groups = store.get_setting("kafka.groups") or None
101
+ if isinstance(groups, str): # coming from the UI as text "g1, g2"
102
+ groups = [g.strip() for g in groups.split(",") if g.strip()] or None
103
+ rows = lag_fn(boot, groups)
104
+ store.add_samples([Sample(now, "kafka", f"{g}:{t}", "consumer_lag", float(lag)) for g, t, lag in rows])
105
+ res["lag"] = len(rows)
106
+ except Exception as e: # a broker that is down does not take the cycle down
107
+ res["errors"].append(f"kafka: {str(e)[:150]}")
108
+ if reg:
109
+ try:
110
+ snap = registry(reg).snapshot()
111
+ store.set_setting("state.kafka_schemas", snap)
112
+ res["subjects"] = len(snap)
113
+ except Exception as e:
114
+ res["errors"].append(f"schema registry: {str(e)[:150]}")
115
+ return res
intentflow/totp.py ADDED
@@ -0,0 +1,38 @@
1
+ """TOTP (RFC 6238) with the standard library: SHA-1, 6 digits, 30 s step."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import hashlib
6
+ import hmac
7
+ import secrets
8
+ import struct
9
+ import time
10
+ from urllib.parse import quote
11
+
12
+
13
+ def new_secret() -> str:
14
+ return base64.b32encode(secrets.token_bytes(20)).decode().rstrip("=")
15
+
16
+
17
+ def code_at(secret: str, step: int, digits: int = 6) -> str:
18
+ key = base64.b32decode(secret + "=" * (-len(secret) % 8), casefold=True)
19
+ mac = hmac.new(key, struct.pack(">Q", step), hashlib.sha1).digest()
20
+ o = mac[-1] & 0x0F
21
+ n = (struct.unpack(">I", mac[o:o + 4])[0] & 0x7FFFFFFF) % (10 ** digits)
22
+ return str(n).zfill(digits)
23
+
24
+
25
+ def verify(secret: str, code: str, now: float | None = None, window: int = 1, last_step: int = 0) -> int | None:
26
+ """Return the accepted step (to prevent reuse) or None. Accepts ±`window` steps of clock tolerance."""
27
+ code = (code or "").strip().replace(" ", "")
28
+ if not (code.isdigit() and len(code) == 6):
29
+ return None
30
+ cur = int((now if now is not None else time.time()) // 30)
31
+ for s in range(cur - window, cur + window + 1):
32
+ if s > last_step and hmac.compare_digest(code_at(secret, s), code):
33
+ return s
34
+ return None
35
+
36
+
37
+ def uri(secret: str, account: str, issuer: str = "IntentFlow") -> str:
38
+ return f"otpauth://totp/{quote(issuer)}:{quote(account)}?secret={secret}&issuer={quote(issuer)}&digits=6&period=30"
@@ -0,0 +1,190 @@
1
+ """Read access to warehouses: probe queries, EXPLAIN and spill reports.
2
+
3
+ Local: DuckDB, PostgreSQL. Cloud: Snowflake, BigQuery, Databricks (cloud.py; credentials only through
4
+ environment variables, read-only, lazy driver import).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from ..i18n import tr
9
+
10
+ import os
11
+
12
+
13
+ class Warehouse:
14
+ dialect = "duckdb"
15
+ name = "warehouse"
16
+
17
+ def rows(self, sql: str) -> list[tuple]:
18
+ raise NotImplementedError
19
+
20
+ def close(self) -> None:
21
+ """Close the connection, if any (idempotent; driver errors are ignored)."""
22
+ for attr in ("con", "client"):
23
+ c = getattr(self, attr, None)
24
+ if c is not None and hasattr(c, "close"):
25
+ try:
26
+ c.close()
27
+ except Exception:
28
+ pass
29
+
30
+ def quote(self, ident: str) -> str:
31
+ return '"' + ident.replace('"', '""') + '"'
32
+
33
+ def differs(self, a: str, b: str) -> str:
34
+ """Inequality comparison that treats NULL as a value."""
35
+ return f"{a} is distinct from {b}"
36
+
37
+ # deterministic key hash per engine: base and new always fall in the SAME bucket, so the sample is consistent between them
38
+ str_type = "varchar"
39
+
40
+ def _bucket(self, text: str) -> str:
41
+ """Integer expression in [0, 10000) derived from `text` (already a string)."""
42
+ return f"abs(mod(hash({text}), 10000))"
43
+
44
+ def sample_pred(self, exprs: list[str], pct: float) -> str:
45
+ """Predicate true for ~pct % of the keys (key hash, not random rows)."""
46
+ text = f"cast({exprs[0]} as {self.str_type})"
47
+ for e in exprs[1:]:
48
+ text = f"concat(concat({text}, '|'), cast({e} as {self.str_type}))"
49
+ return f"{self._bucket(text)} < {max(1, round(pct * 100))}"
50
+
51
+ def scalar(self, sql: str):
52
+ r = self.rows(sql)
53
+ return r[0][0] if r else None
54
+
55
+ def explain(self, sql: str) -> str:
56
+ return "\n".join(str(r[-1]) for r in self.rows("EXPLAIN " + sql))
57
+
58
+ def spill_report(self, hours: int = 24) -> list[dict]:
59
+ """Queries that spilled memory to disk (a sign of memory pressure)."""
60
+ return []
61
+
62
+ def memory_failures(self, hours: int = 24) -> list[dict]:
63
+ """Queries killed for lack of memory: [{source, scope, detail}] (empty if the engine does not expose them)."""
64
+ return []
65
+
66
+ def describe(self, rel: str) -> list[tuple[str, str]]:
67
+ """(column, type) of a relation."""
68
+ raise NotImplementedError
69
+
70
+ def plan(self, sql: str) -> dict:
71
+ """Plano estimado, sem executar: {operators: [...], max_rows: int|None, cost: float|None}."""
72
+ return {"operators": [], "max_rows": None, "cost": None}
73
+
74
+
75
+ class DuckDBWarehouse(Warehouse):
76
+ dialect, name = "duckdb", "duckdb"
77
+
78
+ def __init__(self, path: str, read_only: bool = True):
79
+ import duckdb
80
+ self.con = duckdb.connect(path, read_only=read_only)
81
+
82
+ def rows(self, sql):
83
+ return self.con.execute(sql).fetchall()
84
+
85
+ def describe(self, rel):
86
+ return [(r[0], str(r[1])) for r in self.rows(f"describe select * from {rel}")]
87
+
88
+ def plan(self, sql):
89
+ import json
90
+ raw = self.rows("EXPLAIN (FORMAT json) " + sql)[0][1]
91
+ ops, rows = [], []
92
+
93
+ def walk(n):
94
+ ops.append(n.get("name", ""))
95
+ ec = (n.get("extra_info") or {}).get("Estimated Cardinality")
96
+ if ec is not None:
97
+ try:
98
+ rows.append(int(str(ec).lstrip("~")))
99
+ except ValueError:
100
+ pass
101
+ for c in n.get("children", []):
102
+ walk(c)
103
+ for n in json.loads(raw):
104
+ walk(n)
105
+ return {"operators": ops, "max_rows": max(rows) if rows else None, "cost": None}
106
+
107
+ def memory(self) -> list[dict]:
108
+ return [dict(zip(("tag", "memory_bytes", "temp_bytes"), r[:3])) for r in self.rows(
109
+ "select tag, memory_usage_bytes, temporary_storage_bytes from duckdb_memory()")]
110
+
111
+
112
+ class PostgresWarehouse(Warehouse):
113
+ dialect, name = "postgres", "postgres"
114
+ def _bucket(self, text):
115
+ return f"abs(mod(hashtext({text}), 10000))"
116
+
117
+
118
+ def __init__(self, url_env: str = "INTENTFLOW_PG_URL"):
119
+ import psycopg2
120
+ url = os.environ.get(url_env)
121
+ if not url:
122
+ raise RuntimeError(tr("variable {name} is not set", name=url_env))
123
+ # bounded: a data diff or probe started from the UI must not hold the warehouse indefinitely
124
+ timeout_ms = int(float(os.environ.get("INTENTFLOW_WAREHOUSE_TIMEOUT_S", "300")) * 1000)
125
+ self.con = psycopg2.connect(url, connect_timeout=10, options=f"-c statement_timeout={timeout_ms}")
126
+ self.con.set_session(readonly=True, autocommit=True)
127
+
128
+ def rows(self, sql):
129
+ with self.con.cursor() as c:
130
+ c.execute(sql)
131
+ return c.fetchall() if c.description else []
132
+
133
+ def describe(self, rel):
134
+ with self.con.cursor() as c:
135
+ c.execute(f"select * from {rel} limit 0")
136
+ cols = [(d.name, d.type_code) for d in c.description]
137
+ c.execute("select oid, format_type(oid, null) from pg_type where oid = any(%s)", (list({t for _, t in cols}),))
138
+ names = dict(c.fetchall())
139
+ return [(n, names.get(t, str(t))) for n, t in cols] # type names, not OIDs, in the diff
140
+
141
+ def plan(self, sql):
142
+ import json
143
+ raw = self.rows("EXPLAIN (FORMAT JSON) " + sql)[0][0]
144
+ raw = raw if isinstance(raw, list) else json.loads(raw)
145
+ ops, rows, cost = [], [], []
146
+
147
+ def walk(n):
148
+ ops.append(n.get("Node Type", ""))
149
+ rows.append(int(n.get("Plan Rows", 0)))
150
+ cost.append(float(n.get("Total Cost", 0)))
151
+ for c in n.get("Plans", []):
152
+ walk(c)
153
+ walk(raw[0]["Plan"])
154
+ return {"operators": ops, "max_rows": max(rows) if rows else None, "cost": max(cost) if cost else None}
155
+
156
+ def spill_report(self, hours=24):
157
+ # pg_stat_database.temp_bytes: bytes written to temporary files (insufficient work_mem)
158
+ try:
159
+ r = self.rows("select datname, temp_files, temp_bytes from pg_stat_database where temp_bytes > 0 order by temp_bytes desc limit 20")
160
+ except Exception:
161
+ return []
162
+ return [{"source": "postgres", "scope": d, "spilled_bytes": int(b), "detail": tr("{n} temporary files", n=f)} for d, f, b in r]
163
+
164
+
165
+ TYPES = ("duckdb", "postgres", "redshift", "trino", "clickhouse", "mysql", "sqlserver", "athena", "snowflake", "bigquery", "databricks")
166
+
167
+
168
+ def connect(get) -> Warehouse | None:
169
+ """The configured warehouse. `get` reads settings (e.g. `store.get_setting`).
170
+ `warehouse.type` picks the engine; without it the old behavior applies (`warehouse.duckdb` or `warehouse.postgres_env`)."""
171
+ t = (get("warehouse.type") or "").lower()
172
+ duck, pg = get("warehouse.duckdb"), get("warehouse.postgres_env")
173
+ if not t:
174
+ t = "duckdb" if duck else "postgres" if pg else ""
175
+ if not t:
176
+ return None
177
+ if t == "duckdb":
178
+ if not duck:
179
+ raise RuntimeError(tr("warehouse.duckdb is not configured"))
180
+ return DuckDBWarehouse(duck)
181
+ if t == "postgres":
182
+ return PostgresWarehouse(pg or "INTENTFLOW_PG_URL")
183
+ if t in ("redshift", "trino", "clickhouse", "mysql", "sqlserver", "athena"):
184
+ from . import more
185
+ return {"redshift": lambda: more.RedshiftWarehouse(pg or "REDSHIFT_URL"), "trino": more.TrinoWarehouse,
186
+ "clickhouse": more.ClickHouseWarehouse, "mysql": more.MySQLWarehouse, "sqlserver": more.SQLServerWarehouse, "athena": more.AthenaWarehouse}[t]()
187
+ if t in ("snowflake", "bigquery", "databricks"):
188
+ from . import cloud
189
+ return {"snowflake": cloud.SnowflakeWarehouse, "bigquery": cloud.BigQueryWarehouse, "databricks": cloud.DatabricksWarehouse}[t]()
190
+ raise RuntimeError(tr("unknown warehouse.type: {type} (use one of {types})", type=t, types=", ".join(TYPES)))
@@ -0,0 +1,160 @@
1
+ """Cloud adapters (read-only). NOT exercised against real accounts in this repository:
2
+ the tests use fake connections. Credentials: environment variables; nothing is written to disk.
3
+
4
+ Snowflake : SNOWFLAKE_ACCOUNT, SNOWFLAKE_USER, SNOWFLAKE_PASSWORD, [SNOWFLAKE_WAREHOUSE, SNOWFLAKE_ROLE]
5
+ BigQuery : Google default credentials (GOOGLE_APPLICATION_CREDENTIALS), BIGQUERY_PROJECT
6
+ Databricks: DATABRICKS_HOST, DATABRICKS_HTTP_PATH, DATABRICKS_TOKEN
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from ..i18n import tr
11
+
12
+ import json
13
+ import os
14
+ import re
15
+
16
+ from . import Warehouse
17
+
18
+
19
+ def _env(*names):
20
+ miss = [n for n in names if not os.environ.get(n)]
21
+ if miss:
22
+ raise RuntimeError(tr("missing environment variables: {names}", names=", ".join(miss)))
23
+ return [os.environ[n] for n in names]
24
+
25
+
26
+ class SnowflakeWarehouse(Warehouse):
27
+ dialect, name = "snowflake", "snowflake"
28
+ SPILL_SQL = (
29
+ "select query_id, left(query_text, 200), bytes_spilled_to_local_storage, bytes_spilled_to_remote_storage "
30
+ "from snowflake.account_usage.query_history "
31
+ "where start_time > dateadd(hour, -{hours}, current_timestamp()) "
32
+ "and (bytes_spilled_to_local_storage > 0 or bytes_spilled_to_remote_storage > 0) "
33
+ "order by bytes_spilled_to_remote_storage desc, bytes_spilled_to_local_storage desc limit 50"
34
+ )
35
+
36
+ def __init__(self, connection=None):
37
+ if connection is None:
38
+ import snowflake.connector # type: ignore
39
+ acc, user, pw = _env("SNOWFLAKE_ACCOUNT", "SNOWFLAKE_USER", "SNOWFLAKE_PASSWORD")
40
+ connection = snowflake.connector.connect(account=acc, user=user, password=pw,
41
+ warehouse=os.environ.get("SNOWFLAKE_WAREHOUSE"), role=os.environ.get("SNOWFLAKE_ROLE"))
42
+ self.con = connection
43
+
44
+ def rows(self, sql):
45
+ cur = self.con.cursor()
46
+ try:
47
+ cur.execute(sql)
48
+ return cur.fetchall()
49
+ finally:
50
+ cur.close()
51
+
52
+ def describe(self, rel):
53
+ return [(r[0], str(r[1])) for r in self.rows(f"describe table {rel}")]
54
+
55
+ def plan(self, sql):
56
+ """`EXPLAIN USING JSON`: operations and estimated bytes (Snowflake does not estimate rows in the plan)."""
57
+ raw = self.rows("EXPLAIN USING JSON " + sql)[0][0]
58
+ doc = json.loads(raw) if isinstance(raw, str) else raw
59
+ ops = [o.get("operation", "") for o in doc.get("Operations", [[]])[0] if isinstance(o, dict)]
60
+ g = doc.get("GlobalStats") or {}
61
+ return {"operators": ops, "max_rows": None, "cost": float(g["bytesAssigned"]) if g.get("bytesAssigned") is not None else None}
62
+
63
+ def spill_report(self, hours=24):
64
+ return [{"source": "snowflake", "scope": qid, "spilled_bytes": int(loc or 0) + int(rem or 0),
65
+ "detail": f"local={loc} remoto={rem}: {txt}"} for qid, txt, loc, rem in self.rows(self.SPILL_SQL.format(hours=int(hours)))]
66
+
67
+
68
+ class BigQueryWarehouse(Warehouse):
69
+ dialect, name = "bigquery", "bigquery"
70
+ str_type = "string"
71
+
72
+ def _bucket(self, text):
73
+ return f"abs(mod(farm_fingerprint({text}), 10000))"
74
+
75
+
76
+ def quote(self, ident):
77
+ return "`" + ident.replace("`", "") + "`"
78
+ # BigQuery does not expose spill; the equivalent signal is resources exceeded
79
+ SPILL_SQL = (
80
+ "select job_id, left(query, 200), total_bytes_processed "
81
+ "from `region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT "
82
+ "where creation_time > timestamp_sub(current_timestamp(), interval {hours} hour) "
83
+ "and error_result.reason = 'resourcesExceeded' limit 50"
84
+ )
85
+
86
+ def __init__(self, client=None):
87
+ if client is None:
88
+ from google.cloud import bigquery # type: ignore
89
+ client = bigquery.Client(project=os.environ.get("BIGQUERY_PROJECT"))
90
+ self.client = client
91
+
92
+ def rows(self, sql):
93
+ return [tuple(r.values()) for r in self.client.query(sql).result()]
94
+
95
+ def describe(self, rel):
96
+ t = self.client.get_table(rel.replace("`", ""))
97
+ return [(f.name, f.field_type) for f in t.schema]
98
+
99
+ def plan(self, sql):
100
+ """Dry run: BigQuery reports the bytes that would be read (the basis of cost); there are no operators or estimated rows."""
101
+ from google.cloud import bigquery # type: ignore
102
+ job = self.client.query(sql, job_config=bigquery.QueryJobConfig(dry_run=True, use_query_cache=False))
103
+ return {"operators": [], "max_rows": None, "cost": float(job.total_bytes_processed or 0)}
104
+
105
+ def spill_report(self, hours=24):
106
+ region = os.environ.get("BIGQUERY_REGION", "us").lower() # `us`, `eu`, `southamerica-east1`, ...
107
+ return [{"source": "bigquery", "scope": jid, "spilled_bytes": int(b or 0), "detail": f"resourcesExceeded: {q}"}
108
+ for jid, q, b in self.rows(self.SPILL_SQL.format(hours=int(hours), region=region))]
109
+
110
+
111
+ class DatabricksWarehouse(Warehouse):
112
+ dialect, name = "databricks", "databricks"
113
+ str_type = "string"
114
+
115
+
116
+ def quote(self, ident):
117
+ return "`" + ident.replace("`", "") + "`"
118
+ SPILL_SQL = (
119
+ "select statement_id, left(statement_text, 200), spilled_local_bytes "
120
+ "from system.query.history "
121
+ "where start_time > current_timestamp() - interval {hours} hours and spilled_local_bytes > 0 "
122
+ "order by spilled_local_bytes desc limit 50"
123
+ )
124
+
125
+ def __init__(self, connection=None):
126
+ if connection is None:
127
+ from databricks import sql # type: ignore
128
+ host, path, tok = _env("DATABRICKS_HOST", "DATABRICKS_HTTP_PATH", "DATABRICKS_TOKEN")
129
+ connection = sql.connect(server_hostname=host, http_path=path, access_token=tok)
130
+ self.con = connection
131
+
132
+ def rows(self, sql):
133
+ with self.con.cursor() as c:
134
+ c.execute(sql)
135
+ return [tuple(r) for r in c.fetchall()]
136
+
137
+ def describe(self, rel):
138
+ out = []
139
+ for r in self.rows(f"describe table {rel}"):
140
+ if not r[0] or str(r[0]).startswith("#"): # end of the columns (partition/metadata block)
141
+ break
142
+ out.append((str(r[0]), str(r[1])))
143
+ return out
144
+
145
+ def plan(self, sql):
146
+ """`EXPLAIN COST`: physical plan operators and `rowCount`/`sizeInBytes` from the statistics."""
147
+ txt = "\n".join(str(r[0]) for r in self.rows("EXPLAIN COST " + sql))
148
+ ops = re.findall(r"^[\s:+\-|]*(?:\+- |:- )?([A-Z][A-Za-z]+(?:Exec)?)\b", txt, re.M)
149
+ rows = [int(float(m)) for m in re.findall(r"rowCount=(\d[\d.]*(?:E[+-]?\d+)?)", txt)]
150
+ size = [self._bytes(m) for m in re.findall(r"sizeInBytes=([\d.]+ ?[KMGT]?i?B)", txt)]
151
+ return {"operators": ops, "max_rows": max(rows) if rows else None, "cost": max(size) if size else None}
152
+
153
+ @staticmethod
154
+ def _bytes(s: str) -> float:
155
+ m = re.match(r"([\d.]+)\s*([KMGT]?)i?B", s)
156
+ return float(m.group(1)) * {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4}[m.group(2)] if m else 0.0
157
+
158
+ def spill_report(self, hours=24):
159
+ return [{"source": "databricks", "scope": sid, "spilled_bytes": int(b or 0), "detail": txt}
160
+ for sid, txt, b in self.rows(self.SPILL_SQL.format(hours=int(hours)))]