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,462 @@
|
|
|
1
|
+
"""ACLED consolidator — raw harvester snapshots into event store.
|
|
2
|
+
|
|
3
|
+
Reads ACLED Parquet snapshots from the harvester output directory,
|
|
4
|
+
tags each with source metadata (_source_type, _ingested_at,
|
|
5
|
+
_harvest_digest, _harvest_timestamp), and writes a single
|
|
6
|
+
consolidated Parquet store.
|
|
7
|
+
|
|
8
|
+
Simpler than the UCDP consolidator: ACLED has one source type
|
|
9
|
+
(no annual/candidate/dot9 split) and no vintage complexity.
|
|
10
|
+
|
|
11
|
+
Implements ADR-013 (consolidation principles).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from datetime import UTC, datetime
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
import pyarrow as pa
|
|
25
|
+
import pyarrow.parquet as pq
|
|
26
|
+
|
|
27
|
+
from datafactory_consolidation.consolidation_result import (
|
|
28
|
+
ConsolidationResult,
|
|
29
|
+
)
|
|
30
|
+
from datafactory_consolidation.consolidators import register_consolidator
|
|
31
|
+
from datafactory_consolidation.event_store import read_store, write_store
|
|
32
|
+
from datafactory_consolidation.tagging import tag_table
|
|
33
|
+
from datafactory_provenance import (
|
|
34
|
+
DIGEST_SCHEME,
|
|
35
|
+
LEDGER_VERSION,
|
|
36
|
+
append_ledger_entry,
|
|
37
|
+
compute_content_digest,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
DATASET_ID = "acled_consolidation"
|
|
43
|
+
|
|
44
|
+
REQUIRED_SOURCE_FIELDS: set[str] = {"event_id_cnty"}
|
|
45
|
+
|
|
46
|
+
PRODUCED_METADATA: tuple[str, ...] = (
|
|
47
|
+
"_source_type",
|
|
48
|
+
"_source_version",
|
|
49
|
+
"_ingested_at",
|
|
50
|
+
"_harvest_digest",
|
|
51
|
+
"_harvest_timestamp",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
_SNAPSHOT_PATTERN = re.compile(
|
|
55
|
+
r"acled_(\d+)_(\d+)\.parquet$"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _extract_version(path: Path) -> str:
|
|
60
|
+
"""Extract version string from ACLED snapshot filename.
|
|
61
|
+
|
|
62
|
+
Example: acled_1997_2025.parquet → "1997_2025"
|
|
63
|
+
"""
|
|
64
|
+
match = _SNAPSHOT_PATTERN.search(path.name)
|
|
65
|
+
if not match:
|
|
66
|
+
err_msg = (
|
|
67
|
+
f"Cannot extract version from ACLED filename: "
|
|
68
|
+
f"{path.name}. Expected: acled_<start>_<end>.parquet"
|
|
69
|
+
)
|
|
70
|
+
logger.error(err_msg)
|
|
71
|
+
raise ValueError(err_msg)
|
|
72
|
+
return f"{match.group(1)}_{match.group(2)}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _build_harvest_index(
|
|
76
|
+
ledger_path: Path,
|
|
77
|
+
) -> dict[str, tuple[str, str]]:
|
|
78
|
+
"""Build (digest, timestamp) lookup from harvest ledger."""
|
|
79
|
+
if not ledger_path.exists():
|
|
80
|
+
return {}
|
|
81
|
+
|
|
82
|
+
index: dict[str, tuple[str, str]] = {}
|
|
83
|
+
for line in ledger_path.read_text().strip().splitlines():
|
|
84
|
+
line = line.strip()
|
|
85
|
+
if not line:
|
|
86
|
+
continue
|
|
87
|
+
try:
|
|
88
|
+
entry = json.loads(line)
|
|
89
|
+
except json.JSONDecodeError:
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
if entry.get("outcome") not in ("success", "unchanged"):
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
digest = entry.get("content_digest")
|
|
96
|
+
timestamp = entry.get("timestamp")
|
|
97
|
+
start = entry.get("start_year")
|
|
98
|
+
end = entry.get("end_year")
|
|
99
|
+
|
|
100
|
+
if digest and timestamp and start is not None and end is not None:
|
|
101
|
+
version_key = f"{start}_{end}"
|
|
102
|
+
index[version_key] = (digest, timestamp)
|
|
103
|
+
|
|
104
|
+
return index
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _get_harvest_metadata(
|
|
108
|
+
version: str,
|
|
109
|
+
harvest_index: dict[str, tuple[str, str]],
|
|
110
|
+
fallback_path: Path,
|
|
111
|
+
) -> tuple[str, str]:
|
|
112
|
+
"""Get harvest digest and timestamp for a version."""
|
|
113
|
+
if version in harvest_index:
|
|
114
|
+
return harvest_index[version]
|
|
115
|
+
|
|
116
|
+
digest = compute_content_digest(fallback_path.read_bytes())
|
|
117
|
+
timestamp = datetime.fromtimestamp(
|
|
118
|
+
fallback_path.stat().st_mtime, tz=UTC
|
|
119
|
+
).isoformat()
|
|
120
|
+
logger.info(
|
|
121
|
+
"No ledger entry for version %s — using file digest %s",
|
|
122
|
+
version,
|
|
123
|
+
digest,
|
|
124
|
+
)
|
|
125
|
+
return digest, timestamp
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _check_year_overlap(
|
|
129
|
+
source_files: list[Path],
|
|
130
|
+
) -> list[str]:
|
|
131
|
+
"""Detect overlapping year ranges among source files."""
|
|
132
|
+
ranges = []
|
|
133
|
+
for p in source_files:
|
|
134
|
+
m = _SNAPSHOT_PATTERN.search(p.name)
|
|
135
|
+
if m:
|
|
136
|
+
ranges.append(
|
|
137
|
+
(int(m.group(1)), int(m.group(2)), p.name)
|
|
138
|
+
)
|
|
139
|
+
warnings = []
|
|
140
|
+
for i, (s1, e1, n1) in enumerate(ranges):
|
|
141
|
+
for s2, e2, n2 in ranges[i + 1 :]:
|
|
142
|
+
if s1 <= e2 and s2 <= e1:
|
|
143
|
+
overlap_start = max(s1, s2)
|
|
144
|
+
overlap_end = min(e1, e2)
|
|
145
|
+
warnings.append(
|
|
146
|
+
f"Overlapping year ranges: {n1} "
|
|
147
|
+
f"({s1}-{e1}) and {n2} ({s2}-{e2}), "
|
|
148
|
+
f"overlap: {overlap_start}-{overlap_end}"
|
|
149
|
+
)
|
|
150
|
+
return warnings
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _dedup_by_event_id(
|
|
154
|
+
table: pa.Table,
|
|
155
|
+
) -> tuple[pa.Table, int]:
|
|
156
|
+
"""Deduplicate table on event_id_cnty, keeping latest harvest.
|
|
157
|
+
|
|
158
|
+
When the same event appears in multiple source files, keep the
|
|
159
|
+
row with the latest _harvest_timestamp. ACLED has no vintage
|
|
160
|
+
semantics — only the most recent version of each event matters.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
(deduped_table, n_removed)
|
|
164
|
+
"""
|
|
165
|
+
eids = table.column("event_id_cnty").to_pylist()
|
|
166
|
+
if len(eids) == len(set(eids)):
|
|
167
|
+
return table, 0
|
|
168
|
+
|
|
169
|
+
timestamps = table.column(
|
|
170
|
+
"_harvest_timestamp"
|
|
171
|
+
).to_pylist()
|
|
172
|
+
seen: dict[str, int] = {}
|
|
173
|
+
for i, (eid, ts) in enumerate(
|
|
174
|
+
zip(eids, timestamps, strict=True)
|
|
175
|
+
):
|
|
176
|
+
if eid not in seen or ts > timestamps[seen[eid]]:
|
|
177
|
+
seen[eid] = i
|
|
178
|
+
|
|
179
|
+
keep_indices = sorted(seen.values())
|
|
180
|
+
n_removed = len(eids) - len(keep_indices)
|
|
181
|
+
logger.warning(
|
|
182
|
+
"Cross-file dedup: %d duplicate events removed, "
|
|
183
|
+
"%d unique events retained",
|
|
184
|
+
n_removed,
|
|
185
|
+
len(keep_indices),
|
|
186
|
+
)
|
|
187
|
+
return table.take(keep_indices), n_removed
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass(frozen=True)
|
|
191
|
+
class AcledConsolidationConfig:
|
|
192
|
+
"""Configuration for ACLED consolidation."""
|
|
193
|
+
|
|
194
|
+
source_dir: Path = Path("data/raw/acled")
|
|
195
|
+
harvest_ledger_path: Path = Path(
|
|
196
|
+
"provenance/acled/ingestion_ledger.jsonl"
|
|
197
|
+
)
|
|
198
|
+
output_path: Path = Path(
|
|
199
|
+
"data/consolidated/acled/acled_store.parquet"
|
|
200
|
+
)
|
|
201
|
+
ledger_path: Path = Path(
|
|
202
|
+
"provenance/consolidation/acled_ledger.jsonl"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def consolidate_acled(
|
|
207
|
+
config: AcledConsolidationConfig | None = None,
|
|
208
|
+
) -> ConsolidationResult:
|
|
209
|
+
"""Consolidate ACLED harvester snapshots into a single store.
|
|
210
|
+
|
|
211
|
+
Tags each record with source metadata. Deduplicates on
|
|
212
|
+
event_id_cnty alone — ACLED has no vintage semantics, so
|
|
213
|
+
only the latest version of each event is kept.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
config: Consolidation configuration. Uses defaults if None.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
ConsolidationResult with record counts and output digest.
|
|
220
|
+
|
|
221
|
+
Raises:
|
|
222
|
+
FileNotFoundError: If no source Parquet files are found.
|
|
223
|
+
"""
|
|
224
|
+
if config is None:
|
|
225
|
+
config = AcledConsolidationConfig()
|
|
226
|
+
|
|
227
|
+
ingested_at = datetime.now(tz=UTC).isoformat()
|
|
228
|
+
|
|
229
|
+
harvest_index = _build_harvest_index(
|
|
230
|
+
config.harvest_ledger_path
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
source_files = (
|
|
234
|
+
sorted(
|
|
235
|
+
p for p in config.source_dir.glob("*.parquet")
|
|
236
|
+
if _SNAPSHOT_PATTERN.search(p.name)
|
|
237
|
+
)
|
|
238
|
+
if config.source_dir.exists()
|
|
239
|
+
else []
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
if not source_files:
|
|
243
|
+
err_msg = (
|
|
244
|
+
f"No ACLED Parquet files found in {config.source_dir}"
|
|
245
|
+
)
|
|
246
|
+
logger.error(err_msg)
|
|
247
|
+
raise FileNotFoundError(err_msg)
|
|
248
|
+
|
|
249
|
+
for warning in _check_year_overlap(source_files):
|
|
250
|
+
logger.warning(warning)
|
|
251
|
+
|
|
252
|
+
tagged_tables: list[pa.Table] = []
|
|
253
|
+
source_manifest: list[dict] = []
|
|
254
|
+
|
|
255
|
+
for path in source_files:
|
|
256
|
+
version = _extract_version(path)
|
|
257
|
+
h_digest, h_timestamp = _get_harvest_metadata(
|
|
258
|
+
version, harvest_index, path
|
|
259
|
+
)
|
|
260
|
+
table = pq.read_table(path)
|
|
261
|
+
|
|
262
|
+
missing = REQUIRED_SOURCE_FIELDS - set(table.column_names)
|
|
263
|
+
if missing:
|
|
264
|
+
err_msg = (
|
|
265
|
+
f"{path.name}: missing required fields "
|
|
266
|
+
f"{sorted(missing)}"
|
|
267
|
+
)
|
|
268
|
+
logger.error(err_msg)
|
|
269
|
+
raise ValueError(err_msg)
|
|
270
|
+
|
|
271
|
+
tagged = tag_table(
|
|
272
|
+
table,
|
|
273
|
+
source_type="acled",
|
|
274
|
+
source_version=version,
|
|
275
|
+
ingested_at=ingested_at,
|
|
276
|
+
harvest_digest=h_digest,
|
|
277
|
+
harvest_timestamp=h_timestamp,
|
|
278
|
+
)
|
|
279
|
+
tagged_tables.append(tagged)
|
|
280
|
+
|
|
281
|
+
dates = (
|
|
282
|
+
[
|
|
283
|
+
d
|
|
284
|
+
for d in table.column("event_date").to_pylist()
|
|
285
|
+
if d
|
|
286
|
+
]
|
|
287
|
+
if "event_date" in table.column_names
|
|
288
|
+
else []
|
|
289
|
+
)
|
|
290
|
+
source_manifest.append({
|
|
291
|
+
"path": str(path),
|
|
292
|
+
"source_type": "acled",
|
|
293
|
+
"version": version,
|
|
294
|
+
"n_records": table.num_rows,
|
|
295
|
+
"min_date": min(dates) if dates else None,
|
|
296
|
+
"max_date": max(dates) if dates else None,
|
|
297
|
+
"harvest_digest": h_digest,
|
|
298
|
+
"harvest_timestamp": h_timestamp,
|
|
299
|
+
})
|
|
300
|
+
logger.info(
|
|
301
|
+
"Read ACLED: %s (v%s, %d records, digest %s)",
|
|
302
|
+
path.name,
|
|
303
|
+
version,
|
|
304
|
+
table.num_rows,
|
|
305
|
+
h_digest,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
new_table = pa.concat_tables(
|
|
309
|
+
tagged_tables, promote_options="default"
|
|
310
|
+
)
|
|
311
|
+
n_concat = new_table.num_rows
|
|
312
|
+
new_table, n_dedup_removed = _dedup_by_event_id(new_table)
|
|
313
|
+
n_new_raw = new_table.num_rows
|
|
314
|
+
|
|
315
|
+
if n_concat != n_new_raw + n_dedup_removed:
|
|
316
|
+
raise RuntimeError(
|
|
317
|
+
f"Count conservation violation at cross-file dedup: "
|
|
318
|
+
f"concat ({n_concat}) != "
|
|
319
|
+
f"deduped ({n_new_raw}) + removed ({n_dedup_removed})"
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
existing = read_store(config.output_path)
|
|
323
|
+
n_replaced = 0
|
|
324
|
+
if existing is not None:
|
|
325
|
+
n_before = existing.num_rows
|
|
326
|
+
|
|
327
|
+
existing_eids = existing.column(
|
|
328
|
+
"event_id_cnty"
|
|
329
|
+
).to_pylist()
|
|
330
|
+
existing_ts = existing.column(
|
|
331
|
+
"_harvest_timestamp"
|
|
332
|
+
).to_pylist()
|
|
333
|
+
existing_lookup: dict[str, tuple[int, str]] = {}
|
|
334
|
+
for i, (eid, ts) in enumerate(
|
|
335
|
+
zip(existing_eids, existing_ts, strict=True)
|
|
336
|
+
):
|
|
337
|
+
existing_lookup[eid] = (i, ts)
|
|
338
|
+
|
|
339
|
+
# The merge below assumes one row per event_id. A store
|
|
340
|
+
# with duplicates loses all copies of a replaced event,
|
|
341
|
+
# surfacing later as a cryptic conservation failure.
|
|
342
|
+
if len(existing_lookup) != len(existing_eids):
|
|
343
|
+
raise RuntimeError(
|
|
344
|
+
f"Existing store is corrupted: "
|
|
345
|
+
f"{len(existing_eids)} rows but only "
|
|
346
|
+
f"{len(existing_lookup)} unique event_ids "
|
|
347
|
+
f"(duplicate events). Delete "
|
|
348
|
+
f"{config.output_path} and re-run to rebuild "
|
|
349
|
+
f"from raw snapshots."
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
new_ids = new_table.column("event_id_cnty").to_pylist()
|
|
353
|
+
new_ts = new_table.column(
|
|
354
|
+
"_harvest_timestamp"
|
|
355
|
+
).to_pylist()
|
|
356
|
+
|
|
357
|
+
new_keep_indices: list[int] = []
|
|
358
|
+
replace_eids: set[str] = set()
|
|
359
|
+
for j, (eid, ts) in enumerate(
|
|
360
|
+
zip(new_ids, new_ts, strict=True)
|
|
361
|
+
):
|
|
362
|
+
if eid not in existing_lookup:
|
|
363
|
+
new_keep_indices.append(j)
|
|
364
|
+
elif ts > existing_lookup[eid][1]:
|
|
365
|
+
new_keep_indices.append(j)
|
|
366
|
+
replace_eids.add(eid)
|
|
367
|
+
|
|
368
|
+
n_replaced = len(replace_eids)
|
|
369
|
+
|
|
370
|
+
if replace_eids:
|
|
371
|
+
keep_existing_mask = [
|
|
372
|
+
eid not in replace_eids for eid in existing_eids
|
|
373
|
+
]
|
|
374
|
+
existing = existing.filter(keep_existing_mask)
|
|
375
|
+
|
|
376
|
+
n_new = len(new_keep_indices) - n_replaced
|
|
377
|
+
|
|
378
|
+
if new_keep_indices:
|
|
379
|
+
new_filtered = new_table.take(new_keep_indices)
|
|
380
|
+
combined = pa.concat_tables(
|
|
381
|
+
[existing, new_filtered],
|
|
382
|
+
promote_options="default",
|
|
383
|
+
)
|
|
384
|
+
else:
|
|
385
|
+
combined = existing
|
|
386
|
+
|
|
387
|
+
logger.info(
|
|
388
|
+
"Dedup: %d raw, %d already in store, "
|
|
389
|
+
"%d replaced, %d new added",
|
|
390
|
+
n_new_raw,
|
|
391
|
+
n_new_raw - len(new_keep_indices),
|
|
392
|
+
n_replaced,
|
|
393
|
+
n_new,
|
|
394
|
+
)
|
|
395
|
+
if n_replaced > 0:
|
|
396
|
+
logger.warning(
|
|
397
|
+
"Cross-run replacement: %d events updated "
|
|
398
|
+
"to newer version",
|
|
399
|
+
n_replaced,
|
|
400
|
+
)
|
|
401
|
+
n_kept_from_new = len(new_keep_indices)
|
|
402
|
+
else:
|
|
403
|
+
combined = new_table
|
|
404
|
+
n_new = n_new_raw
|
|
405
|
+
n_before = 0
|
|
406
|
+
n_kept_from_new = n_new_raw
|
|
407
|
+
|
|
408
|
+
expected_total = (n_before - n_replaced) + n_kept_from_new
|
|
409
|
+
if combined.num_rows != expected_total:
|
|
410
|
+
raise RuntimeError(
|
|
411
|
+
f"Count conservation violation at store merge: "
|
|
412
|
+
f"expected ({n_before} - {n_replaced}) + "
|
|
413
|
+
f"{n_kept_from_new} = {expected_total}, "
|
|
414
|
+
f"got {combined.num_rows}"
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
output_digest = write_store(combined, config.output_path)
|
|
418
|
+
|
|
419
|
+
n_total = combined.num_rows
|
|
420
|
+
|
|
421
|
+
schema_cols = sorted(combined.column_names)
|
|
422
|
+
schema_fingerprint = hashlib.sha256(
|
|
423
|
+
",".join(schema_cols).encode()
|
|
424
|
+
).hexdigest()[:16]
|
|
425
|
+
|
|
426
|
+
append_ledger_entry(config.ledger_path, {
|
|
427
|
+
"dataset": DATASET_ID,
|
|
428
|
+
"n_sources": len(source_manifest),
|
|
429
|
+
"n_records_concat": n_concat,
|
|
430
|
+
"n_dedup_removed": n_dedup_removed,
|
|
431
|
+
"n_records_before": n_before,
|
|
432
|
+
"n_records_dedup_filtered": n_new_raw - n_new - n_replaced,
|
|
433
|
+
"n_records_replaced": n_replaced,
|
|
434
|
+
"n_records_new": n_new,
|
|
435
|
+
"n_records_total": n_total,
|
|
436
|
+
"source_manifest": source_manifest,
|
|
437
|
+
"output_path": str(config.output_path),
|
|
438
|
+
"output_digest": output_digest,
|
|
439
|
+
"schema_fingerprint": schema_fingerprint,
|
|
440
|
+
"schema_columns": schema_cols,
|
|
441
|
+
"ledger_version": LEDGER_VERSION,
|
|
442
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
logger.info(
|
|
446
|
+
"ACLED consolidation complete: %d sources, %d new, %d total",
|
|
447
|
+
len(source_manifest),
|
|
448
|
+
n_new,
|
|
449
|
+
n_total,
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
return ConsolidationResult(
|
|
453
|
+
output_path=config.output_path,
|
|
454
|
+
n_sources=len(source_manifest),
|
|
455
|
+
n_records_total=n_total,
|
|
456
|
+
n_records_new=n_new,
|
|
457
|
+
n_records_before=n_before,
|
|
458
|
+
output_digest=output_digest,
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
register_consolidator("acled", consolidate_acled)
|