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,125 @@
|
|
|
1
|
+
"""Concrete shapefile readers for parity validation.
|
|
2
|
+
|
|
3
|
+
Each reader implements the ReferenceGeometryReader protocol defined in
|
|
4
|
+
validation.py. This module is the only place in datafactory_priogrid that
|
|
5
|
+
imports a shapefile library -- everything else stays dependency-free.
|
|
6
|
+
|
|
7
|
+
Current reader: PyShpReader (uses the pure-Python 'pyshp' package).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import shapefile # pyshp
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
# Known PRIO-GRID attribute field names (case-insensitive matching)
|
|
18
|
+
_ID_NAMES = {"gid", "pgid", "priogrid_gid", "cell_id"}
|
|
19
|
+
_LAT_NAMES = {"ycoord", "lat", "latitude", "y"}
|
|
20
|
+
_LON_NAMES = {"xcoord", "lon", "longitude", "x"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _find_field(fields: list[str], candidates: set[str]) -> str | None:
|
|
24
|
+
"""Find the first field name matching any candidate (case-insensitive)."""
|
|
25
|
+
lower_map = {f.lower(): f for f in fields}
|
|
26
|
+
for c in candidates:
|
|
27
|
+
if c.lower() in lower_map:
|
|
28
|
+
return lower_map[c.lower()]
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PyShpReader:
|
|
33
|
+
"""Read PRIO-GRID centroids from a shapefile using pyshp.
|
|
34
|
+
|
|
35
|
+
Expects the shapefile to contain attribute fields for cell ID,
|
|
36
|
+
latitude, and longitude (e.g. gid, ycoord, xcoord). Field names
|
|
37
|
+
are discovered automatically.
|
|
38
|
+
|
|
39
|
+
If centroid coordinate fields are absent, falls back to computing
|
|
40
|
+
centroids from polygon bounding boxes.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def read(self, path: Path) -> list[tuple[int, float, float]]:
|
|
44
|
+
"""Read reference centroids from a PRIO-GRID shapefile.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
path: Path to a .shp file or a directory containing one.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
List of (pgid, centroid_lat, centroid_lon) tuples.
|
|
51
|
+
"""
|
|
52
|
+
shp_path = self._resolve_shp(path)
|
|
53
|
+
logger.info("Reading shapefile: %s", shp_path)
|
|
54
|
+
|
|
55
|
+
with shapefile.Reader(str(shp_path)) as sf:
|
|
56
|
+
# Field names (skip the DeletionFlag field at index 0)
|
|
57
|
+
field_names = [f[0] for f in sf.fields[1:]]
|
|
58
|
+
logger.info("Shapefile fields: %s", field_names)
|
|
59
|
+
|
|
60
|
+
id_field = _find_field(field_names, _ID_NAMES)
|
|
61
|
+
lat_field = _find_field(field_names, _LAT_NAMES)
|
|
62
|
+
lon_field = _find_field(field_names, _LON_NAMES)
|
|
63
|
+
|
|
64
|
+
if id_field is None:
|
|
65
|
+
err_msg = (
|
|
66
|
+
f"No cell ID field found in {field_names}. "
|
|
67
|
+
f"Expected one of: {_ID_NAMES}"
|
|
68
|
+
)
|
|
69
|
+
logger.error(err_msg)
|
|
70
|
+
raise ValueError(err_msg)
|
|
71
|
+
|
|
72
|
+
use_geometry = lat_field is None or lon_field is None
|
|
73
|
+
if use_geometry:
|
|
74
|
+
logger.warning(
|
|
75
|
+
"Centroid fields not found (lat=%s, lon=%s). "
|
|
76
|
+
"Falling back to bounding-box centroids.",
|
|
77
|
+
lat_field,
|
|
78
|
+
lon_field,
|
|
79
|
+
)
|
|
80
|
+
else:
|
|
81
|
+
logger.info(
|
|
82
|
+
"Using fields: id=%s, lat=%s, lon=%s",
|
|
83
|
+
id_field,
|
|
84
|
+
lat_field,
|
|
85
|
+
lon_field,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
cells: list[tuple[int, float, float]] = []
|
|
89
|
+
|
|
90
|
+
for sr in sf.iterShapeRecords():
|
|
91
|
+
rec = sr.record
|
|
92
|
+
gid = int(rec[id_field])
|
|
93
|
+
|
|
94
|
+
if use_geometry:
|
|
95
|
+
bbox = sr.shape.bbox # (min_x, min_y, max_x, max_y)
|
|
96
|
+
lon = (bbox[0] + bbox[2]) / 2
|
|
97
|
+
lat = (bbox[1] + bbox[3]) / 2
|
|
98
|
+
else:
|
|
99
|
+
lat = float(rec[lat_field])
|
|
100
|
+
lon = float(rec[lon_field])
|
|
101
|
+
|
|
102
|
+
cells.append((gid, lat, lon))
|
|
103
|
+
|
|
104
|
+
logger.info("Read %d cells from shapefile", len(cells))
|
|
105
|
+
return cells
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def _resolve_shp(path: Path) -> Path:
|
|
109
|
+
"""Resolve path to the actual .shp file."""
|
|
110
|
+
if path.is_file() and path.suffix.lower() == ".shp":
|
|
111
|
+
return path
|
|
112
|
+
|
|
113
|
+
if path.is_dir():
|
|
114
|
+
shp_files = list(path.glob("*.shp"))
|
|
115
|
+
if len(shp_files) == 1:
|
|
116
|
+
return shp_files[0]
|
|
117
|
+
if len(shp_files) > 1:
|
|
118
|
+
# Prefer the one named 'priogrid'
|
|
119
|
+
for f in shp_files:
|
|
120
|
+
if "priogrid" in f.stem.lower():
|
|
121
|
+
return f
|
|
122
|
+
return shp_files[0]
|
|
123
|
+
raise FileNotFoundError(f"No .shp file found in {path}")
|
|
124
|
+
|
|
125
|
+
raise FileNotFoundError(f"Not a file or directory: {path}")
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Composed spatiotemporal index backbone.
|
|
2
|
+
|
|
3
|
+
Holds a spatial GridConfig and a TemporalConfig. Lazily generates
|
|
4
|
+
the coordinate arrays. This is the index that downstream data cubes
|
|
5
|
+
align to.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import functools
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from datafactory_priogrid.cell_generator import generate_grid
|
|
14
|
+
from datafactory_priogrid.grid_config import GridConfig
|
|
15
|
+
from datafactory_priogrid.temporal_config import TemporalConfig
|
|
16
|
+
from datafactory_priogrid.temporal_generator import generate_time_steps
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class SpatioTemporalGrid:
|
|
21
|
+
"""Spatiotemporal index composing a spatial grid and temporal range.
|
|
22
|
+
|
|
23
|
+
Neither config is modified -- the grid composes them as peers.
|
|
24
|
+
Coordinate arrays are generated lazily via cached_property.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
grid_config: GridConfig = field(default_factory=GridConfig)
|
|
28
|
+
temporal_config: TemporalConfig = field(default_factory=TemporalConfig)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def n_cells(self) -> int:
|
|
32
|
+
return self.grid_config.n_cells
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def n_steps(self) -> int:
|
|
36
|
+
return self.temporal_config.n_steps
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def shape(self) -> tuple[int, int]:
|
|
40
|
+
"""(n_cells, n_steps) -- the index dimensions for a data cube."""
|
|
41
|
+
return (self.n_cells, self.n_steps)
|
|
42
|
+
|
|
43
|
+
@functools.cached_property
|
|
44
|
+
def _spatial_arrays(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
45
|
+
"""Generate spatial arrays once, cache the triple."""
|
|
46
|
+
return generate_grid(self.grid_config)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def pgids(self) -> np.ndarray:
|
|
50
|
+
"""1-D int32 array of PRIO-GRID cell IDs."""
|
|
51
|
+
return self._spatial_arrays[0]
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def lats(self) -> np.ndarray:
|
|
55
|
+
"""1-D float64 array of cell centroid latitudes."""
|
|
56
|
+
return self._spatial_arrays[1]
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def lons(self) -> np.ndarray:
|
|
60
|
+
"""1-D float64 array of cell centroid longitudes."""
|
|
61
|
+
return self._spatial_arrays[2]
|
|
62
|
+
|
|
63
|
+
@functools.cached_property
|
|
64
|
+
def time_steps(self) -> np.ndarray:
|
|
65
|
+
"""1-D datetime64[M] array of monthly time steps."""
|
|
66
|
+
return generate_time_steps(self.temporal_config)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Temporal configuration for the PRIO-GRID spatiotemporal backbone."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class TemporalConfig:
|
|
13
|
+
"""Configuration for the temporal dimension of a spatiotemporal grid.
|
|
14
|
+
|
|
15
|
+
Stores start/end as plain integers (human-readable, serialisable).
|
|
16
|
+
Properties derive numpy datetime64[M] values and step counts.
|
|
17
|
+
|
|
18
|
+
The backbone representation is numpy.datetime64[M] -- standard,
|
|
19
|
+
resolution-aware, and free of arbitrary epoch conventions.
|
|
20
|
+
|
|
21
|
+
Validation uses month ordinals (year * 12 + month) solely to check
|
|
22
|
+
that start is not after end. This is NOT the VIEWS month_id
|
|
23
|
+
convention (which uses a 1980 epoch) -- see temporal_generator.py
|
|
24
|
+
for VIEWS month_id conversion.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
start_year: int = 1989
|
|
28
|
+
start_month: int = 1
|
|
29
|
+
end_year: int = 2026
|
|
30
|
+
end_month: int = 12
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
if self.start_year < 1:
|
|
34
|
+
err_msg = f"Year must be >= 1, got start_year={self.start_year}"
|
|
35
|
+
logger.error(err_msg)
|
|
36
|
+
raise ValueError(err_msg)
|
|
37
|
+
if self.end_year < 1:
|
|
38
|
+
err_msg = f"Year must be >= 1, got end_year={self.end_year}"
|
|
39
|
+
logger.error(err_msg)
|
|
40
|
+
raise ValueError(err_msg)
|
|
41
|
+
if not (1 <= self.start_month <= 12):
|
|
42
|
+
err_msg = f"Month must be in [1, 12], got start_month={self.start_month}"
|
|
43
|
+
logger.error(err_msg)
|
|
44
|
+
raise ValueError(err_msg)
|
|
45
|
+
if not (1 <= self.end_month <= 12):
|
|
46
|
+
err_msg = f"Month must be in [1, 12], got end_month={self.end_month}"
|
|
47
|
+
logger.error(err_msg)
|
|
48
|
+
raise ValueError(err_msg)
|
|
49
|
+
# Ordinal comparison: year * 12 + month gives a monotonic ordering
|
|
50
|
+
# for start-before-end validation. Not related to VIEWS month_id.
|
|
51
|
+
start_ordinal = self.start_year * 12 + self.start_month
|
|
52
|
+
end_ordinal = self.end_year * 12 + self.end_month
|
|
53
|
+
if start_ordinal > end_ordinal:
|
|
54
|
+
err_msg = (
|
|
55
|
+
f"start ({self.start_year}-{self.start_month:02d}) is after "
|
|
56
|
+
f"end ({self.end_year}-{self.end_month:02d})"
|
|
57
|
+
)
|
|
58
|
+
logger.error(err_msg)
|
|
59
|
+
raise ValueError(err_msg)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def start_dt(self) -> np.datetime64:
|
|
63
|
+
"""Start as numpy datetime64[M]."""
|
|
64
|
+
return np.datetime64(f"{self.start_year:04d}-{self.start_month:02d}", "M")
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def end_dt(self) -> np.datetime64:
|
|
68
|
+
"""End as numpy datetime64[M]."""
|
|
69
|
+
return np.datetime64(f"{self.end_year:04d}-{self.end_month:02d}", "M")
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def n_steps(self) -> int:
|
|
73
|
+
"""Total number of monthly time steps (inclusive)."""
|
|
74
|
+
return (
|
|
75
|
+
(self.end_year - self.start_year) * 12
|
|
76
|
+
+ (self.end_month - self.start_month)
|
|
77
|
+
+ 1
|
|
78
|
+
)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Temporal index generator -- pure numpy, same style as generator.py.
|
|
2
|
+
|
|
3
|
+
Generates a 1-D array of numpy datetime64[M] values representing
|
|
4
|
+
monthly time steps. Also provides adapter functions for the VIEWS
|
|
5
|
+
platform month_id convention.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from datafactory_priogrid.temporal_config import TemporalConfig
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
_VIEWS_EPOCH = np.datetime64("1980-01", "M")
|
|
16
|
+
|
|
17
|
+
DEFAULT_TEMPORAL_CONFIG = TemporalConfig()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def generate_time_steps(
|
|
21
|
+
config: TemporalConfig = DEFAULT_TEMPORAL_CONFIG,
|
|
22
|
+
) -> np.ndarray:
|
|
23
|
+
"""Generate monthly time step array for the configured range.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
1-D array of datetime64[M] values, length config.n_steps.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
start = config.start_dt
|
|
30
|
+
# np.arange end is exclusive, so add 1 month
|
|
31
|
+
end = config.end_dt + np.timedelta64(1, "M")
|
|
32
|
+
steps = np.arange(start, end, dtype="datetime64[M]")
|
|
33
|
+
|
|
34
|
+
logger.info(
|
|
35
|
+
"Generated %d time steps (%s to %s)",
|
|
36
|
+
len(steps),
|
|
37
|
+
config.start_dt,
|
|
38
|
+
config.end_dt,
|
|
39
|
+
)
|
|
40
|
+
return steps
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def to_views_month_id(dt: np.datetime64 | np.ndarray) -> np.ndarray:
|
|
44
|
+
"""Convert datetime64[M] to VIEWS month_id (int32).
|
|
45
|
+
|
|
46
|
+
VIEWS convention: month_id = (year - 1980) * 12 + month.
|
|
47
|
+
January 1980 = 1.
|
|
48
|
+
|
|
49
|
+
Note: Returns 0 for December 1979 and negative values for earlier
|
|
50
|
+
dates. If the VIEWS convention requires month_id >= 1, callers
|
|
51
|
+
should validate the result.
|
|
52
|
+
"""
|
|
53
|
+
dt = np.asarray(dt, dtype="datetime64[M]")
|
|
54
|
+
# Months since epoch (0-based), then +1 for 1-based VIEWS convention
|
|
55
|
+
offset = (dt - _VIEWS_EPOCH).astype(np.int32) + 1
|
|
56
|
+
return offset
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def from_views_month_id(month_id: int | np.ndarray) -> np.ndarray:
|
|
60
|
+
"""Convert VIEWS month_id (int) to datetime64[M].
|
|
61
|
+
|
|
62
|
+
Inverse of to_views_month_id.
|
|
63
|
+
"""
|
|
64
|
+
month_id = np.asarray(month_id, dtype=np.int32)
|
|
65
|
+
return _VIEWS_EPOCH + (month_id - 1).astype("timedelta64[M]")
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# datafactory_provenance -- Architecture
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
Provenance tracking — content digests and JSONL ledger operations. Every `datafactory_*` operation that produces output records provenance through this package. This is Layer 0 of the dependency DAG (ADR-012): every other `datafactory_*` package may import from provenance, but provenance imports nothing internal.
|
|
6
|
+
|
|
7
|
+
## Responsibility Boundary
|
|
8
|
+
|
|
9
|
+
**Owns:**
|
|
10
|
+
- Provenance ledger writing (JSONL append-only)
|
|
11
|
+
- Provenance ledger reading (last digest lookup, version-filtered queries)
|
|
12
|
+
- Content digest computation (SHA-256, truncated hex)
|
|
13
|
+
- Infrastructure constants (LEDGER_VERSION, DIGEST_SCHEME)
|
|
14
|
+
- Version declaration
|
|
15
|
+
|
|
16
|
+
**Does NOT own:**
|
|
17
|
+
- Grid coordinate generation (datafactory_priogrid)
|
|
18
|
+
- Data fetching or API interaction (datafactory_harvester)
|
|
19
|
+
- Consolidation logic (datafactory_consolidation)
|
|
20
|
+
- Viewpoint building (datafactory_viewpoint)
|
|
21
|
+
- Compilation logic (datafactory_compilation)
|
|
22
|
+
- Domain-specific configuration (each package owns its own config)
|
|
23
|
+
- I/O beyond provenance ledger append and digest computation
|
|
24
|
+
|
|
25
|
+
## Dependency Rules
|
|
26
|
+
|
|
27
|
+
Per ADR-012 (topology and dependency direction):
|
|
28
|
+
|
|
29
|
+
**May import:** Python standard library, numpy
|
|
30
|
+
**Must never import:** Any other `datafactory_*` package
|
|
31
|
+
|
|
32
|
+
## Key Concepts
|
|
33
|
+
|
|
34
|
+
| Concept | Description |
|
|
35
|
+
|---------|-------------|
|
|
36
|
+
| `append_ledger_entry` | JSONL append-only writer. Auto-generates UTC timestamp. Caller defines entry structure. |
|
|
37
|
+
| `last_digest` / `last_digest_for_version` | Ledger readers for digest lookup. Tolerate malformed trailing lines. |
|
|
38
|
+
| `compute_content_digest` | SHA-256 digest computation, truncated to 16 hex chars by default. Deterministic: same bytes = same digest. |
|
|
39
|
+
| `LEDGER_VERSION` | Centralized constant for ledger schema version. Bump when ledger entry format changes. |
|
|
40
|
+
| `DIGEST_SCHEME` | Centralized constant (`"sha256_16"`) recorded in every ledger entry for forward compatibility. |
|
|
41
|
+
|
|
42
|
+
## Invariants
|
|
43
|
+
- **Single-writer access assumed.** No concurrent operations supported (see technical_risk_register_resolved.md C-16)
|
|
44
|
+
|
|
45
|
+
- Zero imports from any other `datafactory_*` package (ADR-012, Layer 0)
|
|
46
|
+
- All public symbols declared in `__all__` (ADR-001)
|
|
47
|
+
- Provenance ledger entries are append-only; existing entries are never modified or deleted
|
|
48
|
+
- Content digest computation is deterministic: same input = same digest regardless of call order
|
|
49
|
+
- All configuration validation raises on failure; no silent fallbacks (ADR-003)
|
|
50
|
+
|
|
51
|
+
## CIC Stubs
|
|
52
|
+
|
|
53
|
+
### ProvenanceLedger
|
|
54
|
+
**Purpose:** Append structured JSONL entries to ledger files for harvest, consolidation, viewpoint, and compilation operations.
|
|
55
|
+
**Non-goals:** Does not query, aggregate, or visualize ledger data. Does not validate that referenced source files exist.
|
|
56
|
+
**Key guarantees:** Entries are always appended (never overwritten). Every entry includes an auto-generated UTC timestamp. Entry structure is caller-defined. Failure to write is both logged and raised (ADR-008).
|
|
57
|
+
|
|
58
|
+
### ContentDigest
|
|
59
|
+
**Purpose:** Compute SHA-256 content digests for data files and configuration snapshots to enable staleness detection and provenance verification.
|
|
60
|
+
**Non-goals:** Does not store or cache digests. Does not compare digests (that's the caller's responsibility).
|
|
61
|
+
**Key guarantees:** Deterministic: same bytes = same digest. Callers are responsible for consistent serialization order. Returns truncated hex string (16 chars by default). Raises on invalid input (ADR-008).
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Provenance tracking — content digests and JSONL ledger operations.
|
|
2
|
+
|
|
3
|
+
Every datafactory_* operation that produces output records provenance here.
|
|
4
|
+
No outbound imports to other datafactory_* packages.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from datafactory_provenance.constants import VIEWS_EPOCH_YEAR
|
|
8
|
+
from datafactory_provenance.digests_and_ledgers import (
|
|
9
|
+
DIGEST_SCHEME,
|
|
10
|
+
LEDGER_VERSION,
|
|
11
|
+
append_ledger_entry,
|
|
12
|
+
compute_content_digest,
|
|
13
|
+
compute_file_digest,
|
|
14
|
+
file_lock,
|
|
15
|
+
last_digest,
|
|
16
|
+
last_digest_for_version,
|
|
17
|
+
)
|
|
18
|
+
from datafactory_provenance.health import (
|
|
19
|
+
FRESHNESS_SLO_HOURS,
|
|
20
|
+
SOURCE_SLO,
|
|
21
|
+
check_export_freshness,
|
|
22
|
+
read_last_entries,
|
|
23
|
+
report_ledger,
|
|
24
|
+
verify_source_digest,
|
|
25
|
+
)
|
|
26
|
+
from datafactory_provenance.pipeline_lock import (
|
|
27
|
+
PIPELINE_LOCK_PATH,
|
|
28
|
+
PipelineLockHeldError,
|
|
29
|
+
hold_pipeline_lock,
|
|
30
|
+
pipeline_lock,
|
|
31
|
+
)
|
|
32
|
+
from datafactory_provenance.registry import Registry
|
|
33
|
+
from datafactory_provenance.skip import (
|
|
34
|
+
SkipVerdict,
|
|
35
|
+
check_assembly_skip,
|
|
36
|
+
check_export_skip,
|
|
37
|
+
)
|
|
38
|
+
from datafactory_provenance.source_registry import (
|
|
39
|
+
PIPELINE_SOURCES,
|
|
40
|
+
SourceEntry,
|
|
41
|
+
get_all_features,
|
|
42
|
+
get_required_env_vars,
|
|
43
|
+
get_source_slo,
|
|
44
|
+
validate_preflight,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"DIGEST_SCHEME",
|
|
49
|
+
"FRESHNESS_SLO_HOURS",
|
|
50
|
+
"LEDGER_VERSION",
|
|
51
|
+
"PIPELINE_SOURCES",
|
|
52
|
+
"PIPELINE_LOCK_PATH",
|
|
53
|
+
"PipelineLockHeldError",
|
|
54
|
+
"Registry",
|
|
55
|
+
"SOURCE_SLO",
|
|
56
|
+
"SkipVerdict",
|
|
57
|
+
"SourceEntry",
|
|
58
|
+
"VIEWS_EPOCH_YEAR",
|
|
59
|
+
"append_ledger_entry",
|
|
60
|
+
"check_assembly_skip",
|
|
61
|
+
"check_export_freshness",
|
|
62
|
+
"check_export_skip",
|
|
63
|
+
"compute_content_digest",
|
|
64
|
+
"compute_file_digest",
|
|
65
|
+
"file_lock",
|
|
66
|
+
"get_all_features",
|
|
67
|
+
"get_required_env_vars",
|
|
68
|
+
"get_source_slo",
|
|
69
|
+
"hold_pipeline_lock",
|
|
70
|
+
"last_digest",
|
|
71
|
+
"pipeline_lock",
|
|
72
|
+
"last_digest_for_version",
|
|
73
|
+
"read_last_entries",
|
|
74
|
+
"report_ledger",
|
|
75
|
+
"validate_preflight",
|
|
76
|
+
"verify_source_digest",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
from importlib.metadata import version as _pkg_version
|
|
80
|
+
|
|
81
|
+
__version__ = _pkg_version("views-datafactory")
|