The DOC 2.0 API is per-IP quota'd (429 with no Retry-After) and only lands a fetch every 5-6 cycles, so gdel-t2 coverage was near zero. GDELT publishes the same articles every 15 minutes as static files with no key and no quota. ingest_gdelt now parses lastupdate.txt, downloads the newest *.gkg.csv.zip, filters rows to the CONFIG GDELT query terms (matched against GKG theme tokens), and maps each surviving row into the existing events.gdelt shape: title from PAGE_TITLE, url from DocumentIdentifier (so event_dedup on URL is unchanged), body = source domain, location_name/lat/lon from V2Locations, and PAGE_PRECISEPUBTIMESTAMP as source_timestamp. Publishing goes through _publish_unknown, so known URLs are skipped before they hit NATS. The DOC path (with its 429 backoff) still runs, but only when the bulk fetch itself fails.
274 lines
8.5 KiB
Python
274 lines
8.5 KiB
Python
"""GDELT 15-minute bulk GKG ingest (throttle-free path).
|
|
|
|
The DOC 2.0 API is per-IP quota'd (429). The same article coverage is served as
|
|
static 15-minute files with no key and no quota. These tests pin the mapping
|
|
from a GKG row into the existing ``events.gdelt`` event shape, the CONFIG-term
|
|
filter that keeps volume bounded, and the DOC fallback contract.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import zipfile
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
LASTUPDATE = """33287 99e984fd826497ae5765484af3b11521 http://data.gdeltproject.org/gdeltv2/20261121234500.export.CSV.zip
|
|
46052 c09f32f728f695f2bf753540aa92e6ce http://data.gdeltproject.org/gdeltv2/20261121234500.mentions.CSV.zip
|
|
2361330 0804c7df5b359f177aeff85cad63d539 http://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip
|
|
"""
|
|
|
|
# GKG row shape (27 tab-separated fields): id, date, collection, common name,
|
|
# document id, V1Counts, V2Counts, V1Themes, V2Themes, V2Locations, ..., tone,
|
|
# ..., V2ExtrasXML.
|
|
GKG_ROW = "\t".join([
|
|
"20261121234500-11",
|
|
"20261121234500",
|
|
"1",
|
|
"dominicanrepublicpost.com",
|
|
"https://dominicanrepublicpost.com/protest-in-iowa/",
|
|
"PROTEST#29000##0######;",
|
|
"PROTEST#29000##0#######287;",
|
|
"PROTEST;TAX_FNCACT;VIOLENT_UNREST;",
|
|
"PROTEST,12;TAX_FNCACT,4;",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"-4.75,0.5,6.1,7.2,18.3,0,206",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
"",
|
|
(
|
|
"<PAGE_AUTHORS>Gary Stevens</PAGE_AUTHORS>"
|
|
"<PAGE_PRECISEPUBTIMESTAMP>20261121211600</PAGE_PRECISEPUBTIMESTAMP>"
|
|
"<PAGE_TITLE>Protest in Iowa & Nebraska</PAGE_TITLE>"
|
|
),
|
|
])
|
|
|
|
LOCATIONS_ROW = "\t".join([
|
|
"20261121234500-12", "20261121234500", "1", "wkzo.com",
|
|
"https://wkzo.com/power-outage/",
|
|
"", "", "POWER_OUTAGE;CYBER_ATTACK;", "POWER_OUTAGE,9;", "",
|
|
"", "", "", "", "", "-2.0,0.1,1.0,1.0,1.0,0,10", "", "", "", "", "", "", "",
|
|
"", "", "", "<PAGE_TITLE>Power outage hits grid</PAGE_TITLE>",
|
|
])
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_bulk_state(monkeypatch):
|
|
import sources
|
|
|
|
monkeypatch.setattr(sources, "_gdelt_bulk_last_file", None)
|
|
monkeypatch.setattr(sources, "GDELT_BULK_MAX_EVENTS", 100)
|
|
sources._gdelt_clear_backoff()
|
|
yield
|
|
sources._gdelt_clear_backoff()
|
|
|
|
|
|
def _gkg_zip(rows: list[str]) -> bytes:
|
|
buf = io.BytesIO()
|
|
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
zf.writestr("20261121234500.gkg.csv", "\n".join(rows) + "\n")
|
|
return buf.getvalue()
|
|
|
|
|
|
class _FakeClient:
|
|
def __init__(self, index_text: str, archive: bytes | None, calls: list[str], fail_archive=False):
|
|
self._index_text = index_text
|
|
self._archive = archive
|
|
self._calls = calls
|
|
self._fail_archive = fail_archive
|
|
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, *exc):
|
|
return False
|
|
|
|
async def get(self, url, params=None, **kw):
|
|
self._calls.append(url)
|
|
request = httpx.Request("GET", url)
|
|
if url.endswith("lastupdate.txt"):
|
|
return httpx.Response(200, text=self._index_text, request=request)
|
|
if self._fail_archive:
|
|
raise httpx.TransportError("boom")
|
|
return httpx.Response(200, content=self._archive or b"", request=request)
|
|
|
|
|
|
def _install(monkeypatch, index_text=LASTUPDATE, archive=None, fail_archive=False):
|
|
import sources
|
|
|
|
calls: list[str] = []
|
|
monkeypatch.setattr(
|
|
sources.httpx, "AsyncClient",
|
|
lambda **kw: _FakeClient(index_text, archive, calls, fail_archive),
|
|
)
|
|
return calls
|
|
|
|
|
|
def _collect(monkeypatch):
|
|
import sources
|
|
|
|
published: list[dict] = []
|
|
|
|
async def _fake_publish(subject, events):
|
|
assert subject == "events.gdelt"
|
|
published.extend(events)
|
|
return len(events)
|
|
|
|
monkeypatch.setattr(sources, "_publish_unknown", _fake_publish)
|
|
return published
|
|
|
|
|
|
def _no_network(monkeypatch):
|
|
"""Fail the run if anything reaches the DOC 2.0 API."""
|
|
import sources
|
|
|
|
async def _boom(*a, **kw):
|
|
raise AssertionError("DOC API must not be called when bulk data lands")
|
|
|
|
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _boom)
|
|
|
|
|
|
def test_query_terms_from_config_string():
|
|
import sources
|
|
|
|
assert sources.gdelt_query_terms("") == [
|
|
"unrest", "protest", "outage", "cyber", "power outage",
|
|
]
|
|
assert sources.gdelt_query_terms('(flood OR "power outage")') == [
|
|
"flood", "power outage",
|
|
]
|
|
|
|
|
|
def test_select_gdelt_bulk_url_picks_gkg_and_forces_https():
|
|
import sources
|
|
|
|
picked = sources.select_gdelt_bulk_url(LASTUPDATE)
|
|
assert picked == (
|
|
"20261121234500.gkg.csv.zip",
|
|
"https://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip",
|
|
)
|
|
assert sources.select_gdelt_bulk_url("") is None
|
|
|
|
|
|
def test_parse_gkg_row_maps_into_event_shape():
|
|
import sources
|
|
|
|
terms = sources.gdelt_query_terms("")
|
|
event = sources.parse_gkg_row(GKG_ROW.split("\t"), terms, "20261121234500.gkg.csv.zip")
|
|
|
|
assert event["source_type"] == "gdel-t2"
|
|
assert event["url"] == "https://dominicanrepublicpost.com/protest-in-iowa/"
|
|
assert event["title"] == "Protest in Iowa & Nebraska"
|
|
assert event["body"] == "dominicanrepublicpost.com"
|
|
# Publish time comes from PAGE_PRECISEPUBTIMESTAMP, not the window stamp.
|
|
assert event["source_timestamp"] == "2026-11-21T21:16:00+00:00"
|
|
assert "protest" in event["tags"] and "VIOLENT_UNREST" in event["tags"]
|
|
assert event["raw"]["bulk_file"] == "20261121234500.gkg.csv.zip"
|
|
assert event["raw"]["tone"] == pytest.approx(-4.75 / 4249.0)
|
|
# No V2Locations in this row -> no fake geo.
|
|
assert event["location_lat"] is None and event["location_lon"] is None
|
|
|
|
|
|
def test_parse_gkg_row_reads_geo_from_v2locations():
|
|
import sources
|
|
|
|
row = GKG_ROW.split("\t")
|
|
row[9] = (
|
|
"4#Middletown, Iowa, United States#US#IA#40.8284#-91.259#-1834425"
|
|
";1#United States#US#US#39.8283#-98.5795#US"
|
|
)
|
|
event = sources.parse_gkg_row(row, sources.gdelt_query_terms(""))
|
|
assert event["location_lat"] == pytest.approx(40.8284)
|
|
assert event["location_lon"] == pytest.approx(-91.259)
|
|
assert event["location_name"] == "Middletown, Iowa, United States"
|
|
|
|
|
|
def test_gkg_location_tolerates_short_and_bad_forms():
|
|
import sources
|
|
|
|
# adm2 slot dropped: lat/lon are still the last two before the feature id.
|
|
assert sources._gkg_location("2#California, United States#US#USCA#36.17#-119.746#CA") == (
|
|
pytest.approx(36.17), pytest.approx(-119.746), "California, United States",
|
|
)
|
|
assert sources._gkg_location("")[0] is None
|
|
assert sources._gkg_location("1#Nowhere#US#US#999#999#X")[0] is None
|
|
|
|
|
|
def test_parse_gkg_row_drops_rows_without_query_terms():
|
|
import sources
|
|
|
|
row = GKG_ROW.split("\t")
|
|
row[7] = "SPORTS;ENTERTAINMENT;"
|
|
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
|
|
|
|
row = GKG_ROW.split("\t")
|
|
row[4] = ""
|
|
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ingest_gdelt_bulk_publishes_filtered_rows_and_skips_repeat(monkeypatch):
|
|
import sources
|
|
|
|
_install(monkeypatch, archive=_gkg_zip([GKG_ROW, LOCATIONS_ROW]))
|
|
published = _collect(monkeypatch)
|
|
_no_network(monkeypatch)
|
|
|
|
count = await sources.ingest_gdelt()
|
|
assert count == 2
|
|
assert {e["url"] for e in published} == {
|
|
"https://dominicanrepublicpost.com/protest-in-iowa/",
|
|
"https://wkzo.com/power-outage/",
|
|
}
|
|
# Second cycle: same file, nothing new fetched or published.
|
|
before = len(published)
|
|
assert await sources.ingest_gdelt() == 0
|
|
assert len(published) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ingest_gdelt_bulk_caps_events_per_file(monkeypatch):
|
|
import sources
|
|
|
|
rows = []
|
|
for i in range(5):
|
|
row = GKG_ROW.split("\t")
|
|
row[0] = f"20261121234500-{i}"
|
|
row[4] = f"https://example.com/story-{i}"
|
|
rows.append("\t".join(row))
|
|
_install(monkeypatch, archive=_gkg_zip(rows))
|
|
published = _collect(monkeypatch)
|
|
_no_network(monkeypatch)
|
|
|
|
assert await sources.ingest_gdelt_bulk(max_events=2) == 2
|
|
assert len(published) == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ingest_gdelt_falls_back_to_doc_when_bulk_fails(monkeypatch):
|
|
import sources
|
|
|
|
_install(monkeypatch, fail_archive=True)
|
|
calls = {"doc": 0}
|
|
|
|
async def _doc(query="", max_articles=50):
|
|
calls["doc"] += 1
|
|
return 7
|
|
|
|
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _doc)
|
|
assert await sources.ingest_gdelt() == 7
|
|
assert calls["doc"] == 1
|