fix(gdelt): stop retrying 429 over http, add quota backoff
GDELT's DOC 2.0 API answers 429 with a plain-text body, no Retry-After, and
a per-IP block window that widens with request volume. The https->http retry
only doubled the request count against that quota and could never succeed,
and every cycle logged a full traceback.
- ingest_gdelt: a 429 (or a 200 with a prose body) now sets a backoff window
(GDELT_BACKOFF_BASE=300s, doubling to GDELT_BACKOFF_MAX=1800s, Retry-After
honoured when present) and returns 0 instead of raising.
- cycles inside the window skip the call entirely, logging one line.
- the https->http fallback now only covers TransportError (TLS/connect), not
HTTP error statuses.
- producer_loop logs a GDELT failure as one WARNING line, no traceback.
- tests/test_gdelt_backoff.py covers no-retry-on-429, cooldown skip, doubling
and cap, Retry-After, 200-prose, success reset, transport fallback.
2026-11-21 18:12:56 -05:00
|
|
|
"""GDELT DOC 2.0 quota handling: no http retry on 429, backoff, prose bodies.
|
|
|
|
|
|
|
|
|
|
GDELT answers ``429`` with a plain-text "Please limit requests to one every 5
|
|
|
|
|
seconds" body and no Retry-After header. The ingester must not spend a second
|
|
|
|
|
request from the same IP on a status error, and must stop calling until the
|
|
|
|
|
backoff window expires instead of raising a traceback every cycle.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
|
|
import httpx
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
|
def _reset_backoff(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
sources._gdelt_clear_backoff()
|
|
|
|
|
monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300)
|
|
|
|
|
monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800)
|
fix(gdelt): ingest the 15-minute GKG bulk file, keep the DOC API as fallback
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.
2026-11-21 18:37:31 -05:00
|
|
|
# These tests cover the DOC 2.0 path, which is now the fallback behind the
|
|
|
|
|
# 15-minute bulk GKG file (tests/test_gdelt_bulk.py covers that path).
|
|
|
|
|
monkeypatch.setattr(sources, "GDELT_BULK_ENABLED", False)
|
fix(gdelt): stop retrying 429 over http, add quota backoff
GDELT's DOC 2.0 API answers 429 with a plain-text body, no Retry-After, and
a per-IP block window that widens with request volume. The https->http retry
only doubled the request count against that quota and could never succeed,
and every cycle logged a full traceback.
- ingest_gdelt: a 429 (or a 200 with a prose body) now sets a backoff window
(GDELT_BACKOFF_BASE=300s, doubling to GDELT_BACKOFF_MAX=1800s, Retry-After
honoured when present) and returns 0 instead of raising.
- cycles inside the window skip the call entirely, logging one line.
- the https->http fallback now only covers TransportError (TLS/connect), not
HTTP error statuses.
- producer_loop logs a GDELT failure as one WARNING line, no traceback.
- tests/test_gdelt_backoff.py covers no-retry-on-429, cooldown skip, doubling
and cap, Retry-After, 200-prose, success reset, transport fallback.
2026-11-21 18:12:56 -05:00
|
|
|
yield
|
|
|
|
|
sources._gdelt_clear_backoff()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _FakeClient:
|
|
|
|
|
"""Stands in for httpx.AsyncClient; records every GET it is asked for."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, responses, calls):
|
|
|
|
|
self._responses = list(responses)
|
|
|
|
|
self._calls = calls
|
|
|
|
|
|
|
|
|
|
async def __aenter__(self):
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
async def __aexit__(self, *exc):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
async def get(self, url, params=None):
|
|
|
|
|
self._calls.append(url)
|
|
|
|
|
resp = self._responses.pop(0)
|
|
|
|
|
resp.request = httpx.Request("GET", url)
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _install(monkeypatch, responses):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
calls: list[str] = []
|
|
|
|
|
monkeypatch.setattr(
|
|
|
|
|
sources.httpx, "AsyncClient", lambda **kw: _FakeClient(responses, calls)
|
|
|
|
|
)
|
|
|
|
|
return calls
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _no_publish(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
published: list[str] = []
|
|
|
|
|
|
|
|
|
|
async def _fake(subject, event):
|
|
|
|
|
published.append(subject)
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(sources, "publish_event", _fake)
|
|
|
|
|
return published
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_429_does_not_retry_http_and_starts_backoff(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
calls = _install(
|
|
|
|
|
monkeypatch,
|
|
|
|
|
[httpx.Response(429, text="Please limit requests to one every 5 seconds")],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
|
|
|
|
|
assert n == 0
|
|
|
|
|
assert calls == [sources.GDELT_API] # exactly one request, no http fallback
|
|
|
|
|
assert sources.gdelt_backoff_remaining() > 250
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_cycle_skipped_while_backing_off(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
calls = _install(
|
|
|
|
|
monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")]
|
|
|
|
|
)
|
|
|
|
|
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
assert len(calls) == 1
|
|
|
|
|
|
|
|
|
|
# A second cycle inside the window must not touch the network at all.
|
|
|
|
|
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
assert n == 0
|
|
|
|
|
assert len(calls) == 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_backoff_doubles_then_caps(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
sources._gdelt_start_backoff()
|
|
|
|
|
first = sources._gdelt_backoff_secs
|
|
|
|
|
sources._gdelt_start_backoff()
|
|
|
|
|
second = sources._gdelt_backoff_secs
|
|
|
|
|
for _ in range(6):
|
|
|
|
|
sources._gdelt_start_backoff()
|
|
|
|
|
|
|
|
|
|
assert first == 300
|
|
|
|
|
assert second == 600
|
|
|
|
|
assert sources._gdelt_backoff_secs == 1800
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_retry_after_header_is_honoured(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
_install(monkeypatch, [httpx.Response(429, headers={"Retry-After": "45"}, text="busy")])
|
|
|
|
|
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
|
|
|
|
|
assert 40 <= sources.gdelt_backoff_remaining() <= 45
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_200_prose_body_treated_as_throttle(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
calls = _install(
|
|
|
|
|
monkeypatch,
|
|
|
|
|
[httpx.Response(200, text="Please limit requests to one every 5 seconds")],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
|
|
|
|
|
assert n == 0
|
|
|
|
|
assert len(calls) == 1
|
|
|
|
|
assert sources.gdelt_backoff_remaining() > 250
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_success_publishes_and_clears_backoff(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
sources._gdelt_start_backoff()
|
|
|
|
|
sources._gdelt_clear_backoff()
|
|
|
|
|
published = _no_publish(monkeypatch)
|
|
|
|
|
_install(
|
|
|
|
|
monkeypatch,
|
|
|
|
|
[
|
|
|
|
|
httpx.Response(
|
|
|
|
|
200,
|
|
|
|
|
json={
|
|
|
|
|
"articles": [
|
|
|
|
|
{
|
|
|
|
|
"url": "https://example.com/a",
|
|
|
|
|
"title": "Protest",
|
|
|
|
|
"domain": "example.com",
|
|
|
|
|
"seendate": "20261121T120000Z",
|
|
|
|
|
"language": "English",
|
|
|
|
|
"sourcecountry": "United States",
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
|
|
|
|
|
assert n == 1
|
|
|
|
|
assert published == ["events.gdelt"]
|
|
|
|
|
assert sources.gdelt_backoff_remaining() == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_transport_error_still_falls_back_to_http(monkeypatch):
|
|
|
|
|
import sources
|
|
|
|
|
|
|
|
|
|
class _BoomClient(_FakeClient):
|
|
|
|
|
async def get(self, url, params=None):
|
|
|
|
|
self._calls.append(url)
|
|
|
|
|
if url.startswith("https://"):
|
|
|
|
|
raise httpx.ConnectError("tls handshake failed")
|
|
|
|
|
resp = self._responses.pop(0)
|
|
|
|
|
resp.request = httpx.Request("GET", url)
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
calls: list[str] = []
|
|
|
|
|
responses = [httpx.Response(200, json={"articles": []})]
|
|
|
|
|
monkeypatch.setattr(
|
|
|
|
|
sources.httpx, "AsyncClient", lambda **kw: _BoomClient(responses, calls)
|
|
|
|
|
)
|
|
|
|
|
_no_publish(monkeypatch)
|
|
|
|
|
|
|
|
|
|
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
|
|
|
|
|
|
|
|
assert n == 0
|
|
|
|
|
assert calls == [sources.GDELT_API, sources.GDELT_API.replace("https://", "http://", 1)]
|
|
|
|
|
assert sources.gdelt_backoff_remaining() == 0
|