gannet-observability 0.0.1__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.
- gannet_observability/__init__.py +1 -0
- gannet_observability/build_report.py +273 -0
- gannet_observability/cli.py +28 -0
- gannet_observability/dbt_lineage.py +32 -0
- gannet_observability/local_source.py +42 -0
- gannet_observability/partition_continuity.py +105 -0
- gannet_observability/result.py +23 -0
- gannet_observability/results_file.py +71 -0
- gannet_observability/run.py +78 -0
- gannet_observability/s3_source.py +35 -0
- gannet_observability/sync.py +130 -0
- gannet_observability/synthetic.py +43 -0
- gannet_observability/upload.py +216 -0
- gannet_observability-0.0.1.dist-info/METADATA +45 -0
- gannet_observability-0.0.1.dist-info/RECORD +19 -0
- gannet_observability-0.0.1.dist-info/WHEEL +5 -0
- gannet_observability-0.0.1.dist-info/entry_points.txt +2 -0
- gannet_observability-0.0.1.dist-info/licenses/LICENSE +18 -0
- gannet_observability-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Gannet Observability: observability for data lakes, from names, counts and schemas only."""
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Build the report the dashboard reads from dbt's own files, with no dbt package.
|
|
2
|
+
|
|
3
|
+
python -m gannet_observability.build_report --manifest manifest.json \
|
|
4
|
+
--run-results run_results.json [more run_results.json ...] --out report.json
|
|
5
|
+
|
|
6
|
+
`manifest.json` says what exists (tables, tests, what depends on what). Each `run_results.json`
|
|
7
|
+
is one dbt run and says how every test and model did. dbt overwrites `run_results.json` on every
|
|
8
|
+
run, so give one file per run: the latest status of a test is its newest result, and the
|
|
9
|
+
history charts are one point per run. Standard library only.
|
|
10
|
+
|
|
11
|
+
The output has the shape of reportSchema in web/lib/report.ts (the report file the dashboard
|
|
12
|
+
reads), so the dashboard does not change. Only the fields listed here are copied: no SQL, no
|
|
13
|
+
compiled code, no failure messages, no sample rows.
|
|
14
|
+
|
|
15
|
+
Rules, checked on a real dbt project on 2026-12-06 against another tool's own report (tables,
|
|
16
|
+
monitored tables, table health, model runs and test counts were equal):
|
|
17
|
+
- A table is a model, seed, snapshot or source of the project. Packages in SKIP_PACKAGES
|
|
18
|
+
(other observability tools' own models) are tooling and left out.
|
|
19
|
+
- A test belongs to its attached table; if it has none, to its only table parent; if it has
|
|
20
|
+
several parents it belongs to no table and is listed under its own id.
|
|
21
|
+
- A test result needs status pass, warn, fail or error. A skipped test has no result.
|
|
22
|
+
- Only runs inside `days_back` days of `now` count, for the latest status and for history.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import json
|
|
29
|
+
import re
|
|
30
|
+
import sys
|
|
31
|
+
from datetime import datetime, timedelta, timezone
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from .dbt_lineage import KINDS, SKIP_PACKAGES, lineage_from_manifest
|
|
35
|
+
|
|
36
|
+
TABLE_KINDS = KINDS # source, seed, model, snapshot
|
|
37
|
+
TEST_STATUSES = {"pass", "warn", "fail", "error"}
|
|
38
|
+
# From the worst to the best: what a table's list in `filters` is checked in.
|
|
39
|
+
FILTER_STATUS = [("failures", "fail"), ("warnings", "warn"), ("errors", "error"), ("passed", "pass")]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def parse_time(text: str | None) -> datetime | None:
|
|
43
|
+
"""dbt writes `2026-12-05T17:21:52.194868Z`, sometimes with 9 fraction digits.
|
|
44
|
+
|
|
45
|
+
Python 3.10's fromisoformat takes neither the Z nor those, so both are fixed first.
|
|
46
|
+
"""
|
|
47
|
+
if not text:
|
|
48
|
+
return None
|
|
49
|
+
text = text.strip().replace("Z", "+00:00")
|
|
50
|
+
text = re.sub(r"\.(\d+)", lambda m: "." + (m.group(1) + "000000")[:6], text, count=1)
|
|
51
|
+
try:
|
|
52
|
+
parsed = datetime.fromisoformat(text)
|
|
53
|
+
except ValueError:
|
|
54
|
+
return None
|
|
55
|
+
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def iso(moment: datetime) -> str:
|
|
59
|
+
return moment.astimezone(timezone.utc).isoformat()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def own_tables(manifest: dict) -> dict[str, dict]:
|
|
63
|
+
tables: dict[str, dict] = {}
|
|
64
|
+
for section in ("sources", "nodes"):
|
|
65
|
+
for unique_id, node in manifest.get(section, {}).items():
|
|
66
|
+
if node.get("resource_type") in TABLE_KINDS and node.get("package_name") not in SKIP_PACKAGES:
|
|
67
|
+
tables[unique_id] = node
|
|
68
|
+
return tables
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def own_tests(manifest: dict) -> dict[str, dict]:
|
|
72
|
+
return {
|
|
73
|
+
unique_id: node
|
|
74
|
+
for unique_id, node in manifest.get("nodes", {}).items()
|
|
75
|
+
if node.get("resource_type") == "test" and node.get("package_name") not in SKIP_PACKAGES
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def table_of(test: dict, tables: dict[str, dict]) -> str | None:
|
|
80
|
+
"""The table a test belongs to. Several parents and no attached table: none."""
|
|
81
|
+
attached = test.get("attached_node")
|
|
82
|
+
if attached in tables:
|
|
83
|
+
return attached
|
|
84
|
+
parents = [parent for parent in test.get("depends_on", {}).get("nodes", []) if parent in tables]
|
|
85
|
+
return parents[0] if len(parents) == 1 else None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _owners(node: dict) -> list[str]:
|
|
89
|
+
owner = (node.get("meta") or {}).get("owner") or (node.get("config", {}).get("meta") or {}).get("owner")
|
|
90
|
+
if isinstance(owner, str):
|
|
91
|
+
return [part.strip() for part in owner.split(",") if part.strip()]
|
|
92
|
+
if isinstance(owner, list):
|
|
93
|
+
return [str(part) for part in owner]
|
|
94
|
+
return []
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _model_entry(node: dict) -> dict:
|
|
98
|
+
return {
|
|
99
|
+
"name": node.get("name"),
|
|
100
|
+
"table_name": node.get("alias") or node.get("identifier") or node.get("name"),
|
|
101
|
+
"database_name": node.get("database"),
|
|
102
|
+
"schema_name": node.get("schema"),
|
|
103
|
+
"normalized_full_path": node.get("original_file_path"),
|
|
104
|
+
# What the tree beside the test results is built from: where the file is, and a source's group.
|
|
105
|
+
"full_path": node.get("original_file_path"),
|
|
106
|
+
"source_name": node.get("source_name"),
|
|
107
|
+
"artifact_type": node.get("resource_type"),
|
|
108
|
+
"owners": _owners(node),
|
|
109
|
+
"tags": list(node.get("tags") or []),
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _result_time(result: dict, run: dict) -> datetime | None:
|
|
114
|
+
"""When the result happened: the end of its execute step, else when the file was written."""
|
|
115
|
+
for step in result.get("timing") or []:
|
|
116
|
+
if step.get("name") == "execute" and parse_time(step.get("completed_at")):
|
|
117
|
+
return parse_time(step.get("completed_at"))
|
|
118
|
+
return parse_time(run.get("metadata", {}).get("generated_at"))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _history(run_results: list[dict], wanted: set[str], statuses: set[str] | None, since: datetime) -> dict[str, list]:
|
|
122
|
+
"""unique_id -> [(time, status)], oldest first, inside the window."""
|
|
123
|
+
found: dict[str, list] = {}
|
|
124
|
+
for run in run_results:
|
|
125
|
+
for result in run.get("results", []):
|
|
126
|
+
unique_id, status = result.get("unique_id"), result.get("status")
|
|
127
|
+
if unique_id not in wanted or (statuses is not None and status not in statuses):
|
|
128
|
+
continue
|
|
129
|
+
moment = _result_time(result, run)
|
|
130
|
+
if moment is not None and moment >= since:
|
|
131
|
+
found.setdefault(unique_id, []).append((moment, status))
|
|
132
|
+
for points in found.values():
|
|
133
|
+
points.sort(key=lambda point: point[0])
|
|
134
|
+
return found
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def build_report(manifest: dict, run_results: list[dict], now: datetime, days_back: int = 7) -> dict:
|
|
138
|
+
since = now - timedelta(days=days_back)
|
|
139
|
+
tables = own_tables(manifest)
|
|
140
|
+
tests = own_tests(manifest)
|
|
141
|
+
test_history = _history(run_results, set(tests), TEST_STATUSES, since)
|
|
142
|
+
model_history = _history(
|
|
143
|
+
run_results, {key for key, node in tables.items() if node.get("resource_type") != "source"}, None, since
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
test_entries: dict[str, dict] = {}
|
|
147
|
+
test_results: dict[str, list] = {}
|
|
148
|
+
test_runs: dict[str, list] = {}
|
|
149
|
+
statuses_by_table: dict[str, set[str]] = {}
|
|
150
|
+
tested: set[str] = set()
|
|
151
|
+
for test_id in sorted(tests):
|
|
152
|
+
test = tests[test_id]
|
|
153
|
+
table_id = table_of(test, tables)
|
|
154
|
+
metadata = test.get("test_metadata")
|
|
155
|
+
name = metadata["name"] if metadata else test.get("name")
|
|
156
|
+
points = test_history.get(test_id, [])
|
|
157
|
+
latest_time, latest_status = points[-1] if points else (None, None)
|
|
158
|
+
entry = {
|
|
159
|
+
"unique_id": test_id,
|
|
160
|
+
"name": name,
|
|
161
|
+
"display_name": str(name).replace("_", " ").title(),
|
|
162
|
+
# Only "generic" or "singular": finer labels (row_count, freshness) are
|
|
163
|
+
# not in dbt's files, and the dashboard's categories do not need them.
|
|
164
|
+
"test_sub_type": "generic" if metadata else "singular",
|
|
165
|
+
"table_name": tables[table_id].get("name") if table_id else None,
|
|
166
|
+
"column_name": test.get("column_name"),
|
|
167
|
+
"latest_run_status": latest_status,
|
|
168
|
+
"latest_run_time_utc": iso(latest_time) if latest_time else None,
|
|
169
|
+
"model_unique_id": table_id,
|
|
170
|
+
# "tests/..." for a singular test, the yml file for a generic one: places it in the tree.
|
|
171
|
+
"original_path": test.get("original_file_path"),
|
|
172
|
+
}
|
|
173
|
+
test_entries[test_id] = entry
|
|
174
|
+
if table_id:
|
|
175
|
+
tested.add(table_id)
|
|
176
|
+
if not points:
|
|
177
|
+
continue
|
|
178
|
+
group = table_id or test_id
|
|
179
|
+
test_results.setdefault(group, []).append(
|
|
180
|
+
{
|
|
181
|
+
"metadata": {
|
|
182
|
+
"elementary_unique_id": test_id,
|
|
183
|
+
"test_unique_id": test_id,
|
|
184
|
+
"test_name": name,
|
|
185
|
+
"test_display_name": entry["display_name"],
|
|
186
|
+
"test_sub_type": entry["test_sub_type"],
|
|
187
|
+
"table_name": entry["table_name"],
|
|
188
|
+
"column_name": entry["column_name"],
|
|
189
|
+
"latest_run_status": latest_status,
|
|
190
|
+
"latest_run_time_utc": entry["latest_run_time_utc"],
|
|
191
|
+
"model_unique_id": table_id,
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
)
|
|
195
|
+
test_runs.setdefault(group, []).append(
|
|
196
|
+
{
|
|
197
|
+
"metadata": {"elementary_unique_id": test_id},
|
|
198
|
+
"test_runs": {"invocations": [{"time_utc": iso(moment), "status": status} for moment, status in points]},
|
|
199
|
+
}
|
|
200
|
+
)
|
|
201
|
+
if table_id:
|
|
202
|
+
statuses_by_table.setdefault(table_id, set()).add(latest_status)
|
|
203
|
+
|
|
204
|
+
table_ids = sorted(tables)
|
|
205
|
+
filters = [
|
|
206
|
+
{"name": name, "model_unique_ids": [key for key in table_ids if status in statuses_by_table.get(key, set())]}
|
|
207
|
+
for name, status in FILTER_STATUS
|
|
208
|
+
]
|
|
209
|
+
filters.append({"name": "no_test", "model_unique_ids": [key for key in table_ids if key not in tested]})
|
|
210
|
+
|
|
211
|
+
model_runs = []
|
|
212
|
+
for unique_id in sorted(model_history):
|
|
213
|
+
points = model_history[unique_id]
|
|
214
|
+
model_runs.append(
|
|
215
|
+
{
|
|
216
|
+
"unique_id": unique_id,
|
|
217
|
+
"status": points[-1][1],
|
|
218
|
+
"runs": [{"time_utc": iso(moment), "status": status} for moment, status in points],
|
|
219
|
+
}
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
lineage = lineage_from_manifest(manifest)
|
|
223
|
+
metadata = manifest.get("metadata", {})
|
|
224
|
+
newest_run = max(run_results, key=lambda run: run.get("metadata", {}).get("generated_at", ""), default={})
|
|
225
|
+
return {
|
|
226
|
+
"creation_time": iso(now),
|
|
227
|
+
"days_back": days_back,
|
|
228
|
+
"env": {
|
|
229
|
+
"project_name": metadata.get("project_name"),
|
|
230
|
+
"env": (newest_run.get("args") or {}).get("target"),
|
|
231
|
+
"warehouse_type": metadata.get("adapter_type"),
|
|
232
|
+
},
|
|
233
|
+
"models": {key: _model_entry(tables[key]) for key in table_ids},
|
|
234
|
+
"tests": test_entries,
|
|
235
|
+
"test_results": test_results,
|
|
236
|
+
"test_runs": test_runs,
|
|
237
|
+
"model_runs": model_runs,
|
|
238
|
+
"filters": {"test_results": filters},
|
|
239
|
+
"lineage": {
|
|
240
|
+
"nodes": [{"id": node["id"], "type": node["kind"]} for node in lineage["nodes"]],
|
|
241
|
+
# [node, the node it is built from]
|
|
242
|
+
"edges": [[edge["to"], edge["from"]] for edge in lineage["edges"]],
|
|
243
|
+
},
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def main(argv: list[str] | None = None) -> int:
|
|
248
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
249
|
+
parser.add_argument("--manifest", required=True, type=Path, help="the newest manifest.json")
|
|
250
|
+
parser.add_argument("--run-results", required=True, nargs="+", type=Path, help="one run_results.json per run")
|
|
251
|
+
parser.add_argument("--out", required=True, type=Path, help="where to write the report file")
|
|
252
|
+
parser.add_argument("--days-back", type=int, default=7)
|
|
253
|
+
parser.add_argument("--now", help="report time, ISO 8601 (default: now); for repeatable output")
|
|
254
|
+
args = parser.parse_args(argv)
|
|
255
|
+
|
|
256
|
+
manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
|
|
257
|
+
runs = [json.loads(path.read_text(encoding="utf-8")) for path in args.run_results]
|
|
258
|
+
now = parse_time(args.now) if args.now else datetime.now(timezone.utc)
|
|
259
|
+
if now is None:
|
|
260
|
+
parser.error("--now is not a date and time")
|
|
261
|
+
report = build_report(manifest, runs, now, args.days_back)
|
|
262
|
+
args.out.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")
|
|
263
|
+
|
|
264
|
+
results = [item["metadata"]["latest_run_status"] for group in report["test_results"].values() for item in group]
|
|
265
|
+
print(
|
|
266
|
+
f"Wrote {args.out}: {len(report['models'])} tables, {len(report['tests'])} tests "
|
|
267
|
+
f"({len(results)} with a result), {len(report['model_runs'])} models run, from {len(runs)} run file(s)."
|
|
268
|
+
)
|
|
269
|
+
return 0
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
if __name__ == "__main__":
|
|
273
|
+
sys.exit(main())
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The `gannet` command, installed by `pip install`. One command so far:
|
|
2
|
+
|
|
3
|
+
gannet upload send the report built from dbt's files in target/ to a Gannet environment
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import upload
|
|
9
|
+
|
|
10
|
+
USAGE = """usage: gannet upload [--target-dir target] [--report FILE] [--save-to FILE]
|
|
11
|
+
|
|
12
|
+
Set GANNET_TOKEN to the environment's upload token (Settings page), then run this in your dbt
|
|
13
|
+
project's folder after `dbt build`. Run `gannet upload --help` for the options."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv: list[str] | None = None) -> int:
|
|
17
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
18
|
+
if argv[:1] == ["upload"]:
|
|
19
|
+
return upload.main(argv[1:], prog="gannet upload")
|
|
20
|
+
if not argv or argv[0] in ("-h", "--help"):
|
|
21
|
+
print(USAGE)
|
|
22
|
+
return 0
|
|
23
|
+
print(f"Unknown command: {argv[0]}\n{USAGE}", file=sys.stderr)
|
|
24
|
+
return 2
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
sys.exit(main())
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Read what depends on what from dbt's manifest.json. Names and links only.
|
|
2
|
+
|
|
3
|
+
The manifest also holds SQL, descriptions and paths; none of that is copied.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
KINDS = {"source", "seed", "model", "snapshot"}
|
|
9
|
+
# Packages whose own models are tooling, not the user's data.
|
|
10
|
+
SKIP_PACKAGES = {"elementary"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def lineage_from_manifest(manifest: dict) -> dict:
|
|
14
|
+
"""Return {"nodes": [{id, name, kind}], "edges": [{from, to}]}, in a stable order."""
|
|
15
|
+
nodes: dict[str, dict] = {}
|
|
16
|
+
for section in ("sources", "nodes"):
|
|
17
|
+
for unique_id, node in manifest.get(section, {}).items():
|
|
18
|
+
kind = node.get("resource_type")
|
|
19
|
+
if kind in KINDS and node.get("package_name") not in SKIP_PACKAGES:
|
|
20
|
+
nodes[unique_id] = {"id": unique_id, "name": node["name"], "kind": kind}
|
|
21
|
+
|
|
22
|
+
edges = {
|
|
23
|
+
(parent, child)
|
|
24
|
+
for child, node in manifest.get("nodes", {}).items()
|
|
25
|
+
if child in nodes
|
|
26
|
+
for parent in node.get("depends_on", {}).get("nodes", [])
|
|
27
|
+
if parent in nodes
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
"nodes": [nodes[key] for key in sorted(nodes)],
|
|
31
|
+
"edges": [{"from": parent, "to": child} for parent, child in sorted(edges)],
|
|
32
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Source: list the days present in a local folder laid out like S3 prefixes.
|
|
2
|
+
|
|
3
|
+
A stand-in for listing S3, used with synthetic data. It looks at folder names
|
|
4
|
+
only (for example `dt=2026-11-03`) and never opens a file.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from datetime import date
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
# Strict YYYY-MM-DD. date.fromisoformat alone accepts more forms on Python 3.11+
|
|
14
|
+
# (such as 20261103), which would make the result depend on the Python version.
|
|
15
|
+
_DAY_PATTERN = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_day_folder(name: str, key: str) -> date | None:
|
|
19
|
+
"""Return the day in a folder name like `<key>=YYYY-MM-DD`, or None."""
|
|
20
|
+
prefix = f"{key}="
|
|
21
|
+
if not name.startswith(prefix):
|
|
22
|
+
return None
|
|
23
|
+
text = name[len(prefix):]
|
|
24
|
+
if not _DAY_PATTERN.fullmatch(text):
|
|
25
|
+
return None # not written as a day, so it is not ours to judge
|
|
26
|
+
try:
|
|
27
|
+
return date.fromisoformat(text)
|
|
28
|
+
except ValueError:
|
|
29
|
+
return None # written like a day but not one, such as 2026-13-45
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def list_partition_days(table_dir: Path | str, key: str = "dt") -> set[date]:
|
|
33
|
+
"""Return the days that have a `<key>=YYYY-MM-DD` folder holding a file."""
|
|
34
|
+
days: set[date] = set()
|
|
35
|
+
for child in Path(table_dir).iterdir():
|
|
36
|
+
day = parse_day_folder(child.name, key) if child.is_dir() else None
|
|
37
|
+
if day is None:
|
|
38
|
+
continue
|
|
39
|
+
# S3 has no empty folders: a prefix exists only if an object is under it.
|
|
40
|
+
if any(p.is_file() for p in child.rglob("*")):
|
|
41
|
+
days.add(day)
|
|
42
|
+
return days
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Check 1: did every expected day arrive?
|
|
2
|
+
|
|
3
|
+
Reads only partition names (days), never row values. This module is pure logic:
|
|
4
|
+
a source (a local folder now, S3 later) lists the days it found, and this module
|
|
5
|
+
says which expected days are missing. Daily partitions only for now; hourly
|
|
6
|
+
partitions come later.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Iterable
|
|
12
|
+
from datetime import date, datetime, timedelta, timezone
|
|
13
|
+
|
|
14
|
+
from .result import FAIL, PASS, CheckResult
|
|
15
|
+
|
|
16
|
+
CHECK_NAME = "partition_continuity"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def find_missing_days(
|
|
20
|
+
found: Iterable[date], first: date, last: date
|
|
21
|
+
) -> tuple[list[date], list[date]]:
|
|
22
|
+
"""Split the missing days from `first` to `last` (both included).
|
|
23
|
+
|
|
24
|
+
Returns (gaps, late). A gap is a missing day before the newest day found.
|
|
25
|
+
A late day is a missing day after it: the data has not caught up yet. If
|
|
26
|
+
nothing was found, every day comes back as late.
|
|
27
|
+
"""
|
|
28
|
+
found = set(found)
|
|
29
|
+
newest = max(found) if found else None
|
|
30
|
+
gaps: list[date] = []
|
|
31
|
+
late: list[date] = []
|
|
32
|
+
day = first
|
|
33
|
+
while day <= last:
|
|
34
|
+
if day not in found:
|
|
35
|
+
if newest is not None and day < newest:
|
|
36
|
+
gaps.append(day)
|
|
37
|
+
else:
|
|
38
|
+
late.append(day)
|
|
39
|
+
day += timedelta(days=1)
|
|
40
|
+
return gaps, late
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_partition_continuity(
|
|
44
|
+
table: str,
|
|
45
|
+
found_days: Iterable[date],
|
|
46
|
+
today: date,
|
|
47
|
+
*,
|
|
48
|
+
max_lag_days: int = 1,
|
|
49
|
+
first_expected_day: date | None = None,
|
|
50
|
+
run_at: datetime | None = None,
|
|
51
|
+
) -> CheckResult:
|
|
52
|
+
"""Judge whether every day from the first one to (today - max_lag_days) exists.
|
|
53
|
+
|
|
54
|
+
`first_expected_day` defaults to the oldest day found. Set it when you know
|
|
55
|
+
where the table's history should begin, so missing days at the start show up.
|
|
56
|
+
"""
|
|
57
|
+
run_at = run_at or datetime.now(timezone.utc)
|
|
58
|
+
found = set(found_days)
|
|
59
|
+
last = today - timedelta(days=max_lag_days)
|
|
60
|
+
|
|
61
|
+
def result(status: str, observed: str, expected: str, detail: str) -> CheckResult:
|
|
62
|
+
return CheckResult(
|
|
63
|
+
check=CHECK_NAME,
|
|
64
|
+
table=table,
|
|
65
|
+
run_at=run_at,
|
|
66
|
+
status=status,
|
|
67
|
+
observed=observed,
|
|
68
|
+
expected=expected,
|
|
69
|
+
detail=detail,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
if not found:
|
|
73
|
+
return result(FAIL, "0 days found", f"days up to {last}", "no partitions found")
|
|
74
|
+
|
|
75
|
+
first = first_expected_day or min(found)
|
|
76
|
+
newest = max(found)
|
|
77
|
+
expected = f"every day from {first} to {last}"
|
|
78
|
+
gaps, late = find_missing_days(found, first, last)
|
|
79
|
+
|
|
80
|
+
if not gaps and not late:
|
|
81
|
+
observed = f"{len(found)} days found, newest {newest}"
|
|
82
|
+
return result(PASS, observed, expected, "no missing days")
|
|
83
|
+
|
|
84
|
+
total = (last - first).days + 1
|
|
85
|
+
observed = f"{len(gaps) + len(late)} missing of {total} expected days, newest {newest}"
|
|
86
|
+
parts = []
|
|
87
|
+
if gaps:
|
|
88
|
+
parts.append(f"gaps: {_format_ranges(gaps)}")
|
|
89
|
+
if late:
|
|
90
|
+
parts.append(f"late: {_format_ranges(late)}")
|
|
91
|
+
return result(FAIL, observed, expected, "; ".join(parts))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _format_ranges(days: list[date]) -> str:
|
|
95
|
+
"""Turn sorted days into short ranges: '2026-11-03..2026-11-05, 2026-11-08'."""
|
|
96
|
+
ranges: list[tuple[date, date]] = []
|
|
97
|
+
start = prev = days[0]
|
|
98
|
+
for day in days[1:]:
|
|
99
|
+
if day == prev + timedelta(days=1):
|
|
100
|
+
prev = day
|
|
101
|
+
continue
|
|
102
|
+
ranges.append((start, prev))
|
|
103
|
+
start = prev = day
|
|
104
|
+
ranges.append((start, prev))
|
|
105
|
+
return ", ".join(str(a) if a == b else f"{a}..{b}" for a, b in ranges)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""The record every check produces: names and numbers only, never row values."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
PASS = "pass"
|
|
9
|
+
WARN = "warn"
|
|
10
|
+
FAIL = "fail"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class CheckResult:
|
|
15
|
+
"""One result per check, table and run (see docs/first-checks.md)."""
|
|
16
|
+
|
|
17
|
+
check: str # which check ran, for example "partition_continuity"
|
|
18
|
+
table: str # a table name only
|
|
19
|
+
run_at: datetime
|
|
20
|
+
status: str # PASS, WARN or FAIL
|
|
21
|
+
observed: str # short text, numbers and names only
|
|
22
|
+
expected: str # the range or rule the observed value was judged against
|
|
23
|
+
detail: str # short explanation, for example which days are missing
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Turn check output into the records the dashboard reads (docs/results-format.md)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import date, datetime, timedelta
|
|
6
|
+
|
|
7
|
+
from .partition_continuity import check_partition_continuity, find_missing_days
|
|
8
|
+
from .result import FAIL, WARN
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def iso(moment: datetime) -> str:
|
|
12
|
+
"""Write a UTC time the way the dashboard expects it."""
|
|
13
|
+
return moment.isoformat().replace("+00:00", "Z")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def partition_record(
|
|
17
|
+
table: str,
|
|
18
|
+
found: set[date],
|
|
19
|
+
today: date,
|
|
20
|
+
*,
|
|
21
|
+
run_at: datetime,
|
|
22
|
+
max_lag_days: int = 1,
|
|
23
|
+
first_expected_day: date | None = None,
|
|
24
|
+
) -> dict:
|
|
25
|
+
"""Run check 1 on the days found and return one record for the results file.
|
|
26
|
+
|
|
27
|
+
One proposed rule is applied on top of the check: missing days only at the end
|
|
28
|
+
(data that has not arrived) are a warning, a gap in the middle is a failure.
|
|
29
|
+
"""
|
|
30
|
+
result = check_partition_continuity(
|
|
31
|
+
table,
|
|
32
|
+
found,
|
|
33
|
+
today,
|
|
34
|
+
max_lag_days=max_lag_days,
|
|
35
|
+
first_expected_day=first_expected_day,
|
|
36
|
+
run_at=run_at,
|
|
37
|
+
)
|
|
38
|
+
record = {
|
|
39
|
+
"check": result.check,
|
|
40
|
+
"table": result.table,
|
|
41
|
+
"run_at": iso(run_at),
|
|
42
|
+
"status": result.status,
|
|
43
|
+
"observed": result.observed,
|
|
44
|
+
"expected": result.expected,
|
|
45
|
+
"detail": result.detail,
|
|
46
|
+
}
|
|
47
|
+
if not found:
|
|
48
|
+
return record # nothing to draw: the check already says no partitions
|
|
49
|
+
|
|
50
|
+
first = first_expected_day or min(found)
|
|
51
|
+
last = today - timedelta(days=max_lag_days)
|
|
52
|
+
gaps, late = find_missing_days(found, first, last)
|
|
53
|
+
missing = set(gaps) | set(late)
|
|
54
|
+
days = []
|
|
55
|
+
day = first
|
|
56
|
+
while day <= last:
|
|
57
|
+
state = "present" if day not in missing else ("gap" if day in gaps else "late")
|
|
58
|
+
days.append({"day": day.isoformat(), "state": state})
|
|
59
|
+
day += timedelta(days=1)
|
|
60
|
+
|
|
61
|
+
if result.status == FAIL and not gaps:
|
|
62
|
+
record["status"] = WARN
|
|
63
|
+
record["metrics"] = {
|
|
64
|
+
"expected_days": len(days),
|
|
65
|
+
"found_days": len(days) - len(missing),
|
|
66
|
+
"missing_days": len(missing),
|
|
67
|
+
"gap_days": len(gaps),
|
|
68
|
+
"late_days": len(late),
|
|
69
|
+
}
|
|
70
|
+
record["days"] = days
|
|
71
|
+
return record
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Run the partition check on S3 tables and write the results file.
|
|
2
|
+
|
|
3
|
+
Usage: python -m gannet_observability.run --settings settings.json --out results.json
|
|
4
|
+
|
|
5
|
+
The settings file names an AWS profile, never a key:
|
|
6
|
+
|
|
7
|
+
{"profile": "my-profile", "region": "us-east-1",
|
|
8
|
+
"tables": [{"table": "events", "bucket": "my-bucket", "prefix": "raw/events/",
|
|
9
|
+
"partition_key": "dt", "max_lag_days": 1, "first_day": null}]}
|
|
10
|
+
|
|
11
|
+
Optional: "dbt_manifest": "path/to/target/manifest.json" adds lineage (names and links
|
|
12
|
+
only) to the results file.
|
|
13
|
+
|
|
14
|
+
Keep the settings and results of a real system outside this repository.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
from datetime import date, datetime, timezone
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .dbt_lineage import lineage_from_manifest
|
|
26
|
+
from .results_file import iso, partition_record
|
|
27
|
+
from .s3_source import list_partition_days
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def build_payload(settings: dict, client: Any, now: datetime) -> dict:
|
|
31
|
+
"""Check every table in the settings. `now` is in UTC."""
|
|
32
|
+
results = []
|
|
33
|
+
for table in settings["tables"]:
|
|
34
|
+
found = list_partition_days(
|
|
35
|
+
client, table["bucket"], table["prefix"], table.get("partition_key", "dt")
|
|
36
|
+
)
|
|
37
|
+
first = table.get("first_day")
|
|
38
|
+
results.append(
|
|
39
|
+
partition_record(
|
|
40
|
+
table["table"],
|
|
41
|
+
found,
|
|
42
|
+
now.date(),
|
|
43
|
+
run_at=now,
|
|
44
|
+
max_lag_days=table.get("max_lag_days", 1),
|
|
45
|
+
first_expected_day=date.fromisoformat(first) if first else None,
|
|
46
|
+
)
|
|
47
|
+
)
|
|
48
|
+
return {"generated_at": iso(now), "source": "s3 listing", "results": results}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def main(argv: list[str] | None = None) -> None:
|
|
52
|
+
parser = argparse.ArgumentParser(description="Check S3 tables for missing days.")
|
|
53
|
+
parser.add_argument("--settings", required=True, type=Path)
|
|
54
|
+
parser.add_argument("--out", required=True, type=Path)
|
|
55
|
+
args = parser.parse_args(argv)
|
|
56
|
+
|
|
57
|
+
import boto3 # here so the tests run without it
|
|
58
|
+
|
|
59
|
+
# utf-8-sig: Windows editors may add a byte order mark.
|
|
60
|
+
settings = json.loads(args.settings.read_text(encoding="utf-8-sig"))
|
|
61
|
+
session = boto3.Session(
|
|
62
|
+
profile_name=settings.get("profile"), region_name=settings.get("region")
|
|
63
|
+
)
|
|
64
|
+
now = datetime.now(timezone.utc).replace(microsecond=0)
|
|
65
|
+
payload = build_payload(settings, session.client("s3"), now)
|
|
66
|
+
manifest = settings.get("dbt_manifest")
|
|
67
|
+
if manifest:
|
|
68
|
+
text = Path(manifest).read_text(encoding="utf-8")
|
|
69
|
+
payload["lineage"] = lineage_from_manifest(json.loads(text))
|
|
70
|
+
|
|
71
|
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
args.out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
|
73
|
+
for r in payload["results"]:
|
|
74
|
+
print(f"{r['table']}: {r['status']}. {r['observed']}. {r['detail']}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
if __name__ == "__main__":
|
|
78
|
+
main()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Source: list the days present under an S3 prefix.
|
|
2
|
+
|
|
3
|
+
Looks at folder names only, with ListObjectsV2. It never opens an object, so it
|
|
4
|
+
needs `s3:ListBucket` and nothing else.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from datetime import date
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .local_source import parse_day_folder
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def list_partition_days(
|
|
16
|
+
client: Any, bucket: str, prefix: str, key: str = "dt"
|
|
17
|
+
) -> set[date]:
|
|
18
|
+
"""Return the days that have a `<prefix><key>=YYYY-MM-DD/` folder.
|
|
19
|
+
|
|
20
|
+
`client` is a boto3 S3 client, or anything with the same paginator. S3 has no
|
|
21
|
+
real folders: a prefix appears when any object is under it, even an empty one.
|
|
22
|
+
"""
|
|
23
|
+
if prefix and not prefix.endswith("/"):
|
|
24
|
+
prefix += "/"
|
|
25
|
+
pages = client.get_paginator("list_objects_v2").paginate(
|
|
26
|
+
Bucket=bucket, Prefix=prefix, Delimiter="/"
|
|
27
|
+
)
|
|
28
|
+
days: set[date] = set()
|
|
29
|
+
for page in pages:
|
|
30
|
+
for entry in page.get("CommonPrefixes", []):
|
|
31
|
+
name = entry["Prefix"][len(prefix):].rstrip("/")
|
|
32
|
+
day = parse_day_folder(name, key)
|
|
33
|
+
if day is not None:
|
|
34
|
+
days.add(day)
|
|
35
|
+
return days
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""The core of Gannet's scheduled sync: read dbt's files from the customer's S3 and build the report.
|
|
2
|
+
|
|
3
|
+
The customer's pipeline copies dbt's two files after each run (the copy command on the Settings
|
|
4
|
+
page), each run into a folder of its own:
|
|
5
|
+
|
|
6
|
+
s3://<bucket>/<prefix>/<RUN>/manifest.json
|
|
7
|
+
s3://<bucket>/<prefix>/<RUN>/run_results.json <RUN> is YYYYMMDDTHHMMSSZ, in UTC
|
|
8
|
+
|
|
9
|
+
Every hour Gannet's job assumes the customer's read-only role and calls `sync_report` with an S3
|
|
10
|
+
client made from it. The report is built from every run inside the window, so the latest status of
|
|
11
|
+
each test is its newest result and the history charts have one point per run: what one upload of a
|
|
12
|
+
single `run_results.json` (`gannet upload`) cannot give.
|
|
13
|
+
|
|
14
|
+
Reads only, with `s3:ListBucket` on the folder and `s3:GetObject` on its files: the same two actions
|
|
15
|
+
the policy on the Settings page allows. Standard library only; `client` is a boto3 S3 client or
|
|
16
|
+
anything with `get_paginator("list_objects_v2")` and `get_object`. Nothing here touches AWS by
|
|
17
|
+
itself, so the tests run on a fake.
|
|
18
|
+
|
|
19
|
+
Not here yet: assuming the role, the schedule, storing the report. Those need Gannet's own AWS side.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from datetime import datetime, timedelta, timezone
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from .build_report import build_report
|
|
31
|
+
|
|
32
|
+
RUN_FOLDER = re.compile(r"^\d{8}T\d{6}Z$")
|
|
33
|
+
MAX_RUNS = 200 # an hourly pipeline for a week is 168; more would be slow to read every hour
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SyncError(Exception):
|
|
37
|
+
"""A plain message for the person (shown as the reason a check failed)."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class SyncResult:
|
|
42
|
+
report: dict
|
|
43
|
+
runs_read: int
|
|
44
|
+
runs_skipped: int # folders with a missing or unreadable run_results.json
|
|
45
|
+
newest_run: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def split_s3(uri: str) -> tuple[str, str]:
|
|
49
|
+
"""`s3://bucket/some/folder/` gives ("bucket", "some/folder/"); the folder ends with a slash or is empty."""
|
|
50
|
+
match = re.fullmatch(r"s3://([^/]+)(?:/(.*))?", uri.strip())
|
|
51
|
+
if not match:
|
|
52
|
+
raise SyncError(f"{uri!r} is not an S3 address such as s3://my-bucket/gannet-artifacts/")
|
|
53
|
+
prefix = (match.group(2) or "").strip("/")
|
|
54
|
+
return match.group(1), f"{prefix}/" if prefix else ""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _error_code(error: Exception) -> str:
|
|
58
|
+
return str(getattr(error, "response", {}).get("Error", {}).get("Code", ""))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def read_json(client: Any, bucket: str, key: str) -> dict | None:
|
|
62
|
+
"""The JSON in an object, or None when there is no such object or it is not JSON."""
|
|
63
|
+
try:
|
|
64
|
+
body = client.get_object(Bucket=bucket, Key=key)["Body"].read()
|
|
65
|
+
except Exception as error: # boto3's ClientError, not imported so the tests need no boto3
|
|
66
|
+
code = _error_code(error)
|
|
67
|
+
if code in ("NoSuchKey", "404"):
|
|
68
|
+
return None
|
|
69
|
+
raise SyncError(f"Could not read s3://{bucket}/{key} ({code or type(error).__name__}).") from error
|
|
70
|
+
try:
|
|
71
|
+
parsed = json.loads(body)
|
|
72
|
+
except ValueError:
|
|
73
|
+
return None
|
|
74
|
+
return parsed if isinstance(parsed, dict) else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def run_folders(client: Any, bucket: str, prefix: str) -> list[str]:
|
|
78
|
+
"""The run folders under `prefix`, oldest first. Anything else in there is ignored."""
|
|
79
|
+
names: list[str] = []
|
|
80
|
+
try:
|
|
81
|
+
pages = client.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix, Delimiter="/")
|
|
82
|
+
for page in pages:
|
|
83
|
+
for entry in page.get("CommonPrefixes", []):
|
|
84
|
+
name = entry["Prefix"][len(prefix):].rstrip("/")
|
|
85
|
+
if RUN_FOLDER.match(name):
|
|
86
|
+
names.append(name)
|
|
87
|
+
except Exception as error:
|
|
88
|
+
raise SyncError(f"Could not list s3://{bucket}/{prefix} ({_error_code(error) or type(error).__name__}).") from error
|
|
89
|
+
return sorted(names)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run_time(name: str) -> datetime:
|
|
93
|
+
return datetime.strptime(name, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def sync_report(client: Any, artifacts_location: str, now: datetime, days_back: int = 7) -> SyncResult:
|
|
97
|
+
"""The report built from every run folder inside `days_back` days of `now`. Raises SyncError."""
|
|
98
|
+
bucket, prefix = split_s3(artifacts_location)
|
|
99
|
+
since = now - timedelta(days=days_back)
|
|
100
|
+
folders = [name for name in run_folders(client, bucket, prefix) if run_time(name) >= since][-MAX_RUNS:]
|
|
101
|
+
if not folders:
|
|
102
|
+
raise SyncError(
|
|
103
|
+
f"No dbt runs in s3://{bucket}/{prefix} from the last {days_back} days. "
|
|
104
|
+
"Is the pipeline's copy step running after dbt?"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
runs, skipped = [], 0
|
|
108
|
+
for name in folders:
|
|
109
|
+
run = read_json(client, bucket, f"{prefix}{name}/run_results.json")
|
|
110
|
+
if run is None:
|
|
111
|
+
skipped += 1
|
|
112
|
+
else:
|
|
113
|
+
runs.append(run)
|
|
114
|
+
if not runs:
|
|
115
|
+
raise SyncError(f"The {len(folders)} run folder(s) in s3://{bucket}/{prefix} have no readable run_results.json.")
|
|
116
|
+
|
|
117
|
+
# The newest manifest that can be read says what exists now; an older run only matters for its results.
|
|
118
|
+
manifest = next(
|
|
119
|
+
(found for name in reversed(folders) if (found := read_json(client, bucket, f"{prefix}{name}/manifest.json"))),
|
|
120
|
+
None,
|
|
121
|
+
)
|
|
122
|
+
if manifest is None:
|
|
123
|
+
raise SyncError(f"No readable manifest.json in the run folders of s3://{bucket}/{prefix}.")
|
|
124
|
+
|
|
125
|
+
return SyncResult(
|
|
126
|
+
report=build_report(manifest, runs, now, days_back),
|
|
127
|
+
runs_read=len(runs),
|
|
128
|
+
runs_skipped=skipped,
|
|
129
|
+
newest_run=folders[-1],
|
|
130
|
+
)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Synthetic test data with known faults. No data from any real system.
|
|
2
|
+
|
|
3
|
+
Writes one folder per day, laid out like Hive-style S3 prefixes
|
|
4
|
+
(`events/dt=2026-11-03/`). Each folder holds one empty placeholder file, not real
|
|
5
|
+
Parquet: check 1 only reads names. Real Parquet arrives with the volume check.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from datetime import date, timedelta
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def generate_daily_table(
|
|
16
|
+
root: Path | str,
|
|
17
|
+
table: str,
|
|
18
|
+
start: date,
|
|
19
|
+
days: int,
|
|
20
|
+
*,
|
|
21
|
+
missing: Iterable[date] = (),
|
|
22
|
+
skip_last: int = 0,
|
|
23
|
+
key: str = "dt",
|
|
24
|
+
) -> Path:
|
|
25
|
+
"""Create `root/table/<key>=YYYY-MM-DD/` for `days` days starting at `start`.
|
|
26
|
+
|
|
27
|
+
Injected faults:
|
|
28
|
+
- `missing`: these days get no folder (a gap in the middle).
|
|
29
|
+
- `skip_last`: the newest N days get no folder (data that has not arrived yet).
|
|
30
|
+
|
|
31
|
+
Returns the table folder.
|
|
32
|
+
"""
|
|
33
|
+
missing_days = set(missing)
|
|
34
|
+
table_dir = Path(root) / table
|
|
35
|
+
table_dir.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
for i in range(days - skip_last):
|
|
37
|
+
day = start + timedelta(days=i)
|
|
38
|
+
if day in missing_days:
|
|
39
|
+
continue
|
|
40
|
+
partition = table_dir / f"{key}={day.isoformat()}"
|
|
41
|
+
partition.mkdir(exist_ok=True)
|
|
42
|
+
(partition / "part-0000.placeholder").touch()
|
|
43
|
+
return table_dir
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Send a report to a Gannet environment.
|
|
2
|
+
|
|
3
|
+
set GANNET_TOKEN to the environment's upload token, then, in the dbt project's folder,
|
|
4
|
+
after `dbt build` (or `dbt run` and `dbt test`):
|
|
5
|
+
|
|
6
|
+
gannet upload # reads target/manifest.json and target/run_results.json
|
|
7
|
+
|
|
8
|
+
The report is built here, on the engineer's machine, from those two files that dbt itself
|
|
9
|
+
writes (build_report.py): no dbt package and no AWS needed. Or send a report file that
|
|
10
|
+
already exists, in the same format:
|
|
11
|
+
|
|
12
|
+
gannet upload --report path/to/report.json
|
|
13
|
+
|
|
14
|
+
Only the fields the dashboard shows are sent: no SQL and no sample rows. `--save-to` writes
|
|
15
|
+
exactly what would be sent to a file, and sends nothing. Needs only the standard library.
|
|
16
|
+
(`python -m gannet_observability.upload` does the same as `gannet upload`.)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
import urllib.error
|
|
24
|
+
import urllib.request
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import datetime, timezone
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from urllib.parse import urlsplit
|
|
29
|
+
|
|
30
|
+
from .build_report import build_report
|
|
31
|
+
|
|
32
|
+
# Public: the function refuses a caller without a good token.
|
|
33
|
+
DEFAULT_URL = "https://jdqerefuxlbucapwxpdv.supabase.co/functions/v1/upload-report"
|
|
34
|
+
|
|
35
|
+
# What is sent: the same fields as reportSchema in web/lib/report.ts, which is all the
|
|
36
|
+
# dashboard reads. Change the two together (web/lib/report-upload.test.ts checks them).
|
|
37
|
+
# True keeps a value as it is; a dict keeps those keys; Record and Each apply a shape to
|
|
38
|
+
# every value of a mapping or every item of a list.
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Record:
|
|
43
|
+
shape: object
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Each:
|
|
48
|
+
shape: object
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _keys(*names):
|
|
52
|
+
return {name: True for name in names}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
_RUNS = Each(_keys("time_utc", "status"))
|
|
56
|
+
|
|
57
|
+
SHAPE = {
|
|
58
|
+
"creation_time": True,
|
|
59
|
+
"days_back": True,
|
|
60
|
+
"env": _keys("project_name", "env", "warehouse_type"),
|
|
61
|
+
"models": Record(
|
|
62
|
+
{
|
|
63
|
+
**_keys("name", "table_name", "database_name", "schema_name", "normalized_full_path"),
|
|
64
|
+
**_keys("full_path", "source_name"),
|
|
65
|
+
**_keys("artifact_type", "label", "owners", "tags"),
|
|
66
|
+
"meta": _keys("sub_type"),
|
|
67
|
+
}
|
|
68
|
+
),
|
|
69
|
+
"test_results": Record(
|
|
70
|
+
Each(
|
|
71
|
+
{
|
|
72
|
+
"metadata": _keys(
|
|
73
|
+
"elementary_unique_id",
|
|
74
|
+
"test_unique_id",
|
|
75
|
+
"test_name",
|
|
76
|
+
"test_display_name",
|
|
77
|
+
"test_sub_type",
|
|
78
|
+
"table_name",
|
|
79
|
+
"column_name",
|
|
80
|
+
"latest_run_status",
|
|
81
|
+
"latest_run_time_utc",
|
|
82
|
+
"model_unique_id",
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
)
|
|
86
|
+
),
|
|
87
|
+
# Every test, including those that run on no table. A file path, never the test's SQL.
|
|
88
|
+
"tests": Record(
|
|
89
|
+
_keys(
|
|
90
|
+
"unique_id",
|
|
91
|
+
"name",
|
|
92
|
+
"display_name",
|
|
93
|
+
"test_sub_type",
|
|
94
|
+
"table_name",
|
|
95
|
+
"column_name",
|
|
96
|
+
"latest_run_status",
|
|
97
|
+
"latest_run_time_utc",
|
|
98
|
+
"model_unique_id",
|
|
99
|
+
"original_path",
|
|
100
|
+
)
|
|
101
|
+
),
|
|
102
|
+
"test_runs": Record(
|
|
103
|
+
Each({"metadata": _keys("elementary_unique_id"), "test_runs": {"invocations": _RUNS}})
|
|
104
|
+
),
|
|
105
|
+
"model_runs": Each({"unique_id": True, "status": True, "runs": _RUNS}),
|
|
106
|
+
"filters": {"test_results": Each(_keys("name", "model_unique_ids"))},
|
|
107
|
+
"lineage": {"nodes": Each(_keys("id", "type")), "edges": True},
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def trim(value, shape=SHAPE):
|
|
112
|
+
"""Only the parts of `value` that `shape` names. A value of the wrong kind becomes
|
|
113
|
+
None, so nothing unnamed slips through."""
|
|
114
|
+
if shape is True:
|
|
115
|
+
return value
|
|
116
|
+
if isinstance(shape, Each):
|
|
117
|
+
return [trim(item, shape.shape) for item in value] if isinstance(value, list) else None
|
|
118
|
+
if not isinstance(value, dict):
|
|
119
|
+
return None
|
|
120
|
+
if isinstance(shape, Record):
|
|
121
|
+
return {key: trim(item, shape.shape) for key, item in value.items()}
|
|
122
|
+
return {key: trim(value[key], inner) for key, inner in shape.items() if key in value}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _is_safe(url: str) -> bool:
|
|
126
|
+
"""The token goes in a header, so only over HTTPS, or to this PC."""
|
|
127
|
+
parts = urlsplit(url)
|
|
128
|
+
return parts.scheme == "https" or (parts.scheme == "http" and parts.hostname in ("localhost", "127.0.0.1"))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def send(url: str, token: str, body: bytes) -> str:
|
|
132
|
+
"""Posts the report and gives its id. Raises RuntimeError with a plain message."""
|
|
133
|
+
request = urllib.request.Request(
|
|
134
|
+
url,
|
|
135
|
+
data=body,
|
|
136
|
+
method="POST",
|
|
137
|
+
headers={"Content-Type": "application/json", "x-gannet-token": token},
|
|
138
|
+
)
|
|
139
|
+
try:
|
|
140
|
+
with urllib.request.urlopen(request, timeout=60) as response:
|
|
141
|
+
return json.load(response)["report_id"]
|
|
142
|
+
except urllib.error.HTTPError as error:
|
|
143
|
+
try:
|
|
144
|
+
reason = json.load(error)["error"]
|
|
145
|
+
except (ValueError, KeyError, TypeError):
|
|
146
|
+
reason = error.reason
|
|
147
|
+
raise RuntimeError(f"Refused ({error.code}): {reason}") from error
|
|
148
|
+
except urllib.error.URLError as error:
|
|
149
|
+
raise RuntimeError(f"Could not reach Gannet: {error.reason}") from error
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def report_from_target(target: Path) -> dict:
|
|
153
|
+
"""The report built from dbt's two files in `target`. Raises ValueError with a plain message.
|
|
154
|
+
|
|
155
|
+
`run_results.json` is the last run only, so the report holds the tests of that run: run
|
|
156
|
+
`dbt build`, or the tests with the models, before uploading, to have every test in it.
|
|
157
|
+
"""
|
|
158
|
+
files = {}
|
|
159
|
+
for name in ("manifest.json", "run_results.json"):
|
|
160
|
+
path = target / name
|
|
161
|
+
try:
|
|
162
|
+
files[name] = json.loads(path.read_text(encoding="utf-8"))
|
|
163
|
+
except FileNotFoundError:
|
|
164
|
+
raise ValueError(f"{path} is missing. Run dbt first, in your dbt project's folder, or pass --target-dir.") from None
|
|
165
|
+
except (OSError, ValueError) as error:
|
|
166
|
+
raise ValueError(f"Could not read {path}: {error}") from error
|
|
167
|
+
return build_report(files["manifest.json"], [files["run_results.json"]], datetime.now(timezone.utc))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def main(argv=None, prog="python -m gannet_observability.upload") -> int:
|
|
171
|
+
parser = argparse.ArgumentParser(prog=prog, description="Send a report to a Gannet environment.")
|
|
172
|
+
source = parser.add_mutually_exclusive_group()
|
|
173
|
+
source.add_argument("--target-dir", default="target", type=Path, help="dbt's target folder (default: target)")
|
|
174
|
+
source.add_argument("--report", help="a report file in the dashboard's format, instead of dbt's files")
|
|
175
|
+
parser.add_argument("--url", default=os.environ.get("GANNET_UPLOAD_URL", DEFAULT_URL), help="where to send it")
|
|
176
|
+
parser.add_argument("--save-to", help="write what would be sent to this file, and send nothing")
|
|
177
|
+
args = parser.parse_args(argv)
|
|
178
|
+
|
|
179
|
+
if args.report:
|
|
180
|
+
try:
|
|
181
|
+
report = json.loads(Path(args.report).read_text(encoding="utf-8"))
|
|
182
|
+
except (OSError, ValueError) as error:
|
|
183
|
+
print(f"Could not read the report: {error}", file=sys.stderr)
|
|
184
|
+
return 1
|
|
185
|
+
else:
|
|
186
|
+
try:
|
|
187
|
+
report = report_from_target(args.target_dir)
|
|
188
|
+
except ValueError as error:
|
|
189
|
+
print(error, file=sys.stderr)
|
|
190
|
+
return 1
|
|
191
|
+
body = json.dumps(trim(report), separators=(",", ":")).encode("utf-8")
|
|
192
|
+
|
|
193
|
+
if args.save_to:
|
|
194
|
+
Path(args.save_to).write_bytes(body)
|
|
195
|
+
print(f"Wrote {len(body):,} bytes to {args.save_to}. Nothing was sent.")
|
|
196
|
+
return 0
|
|
197
|
+
|
|
198
|
+
token = os.environ.get("GANNET_TOKEN", "").strip()
|
|
199
|
+
if not token:
|
|
200
|
+
print("Set GANNET_TOKEN to the environment's upload token.", file=sys.stderr)
|
|
201
|
+
return 2
|
|
202
|
+
if not _is_safe(args.url):
|
|
203
|
+
print("The address must start with https://.", file=sys.stderr)
|
|
204
|
+
return 2
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
report_id = send(args.url, token, body)
|
|
208
|
+
except RuntimeError as error:
|
|
209
|
+
print(error, file=sys.stderr)
|
|
210
|
+
return 1
|
|
211
|
+
print(f"Sent {len(body):,} bytes. Report {report_id}.")
|
|
212
|
+
return 0
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
if __name__ == "__main__":
|
|
216
|
+
sys.exit(main())
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gannet-observability
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Observability for data lakes on AWS, from names, counts and schemas only. Early stage.
|
|
5
|
+
License: Proprietary. All rights reserved. See the LICENSE file.
|
|
6
|
+
Keywords: dbt,data observability,data quality,athena,glue
|
|
7
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: License :: Other/Proprietary License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Database
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Provides-Extra: s3
|
|
16
|
+
Requires-Dist: boto3; extra == "s3"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# gannet-observability
|
|
20
|
+
|
|
21
|
+
The small command that sends your dbt project's results to Gannet Observability. Early stage.
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
pip install gannet-observability
|
|
25
|
+
dbt build
|
|
26
|
+
GANNET_TOKEN=<your upload token> gannet upload
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Run `gannet upload` in your dbt project's folder, after each dbt run. Make the upload token in
|
|
30
|
+
your environment's Settings page in the Gannet Observability dashboard, and keep it in a secret
|
|
31
|
+
variable if you run this in a pipeline.
|
|
32
|
+
|
|
33
|
+
## What it does
|
|
34
|
+
|
|
35
|
+
It reads dbt's own `target/manifest.json` and `target/run_results.json` on your machine, builds a
|
|
36
|
+
report from them, and sends it over HTTPS. It sends names, statuses and times only: no SQL, no
|
|
37
|
+
failure messages, no sample rows and no table data. `gannet upload --save-to report.json` writes
|
|
38
|
+
exactly what would be sent to a file and sends nothing.
|
|
39
|
+
|
|
40
|
+
It needs Python 3.10 or newer and installs no other packages. It needs no AWS account and no dbt
|
|
41
|
+
package.
|
|
42
|
+
|
|
43
|
+
## Licence
|
|
44
|
+
|
|
45
|
+
Not open source. See the LICENSE file. No licence key is needed.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
gannet_observability/__init__.py,sha256=JlkJJIcME3cTbAYU8W4abtKAfD-MK2TNHrCiZG6ESQk,95
|
|
2
|
+
gannet_observability/build_report.py,sha256=VcNllnD-B7Umrglm-L8i_ydGfnp2OBqqswvAf9yynok,12422
|
|
3
|
+
gannet_observability/cli.py,sha256=LYci0rTJrsE-GaxZEZBVR1XO1rAW7jcX8ySCZ_ubFAU,880
|
|
4
|
+
gannet_observability/dbt_lineage.py,sha256=u86NyDmsE3Ye_7Sw2VneLWdK4qN2ZoETWxX1-VM2sKU,1218
|
|
5
|
+
gannet_observability/local_source.py,sha256=eNR43fZYUrrWDtHFR6dMmY5oGdIxb3cbAh_QaVHlSkg,1573
|
|
6
|
+
gannet_observability/partition_continuity.py,sha256=vtwximf7_LrCVN5n20zcIU1z99RCKgkwlm5jzpnOO08,3502
|
|
7
|
+
gannet_observability/result.py,sha256=vfPi851oNtvO6MVUnOsqqsHc54FSpZXfGGvn2VxXzms,716
|
|
8
|
+
gannet_observability/results_file.py,sha256=FBwagevjrcjvkVUV1DEPc6ObgEX1RmUxFcOB8cN4Zvw,2183
|
|
9
|
+
gannet_observability/run.py,sha256=J41sCilgX5KDbnfbdgjRvyJU7Fk2YHoOttrJtBaUVgQ,2890
|
|
10
|
+
gannet_observability/s3_source.py,sha256=xbMVOrmtdl6bGd_IreRyy0Pp8s6epG9HJeRC4sOkUSE,1130
|
|
11
|
+
gannet_observability/sync.py,sha256=q0riXT1xFG54BkPO9gTvnW_Jbao0XHdAzAUmKS4WiDg,5425
|
|
12
|
+
gannet_observability/synthetic.py,sha256=W8V70_9pn8sbCfBDcA44dQehcIC2URLjR1dDrsQmwQk,1345
|
|
13
|
+
gannet_observability/upload.py,sha256=erWfXw0vZsSeyD0ufeAMa7UrJzbj2dNRjmeriIKVBXY,8259
|
|
14
|
+
gannet_observability-0.0.1.dist-info/licenses/LICENSE,sha256=Gf-r-6Gb5ebZREZ7MFtUJo-BRU28QqAX1cvrOS6Vd3I,840
|
|
15
|
+
gannet_observability-0.0.1.dist-info/METADATA,sha256=AQ9RBioib5ANRicCb9hTJGTX8hEfTvcmSCPw2XW9UeA,1709
|
|
16
|
+
gannet_observability-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
gannet_observability-0.0.1.dist-info/entry_points.txt,sha256=THBtY_VKx_LzbjSFmOq_1hreuxf1055sqrXNLnrdPR0,57
|
|
18
|
+
gannet_observability-0.0.1.dist-info/top_level.txt,sha256=H91GNy1ie7rP5wvW54XZEdvohtyoZPIlvK-njXzboDw,21
|
|
19
|
+
gannet_observability-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Gannet Observability - client package licence (DRAFT, not yet reviewed by a lawyer)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the authors of Gannet Observability. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This package is not open source.
|
|
6
|
+
|
|
7
|
+
You may install it and run it, unchanged, for one purpose: to read your own dbt
|
|
8
|
+
project's files and send the results to a Gannet Observability environment that you
|
|
9
|
+
or your organisation have an account for.
|
|
10
|
+
|
|
11
|
+
You may not copy it, change it, redistribute it, sell it, rent it, or use it to
|
|
12
|
+
build a competing product or service, and you may not remove this notice.
|
|
13
|
+
|
|
14
|
+
The package is provided "as is", without warranty of any kind. The authors are not
|
|
15
|
+
liable for any damage that comes from using it.
|
|
16
|
+
|
|
17
|
+
This package does not need a licence key. Sending results needs an upload token,
|
|
18
|
+
which you make in your Gannet Observability environment's settings.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gannet_observability
|