views-datafactory 1.9.0__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.
- datafactory_adapters/ARCHITECTURE.md +54 -0
- datafactory_adapters/__init__.py +38 -0
- datafactory_adapters/_conservation.py +95 -0
- datafactory_adapters/_reconciliation.py +92 -0
- datafactory_adapters/_validation.py +39 -0
- datafactory_adapters/feature_frame.py +25 -0
- datafactory_adapters/grid_from_feature_frame.py +89 -0
- datafactory_adapters/grid_to_country_month.py +169 -0
- datafactory_adapters/grid_to_dataframe.py +176 -0
- datafactory_compilation/ARCHITECTURE.md +63 -0
- datafactory_compilation/__init__.py +39 -0
- datafactory_compilation/aggregation.py +64 -0
- datafactory_compilation/compilation_config.py +97 -0
- datafactory_compilation/conservation.py +36 -0
- datafactory_compilation/grid_compilation.py +352 -0
- datafactory_compilation/output.py +85 -0
- datafactory_compilation/preflight.py +61 -0
- datafactory_compilation/pregridded_compilation.py +291 -0
- datafactory_consolidation/ARCHITECTURE.md +58 -0
- datafactory_consolidation/__init__.py +28 -0
- datafactory_consolidation/consolidation_result.py +27 -0
- datafactory_consolidation/consolidators/__init__.py +32 -0
- datafactory_consolidation/consolidators/acled.py +462 -0
- datafactory_consolidation/consolidators/ucdp.py +524 -0
- datafactory_consolidation/event_store.py +67 -0
- datafactory_consolidation/tagging.py +46 -0
- datafactory_harvester/ARCHITECTURE.md +103 -0
- datafactory_harvester/__init__.py +37 -0
- datafactory_harvester/event_validation.py +372 -0
- datafactory_harvester/harvest_runner.py +72 -0
- datafactory_harvester/pipeline_runner.py +125 -0
- datafactory_harvester/snapshot_storage.py +117 -0
- datafactory_harvester/sources/__init__.py +36 -0
- datafactory_harvester/sources/_ucdp_common.py +34 -0
- datafactory_harvester/sources/acled.py +743 -0
- datafactory_harvester/sources/gaul_admin.py +567 -0
- datafactory_harvester/sources/ghsbuilts.py +271 -0
- datafactory_harvester/sources/ghspop.py +267 -0
- datafactory_harvester/sources/priogrid_static.py +359 -0
- datafactory_harvester/sources/shdi.py +625 -0
- datafactory_harvester/sources/ucdp_annual.py +616 -0
- datafactory_harvester/sources/ucdp_candidate.py +419 -0
- datafactory_harvester/sources/ucdp_dot9.py +407 -0
- datafactory_harvester/sources/vdem.py +350 -0
- datafactory_harvester/validation.py +74 -0
- datafactory_http/__init__.py +10 -0
- datafactory_http/retry.py +102 -0
- datafactory_priogrid/ARCHITECTURE.md +62 -0
- datafactory_priogrid/__init__.py +51 -0
- datafactory_priogrid/cell_generator.py +137 -0
- datafactory_priogrid/grid_config.py +107 -0
- datafactory_priogrid/land_mask.py +62 -0
- datafactory_priogrid/parity_validation.py +176 -0
- datafactory_priogrid/shapefile_harvester.py +174 -0
- datafactory_priogrid/shapefile_reader.py +125 -0
- datafactory_priogrid/spatiotemporal.py +66 -0
- datafactory_priogrid/temporal_config.py +78 -0
- datafactory_priogrid/temporal_generator.py +65 -0
- datafactory_provenance/ARCHITECTURE.md +61 -0
- datafactory_provenance/__init__.py +81 -0
- datafactory_provenance/constants.py +3 -0
- datafactory_provenance/digests_and_ledgers.py +370 -0
- datafactory_provenance/health.py +310 -0
- datafactory_provenance/pipeline_lock.py +200 -0
- datafactory_provenance/registry.py +92 -0
- datafactory_provenance/skip.py +212 -0
- datafactory_provenance/source_registry.py +466 -0
- datafactory_query/ARCHITECTURE.md +60 -0
- datafactory_query/__init__.py +36 -0
- datafactory_query/africa_me_gaul_pgids.json +1 -0
- datafactory_query/africa_me_legacy_pgids.json +1 -0
- datafactory_query/backends_npy.py +90 -0
- datafactory_query/backends_zarr.py +259 -0
- datafactory_query/coverage.py +64 -0
- datafactory_query/dataset.py +263 -0
- datafactory_query/defaults.py +101 -0
- datafactory_query/land_gaul_pgids.json +1 -0
- datafactory_query/land_pgids.json +1 -0
- datafactory_query/output_format.py +52 -0
- datafactory_query/regions.py +293 -0
- datafactory_query/temporal.py +115 -0
- datafactory_viewpoint/ARCHITECTURE.md +68 -0
- datafactory_viewpoint/__init__.py +33 -0
- datafactory_viewpoint/builders/__init__.py +32 -0
- datafactory_viewpoint/builders/acled_v1.py +213 -0
- datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
- datafactory_viewpoint/builders/ghspop_v1.py +471 -0
- datafactory_viewpoint/builders/shdi_v1.py +389 -0
- datafactory_viewpoint/builders/ucdp_v1.py +437 -0
- datafactory_viewpoint/builders/vdem_v1.py +419 -0
- datafactory_viewpoint/profiles.py +169 -0
- datafactory_viewpoint/raster_io.py +49 -0
- datafactory_viewpoint/spatial_distribution.py +203 -0
- datafactory_viewpoint/spatial_weights.py +207 -0
- datafactory_viewpoint/survivorship.py +108 -0
- datafactory_viewpoint/temporal.py +111 -0
- datafactory_viewpoint/temporal_distribution.py +295 -0
- datafactory_viewpoint/viewpoint_config.py +124 -0
- datafactory_viewpoint/viewpoint_result.py +33 -0
- views_datafactory-1.9.0.dist-info/METADATA +528 -0
- views_datafactory-1.9.0.dist-info/RECORD +103 -0
- views_datafactory-1.9.0.dist-info/WHEEL +4 -0
- views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
"""Provenance tracking — content digests and JSONL ledger operations.
|
|
2
|
+
|
|
3
|
+
Every datafactory_* operation that produces output must record provenance.
|
|
4
|
+
This module provides the shared primitives. Each consuming module defines
|
|
5
|
+
its own entry structure (dict fields); this module handles serialization,
|
|
6
|
+
timestamping, and append.
|
|
7
|
+
|
|
8
|
+
No outbound imports to other datafactory_* packages.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import fcntl
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import tempfile
|
|
19
|
+
import time
|
|
20
|
+
from collections.abc import Iterator
|
|
21
|
+
from contextlib import contextmanager
|
|
22
|
+
from datetime import UTC, datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"compute_content_digest",
|
|
28
|
+
"compute_file_digest",
|
|
29
|
+
"append_ledger_entry",
|
|
30
|
+
"file_lock",
|
|
31
|
+
"last_digest",
|
|
32
|
+
"last_digest_for_version",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
# ---- Provenance infrastructure constants ----
|
|
38
|
+
# These define the ledger schema and digest scheme used across all modules.
|
|
39
|
+
# Change here = change everywhere. Bump LEDGER_VERSION when ledger schema changes.
|
|
40
|
+
|
|
41
|
+
LEDGER_VERSION: int = 1
|
|
42
|
+
DIGEST_ALGORITHM: str = "sha256"
|
|
43
|
+
DIGEST_TRUNCATE: int = 16
|
|
44
|
+
DIGEST_SCHEME: str = f"{DIGEST_ALGORITHM}_{DIGEST_TRUNCATE}"
|
|
45
|
+
|
|
46
|
+
# I/O buffer sizes — tune for throughput vs. memory tradeoff.
|
|
47
|
+
_FILE_CHUNK_SIZE: int = 65536 # 64 KB — file digest streaming reads
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def compute_content_digest(
|
|
51
|
+
data: bytes,
|
|
52
|
+
*,
|
|
53
|
+
algorithm: str = DIGEST_ALGORITHM,
|
|
54
|
+
truncate: int = DIGEST_TRUNCATE,
|
|
55
|
+
) -> str:
|
|
56
|
+
"""Compute a content digest from raw bytes.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
data: Raw bytes to hash. Caller is responsible for serialization.
|
|
60
|
+
algorithm: Hash algorithm name (passed to hashlib).
|
|
61
|
+
truncate: Number of hex characters to keep. 0 for full digest.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
Hex digest string, truncated to ``truncate`` characters.
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
TypeError: If data is not bytes.
|
|
68
|
+
"""
|
|
69
|
+
if not isinstance(data, bytes):
|
|
70
|
+
err_msg = f"data must be bytes, got {type(data).__name__}"
|
|
71
|
+
logger.error(err_msg)
|
|
72
|
+
raise TypeError(err_msg)
|
|
73
|
+
if truncate < 0:
|
|
74
|
+
err_msg = f"truncate must be >= 0, got {truncate}"
|
|
75
|
+
logger.error(err_msg)
|
|
76
|
+
raise ValueError(err_msg)
|
|
77
|
+
try:
|
|
78
|
+
h = hashlib.new(algorithm, data)
|
|
79
|
+
except ValueError:
|
|
80
|
+
err_msg = f"Unknown hash algorithm: {algorithm}"
|
|
81
|
+
logger.error(err_msg)
|
|
82
|
+
raise
|
|
83
|
+
hexdigest = h.hexdigest()
|
|
84
|
+
if truncate > 0:
|
|
85
|
+
return hexdigest[:truncate]
|
|
86
|
+
return hexdigest
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def compute_file_digest(
|
|
90
|
+
path: Path,
|
|
91
|
+
*,
|
|
92
|
+
algorithm: str = DIGEST_ALGORITHM,
|
|
93
|
+
truncate: int = DIGEST_TRUNCATE,
|
|
94
|
+
chunk_size: int = _FILE_CHUNK_SIZE,
|
|
95
|
+
) -> str:
|
|
96
|
+
"""Compute a content digest from a file without loading it all.
|
|
97
|
+
|
|
98
|
+
Reads the file in chunks to avoid doubling memory usage for
|
|
99
|
+
large files (e.g., 50MB+ Parquet stores).
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
path: Path to the file to hash.
|
|
103
|
+
algorithm: Hash algorithm name (passed to hashlib).
|
|
104
|
+
truncate: Number of hex characters to keep. 0 for full.
|
|
105
|
+
chunk_size: Bytes to read per iteration (default 64KB).
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
Hex digest string, truncated to ``truncate`` characters.
|
|
109
|
+
|
|
110
|
+
Raises:
|
|
111
|
+
FileNotFoundError: If the file does not exist.
|
|
112
|
+
"""
|
|
113
|
+
h = hashlib.new(algorithm)
|
|
114
|
+
with open(path, "rb") as f:
|
|
115
|
+
while chunk := f.read(chunk_size):
|
|
116
|
+
h.update(chunk)
|
|
117
|
+
hexdigest = h.hexdigest()
|
|
118
|
+
return hexdigest[:truncate] if truncate > 0 else hexdigest
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
_DEFAULT_LOCK_TIMEOUT: float = 60.0
|
|
122
|
+
_LOCK_POLL_INTERVAL: float = 0.1
|
|
123
|
+
_LOCK_WARN_SECONDS: float = 5.0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@contextmanager
|
|
127
|
+
def file_lock(
|
|
128
|
+
path: Path,
|
|
129
|
+
timeout: float = _DEFAULT_LOCK_TIMEOUT,
|
|
130
|
+
) -> Iterator[None]:
|
|
131
|
+
"""Advisory file lock via fcntl.flock with timeout.
|
|
132
|
+
|
|
133
|
+
Creates a .lock file alongside the target path and holds an
|
|
134
|
+
exclusive lock for the duration of the context. Other processes
|
|
135
|
+
using file_lock on the same path will block until the lock is
|
|
136
|
+
released or the timeout expires.
|
|
137
|
+
|
|
138
|
+
Crash safety comes from the kernel, not from heuristics: an
|
|
139
|
+
fcntl.flock dies with its holder, so a crashed process's lock
|
|
140
|
+
is releasable instantly and a live process's lock is never
|
|
141
|
+
stealable. The previous age-based "stale lock" deletion
|
|
142
|
+
(>300s) actively broke mutual exclusion — deleting a live
|
|
143
|
+
holder's lock file made the next acquirer flock a different
|
|
144
|
+
inode, so both held "the" lock (C-267, fired 2026-07-21 when
|
|
145
|
+
a 9-hour swap-bound export exceeded the age threshold).
|
|
146
|
+
Leftover .lock files from crashed holders are harmless: their
|
|
147
|
+
flock is gone, so acquisition succeeds immediately.
|
|
148
|
+
|
|
149
|
+
The lock file records the holder's PID for operator
|
|
150
|
+
diagnostics only — it is never interpreted programmatically.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
path: Path to the file being protected.
|
|
154
|
+
timeout: Maximum seconds to wait for lock acquisition.
|
|
155
|
+
Raises TimeoutError if exceeded.
|
|
156
|
+
"""
|
|
157
|
+
lock_path = path.with_suffix(path.suffix + ".lock")
|
|
158
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
159
|
+
|
|
160
|
+
with open(lock_path, "a+") as lock_file:
|
|
161
|
+
deadline = time.monotonic() + timeout
|
|
162
|
+
warned = False
|
|
163
|
+
while True:
|
|
164
|
+
try:
|
|
165
|
+
fcntl.flock(
|
|
166
|
+
lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB,
|
|
167
|
+
)
|
|
168
|
+
break
|
|
169
|
+
except BlockingIOError:
|
|
170
|
+
elapsed = timeout - (deadline - time.monotonic())
|
|
171
|
+
if not warned and elapsed >= _LOCK_WARN_SECONDS:
|
|
172
|
+
logger.warning(
|
|
173
|
+
"Waiting for lock on %s (%.1fs elapsed)",
|
|
174
|
+
lock_path,
|
|
175
|
+
elapsed,
|
|
176
|
+
)
|
|
177
|
+
warned = True
|
|
178
|
+
if time.monotonic() >= deadline:
|
|
179
|
+
msg = (
|
|
180
|
+
f"Timed out waiting for lock on "
|
|
181
|
+
f"{lock_path} after {timeout:.0f}s"
|
|
182
|
+
)
|
|
183
|
+
raise TimeoutError(msg) from None
|
|
184
|
+
time.sleep(_LOCK_POLL_INTERVAL)
|
|
185
|
+
try:
|
|
186
|
+
# Holder PID — diagnostics only, never interpreted.
|
|
187
|
+
lock_file.seek(0)
|
|
188
|
+
lock_file.truncate()
|
|
189
|
+
lock_file.write(str(os.getpid()))
|
|
190
|
+
lock_file.flush()
|
|
191
|
+
yield
|
|
192
|
+
finally:
|
|
193
|
+
fcntl.flock(lock_file, fcntl.LOCK_UN)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
_MAX_LEDGER_BYTES: int = 10 * 1024 * 1024 # 10 MB
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _rotate_ledger(ledger_path: Path) -> None:
|
|
200
|
+
"""Rotate ledger: current → .1, .1 → .2, etc. (max 9)."""
|
|
201
|
+
stem = ledger_path.stem
|
|
202
|
+
parent = ledger_path.parent
|
|
203
|
+
suffix = ledger_path.suffix
|
|
204
|
+
for i in range(9, 0, -1):
|
|
205
|
+
old = parent / f"{stem}.{i}{suffix}"
|
|
206
|
+
new_path = parent / f"{stem}.{i + 1}{suffix}"
|
|
207
|
+
if old.exists():
|
|
208
|
+
old.rename(new_path)
|
|
209
|
+
ledger_path.rename(parent / f"{stem}.1{suffix}")
|
|
210
|
+
logger.info("Rotated ledger %s (exceeded %d bytes)", ledger_path, _MAX_LEDGER_BYTES)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def append_ledger_entry(
|
|
214
|
+
ledger_path: Path,
|
|
215
|
+
entry: dict[str, Any],
|
|
216
|
+
) -> None:
|
|
217
|
+
"""Append a provenance entry to a JSONL ledger file.
|
|
218
|
+
|
|
219
|
+
Adds an ISO 8601 UTC timestamp to the entry automatically.
|
|
220
|
+
Creates parent directories if they don't exist.
|
|
221
|
+
Writes to a temp file before appending to reduce risk from
|
|
222
|
+
serialization failures. The ledger append itself is not atomic;
|
|
223
|
+
``_read_ledger_entries`` tolerates malformed trailing lines.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
ledger_path: Path to the JSONL ledger file.
|
|
227
|
+
entry: Dict of entry fields. Must be JSON-serializable.
|
|
228
|
+
|
|
229
|
+
Raises:
|
|
230
|
+
OSError: If the ledger file cannot be written.
|
|
231
|
+
TypeError: If entry contains non-serializable values.
|
|
232
|
+
"""
|
|
233
|
+
stamped = {
|
|
234
|
+
**entry,
|
|
235
|
+
"timestamp": datetime.now(tz=UTC).isoformat(),
|
|
236
|
+
}
|
|
237
|
+
try:
|
|
238
|
+
line = json.dumps(stamped, sort_keys=True) + "\n"
|
|
239
|
+
except TypeError as exc:
|
|
240
|
+
err_msg = f"Entry is not JSON-serializable: {exc}"
|
|
241
|
+
logger.error(err_msg)
|
|
242
|
+
raise
|
|
243
|
+
|
|
244
|
+
ledger_path.parent.mkdir(parents=True, exist_ok=True)
|
|
245
|
+
|
|
246
|
+
tmp_path: Path | None = None
|
|
247
|
+
try:
|
|
248
|
+
with tempfile.NamedTemporaryFile(
|
|
249
|
+
mode="w",
|
|
250
|
+
dir=ledger_path.parent,
|
|
251
|
+
delete=False,
|
|
252
|
+
suffix=".tmp",
|
|
253
|
+
) as tmp:
|
|
254
|
+
tmp.write(line)
|
|
255
|
+
tmp_path = Path(tmp.name)
|
|
256
|
+
|
|
257
|
+
with file_lock(ledger_path):
|
|
258
|
+
with open(ledger_path, "a") as ledger:
|
|
259
|
+
ledger.write(tmp_path.read_text())
|
|
260
|
+
|
|
261
|
+
# Rotate if ledger exceeds size threshold
|
|
262
|
+
if (
|
|
263
|
+
ledger_path.exists()
|
|
264
|
+
and ledger_path.stat().st_size > _MAX_LEDGER_BYTES
|
|
265
|
+
):
|
|
266
|
+
_rotate_ledger(ledger_path)
|
|
267
|
+
|
|
268
|
+
tmp_path.unlink()
|
|
269
|
+
except OSError as exc:
|
|
270
|
+
err_msg = (
|
|
271
|
+
f"Failed to write ledger entry to {ledger_path}: {exc}"
|
|
272
|
+
)
|
|
273
|
+
logger.error(err_msg)
|
|
274
|
+
if tmp_path is not None:
|
|
275
|
+
tmp_path.unlink(missing_ok=True)
|
|
276
|
+
raise
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _read_ledger_entries(ledger_path: Path) -> list[dict[str, Any]]:
|
|
280
|
+
"""Read all valid JSONL entries from a ledger file.
|
|
281
|
+
|
|
282
|
+
Skips malformed lines (e.g., partial writes from interrupted appends)
|
|
283
|
+
with a warning log.
|
|
284
|
+
"""
|
|
285
|
+
if not ledger_path.exists():
|
|
286
|
+
return []
|
|
287
|
+
|
|
288
|
+
entries: list[dict[str, Any]] = []
|
|
289
|
+
for i, line in enumerate(ledger_path.read_text().splitlines(), start=1):
|
|
290
|
+
line = line.strip()
|
|
291
|
+
if not line:
|
|
292
|
+
continue
|
|
293
|
+
try:
|
|
294
|
+
entries.append(json.loads(line))
|
|
295
|
+
except json.JSONDecodeError:
|
|
296
|
+
logger.warning("Skipping malformed ledger line %d in %s", i, ledger_path)
|
|
297
|
+
return entries
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
_VALID_CACHE_OUTCOMES: frozenset[str] = frozenset({
|
|
301
|
+
"success", "unchanged",
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def last_digest(
|
|
306
|
+
ledger_path: Path,
|
|
307
|
+
*,
|
|
308
|
+
digest_field: str = "content_digest",
|
|
309
|
+
) -> str | None:
|
|
310
|
+
"""Return the most recent content digest from a ledger.
|
|
311
|
+
|
|
312
|
+
Scans the ledger in reverse for the first entry with a valid
|
|
313
|
+
outcome. Accepted outcomes: "success", "unchanged", or absent
|
|
314
|
+
(backward compatibility). Skipped: "failed", "cached".
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
ledger_path: Path to the JSONL ledger file.
|
|
318
|
+
digest_field: Name of the digest field in ledger entries.
|
|
319
|
+
|
|
320
|
+
Returns:
|
|
321
|
+
The digest string, or None if the ledger is empty, missing,
|
|
322
|
+
or contains no entries with a valid outcome.
|
|
323
|
+
"""
|
|
324
|
+
if not ledger_path.exists():
|
|
325
|
+
return None
|
|
326
|
+
entries = _read_ledger_entries(ledger_path)
|
|
327
|
+
for entry in reversed(entries):
|
|
328
|
+
outcome = entry.get("outcome")
|
|
329
|
+
if outcome is not None and outcome not in _VALID_CACHE_OUTCOMES:
|
|
330
|
+
continue
|
|
331
|
+
digest: str | None = entry.get(digest_field)
|
|
332
|
+
if digest is not None:
|
|
333
|
+
return digest
|
|
334
|
+
return None
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def last_digest_for_version(
|
|
338
|
+
ledger_path: Path,
|
|
339
|
+
version: str,
|
|
340
|
+
*,
|
|
341
|
+
version_field: str = "version",
|
|
342
|
+
digest_field: str = "content_digest",
|
|
343
|
+
) -> str | None:
|
|
344
|
+
"""Return the most recent content digest for a successful version.
|
|
345
|
+
|
|
346
|
+
Scans the ledger in reverse for the first entry matching the
|
|
347
|
+
requested version with a non-failed outcome. Accepted outcomes:
|
|
348
|
+
"success", "unchanged", or absent (backward compatibility with
|
|
349
|
+
pre-outcome ledger entries). Skipped: "failed", "cached".
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
ledger_path: Path to the JSONL ledger file.
|
|
353
|
+
version: Version string to match.
|
|
354
|
+
version_field: Name of the version field in ledger entries.
|
|
355
|
+
digest_field: Name of the digest field in ledger entries.
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
The digest string, or None if no matching entry is found.
|
|
359
|
+
"""
|
|
360
|
+
entries = _read_ledger_entries(ledger_path)
|
|
361
|
+
for entry in reversed(entries):
|
|
362
|
+
if entry.get(version_field) != version:
|
|
363
|
+
continue
|
|
364
|
+
outcome = entry.get("outcome")
|
|
365
|
+
if outcome is not None and outcome not in _VALID_CACHE_OUTCOMES:
|
|
366
|
+
continue
|
|
367
|
+
digest: str | None = entry.get(digest_field)
|
|
368
|
+
if digest is not None:
|
|
369
|
+
return digest
|
|
370
|
+
return None
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""Health diagnostics — ledger freshness and SLO evaluation.
|
|
2
|
+
|
|
3
|
+
Read-only functions that assess pipeline health by inspecting
|
|
4
|
+
provenance ledgers and export metadata. Used by check_health.py
|
|
5
|
+
and available for programmatic monitoring.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from datafactory_provenance.source_registry import get_source_slo
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"FRESHNESS_SLO_HOURS",
|
|
18
|
+
"SOURCE_SLO",
|
|
19
|
+
"check_export_freshness",
|
|
20
|
+
"read_last_entries",
|
|
21
|
+
"report_ledger",
|
|
22
|
+
"verify_source_digest",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
# Freshness SLO: maximum acceptable age of exported data (ADR-018).
|
|
26
|
+
# Monthly pipeline runs on the 21st. 7 days (168h) allows one missed
|
|
27
|
+
# cycle before data is flagged as stale.
|
|
28
|
+
FRESHNESS_SLO_HOURS = 168
|
|
29
|
+
|
|
30
|
+
# Per-source freshness SLO (hours). Derived from the source registry
|
|
31
|
+
# (single source of truth). None = static (never stale from age).
|
|
32
|
+
SOURCE_SLO: dict[str, int | None] = get_source_slo()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _format_age(age_hours: float) -> str:
|
|
36
|
+
if age_hours < 48:
|
|
37
|
+
return f"{age_hours:.0f}h ago"
|
|
38
|
+
return f"{age_hours / 24:.0f}d ago"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def read_last_entries(
|
|
42
|
+
ledger_path: Path, n: int = 5
|
|
43
|
+
) -> list[dict]:
|
|
44
|
+
"""Read last N entries from a JSONL ledger."""
|
|
45
|
+
if not ledger_path.exists():
|
|
46
|
+
return []
|
|
47
|
+
lines = ledger_path.read_text().strip().splitlines()
|
|
48
|
+
entries = []
|
|
49
|
+
for line in reversed(lines):
|
|
50
|
+
line = line.strip()
|
|
51
|
+
if not line:
|
|
52
|
+
continue
|
|
53
|
+
try:
|
|
54
|
+
entries.append(json.loads(line))
|
|
55
|
+
except json.JSONDecodeError:
|
|
56
|
+
continue
|
|
57
|
+
if len(entries) >= n:
|
|
58
|
+
break
|
|
59
|
+
return entries
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _slo_label(slo_hours: int | None) -> str:
|
|
63
|
+
if slo_hours is None:
|
|
64
|
+
return "static"
|
|
65
|
+
if slo_hours >= 8760:
|
|
66
|
+
return f"{slo_hours // 8760}y"
|
|
67
|
+
if slo_hours >= 720:
|
|
68
|
+
return f"{slo_hours // 24}d"
|
|
69
|
+
return f"{slo_hours}h"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def report_ledger(
|
|
73
|
+
name: str,
|
|
74
|
+
ledger_path: Path,
|
|
75
|
+
now: datetime,
|
|
76
|
+
slo_hours: int | None = FRESHNESS_SLO_HOURS,
|
|
77
|
+
) -> dict:
|
|
78
|
+
"""Report health for one ledger.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
slo_hours : int | None
|
|
83
|
+
Maximum acceptable age in hours. ``None`` means the source is
|
|
84
|
+
static and never stale from age alone (only from missing data).
|
|
85
|
+
"""
|
|
86
|
+
entries = read_last_entries(ledger_path, n=10)
|
|
87
|
+
|
|
88
|
+
if not entries:
|
|
89
|
+
return {
|
|
90
|
+
"name": name,
|
|
91
|
+
"status": "NO DATA",
|
|
92
|
+
"detail": f"Ledger not found: {ledger_path}",
|
|
93
|
+
"slo": _slo_label(slo_hours),
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
# Find last success. Some ledgers (consolidation, viewpoint,
|
|
97
|
+
# compilation) don't have an "outcome" field — entries only
|
|
98
|
+
# exist for successful operations (failures raise exceptions).
|
|
99
|
+
last_success = None
|
|
100
|
+
for entry in entries:
|
|
101
|
+
outcome = entry.get("outcome")
|
|
102
|
+
if outcome is None or outcome in (
|
|
103
|
+
"success", "unchanged", "cached"
|
|
104
|
+
):
|
|
105
|
+
last_success = entry
|
|
106
|
+
break
|
|
107
|
+
|
|
108
|
+
# Find recent failures
|
|
109
|
+
recent_failures = [
|
|
110
|
+
e for e in entries
|
|
111
|
+
if e.get("outcome") == "failed"
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
if last_success:
|
|
115
|
+
ts_str = last_success.get("timestamp", "")
|
|
116
|
+
try:
|
|
117
|
+
ts = datetime.fromisoformat(ts_str)
|
|
118
|
+
age = now - ts
|
|
119
|
+
age_hours = age.total_seconds() / 3600
|
|
120
|
+
age_str = _format_age(age_hours)
|
|
121
|
+
except (ValueError, TypeError):
|
|
122
|
+
age_str = "unknown"
|
|
123
|
+
age_hours = -1
|
|
124
|
+
|
|
125
|
+
if age_hours < 0:
|
|
126
|
+
status = "STALE"
|
|
127
|
+
elif slo_hours is None:
|
|
128
|
+
status = "OK"
|
|
129
|
+
else:
|
|
130
|
+
status = "OK" if age_hours < slo_hours else "STALE"
|
|
131
|
+
|
|
132
|
+
detail = (
|
|
133
|
+
f"Last success: {ts_str[:19]} ({age_str})"
|
|
134
|
+
)
|
|
135
|
+
if recent_failures:
|
|
136
|
+
detail += (
|
|
137
|
+
f" | {len(recent_failures)} recent failures"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"name": name,
|
|
142
|
+
"status": status,
|
|
143
|
+
"detail": detail,
|
|
144
|
+
"slo": _slo_label(slo_hours),
|
|
145
|
+
"version": last_success.get("version", ""),
|
|
146
|
+
"digest": last_success.get(
|
|
147
|
+
"content_digest",
|
|
148
|
+
last_success.get("output_digest", ""),
|
|
149
|
+
),
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
"name": name,
|
|
154
|
+
"status": "FAILING",
|
|
155
|
+
"detail": (
|
|
156
|
+
f"No successful entries in last 10. "
|
|
157
|
+
f"{len(recent_failures)} failures."
|
|
158
|
+
),
|
|
159
|
+
"slo": _slo_label(slo_hours),
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def verify_source_digest(
|
|
164
|
+
source_path: Path,
|
|
165
|
+
recorded_digest: str,
|
|
166
|
+
*,
|
|
167
|
+
algorithm: str = "sha256",
|
|
168
|
+
truncate: int = 16,
|
|
169
|
+
) -> dict:
|
|
170
|
+
"""Verify a derived artifact's source digest matches the actual source.
|
|
171
|
+
|
|
172
|
+
Compares *recorded_digest* (stored in a derived artifact's
|
|
173
|
+
metadata) against the current content digest of *source_path*.
|
|
174
|
+
|
|
175
|
+
Returns dict with: match, actual_digest, recorded_digest, detail.
|
|
176
|
+
"""
|
|
177
|
+
from datafactory_provenance.digests_and_ledgers import (
|
|
178
|
+
compute_file_digest,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if not source_path.exists():
|
|
182
|
+
return {
|
|
183
|
+
"match": False,
|
|
184
|
+
"actual_digest": None,
|
|
185
|
+
"recorded_digest": recorded_digest,
|
|
186
|
+
"detail": f"Source file not found: {source_path}",
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
actual = compute_file_digest(
|
|
190
|
+
source_path, algorithm=algorithm, truncate=truncate,
|
|
191
|
+
)
|
|
192
|
+
match = actual == recorded_digest
|
|
193
|
+
if match:
|
|
194
|
+
detail = f"Digest match: {actual}"
|
|
195
|
+
else:
|
|
196
|
+
detail = (
|
|
197
|
+
f"Digest MISMATCH: source={actual}, "
|
|
198
|
+
f"recorded={recorded_digest}"
|
|
199
|
+
)
|
|
200
|
+
return {
|
|
201
|
+
"match": match,
|
|
202
|
+
"actual_digest": actual,
|
|
203
|
+
"recorded_digest": recorded_digest,
|
|
204
|
+
"detail": detail,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def check_export_freshness(
|
|
209
|
+
zarr_path: Path,
|
|
210
|
+
now: datetime,
|
|
211
|
+
provenance_path: Path | None = None,
|
|
212
|
+
) -> dict:
|
|
213
|
+
"""Check export timestamp and content freshness against SLO.
|
|
214
|
+
|
|
215
|
+
When *provenance_path* is provided (or defaults to
|
|
216
|
+
``zarr_path.parent / "provenance.json"``), also compares the
|
|
217
|
+
assembly digest against the zarr's recorded source digest.
|
|
218
|
+
"""
|
|
219
|
+
zattrs_path = zarr_path / ".zattrs"
|
|
220
|
+
if not zattrs_path.exists():
|
|
221
|
+
return {
|
|
222
|
+
"export_timestamp": None,
|
|
223
|
+
"export_age_hours": -1,
|
|
224
|
+
"export_slo_met": False,
|
|
225
|
+
"detail": f"No zarr store at {zarr_path}",
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
try:
|
|
229
|
+
attrs = json.loads(zattrs_path.read_text())
|
|
230
|
+
except (json.JSONDecodeError, OSError) as e:
|
|
231
|
+
return {
|
|
232
|
+
"export_timestamp": None,
|
|
233
|
+
"export_age_hours": -1,
|
|
234
|
+
"export_slo_met": False,
|
|
235
|
+
"detail": f"Cannot read .zattrs: {e}",
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
ts_str = attrs.get("export_timestamp")
|
|
239
|
+
if not ts_str:
|
|
240
|
+
return {
|
|
241
|
+
"export_timestamp": None,
|
|
242
|
+
"export_age_hours": -1,
|
|
243
|
+
"export_slo_met": False,
|
|
244
|
+
"detail": "export_timestamp missing from zarr attrs",
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
try:
|
|
248
|
+
ts = datetime.fromisoformat(ts_str)
|
|
249
|
+
age_hours = (now - ts).total_seconds() / 3600
|
|
250
|
+
except (ValueError, TypeError):
|
|
251
|
+
return {
|
|
252
|
+
"export_timestamp": ts_str,
|
|
253
|
+
"export_age_hours": -1,
|
|
254
|
+
"export_slo_met": False,
|
|
255
|
+
"detail": f"Cannot parse timestamp: {ts_str}",
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
slo_met = age_hours < FRESHNESS_SLO_HOURS
|
|
259
|
+
age_str = _format_age(age_hours)
|
|
260
|
+
|
|
261
|
+
# Data boundary: last month with real UCDP observations.
|
|
262
|
+
# UCDP releases around the 20th with data for the prior month,
|
|
263
|
+
# so expected minimum is (current_month - 2) to allow lag.
|
|
264
|
+
last_valid = attrs.get("last_valid_month_id")
|
|
265
|
+
expected_min = (now.year - 1980) * 12 + now.month - 2
|
|
266
|
+
data_boundary_current: bool | None = None
|
|
267
|
+
if last_valid is not None:
|
|
268
|
+
last_valid = int(last_valid)
|
|
269
|
+
data_boundary_current = last_valid >= expected_min
|
|
270
|
+
|
|
271
|
+
detail = (
|
|
272
|
+
f"Exported {ts_str[:19]} ({age_str})"
|
|
273
|
+
f" — SLO {FRESHNESS_SLO_HOURS}h: "
|
|
274
|
+
f"{'MET' if slo_met else 'BREACHED'}"
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
result: dict = {
|
|
278
|
+
"export_timestamp": ts_str,
|
|
279
|
+
"export_age_hours": round(age_hours, 1),
|
|
280
|
+
"export_slo_met": slo_met,
|
|
281
|
+
"last_valid_month_id": last_valid,
|
|
282
|
+
"data_boundary_current": data_boundary_current,
|
|
283
|
+
"detail": detail,
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
# Content-based staleness: compare assembly digest against
|
|
287
|
+
# the zarr's recorded source digest (C-255).
|
|
288
|
+
if provenance_path is None:
|
|
289
|
+
provenance_path = zarr_path.parent / "provenance.json"
|
|
290
|
+
zarr_digest = attrs.get("source_digest")
|
|
291
|
+
if provenance_path.exists() and zarr_digest:
|
|
292
|
+
try:
|
|
293
|
+
prov = json.loads(provenance_path.read_text())
|
|
294
|
+
prov_digest = prov.get("output_digest")
|
|
295
|
+
if prov_digest:
|
|
296
|
+
result["source_digest_match"] = (
|
|
297
|
+
prov_digest == zarr_digest
|
|
298
|
+
)
|
|
299
|
+
result["content_fresh"] = (
|
|
300
|
+
prov_digest == zarr_digest
|
|
301
|
+
)
|
|
302
|
+
if not result["content_fresh"]:
|
|
303
|
+
result["detail"] += (
|
|
304
|
+
" — CONTENT STALE: zarr source_digest "
|
|
305
|
+
"does not match assembly output_digest"
|
|
306
|
+
)
|
|
307
|
+
except (json.JSONDecodeError, OSError):
|
|
308
|
+
pass
|
|
309
|
+
|
|
310
|
+
return result
|