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,524 @@
|
|
|
1
|
+
"""UCDP consolidator — annual, candidate, and .9 into event store.
|
|
2
|
+
|
|
3
|
+
Reads all Parquet snapshots from the harvester's annual, candidate,
|
|
4
|
+
and .9 directories, tags each with source metadata (_source_type,
|
|
5
|
+
_ingested_at, _harvest_digest, _harvest_timestamp), and writes a single
|
|
6
|
+
consolidated Parquet store.
|
|
7
|
+
|
|
8
|
+
Vintage-aware (ADR-017): deduplicates on content digest, not just
|
|
9
|
+
version number. Two fetches of the same version that return different
|
|
10
|
+
data are preserved as distinct vintages.
|
|
11
|
+
|
|
12
|
+
No survivorship decisions. No temporal distribution. No field dropping.
|
|
13
|
+
Those belong to the viewpoint layer (Layer 3).
|
|
14
|
+
|
|
15
|
+
Implements ADR-013 (consolidation principles), ADR-015 (UCDP specifics),
|
|
16
|
+
and ADR-017 (vintage-aware consolidation).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
import json
|
|
23
|
+
import logging
|
|
24
|
+
import re
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import UTC, datetime
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
import pyarrow as pa
|
|
30
|
+
|
|
31
|
+
from datafactory_consolidation.consolidation_result import (
|
|
32
|
+
ConsolidationResult,
|
|
33
|
+
)
|
|
34
|
+
from datafactory_consolidation.consolidators import register_consolidator
|
|
35
|
+
from datafactory_consolidation.event_store import read_store, write_store
|
|
36
|
+
from datafactory_consolidation.tagging import tag_table
|
|
37
|
+
from datafactory_provenance import (
|
|
38
|
+
DIGEST_SCHEME,
|
|
39
|
+
LEDGER_VERSION,
|
|
40
|
+
append_ledger_entry,
|
|
41
|
+
compute_content_digest,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
DATASET_ID = "ucdp_consolidation"
|
|
47
|
+
|
|
48
|
+
# ---- Boundary declarations (ADR-009) ----
|
|
49
|
+
# What this layer REQUIRES from source Parquet files
|
|
50
|
+
REQUIRED_SOURCE_FIELDS: set[str] = {"id"}
|
|
51
|
+
|
|
52
|
+
# What this layer PRODUCES (metadata columns added during consolidation)
|
|
53
|
+
PRODUCED_METADATA: tuple[str, ...] = (
|
|
54
|
+
"_source_type",
|
|
55
|
+
"_source_version",
|
|
56
|
+
"_ingested_at",
|
|
57
|
+
"_harvest_digest",
|
|
58
|
+
"_harvest_timestamp",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
# Filename patterns for version extraction
|
|
62
|
+
_ANNUAL_PATTERN = re.compile(
|
|
63
|
+
r"ucdp_ged_v([\d.]+)_\d+_\d+\.parquet$"
|
|
64
|
+
)
|
|
65
|
+
_CANDIDATE_PATTERN = re.compile(
|
|
66
|
+
r"ucdp_ged_candidate_([\d.]+)\.parquet$"
|
|
67
|
+
)
|
|
68
|
+
_DOT9_PATTERN = re.compile(
|
|
69
|
+
r"ucdp_ged_dot9_([\d.]+)\.parquet$"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _extract_annual_version(path: Path) -> str:
|
|
74
|
+
"""Extract version string from annual snapshot filename.
|
|
75
|
+
|
|
76
|
+
Example: ucdp_ged_v25.1_1989_2024.parquet → "25.1"
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
ValueError: If filename does not match expected pattern.
|
|
80
|
+
"""
|
|
81
|
+
match = _ANNUAL_PATTERN.search(path.name)
|
|
82
|
+
if not match:
|
|
83
|
+
err_msg = (
|
|
84
|
+
f"Cannot extract version from annual filename: "
|
|
85
|
+
f"{path.name}. Expected pattern: "
|
|
86
|
+
f"ucdp_ged_v<version>_<start>_<end>.parquet"
|
|
87
|
+
)
|
|
88
|
+
logger.error(err_msg)
|
|
89
|
+
raise ValueError(err_msg)
|
|
90
|
+
return match.group(1)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _extract_candidate_version(path: Path) -> str:
|
|
94
|
+
"""Extract version string from candidate snapshot filename.
|
|
95
|
+
|
|
96
|
+
Example: ucdp_ged_candidate_25.0.3.parquet → "25.0.3"
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
ValueError: If filename does not match expected pattern.
|
|
100
|
+
"""
|
|
101
|
+
match = _CANDIDATE_PATTERN.search(path.name)
|
|
102
|
+
if not match:
|
|
103
|
+
err_msg = (
|
|
104
|
+
f"Cannot extract version from candidate filename: "
|
|
105
|
+
f"{path.name}. Expected pattern: "
|
|
106
|
+
f"ucdp_ged_candidate_<version>.parquet"
|
|
107
|
+
)
|
|
108
|
+
logger.error(err_msg)
|
|
109
|
+
raise ValueError(err_msg)
|
|
110
|
+
return match.group(1)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _extract_dot9_version(path: Path) -> str:
|
|
114
|
+
"""Extract version string from .9 snapshot filename.
|
|
115
|
+
|
|
116
|
+
Example: ucdp_ged_dot9_25.9.11.parquet → "25.9.11"
|
|
117
|
+
|
|
118
|
+
Raises:
|
|
119
|
+
ValueError: If filename does not match expected pattern.
|
|
120
|
+
"""
|
|
121
|
+
match = _DOT9_PATTERN.search(path.name)
|
|
122
|
+
if not match:
|
|
123
|
+
err_msg = (
|
|
124
|
+
f"Cannot extract version from .9 filename: "
|
|
125
|
+
f"{path.name}. Expected pattern: "
|
|
126
|
+
f"ucdp_ged_dot9_<version>.parquet"
|
|
127
|
+
)
|
|
128
|
+
logger.error(err_msg)
|
|
129
|
+
raise ValueError(err_msg)
|
|
130
|
+
return match.group(1)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _build_harvest_index(
|
|
134
|
+
ledger_path: Path,
|
|
135
|
+
) -> dict[str, tuple[str, str]]:
|
|
136
|
+
"""Build version → (digest, timestamp) lookup from harvest ledger.
|
|
137
|
+
|
|
138
|
+
Reads the harvest JSONL ledger and returns the latest successful
|
|
139
|
+
entry per version. This connects the consolidator to the
|
|
140
|
+
harvester's provenance chain (ADR-017).
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
Dict mapping version string to (content_digest, timestamp).
|
|
144
|
+
Empty dict if ledger doesn't exist.
|
|
145
|
+
"""
|
|
146
|
+
if not ledger_path.exists():
|
|
147
|
+
return {}
|
|
148
|
+
|
|
149
|
+
index: dict[str, tuple[str, str]] = {}
|
|
150
|
+
for line in ledger_path.read_text().strip().splitlines():
|
|
151
|
+
line = line.strip()
|
|
152
|
+
if not line:
|
|
153
|
+
continue
|
|
154
|
+
try:
|
|
155
|
+
entry = json.loads(line)
|
|
156
|
+
except json.JSONDecodeError:
|
|
157
|
+
continue
|
|
158
|
+
|
|
159
|
+
outcome = entry.get("outcome")
|
|
160
|
+
if outcome not in ("success", "unchanged"):
|
|
161
|
+
continue
|
|
162
|
+
|
|
163
|
+
version = entry.get("version")
|
|
164
|
+
digest = entry.get("content_digest")
|
|
165
|
+
timestamp = entry.get("timestamp")
|
|
166
|
+
|
|
167
|
+
if version and digest and timestamp:
|
|
168
|
+
index[version] = (digest, timestamp)
|
|
169
|
+
|
|
170
|
+
return index
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _get_harvest_metadata(
|
|
174
|
+
version: str,
|
|
175
|
+
harvest_index: dict[str, tuple[str, str]],
|
|
176
|
+
fallback_path: Path,
|
|
177
|
+
) -> tuple[str, str]:
|
|
178
|
+
"""Get harvest digest and timestamp for a source version.
|
|
179
|
+
|
|
180
|
+
Looks up the version in the harvest index (from ledger).
|
|
181
|
+
Falls back to computing digest from the file itself if
|
|
182
|
+
the ledger doesn't have an entry (graceful degradation).
|
|
183
|
+
"""
|
|
184
|
+
if version in harvest_index:
|
|
185
|
+
return harvest_index[version]
|
|
186
|
+
|
|
187
|
+
# Fallback: compute from file
|
|
188
|
+
digest = compute_content_digest(fallback_path.read_bytes())
|
|
189
|
+
timestamp = datetime.fromtimestamp(
|
|
190
|
+
fallback_path.stat().st_mtime, tz=UTC
|
|
191
|
+
).isoformat()
|
|
192
|
+
logger.info(
|
|
193
|
+
"No ledger entry for version %s — using file digest %s",
|
|
194
|
+
version, digest,
|
|
195
|
+
)
|
|
196
|
+
return digest, timestamp
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---- Config ----
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@dataclass(frozen=True)
|
|
203
|
+
class UcdpConsolidationConfig:
|
|
204
|
+
"""Configuration for UCDP consolidation.
|
|
205
|
+
|
|
206
|
+
Paths to harvester output directories, harvest ledgers,
|
|
207
|
+
and consolidated store output. Directory and ledger existence
|
|
208
|
+
is checked at consolidation time, not config time.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
annual_dir: Path = Path("data/raw/ucdp_annual")
|
|
212
|
+
candidate_dir: Path = Path("data/raw/ucdp_candidate")
|
|
213
|
+
dot9_dir: Path = Path("data/raw/ucdp_dot9")
|
|
214
|
+
annual_ledger_path: Path = Path(
|
|
215
|
+
"provenance/ucdp_annual/ingestion_ledger.jsonl"
|
|
216
|
+
)
|
|
217
|
+
candidate_ledger_path: Path = Path(
|
|
218
|
+
"provenance/ucdp_candidate/ingestion_ledger.jsonl"
|
|
219
|
+
)
|
|
220
|
+
dot9_ledger_path: Path = Path(
|
|
221
|
+
"provenance/ucdp_dot9/ingestion_ledger.jsonl"
|
|
222
|
+
)
|
|
223
|
+
output_path: Path = Path(
|
|
224
|
+
"data/consolidated/ucdp_store.parquet"
|
|
225
|
+
)
|
|
226
|
+
ledger_path: Path = Path(
|
|
227
|
+
"provenance/consolidation/ucdp_ledger.jsonl"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ---- Consolidation ----
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def consolidate_ucdp(
|
|
235
|
+
config: UcdpConsolidationConfig | None = None,
|
|
236
|
+
) -> ConsolidationResult:
|
|
237
|
+
"""Consolidate UCDP annual + candidate snapshots.
|
|
238
|
+
|
|
239
|
+
Vintage-aware (ADR-017): tags each record with the harvest
|
|
240
|
+
content digest and timestamp. Deduplicates on
|
|
241
|
+
(id, _source_type, _source_version, _harvest_digest) so
|
|
242
|
+
identical re-fetches are skipped but updated versions are
|
|
243
|
+
preserved as distinct vintages.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
config: Consolidation configuration. Uses defaults if None.
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
ConsolidationResult with record counts and output digest.
|
|
250
|
+
|
|
251
|
+
Raises:
|
|
252
|
+
FileNotFoundError: If no source Parquet files are found.
|
|
253
|
+
ValueError: If a source filename doesn't match patterns.
|
|
254
|
+
"""
|
|
255
|
+
if config is None:
|
|
256
|
+
config = UcdpConsolidationConfig()
|
|
257
|
+
|
|
258
|
+
ingested_at = datetime.now(tz=UTC).isoformat()
|
|
259
|
+
|
|
260
|
+
# Build harvest indexes from ledgers
|
|
261
|
+
annual_index = _build_harvest_index(config.annual_ledger_path)
|
|
262
|
+
candidate_index = _build_harvest_index(
|
|
263
|
+
config.candidate_ledger_path
|
|
264
|
+
)
|
|
265
|
+
dot9_index = _build_harvest_index(config.dot9_ledger_path)
|
|
266
|
+
|
|
267
|
+
# Discover source files
|
|
268
|
+
annual_files = (
|
|
269
|
+
sorted(
|
|
270
|
+
p for p in config.annual_dir.glob("*.parquet")
|
|
271
|
+
if _ANNUAL_PATTERN.search(p.name)
|
|
272
|
+
)
|
|
273
|
+
if config.annual_dir.exists()
|
|
274
|
+
else []
|
|
275
|
+
)
|
|
276
|
+
candidate_files = (
|
|
277
|
+
sorted(
|
|
278
|
+
p for p in config.candidate_dir.glob("*.parquet")
|
|
279
|
+
if _CANDIDATE_PATTERN.search(p.name)
|
|
280
|
+
)
|
|
281
|
+
if config.candidate_dir.exists()
|
|
282
|
+
else []
|
|
283
|
+
)
|
|
284
|
+
dot9_files = (
|
|
285
|
+
sorted(
|
|
286
|
+
p for p in config.dot9_dir.glob("*.parquet")
|
|
287
|
+
if _DOT9_PATTERN.search(p.name)
|
|
288
|
+
)
|
|
289
|
+
if config.dot9_dir.exists()
|
|
290
|
+
else []
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
if not annual_files and not candidate_files and not dot9_files:
|
|
294
|
+
err_msg = (
|
|
295
|
+
f"No source Parquet files found in "
|
|
296
|
+
f"{config.annual_dir}, {config.candidate_dir}, "
|
|
297
|
+
f"or {config.dot9_dir}"
|
|
298
|
+
)
|
|
299
|
+
logger.error(err_msg)
|
|
300
|
+
raise FileNotFoundError(err_msg)
|
|
301
|
+
|
|
302
|
+
# Read and tag each source
|
|
303
|
+
tagged_tables: list[pa.Table] = []
|
|
304
|
+
source_manifest: list[dict] = []
|
|
305
|
+
|
|
306
|
+
for path in annual_files:
|
|
307
|
+
version = _extract_annual_version(path)
|
|
308
|
+
h_digest, h_timestamp = _get_harvest_metadata(
|
|
309
|
+
version, annual_index, path
|
|
310
|
+
)
|
|
311
|
+
table = pa.parquet.read_table(path)
|
|
312
|
+
tagged = tag_table(
|
|
313
|
+
table,
|
|
314
|
+
source_type="annual",
|
|
315
|
+
source_version=version,
|
|
316
|
+
ingested_at=ingested_at,
|
|
317
|
+
harvest_digest=h_digest,
|
|
318
|
+
harvest_timestamp=h_timestamp,
|
|
319
|
+
)
|
|
320
|
+
tagged_tables.append(tagged)
|
|
321
|
+
dates = [
|
|
322
|
+
d for d in table.column("date_start").to_pylist()
|
|
323
|
+
if d
|
|
324
|
+
] if "date_start" in table.column_names else []
|
|
325
|
+
source_manifest.append({
|
|
326
|
+
"path": str(path),
|
|
327
|
+
"source_type": "annual",
|
|
328
|
+
"version": version,
|
|
329
|
+
"n_records": table.num_rows,
|
|
330
|
+
"min_date_start": min(dates) if dates else None,
|
|
331
|
+
"max_date_start": max(dates) if dates else None,
|
|
332
|
+
"harvest_digest": h_digest,
|
|
333
|
+
"harvest_timestamp": h_timestamp,
|
|
334
|
+
})
|
|
335
|
+
logger.info(
|
|
336
|
+
"Read annual: %s (v%s, %d records, digest %s)",
|
|
337
|
+
path.name, version, table.num_rows, h_digest,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
for path in candidate_files:
|
|
341
|
+
version = _extract_candidate_version(path)
|
|
342
|
+
h_digest, h_timestamp = _get_harvest_metadata(
|
|
343
|
+
version, candidate_index, path
|
|
344
|
+
)
|
|
345
|
+
table = pa.parquet.read_table(path)
|
|
346
|
+
tagged = tag_table(
|
|
347
|
+
table,
|
|
348
|
+
source_type="candidate",
|
|
349
|
+
source_version=version,
|
|
350
|
+
ingested_at=ingested_at,
|
|
351
|
+
harvest_digest=h_digest,
|
|
352
|
+
harvest_timestamp=h_timestamp,
|
|
353
|
+
)
|
|
354
|
+
tagged_tables.append(tagged)
|
|
355
|
+
dates = [
|
|
356
|
+
d for d in table.column("date_start").to_pylist()
|
|
357
|
+
if d
|
|
358
|
+
] if "date_start" in table.column_names else []
|
|
359
|
+
source_manifest.append({
|
|
360
|
+
"path": str(path),
|
|
361
|
+
"source_type": "candidate",
|
|
362
|
+
"version": version,
|
|
363
|
+
"n_records": table.num_rows,
|
|
364
|
+
"min_date_start": min(dates) if dates else None,
|
|
365
|
+
"max_date_start": max(dates) if dates else None,
|
|
366
|
+
"harvest_digest": h_digest,
|
|
367
|
+
"harvest_timestamp": h_timestamp,
|
|
368
|
+
})
|
|
369
|
+
logger.info(
|
|
370
|
+
"Read candidate: %s (v%s, %d records, digest %s)",
|
|
371
|
+
path.name, version, table.num_rows, h_digest,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
for path in dot9_files:
|
|
375
|
+
version = _extract_dot9_version(path)
|
|
376
|
+
h_digest, h_timestamp = _get_harvest_metadata(
|
|
377
|
+
version, dot9_index, path
|
|
378
|
+
)
|
|
379
|
+
table = pa.parquet.read_table(path)
|
|
380
|
+
tagged = tag_table(
|
|
381
|
+
table,
|
|
382
|
+
source_type="dot9",
|
|
383
|
+
source_version=version,
|
|
384
|
+
ingested_at=ingested_at,
|
|
385
|
+
harvest_digest=h_digest,
|
|
386
|
+
harvest_timestamp=h_timestamp,
|
|
387
|
+
)
|
|
388
|
+
tagged_tables.append(tagged)
|
|
389
|
+
dates = [
|
|
390
|
+
d for d in table.column("date_start").to_pylist()
|
|
391
|
+
if d
|
|
392
|
+
] if "date_start" in table.column_names else []
|
|
393
|
+
source_manifest.append({
|
|
394
|
+
"path": str(path),
|
|
395
|
+
"source_type": "dot9",
|
|
396
|
+
"version": version,
|
|
397
|
+
"n_records": table.num_rows,
|
|
398
|
+
"min_date_start": min(dates) if dates else None,
|
|
399
|
+
"max_date_start": max(dates) if dates else None,
|
|
400
|
+
"harvest_digest": h_digest,
|
|
401
|
+
"harvest_timestamp": h_timestamp,
|
|
402
|
+
})
|
|
403
|
+
logger.info(
|
|
404
|
+
"Read .9: %s (v%s, %d records, digest %s)",
|
|
405
|
+
path.name, version, table.num_rows, h_digest,
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
# Concatenate new records
|
|
409
|
+
new_table = pa.concat_tables(
|
|
410
|
+
tagged_tables, promote_options="default"
|
|
411
|
+
)
|
|
412
|
+
n_new_raw = new_table.num_rows
|
|
413
|
+
|
|
414
|
+
expected_raw = sum(m["n_records"] for m in source_manifest)
|
|
415
|
+
if n_new_raw != expected_raw:
|
|
416
|
+
raise RuntimeError(
|
|
417
|
+
f"Row count mismatch after concat: "
|
|
418
|
+
f"expected {expected_raw}, got {n_new_raw}"
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
# Read existing store and deduplicate (vintage-aware, ADR-017)
|
|
422
|
+
existing = read_store(config.output_path)
|
|
423
|
+
if existing is not None:
|
|
424
|
+
n_before = existing.num_rows
|
|
425
|
+
|
|
426
|
+
# Dedup key includes harvest_digest (ADR-017)
|
|
427
|
+
existing_keys = set(
|
|
428
|
+
zip(
|
|
429
|
+
existing.column("id").to_pylist(),
|
|
430
|
+
existing.column("_source_type").to_pylist(),
|
|
431
|
+
existing.column("_source_version").to_pylist(),
|
|
432
|
+
existing.column("_harvest_digest").to_pylist(),
|
|
433
|
+
strict=True,
|
|
434
|
+
)
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
new_ids = new_table.column("id").to_pylist()
|
|
438
|
+
new_types = new_table.column("_source_type").to_pylist()
|
|
439
|
+
new_vers = new_table.column("_source_version").to_pylist()
|
|
440
|
+
new_digests = new_table.column(
|
|
441
|
+
"_harvest_digest"
|
|
442
|
+
).to_pylist()
|
|
443
|
+
|
|
444
|
+
keep_mask = [
|
|
445
|
+
(eid, etype, ever, edigest) not in existing_keys
|
|
446
|
+
for eid, etype, ever, edigest in zip(
|
|
447
|
+
new_ids, new_types, new_vers, new_digests,
|
|
448
|
+
strict=True,
|
|
449
|
+
)
|
|
450
|
+
]
|
|
451
|
+
new_filtered = new_table.filter(keep_mask)
|
|
452
|
+
n_new = new_filtered.num_rows
|
|
453
|
+
|
|
454
|
+
if n_new > 0:
|
|
455
|
+
combined = pa.concat_tables(
|
|
456
|
+
[existing, new_filtered],
|
|
457
|
+
promote_options="default",
|
|
458
|
+
)
|
|
459
|
+
else:
|
|
460
|
+
combined = existing
|
|
461
|
+
|
|
462
|
+
logger.info(
|
|
463
|
+
"Dedup: %d raw, %d already in store, %d new added",
|
|
464
|
+
n_new_raw, n_new_raw - n_new, n_new,
|
|
465
|
+
)
|
|
466
|
+
else:
|
|
467
|
+
combined = new_table
|
|
468
|
+
n_new = n_new_raw
|
|
469
|
+
n_before = 0
|
|
470
|
+
|
|
471
|
+
expected_total = n_before + n_new
|
|
472
|
+
if combined.num_rows != expected_total:
|
|
473
|
+
raise RuntimeError(
|
|
474
|
+
f"Row count mismatch after merge: "
|
|
475
|
+
f"expected {n_before} + {n_new} = {expected_total}, "
|
|
476
|
+
f"got {combined.num_rows}"
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# Write consolidated store
|
|
480
|
+
output_digest = write_store(combined, config.output_path)
|
|
481
|
+
|
|
482
|
+
n_total = combined.num_rows
|
|
483
|
+
|
|
484
|
+
# Schema fingerprint for drift detection
|
|
485
|
+
schema_cols = sorted(combined.column_names)
|
|
486
|
+
schema_fingerprint = hashlib.sha256(
|
|
487
|
+
",".join(schema_cols).encode()
|
|
488
|
+
).hexdigest()[:16]
|
|
489
|
+
|
|
490
|
+
# Record provenance
|
|
491
|
+
append_ledger_entry(config.ledger_path, {
|
|
492
|
+
"dataset": DATASET_ID,
|
|
493
|
+
"n_sources": len(source_manifest),
|
|
494
|
+
"n_records_before": n_before,
|
|
495
|
+
"n_records_raw": n_new_raw,
|
|
496
|
+
"n_records_dedup_filtered": n_new_raw - n_new,
|
|
497
|
+
"n_records_new": n_new,
|
|
498
|
+
"n_records_total": n_total,
|
|
499
|
+
"source_manifest": source_manifest,
|
|
500
|
+
"output_path": str(config.output_path),
|
|
501
|
+
"output_digest": output_digest,
|
|
502
|
+
"schema_fingerprint": schema_fingerprint,
|
|
503
|
+
"schema_columns": schema_cols,
|
|
504
|
+
"ledger_version": LEDGER_VERSION,
|
|
505
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
506
|
+
})
|
|
507
|
+
|
|
508
|
+
logger.info(
|
|
509
|
+
"Consolidation complete: %d sources, %d new, %d total",
|
|
510
|
+
len(source_manifest), n_new, n_total,
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
return ConsolidationResult(
|
|
514
|
+
output_path=config.output_path,
|
|
515
|
+
n_sources=len(source_manifest),
|
|
516
|
+
n_records_total=n_total,
|
|
517
|
+
n_records_new=n_new,
|
|
518
|
+
n_records_before=n_before,
|
|
519
|
+
output_digest=output_digest,
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
# Auto-register
|
|
524
|
+
register_consolidator("ucdp", consolidate_ucdp)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Source-agnostic consolidated store I/O.
|
|
2
|
+
|
|
3
|
+
Reads and writes consolidated Parquet stores. The store is a single
|
|
4
|
+
Parquet file — simple, queryable, and sufficient at current scale.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import pyarrow as pa
|
|
15
|
+
import pyarrow.parquet as pq
|
|
16
|
+
|
|
17
|
+
from datafactory_provenance import compute_file_digest, file_lock
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
_PARQUET_COMPRESSION: str = "snappy"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def read_store(path: Path) -> pa.Table | None:
|
|
25
|
+
"""Read an existing consolidated store.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
A PyArrow Table, or None if the file does not exist.
|
|
29
|
+
"""
|
|
30
|
+
if not path.exists():
|
|
31
|
+
return None
|
|
32
|
+
return pq.read_table(path)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def write_store(table: pa.Table, path: Path) -> str:
|
|
36
|
+
"""Write a consolidated store to disk.
|
|
37
|
+
|
|
38
|
+
Creates parent directories if needed. Computes and returns the
|
|
39
|
+
content digest of the written file.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Content digest (SHA-256, truncated to 16 hex chars).
|
|
43
|
+
"""
|
|
44
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
with file_lock(path):
|
|
46
|
+
# Atomic write: temp file then rename to prevent corruption on crash
|
|
47
|
+
fd, tmp = tempfile.mkstemp(
|
|
48
|
+
dir=path.parent, suffix=".tmp",
|
|
49
|
+
)
|
|
50
|
+
try:
|
|
51
|
+
os.close(fd)
|
|
52
|
+
tmp_path = Path(tmp)
|
|
53
|
+
pq.write_table(
|
|
54
|
+
table, tmp_path, compression=_PARQUET_COMPRESSION,
|
|
55
|
+
)
|
|
56
|
+
tmp_path.rename(path)
|
|
57
|
+
except BaseException:
|
|
58
|
+
Path(tmp).unlink(missing_ok=True)
|
|
59
|
+
raise
|
|
60
|
+
digest = compute_file_digest(path)
|
|
61
|
+
logger.info(
|
|
62
|
+
"Wrote consolidated store: %s (%d rows, digest: %s)",
|
|
63
|
+
path,
|
|
64
|
+
table.num_rows,
|
|
65
|
+
digest,
|
|
66
|
+
)
|
|
67
|
+
return digest
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Consolidation metadata tagging for PyArrow tables."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pyarrow as pa
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def tag_table(
|
|
9
|
+
table: pa.Table,
|
|
10
|
+
*,
|
|
11
|
+
source_type: str,
|
|
12
|
+
source_version: str,
|
|
13
|
+
ingested_at: str,
|
|
14
|
+
harvest_digest: str,
|
|
15
|
+
harvest_timestamp: str,
|
|
16
|
+
) -> pa.Table:
|
|
17
|
+
"""Add consolidation metadata columns to a PyArrow table.
|
|
18
|
+
|
|
19
|
+
Adds _source_type, _source_version, _ingested_at,
|
|
20
|
+
_harvest_digest, and _harvest_timestamp columns without
|
|
21
|
+
removing any existing columns (lossless per ADR-013).
|
|
22
|
+
Vintage-aware per ADR-017.
|
|
23
|
+
"""
|
|
24
|
+
n = table.num_rows
|
|
25
|
+
return (
|
|
26
|
+
table.append_column(
|
|
27
|
+
"_source_type",
|
|
28
|
+
pa.array([source_type] * n, type=pa.string()),
|
|
29
|
+
)
|
|
30
|
+
.append_column(
|
|
31
|
+
"_source_version",
|
|
32
|
+
pa.array([source_version] * n, type=pa.string()),
|
|
33
|
+
)
|
|
34
|
+
.append_column(
|
|
35
|
+
"_ingested_at",
|
|
36
|
+
pa.array([ingested_at] * n, type=pa.string()),
|
|
37
|
+
)
|
|
38
|
+
.append_column(
|
|
39
|
+
"_harvest_digest",
|
|
40
|
+
pa.array([harvest_digest] * n, type=pa.string()),
|
|
41
|
+
)
|
|
42
|
+
.append_column(
|
|
43
|
+
"_harvest_timestamp",
|
|
44
|
+
pa.array([harvest_timestamp] * n, type=pa.string()),
|
|
45
|
+
)
|
|
46
|
+
)
|