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.
Files changed (103) hide show
  1. datafactory_adapters/ARCHITECTURE.md +54 -0
  2. datafactory_adapters/__init__.py +38 -0
  3. datafactory_adapters/_conservation.py +95 -0
  4. datafactory_adapters/_reconciliation.py +92 -0
  5. datafactory_adapters/_validation.py +39 -0
  6. datafactory_adapters/feature_frame.py +25 -0
  7. datafactory_adapters/grid_from_feature_frame.py +89 -0
  8. datafactory_adapters/grid_to_country_month.py +169 -0
  9. datafactory_adapters/grid_to_dataframe.py +176 -0
  10. datafactory_compilation/ARCHITECTURE.md +63 -0
  11. datafactory_compilation/__init__.py +39 -0
  12. datafactory_compilation/aggregation.py +64 -0
  13. datafactory_compilation/compilation_config.py +97 -0
  14. datafactory_compilation/conservation.py +36 -0
  15. datafactory_compilation/grid_compilation.py +352 -0
  16. datafactory_compilation/output.py +85 -0
  17. datafactory_compilation/preflight.py +61 -0
  18. datafactory_compilation/pregridded_compilation.py +291 -0
  19. datafactory_consolidation/ARCHITECTURE.md +58 -0
  20. datafactory_consolidation/__init__.py +28 -0
  21. datafactory_consolidation/consolidation_result.py +27 -0
  22. datafactory_consolidation/consolidators/__init__.py +32 -0
  23. datafactory_consolidation/consolidators/acled.py +462 -0
  24. datafactory_consolidation/consolidators/ucdp.py +524 -0
  25. datafactory_consolidation/event_store.py +67 -0
  26. datafactory_consolidation/tagging.py +46 -0
  27. datafactory_harvester/ARCHITECTURE.md +103 -0
  28. datafactory_harvester/__init__.py +37 -0
  29. datafactory_harvester/event_validation.py +372 -0
  30. datafactory_harvester/harvest_runner.py +72 -0
  31. datafactory_harvester/pipeline_runner.py +125 -0
  32. datafactory_harvester/snapshot_storage.py +117 -0
  33. datafactory_harvester/sources/__init__.py +36 -0
  34. datafactory_harvester/sources/_ucdp_common.py +34 -0
  35. datafactory_harvester/sources/acled.py +743 -0
  36. datafactory_harvester/sources/gaul_admin.py +567 -0
  37. datafactory_harvester/sources/ghsbuilts.py +271 -0
  38. datafactory_harvester/sources/ghspop.py +267 -0
  39. datafactory_harvester/sources/priogrid_static.py +359 -0
  40. datafactory_harvester/sources/shdi.py +625 -0
  41. datafactory_harvester/sources/ucdp_annual.py +616 -0
  42. datafactory_harvester/sources/ucdp_candidate.py +419 -0
  43. datafactory_harvester/sources/ucdp_dot9.py +407 -0
  44. datafactory_harvester/sources/vdem.py +350 -0
  45. datafactory_harvester/validation.py +74 -0
  46. datafactory_http/__init__.py +10 -0
  47. datafactory_http/retry.py +102 -0
  48. datafactory_priogrid/ARCHITECTURE.md +62 -0
  49. datafactory_priogrid/__init__.py +51 -0
  50. datafactory_priogrid/cell_generator.py +137 -0
  51. datafactory_priogrid/grid_config.py +107 -0
  52. datafactory_priogrid/land_mask.py +62 -0
  53. datafactory_priogrid/parity_validation.py +176 -0
  54. datafactory_priogrid/shapefile_harvester.py +174 -0
  55. datafactory_priogrid/shapefile_reader.py +125 -0
  56. datafactory_priogrid/spatiotemporal.py +66 -0
  57. datafactory_priogrid/temporal_config.py +78 -0
  58. datafactory_priogrid/temporal_generator.py +65 -0
  59. datafactory_provenance/ARCHITECTURE.md +61 -0
  60. datafactory_provenance/__init__.py +81 -0
  61. datafactory_provenance/constants.py +3 -0
  62. datafactory_provenance/digests_and_ledgers.py +370 -0
  63. datafactory_provenance/health.py +310 -0
  64. datafactory_provenance/pipeline_lock.py +200 -0
  65. datafactory_provenance/registry.py +92 -0
  66. datafactory_provenance/skip.py +212 -0
  67. datafactory_provenance/source_registry.py +466 -0
  68. datafactory_query/ARCHITECTURE.md +60 -0
  69. datafactory_query/__init__.py +36 -0
  70. datafactory_query/africa_me_gaul_pgids.json +1 -0
  71. datafactory_query/africa_me_legacy_pgids.json +1 -0
  72. datafactory_query/backends_npy.py +90 -0
  73. datafactory_query/backends_zarr.py +259 -0
  74. datafactory_query/coverage.py +64 -0
  75. datafactory_query/dataset.py +263 -0
  76. datafactory_query/defaults.py +101 -0
  77. datafactory_query/land_gaul_pgids.json +1 -0
  78. datafactory_query/land_pgids.json +1 -0
  79. datafactory_query/output_format.py +52 -0
  80. datafactory_query/regions.py +293 -0
  81. datafactory_query/temporal.py +115 -0
  82. datafactory_viewpoint/ARCHITECTURE.md +68 -0
  83. datafactory_viewpoint/__init__.py +33 -0
  84. datafactory_viewpoint/builders/__init__.py +32 -0
  85. datafactory_viewpoint/builders/acled_v1.py +213 -0
  86. datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
  87. datafactory_viewpoint/builders/ghspop_v1.py +471 -0
  88. datafactory_viewpoint/builders/shdi_v1.py +389 -0
  89. datafactory_viewpoint/builders/ucdp_v1.py +437 -0
  90. datafactory_viewpoint/builders/vdem_v1.py +419 -0
  91. datafactory_viewpoint/profiles.py +169 -0
  92. datafactory_viewpoint/raster_io.py +49 -0
  93. datafactory_viewpoint/spatial_distribution.py +203 -0
  94. datafactory_viewpoint/spatial_weights.py +207 -0
  95. datafactory_viewpoint/survivorship.py +108 -0
  96. datafactory_viewpoint/temporal.py +111 -0
  97. datafactory_viewpoint/temporal_distribution.py +295 -0
  98. datafactory_viewpoint/viewpoint_config.py +124 -0
  99. datafactory_viewpoint/viewpoint_result.py +33 -0
  100. views_datafactory-1.9.0.dist-info/METADATA +528 -0
  101. views_datafactory-1.9.0.dist-info/RECORD +103 -0
  102. views_datafactory-1.9.0.dist-info/WHEEL +4 -0
  103. views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,103 @@
