gannet-observability 0.0.1__tar.gz

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 (31) hide show
  1. gannet_observability-0.0.1/LICENSE +18 -0
  2. gannet_observability-0.0.1/PKG-INFO +45 -0
  3. gannet_observability-0.0.1/README-package.md +27 -0
  4. gannet_observability-0.0.1/README.md +36 -0
  5. gannet_observability-0.0.1/pyproject.toml +33 -0
  6. gannet_observability-0.0.1/setup.cfg +4 -0
  7. gannet_observability-0.0.1/src/gannet_observability/__init__.py +1 -0
  8. gannet_observability-0.0.1/src/gannet_observability/build_report.py +273 -0
  9. gannet_observability-0.0.1/src/gannet_observability/cli.py +28 -0
  10. gannet_observability-0.0.1/src/gannet_observability/dbt_lineage.py +32 -0
  11. gannet_observability-0.0.1/src/gannet_observability/local_source.py +42 -0
  12. gannet_observability-0.0.1/src/gannet_observability/partition_continuity.py +105 -0
  13. gannet_observability-0.0.1/src/gannet_observability/result.py +23 -0
  14. gannet_observability-0.0.1/src/gannet_observability/results_file.py +71 -0
  15. gannet_observability-0.0.1/src/gannet_observability/run.py +78 -0
  16. gannet_observability-0.0.1/src/gannet_observability/s3_source.py +35 -0
  17. gannet_observability-0.0.1/src/gannet_observability/sync.py +130 -0
  18. gannet_observability-0.0.1/src/gannet_observability/synthetic.py +43 -0
  19. gannet_observability-0.0.1/src/gannet_observability/upload.py +216 -0
  20. gannet_observability-0.0.1/src/gannet_observability.egg-info/PKG-INFO +45 -0
  21. gannet_observability-0.0.1/src/gannet_observability.egg-info/SOURCES.txt +29 -0
  22. gannet_observability-0.0.1/src/gannet_observability.egg-info/dependency_links.txt +1 -0
  23. gannet_observability-0.0.1/src/gannet_observability.egg-info/entry_points.txt +2 -0
  24. gannet_observability-0.0.1/src/gannet_observability.egg-info/requires.txt +3 -0
  25. gannet_observability-0.0.1/src/gannet_observability.egg-info/top_level.txt +1 -0
  26. gannet_observability-0.0.1/tests/test_build_report.py +227 -0
  27. gannet_observability-0.0.1/tests/test_dbt_lineage.py +49 -0
  28. gannet_observability-0.0.1/tests/test_end_to_end.py +73 -0
  29. gannet_observability-0.0.1/tests/test_partition_continuity.py +81 -0
  30. gannet_observability-0.0.1/tests/test_s3_run.py +90 -0
  31. gannet_observability-0.0.1/tests/test_upload.py +212 -0
@@ -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,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,27 @@
1
+ # gannet-observability
2
+
3
+ The small command that sends your dbt project's results to Gannet Observability. Early stage.
4
+
5
+ ```
6
+ pip install gannet-observability
7
+ dbt build
8
+ GANNET_TOKEN=<your upload token> gannet upload
9
+ ```
10
+
11
+ Run `gannet upload` in your dbt project's folder, after each dbt run. Make the upload token in
12
+ your environment's Settings page in the Gannet Observability dashboard, and keep it in a secret
13
+ variable if you run this in a pipeline.
14
+
15
+ ## What it does
16
+
17
+ It reads dbt's own `target/manifest.json` and `target/run_results.json` on your machine, builds a
18
+ report from them, and sends it over HTTPS. It sends names, statuses and times only: no SQL, no
19
+ failure messages, no sample rows and no table data. `gannet upload --save-to report.json` writes
20
+ exactly what would be sent to a file and sends nothing.
21
+
22
+ It needs Python 3.10 or newer and installs no other packages. It needs no AWS account and no dbt
23
+ package.
24
+
25
+ ## Licence
26
+
27
+ Not open source. See the LICENSE file. No licence key is needed.
@@ -0,0 +1,36 @@
1
+ # Gannet Observability
2
+
3
+ Working name. Private, early stage. Work starts from a copy of Elementary's
4
+ open-source code (Apache-2.0, see `docs/credits.md`); nothing runs on AWS yet.
5
+
6
+ ## Idea
7
+
8
+ Observability for data lakes on AWS (Athena, Glue, S3, Iceberg): catch missing
9
+ partitions, abnormal volumes and schema changes using metadata and counts only,
10
+ with no row values read or stored.
11
+
12
+ The first three checks and the open questions are in `docs/first-checks.md`.
13
+
14
+ ## Where it comes from
15
+
16
+ A learning pipeline (Postgres to Parquet to S3 to Athena, then dbt and Airflow)
17
+ and a one-day trial of the open-source Elementary package on it. What was learned
18
+ is in `docs/elementary-walkthrough.md`.
19
+
20
+ ## Rules for this repo
21
+
22
+ - No data from any real system. Demos and tests use synthetic data.
23
+ - No credentials or keys.
24
+ - Not affiliated with Elementary, Boomi or dbt Labs. See `docs/credits.md`.
25
+
26
+ ## Folders
27
+
28
+ | Path | Holds |
29
+ |---|---|
30
+ | `docs/` | Design notes, credits |
31
+ | `src/elementary/`, `src/dbt-data-reliability/` | Our editable copy of Elementary's two repos, the starting point. Same folder layout and names as upstream |
32
+ | `src/gannet_observability/`, `tests/` | An early from-scratch experiment (check 1, partition continuity, and a synthetic data generator). Parked until we place it in the copied layout. Tests run with `python -m unittest` from the repo root |
33
+ | `scripts/` | `report_local.cmd` runs Elementary's report on the local DuckDB results, for testing only, and opens its page unchanged |
34
+ | `assets/branding/` | The Gannet logo used by our dashboard |
35
+ | `web/` | Our own dashboard (Next.js, Tailwind, shadcn). The design is ours; the counting rules are ported from Elementary's page (`docs/credits.md`). `npm run dev` there. Reads the `elementary_output.json` that `edr report` writes |
36
+ | `elementary/`, `dbt-data-reliability/` | Untouched local clones of Elementary's two repos, the reference to compare our copy against. Git-ignored, never part of this repo |
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "gannet-observability"
3
+ version = "0.0.1"
4
+ description = "Observability for data lakes on AWS, from names, counts and schemas only. Early stage."
5
+ readme = "README-package.md"
6
+ license = { text = "Proprietary. All rights reserved. See the LICENSE file." }
7
+ keywords = ["dbt", "data observability", "data quality", "athena", "glue"]
8
+ classifiers = [
9
+ "Development Status :: 2 - Pre-Alpha",
10
+ "Intended Audience :: Developers",
11
+ "License :: Other/Proprietary License",
12
+ "Programming Language :: Python :: 3",
13
+ "Topic :: Database",
14
+ ]
15
+ requires-python = ">=3.10"
16
+ # `gannet upload` needs only the standard library, so installing it pulls in nothing else
17
+ # (a dbt CI should not get boto3 for it). The parked missing-day check reads S3: `pip install .[s3]`.
18
+ dependencies = []
19
+
20
+ [project.optional-dependencies]
21
+ s3 = ["boto3"]
22
+
23
+ [project.scripts]
24
+ gannet = "gannet_observability.cli:main"
25
+
26
+ [build-system]
27
+ requires = ["setuptools>=68"]
28
+ build-backend = "setuptools.build_meta"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
32
+ # Only ours: src/ also holds the copies of Elementary's code, which must never be installed as a package.
33
+ include = ["gannet_observability*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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)