1
+ # datafactory_harvester -- Architecture
2
+
3
+ ## Purpose
4
+
5
+ Data ingestion framework with pluggable sources. Follows the pattern: config -> fetch -> validate -> store -> provenance. Raw data is stored unaltered -- no transformation at fetch time. This is a Source Node in the graph architecture (ADR-001) and a Layer 1 package in the dependency DAG (ADR-012).
6
+
7
+ ## Responsibility Boundary
8
+
9
+ **Owns:**
10
+ - Data fetching from external APIs (UCDP/GED, ACLED, GHS-POP, GHS-BUILT-S, PRIO-GRID static, GAUL admin)
11
+ - Schema validation of fetched data (required fields, types, domain constraints)
12
+ - Raw data storage as Parquet snapshots (verbatim, all fields preserved)
13
+ - Snapshot comparison (new vs. previous: added, removed, revised events)
14
+ - Provenance ledger entries for each harvest operation
15
+ - Source plugin registry
16
+
17
+ **Does NOT own:**
18
+ - Grid coordinate generation or spatial alignment (datafactory_priogrid)
19
+ - Event-to-grid compilation (datafactory_compilation)
20
+ - Data transformation or aggregation (stored raw)
21
+ - Consumer-specific formatting (no knowledge of downstream models)
22
+ - Audit report generation (planned, not yet implemented)
23
+
24
+ ## Dependency Rules
25
+
26
+ **May import:** `datafactory_provenance`, requests, pyarrow
27
+ **Must never import:** `datafactory_priogrid`, `datafactory_compilation`, or any consumer
28
+
29
+ ## Package Structure
30
+
31
+ ```
32
+ datafactory_harvester/
33
+ __init__.py -- public API exports
34
+ event_validation.py -- ValidationResult, ComparisonResult, validate_events, compare_snapshots
35
+ snapshot_storage.py -- save_event_snapshot, archive_snapshot
36
+ sources/
37
+ __init__.py -- source registry (register_source, fetch_source, list_sources)
38
+ _ucdp_common.py -- shared UCDP utilities (version discovery, digest caching)
39
+ ucdp_annual.py -- UCDP/GED Annual: config, API client, schema, fetch orchestrator
40
+ ucdp_candidate.py -- UCDP/GED Candidate Monthly: version discovery, digest caching, multi-version fetch
41
+ ucdp_dot9.py -- UCDP/GED .9 Consolidated Monthly: version discovery, digest caching, multi-version fetch
42
+ priogrid_static.py -- PRIO-GRID 2.0 static features: terrain, resources, land cover (64,818 land cells)
43
+ acled.py -- ACLED event data: OAuth2 API, daily events, year-by-year pagination
44
+ ghspop.py -- GHS-POP: JRC population rasters (GeoTIFF download, 12 epochs)
45
+ ghsbuilts.py -- GHS-BUILT-S: JRC built-up surface rasters (GeoTIFF download, 12 epochs)
46
+ gaul_admin.py -- GAUL 2024 admin boundaries: FAO shapefiles, spatial join to PRIO-GRID
47
+ ```
48
+
49
+ ## Key Concepts
50
+
51
+ | Concept | Description |
52
+ |---------|-------------|
53
+ | ValidationResult | Schema validation outcome: n_events, warnings, errors, schema_snapshot, content_digest. Source-agnostic. |
54
+ | ComparisonResult | Revision detection between snapshots: n_added, n_removed, n_revised, total_revision_magnitude. Source-agnostic. |
55
+ | validate_events | Validates events against injected schema (required_fields, field_types). Uses `datafactory_provenance.compute_content_digest`. |
56
+ | compare_snapshots | Compares new events against previous Parquet snapshot. Injected id_field and key_fields. |
57
+ | save_event_snapshot | Parquet persistence of raw events with snappy compression. All source fields preserved. |
58
+ | Source registry | Dict-based registry. Sources auto-register on import. `fetch_source("ucdp_annual")` dispatches to the right function. |
59
+ | UcdpAnnualConfig | Frozen dataclass with `__post_init__` validation. Harvest-only params (no report params). |
60
+ | UcdpCandidateConfig | Frozen dataclass with `__post_init__` validation. Version discovery + rate limiting. |
61
+ | UcdpDot9Config | Frozen dataclass with `__post_init__` validation. .9 stream version discovery + rate limiting. |
62
+ | PriogridStaticConfig | Frozen dataclass with `__post_init__` validation. PRIO-GRID 2.0 API, variable selection, timeout. |
63
+
64
+ ## Source Plugin Pattern
65
+
66
+ Each data source lives in `sources/` as its own module. The shared skeleton provides:
67
+ - `validation.py`: validate_events (accepts schema as params), compare_snapshots (accepts id_field/key_fields)
68
+ - `storage.py`: save_event_snapshot, archive_snapshot
69
+ - `sources/__init__.py`: register_source, fetch_source
70
+
71
+ Each source module provides:
72
+ - Config (frozen dataclass with `__post_init__`)
73
+ - API client (fetch logic, pagination, retry)
74
+ - Schema contract (REQUIRED_FIELDS, FIELD_TYPES)
75
+ - Orchestrator (fetch -> validate -> compare -> store -> provenance)
76
+
77
+ Adding a new source means adding `sources/<name>.py`. No changes to existing sources.
78
+
79
+ ## Invariants
80
+ - **Single-writer access assumed.** No concurrent operations supported (see technical_risk_register_resolved.md C-16)
81
+
82
+ - Raw data is stored unaltered (all source fields preserved in Parquet)
83
+ - Content digest (via `datafactory_provenance.compute_content_digest`) on every harvest
84
+ - Schema validation on every fetch -- fail-loud on missing required fields (ADR-003)
85
+ - Provenance ledger entry appended for every harvest operation, success or failure (ADR-008)
86
+ - Sources are independent: no source module imports from another source module
87
+ - **Local-first skip:** if snapshot file exists on disk AND ledger has a digest for that version, skip without touching the API (outcome: `"cached"`). Other outcomes: `"success"`, `"unchanged"`, `"failed"`
88
+ - **Archive retention:** Snapshot archives are kept indefinitely. No automatic cleanup.
89
+ - All error paths log before raising (ADR-008)
90
+
91
+ ## Intent Contracts
92
+
93
+ CICs exist for:
94
+ - `UcdpAnnualConfig` -- governs UCDP annual harvest parameters
95
+ - `UcdpCandidateConfig` -- governs UCDP candidate monthly harvest parameters
96
+ - `UcdpDot9Config` -- governs UCDP .9 consolidated monthly harvest parameters
97
+ - `PriogridStaticConfig` -- governs PRIO-GRID static feature harvest parameters
98
+ - `AcledConfig` -- governs ACLED event data harvest parameters
99
+ - `GhsPopConfig` -- governs GHS-POP raster harvest parameters
100
+ - `GhsBuiltSConfig` -- governs GHS-BUILT-S raster harvest parameters
101
+ - `GaulAdminConfig` -- governs GAUL admin boundary harvest parameters
102
+ - `ValidationResult` -- structured validation outcome
103
+ - `ComparisonResult` -- structured revision detection outcome
@@ -0,0 +1,37 @@
1
+ """Data harvesting framework with pluggable sources.
2
+
3
+ Pattern: config -> fetch -> validate -> store -> provenance.
4
+ Raw data stored unaltered. No transformation at fetch time.
5
+
6
+ Access specific sources via:
7
+ from datafactory_harvester.sources.ucdp_annual import fetch_ucdp_annual
8
+
9
+ Or use the registry:
10
+ from datafactory_harvester.sources import fetch_source
11
+ fetch_source("ucdp_annual", config=...)
12
+ """
13
+
14
+ from datafactory_harvester.event_validation import (
15
+ ComparisonResult,
16
+ ValidationResult,
17
+ compare_snapshots,
18
+ date_range,
19
+ validate_dgp_assumptions,
20
+ validate_events,
21
+ )
22
+ from datafactory_harvester.snapshot_storage import archive_snapshot, save_event_snapshot
23
+ from datafactory_harvester.sources import fetch_source, list_sources, register_source
24
+
25
+ __all__ = [
26
+ "ValidationResult",
27
+ "ComparisonResult",
28
+ "validate_events",
29
+ "validate_dgp_assumptions",
30
+ "compare_snapshots",
31
+ "date_range",
32
+ "save_event_snapshot",
33
+ "archive_snapshot",
34
+ "register_source",
35
+ "fetch_source",
36
+ "list_sources",
37
+ ]
@@ -0,0 +1,372 @@
1
+ """Source-agnostic event validation and snapshot comparison.
2
+
3
+ Provides structured result types and reusable validation/comparison
4
+ logic for any harvested event data. Source-specific schema definitions
5
+ (required fields, type mappings) are injected by the caller.
6
+
7
+ No knowledge of specific data sources (UCDP, ACLED, etc.).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ from collections.abc import Callable, Sequence
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+
18
+ import pyarrow.parquet as pq
19
+
20
+ from datafactory_provenance import compute_content_digest
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass
26
+ class ValidationResult:
27
+ """Outcome of validating a batch of raw events."""
28
+
29
+ valid: bool
30
+ n_events: int
31
+ warnings: list[str] = field(default_factory=list)
32
+ errors: list[str] = field(default_factory=list)
33
+ schema_snapshot: dict[str, str] = field(default_factory=dict)
34
+ content_digest: str = ""
35
+
36
+
37
+ @dataclass
38
+ class ComparisonResult:
39
+ """Structured result from comparing two event snapshots."""
40
+
41
+ has_previous: bool
42
+ n_added: int = 0
43
+ n_removed: int = 0
44
+ n_revised: int = 0
45
+ total_revision_magnitude: float = 0.0
46
+ revised_events: list[dict] = field(default_factory=list)
47
+ warnings: list[str] = field(default_factory=list)
48
+
49
+
50
+ def date_range(
51
+ events: list[dict],
52
+ field_name: str = "date_start",
53
+ ) -> tuple[str | None, str | None]:
54
+ """Extract min/max date strings from events.
55
+
56
+ Returns (min_date, max_date) or (None, None) if no dates found.
57
+ """
58
+ dates: list[str] = [
59
+ str(e[field_name])
60
+ for e in events
61
+ if e.get(field_name)
62
+ ]
63
+ if not dates:
64
+ return None, None
65
+ return min(dates), max(dates)
66
+
67
+
68
+ def validate_events(
69
+ events: list[dict],
70
+ required_fields: set[str],
71
+ field_types: dict[str, tuple[type, ...]],
72
+ *,
73
+ digest_fields: tuple[str, ...] = ("id", "best"),
74
+ ) -> ValidationResult:
75
+ """Validate raw events against a schema contract.
76
+
77
+ Checks every event for required field presence and type correctness.
78
+ Collects warnings for non-fatal issues (bound inconsistencies, etc.)
79
+ without halting. Fatal schema violations are recorded as errors.
80
+
81
+ Args:
82
+ events: List of raw event dicts.
83
+ required_fields: Field names that must be present.
84
+ field_types: Mapping of field name to acceptable types.
85
+ digest_fields: Fields to include in the content digest.
86
+
87
+ Returns:
88
+ ValidationResult; caller decides whether to halt or continue.
89
+ """
90
+ if not events:
91
+ err_msg = "No events to validate."
92
+ logger.error(err_msg)
93
+ return ValidationResult(valid=False, n_events=0, errors=[err_msg])
94
+
95
+ warnings: list[str] = []
96
+ errors: list[str] = []
97
+
98
+ # Schema snapshot from first event
99
+ first = events[0]
100
+ schema_snapshot = {k: type(v).__name__ for k, v in first.items()}
101
+
102
+ # Check required fields on first event (fast fail)
103
+ missing = required_fields - set(first.keys())
104
+ if missing:
105
+ err_msg = f"Required fields missing: {sorted(missing)}"
106
+ logger.error(err_msg)
107
+ errors.append(err_msg)
108
+ return ValidationResult(
109
+ valid=False,
110
+ n_events=len(events),
111
+ warnings=warnings,
112
+ errors=errors,
113
+ schema_snapshot=schema_snapshot,
114
+ )
115
+
116
+ # Check ID uniqueness (skip if ids are unhashable — type errors
117
+ # will be caught by the per-event type check below)
118
+ ids = [ev.get("id") for ev in events]
119
+ try:
120
+ unique_ids = set(ids)
121
+ if len(unique_ids) != len(ids):
122
+ n_dupes = len(ids) - len(unique_ids)
123
+ warnings.append(
124
+ f"Duplicate event IDs: {n_dupes} duplicates in {len(ids)} events"
125
+ )
126
+ except TypeError:
127
+ warnings.append("Cannot check ID uniqueness: IDs contain unhashable types")
128
+
129
+ # Validate types and values across all events
130
+ negative_best = 0
131
+ bound_violations = 0
132
+ coord_violations = 0
133
+
134
+ for i, ev in enumerate(events):
135
+ ev_missing = required_fields - set(ev.keys())
136
+ if ev_missing:
137
+ errors.append(
138
+ f"Event at index {i} (id={ev.get('id', '?')}) "
139
+ f"missing fields: {sorted(ev_missing)}"
140
+ )
141
+ continue
142
+
143
+ # Type checks on critical fields
144
+ for field_name, expected_types in field_types.items():
145
+ value = ev.get(field_name)
146
+ if value is not None and not isinstance(value, expected_types):
147
+ errors.append(
148
+ f"Event {ev.get('id', '?')}: field '{field_name}' "
149
+ f"is {type(value).__name__}, expected "
150
+ f"{'/'.join(t.__name__ for t in expected_types)}"
151
+ )
152
+
153
+ # Fatality bound checks (warnings, not errors)
154
+ best = ev.get("best")
155
+ high = ev.get("high")
156
+ low = ev.get("low")
157
+
158
+ if best is not None and isinstance(best, (int, float)):
159
+ if best < 0:
160
+ negative_best += 1
161
+ if high is not None and isinstance(high, (int, float)) and best > high:
162
+ bound_violations += 1
163
+ if low is not None and isinstance(low, (int, float)) and low > best:
164
+ bound_violations += 1
165
+
166
+ # Coordinate range checks (warnings)
167
+ lat = ev.get("latitude")
168
+ lon = ev.get("longitude")
169
+ if (
170
+ lat is not None
171
+ and isinstance(lat, (int, float))
172
+ and not (-90 <= lat <= 90)
173
+ ):
174
+ coord_violations += 1
175
+ if (
176
+ lon is not None
177
+ and isinstance(lon, (int, float))
178
+ and not (-180 <= lon <= 180)
179
+ ):
180
+ coord_violations += 1
181
+
182
+ if coord_violations > 0:
183
+ warnings.append(
184
+ f"Coordinate range violations on {coord_violations} "
185
+ f"field values (lat outside [-90,90] or lon outside "
186
+ f"[-180,180])"
187
+ )
188
+ if negative_best > 0:
189
+ warnings.append(f"Negative 'best' values on {negative_best} events")
190
+ if bound_violations > 0:
191
+ warnings.append(
192
+ f"Fatality bound violations (best>high or low>best) "
193
+ f"on {bound_violations} events"
194
+ )
195
+
196
+ # Content digest from specified fields
197
+ digest_data = sorted(
198
+ tuple(ev.get(f, 0) for f in digest_fields) for ev in events
199
+ )
200
+ content_digest = compute_content_digest(
201
+ json.dumps(digest_data, sort_keys=True).encode()
202
+ )
203
+
204
+ return ValidationResult(
205
+ valid=len(errors) == 0,
206
+ n_events=len(events),
207
+ warnings=warnings,
208
+ errors=errors,
209
+ schema_snapshot=schema_snapshot,
210
+ content_digest=content_digest,
211
+ )
212
+
213
+
214
+ def validate_dgp_assumptions(
215
+ events: list[dict],
216
+ checks: Sequence[Callable[[dict], str | None]],
217
+ *,
218
+ source_name: str = "unknown",
219
+ warn_only: bool = False,
220
+ ) -> None:
221
+ """Validate data-generating process assumptions on harvested events.
222
+
223
+ Each check callable receives a single event dict and returns None
224
+ if the assumption holds, or a violation description string if not.
225
+ Collects all violations across all events and checks, then raises
226
+ ValueError with the full report if any are found.
227
+
228
+ Args:
229
+ events: List of raw event dicts.
230
+ checks: Sequence of check callables.
231
+ source_name: Source identifier for the error message.
232
+ warn_only: If True, log violations as a warning instead of
233
+ raising. For checks that describe known characteristics
234
+ of the published source data rather than hard invariants.
235
+
236
+ Raises:
237
+ ValueError: If any DGP assumption is violated and warn_only
238
+ is False.
239
+ """
240
+ violations: list[str] = []
241
+ for i, event in enumerate(events):
242
+ for check in checks:
243
+ result = check(event)
244
+ if result is not None:
245
+ violations.append(
246
+ f"Event {i} (id={event.get('id', '?')}): {result}"
247
+ )
248
+
249
+ if violations:
250
+ summary = "; ".join(violations[:20])
251
+ if warn_only:
252
+ logger.warning(
253
+ "%s DGP validation: %d violation(s) "
254
+ "(known source characteristic, not blocking): %s",
255
+ source_name,
256
+ len(violations),
257
+ summary,
258
+ )
259
+ return
260
+ raise ValueError(
261
+ f"{source_name} DGP validation: {len(violations)} "
262
+ f"violation(s): {summary}"
263
+ )
264
+
265
+
266
+ def compare_snapshots(
267
+ old_path: Path,
268
+ new_events: list[dict],
269
+ *,
270
+ id_field: str = "id",
271
+ key_fields: tuple[str, ...] = ("best", "country_id", "date_start"),
272
+ ) -> ComparisonResult:
273
+ """Compare new events against a previous Parquet snapshot.
274
+
275
+ Uses the id_field to match events across fetches. Detects added,
276
+ removed, and revised events. Revision magnitude is computed on the
277
+ first key_field (typically 'best' / fatality count).
278
+
279
+ Args:
280
+ old_path: Path to the previous Parquet snapshot.
281
+ new_events: List of new event dicts.
282
+ id_field: Field name used as the event identifier.
283
+ key_fields: Fields to extract for comparison.
284
+
285
+ Returns:
286
+ ComparisonResult with structured diff data.
287
+ """
288
+ if not old_path.exists():
289
+ return ComparisonResult(has_previous=False)
290
+
291
+ old_table = pq.read_table(old_path)
292
+
293
+ if id_field not in old_table.column_names:
294
+ return ComparisonResult(
295
+ has_previous=True,
296
+ warnings=[
297
+ f"Previous snapshot lacks '{id_field}' column; cannot compare"
298
+ ],
299
+ )
300
+
301
+ # Build old lookup: id -> {key_field: value, ...}
302
+ old_id_list = old_table.column(id_field).to_pylist()
303
+ old_key_data: dict[str, list] = {}
304
+ for kf in key_fields:
305
+ if kf in old_table.column_names:
306
+ old_key_data[kf] = old_table.column(kf).to_pylist()
307
+ else:
308
+ old_key_data[kf] = [None] * len(old_id_list)
309
+
310
+ old_ids: set[int] = set()
311
+ old_lookup: dict[int, dict] = {}
312
+ for idx, oid in enumerate(old_id_list):
313
+ if oid is not None:
314
+ old_ids.add(oid)
315
+ old_lookup[oid] = {kf: old_key_data[kf][idx] for kf in key_fields}
316
+
317
+ # Build new lookup
318
+ new_ids: set[int] = set()
319
+ new_lookup: dict[int, dict] = {}
320
+ for ev in new_events:
321
+ eid = ev.get(id_field)
322
+ if eid is not None:
323
+ new_ids.add(eid)
324
+ new_lookup[eid] = {kf: ev.get(kf) for kf in key_fields}
325
+
326
+ # Compute diffs
327
+ added = new_ids - old_ids
328
+ removed = old_ids - new_ids
329
+ common = old_ids & new_ids
330
+
331
+ # Detect revised events (first key_field changed)
332
+ magnitude_field = key_fields[0] if key_fields else None
333
+ revised_events: list[dict] = []
334
+ total_magnitude = 0.0
335
+
336
+ if magnitude_field:
337
+ for eid in common:
338
+ old_val = old_lookup[eid].get(magnitude_field, 0) or 0
339
+ new_val = new_lookup[eid].get(magnitude_field, 0) or 0
340
+ if old_val != new_val:
341
+ delta = new_val - old_val
342
+ total_magnitude += abs(delta)
343
+ revised_events.append({
344
+ id_field: eid,
345
+ f"old_{magnitude_field}": old_val,
346
+ f"new_{magnitude_field}": new_val,
347
+ "delta": delta,
348
+ })
349
+
350
+ revised_events.sort(key=lambda r: abs(r.get("delta", 0)), reverse=True)
351
+
352
+ warnings = []
353
+ if added:
354
+ warnings.append(f"Revision: {len(added)} new events added")
355
+ if removed:
356
+ warnings.append(f"Revision: {len(removed)} events removed")
357
+ if revised_events:
358
+ warnings.append(
359
+ f"Revision: {len(revised_events)} events with changed "
360
+ f"'{magnitude_field}' values (total magnitude: "
361
+ f"{total_magnitude:,.0f})"
362
+ )
363
+
364
+ return ComparisonResult(
365
+ has_previous=True,
366
+ n_added=len(added),
367
+ n_removed=len(removed),
368
+ n_revised=len(revised_events),
369
+ total_revision_magnitude=total_magnitude,
370
+ revised_events=revised_events,
371
+ warnings=warnings,
372
+ )
@@ -0,0 +1,72 @@
1
+ """Shared harvest execution wrapper (C-164 Pattern #8).
2
+
3
+ Provides run_harvest() — the common skeleton for all harvest
4
+ scripts: line buffering, banner, timing, and error handling.
5
+ Source-specific logic stays in the calling script.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ import time
12
+ from collections.abc import Callable
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class HarvestResult:
19
+ """Uniform result from a harvest run."""
20
+
21
+ source_name: str
22
+ outcome: str
23
+ elapsed: float
24
+ data: Any = None
25
+ error: str | None = None
26
+
27
+
28
+ def run_harvest(
29
+ *,
30
+ source_name: str,
31
+ fetch_fn: Callable[..., Any],
32
+ config_summary: dict[str, str],
33
+ force_refresh: bool = False,
34
+ fetch_kwargs: dict[str, Any] | None = None,
35
+ ) -> HarvestResult:
36
+ """Execute a harvest with standard banner, timing, and error handling.
37
+
38
+ Prints banner, calls fetch_fn, catches exceptions, returns result
39
+ with timing. The calling script handles source-specific reporting.
40
+ """
41
+ sys.stdout.reconfigure(line_buffering=True) # type: ignore[union-attr]
42
+
43
+ print("=" * 60)
44
+ print(f"{source_name} HARVEST")
45
+ for key, value in config_summary.items():
46
+ print(f"{key}: {value}")
47
+ print("=" * 60)
48
+ print()
49
+
50
+ kwargs = dict(fetch_kwargs or {})
51
+ kwargs["force_refresh"] = force_refresh
52
+
53
+ t0 = time.monotonic()
54
+ try:
55
+ raw = fetch_fn(**kwargs)
56
+ except Exception as e:
57
+ elapsed = time.monotonic() - t0
58
+ print(f"FAIL: {e}")
59
+ return HarvestResult(
60
+ source_name=source_name,
61
+ outcome="failed",
62
+ elapsed=elapsed,
63
+ error=str(e),
64
+ )
65
+
66
+ elapsed = time.monotonic() - t0
67
+ return HarvestResult(
68
+ source_name=source_name,
69
+ outcome="success",
70
+ elapsed=elapsed,
71
+ data=raw,
72
+ )