fix: pipeline reliability — WS, summarizer, ingest, health

Stop the live HUD reconnect storm (nginx WS snippet + backoff), copy
intel/nous_client into the summarizer image, and make event ingest
idempotent on URL. GDELT uses the DOC API; NWS no longer sends bbox;
FIRMS is one ON CONFLICT batch; GET /api/aircraft serves last-known.
Health reports freshness without 503ing docker. EONET + CISA KEV added.
This commit is contained in:
Sirius DevOps 2026-08-28 21:49:05 -04:00
commit d81ea68dec
26 changed files with 1164 additions and 110 deletions

View file

@ -0,0 +1,21 @@
"""Timeline bucket_hours + static Cache-Control."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def test_timeline_uses_bucket_hours():
src = (ROOT / "app/main.py").read_text()
fn = src.split("async def get_timeline")[1].split("async def sentiment_by_source")[0]
assert "bucket_hours" in fn
assert "date_trunc('hour'" not in fn or "bucket" in fn.lower()
# Must not ignore the query param.
assert ":bucket" in fn or "bucket_hours" in fn.split("text(")[1][:800]
def test_static_vendor_cache_control():
src = (ROOT / "app/main.py").read_text()
assert "max-age=31536000" in src or "immutable" in src.lower()

133
tests/test_event_ingest.py Normal file
View file

@ -0,0 +1,133 @@
"""Generic event ingest: idempotency, USGS ids, GDELT DOC URL."""
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
def test_event_dedup_key_prefers_url():
from sources import event_dedup_key
assert event_dedup_key({"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1"}) == (
"https://earthquake.usgs.gov/earthquakes/eventpage/ci1"
)
assert event_dedup_key({"url": " "}) is None
assert event_dedup_key({}) is None
def test_usgs_feature_keeps_id_and_url():
from sources import parse_usgs_feature
feature = {
"id": "ci39818991",
"properties": {
"title": "M 2.1 - 5 km W of",
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci39818991",
"place": "5 km W of",
"mag": 2.1,
"time": 1_700_000_000_000,
},
"geometry": {"coordinates": [-118.5, 34.1, 10.0]},
}
event = parse_usgs_feature(feature)
assert event["url"] == "https://earthquake.usgs.gov/earthquakes/eventpage/ci39818991"
assert event["raw"]["usgs_id"] == "ci39818991"
assert event["location_lat"] == 34.1
assert event["location_lon"] == -118.5
assert event["source_type"] == "earthquake"
def test_gdelt_uses_doc_api_and_query_param():
from sources import GDELT_API, gdelt_params
assert GDELT_API == "https://api.gdeltproject.org/api/v2/doc/doc"
params = gdelt_params(query="unrest", max_articles=50)
assert params["query"] == "unrest"
assert "search" not in params
assert params["mode"] == "ArtList"
assert params["format"] == "json"
assert int(params["maxrecords"]) == 50
def test_gdelt_default_query_when_empty():
from sources import gdelt_params
params = gdelt_params(query="", max_articles=25)
assert params["query"]
assert "unrest" in params["query"].lower() or "cyber" in params["query"].lower()
def test_parse_gdelt_articles_maps_doc_payload():
from sources import parse_gdelt_articles
payload = {
"articles": [
{
"url": "https://example.com/a",
"title": "Outage",
"seendate": "20240101T120000Z",
"domain": "example.com",
"language": "English",
"sourcecountry": "US",
}
]
}
events = parse_gdelt_articles(payload)
assert len(events) == 1
assert events[0]["source_type"] == "gdel-t2"
assert events[0]["url"] == "https://example.com/a"
assert events[0]["title"] == "Outage"
def test_ingest_event_skips_duplicate_url(monkeypatch):
"""Second insert with the same url must not hit events_table.insert."""
from ingestor import ingest_event
calls = {"insert": 0, "dedup": 0}
class _Result:
rowcount = 1
inserted_primary_key = ["evt-1"]
class _Session:
async def execute(self, stmt):
sql = str(stmt).lower()
if "event_dedup" in sql or "on conflict" in sql:
calls["dedup"] += 1
self_result = _Result()
if calls["dedup"] > 1:
self_result.rowcount = 0
return self_result
calls["insert"] += 1
return _Result()
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
import ingestor
monkeypatch.setattr(ingestor, "async_session", lambda: _Session())
msg = {
"source_type": "earthquake",
"title": "M 2.1",
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1",
"source_timestamp": datetime(2026, 1, 1, tzinfo=timezone.utc).isoformat(),
}
async def run():
first = await ingest_event(msg)
second = await ingest_event(msg)
return first, second
first, second = asyncio.run(run())
assert first is not None
assert second is None
assert calls["insert"] == 1

View file

@ -169,3 +169,47 @@ def test_ingest_fire_row_correlates_from_hypertable_when_last_known_empty(monkey
assert len(correlated) == 1
assert correlated[0][1][0]["id"] == "acf001"
assert correlated[0][0][0]["lat"] == 39.45678
def test_ingest_fire_rows_one_execute_one_commit(monkeypatch):
"""93k FIRMS points must not be 93k commits."""
from ingestor import ingest_fire_rows
class _Session:
def __init__(self):
self.executes = 0
self.commits = 0
self.rowcount = 3
async def execute(self, *a, **k):
self.executes += 1
return self
async def commit(self):
self.commits += 1
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
session = _Session()
import ingestor
monkeypatch.setattr(ingestor, "async_session", lambda: session)
msgs = [
make_fire_msg(latitude=39.1 + i * 0.01, longitude=-121.1)
for i in range(3)
]
async def no_corr(*a, **k):
return []
monkeypatch.setattr("fire_aircraft.correlate_and_notify", no_corr)
monkeypatch.setattr("geofence.record_and_notify", no_corr)
inserted = asyncio.run(ingest_fire_rows(msgs))
assert inserted == 3
assert session.executes == 1
assert session.commits == 1

View file

@ -123,7 +123,7 @@ def test_ingest_fires_uses_keystore_key(monkeypatch):
published.extend(points)
return len(points)
monkeypatch.setattr("fire_sources.publish_fire_batch", fake_publish)
monkeypatch.setattr("fire_sources.persist_hotspots", fake_publish)
assert asyncio.run(ingest_fires()) == 10 # NOAA-20 + NOAA-21 dual-write
assert "a" * 32 in captured["url"]

View file

@ -0,0 +1,44 @@
"""HUD load-time: no market 404 poll, deferred overlays, WS backoff, nginx snippet."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
HTML = (ROOT / "app/static/index.html").read_text()
def test_summarizer_dockerfile_copies_intel_modules():
df = (ROOT / "news/summerizer/Dockerfile").read_text()
assert "intel.py" in df
assert "nous_client.py" in df
def test_nginx_ws_snippet_has_upgrade_headers():
conf = (ROOT / "deploy/osint-ws.nginx.conf").read_text()
assert "proxy_http_version 1.1" in conf
assert "Upgrade" in conf
assert "Connection" in conf
assert "/ws/" in conf
def test_market_ticker_does_not_poll_unwired_endpoint():
assert "setInterval(probeMarket" not in HTML
assert "initMarketTicker()" not in HTML or "probeMarket();" not in HTML.split("function initMarketTicker")[1][:400]
def test_startup_defers_nonessential_overlays():
init = HTML.split("function initMap")[1].split("function readMapPrefs")[0]
# Must not fire all four DB loads + live overlays in the same tick.
assert "setTimeout" in init or "requestAnimationFrame" in init
def test_ws_reconnect_uses_backoff():
assert "setTimeout(connectLiveWs, 4000)" not in HTML
ws = HTML.split("function connectLiveWs")[1][:1200]
assert "backoff" in ws.lower() or "wsRetry" in ws or "wsDelay" in ws
def test_check_health_treats_degraded_status():
fn = HTML.split("async function checkHealth")[1].split("/* ═══════════════ NAV")[0]
assert "degraded" in fn.lower() or "d.status" in fn

View file

@ -0,0 +1,33 @@
"""Liveness stays up; readiness/freshness is explicit."""
from __future__ import annotations
import asyncio
import httpx
from main import app
BASE = "http://test"
async def _get(path: str) -> httpx.Response:
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
return await client.get(path)
def test_health_includes_checks_even_when_db_ok(monkeypatch):
"""HUD must be able to show degraded without docker killing the container."""
body = asyncio.run(_get("/api/health")).json()
assert "status" in body
assert "checks" in body
assert "db" in body["checks"]
def test_ready_endpoint_exists():
resp = asyncio.run(_get("/api/ready"))
assert resp.status_code in (200, 503)
body = resp.json()
assert "checks" in body
assert "status" in body

View file

@ -472,3 +472,103 @@ def test_transform_ais_position_decodes_navstat():
assert row is not None
assert row["extra"]["nav"] == "moored"
assert row["extra"]["navstat"] == 5
def test_nws_alerts_does_not_send_bbox_param(monkeypatch):
"""api.weather.gov/alerts/active 400s on bbox — clip locally instead."""
import asyncio
from live_layers import fetch_weather_alerts, _cache
seen = []
async def fake_get(url, params=None):
seen.append((url, dict(params or {})))
if "weather.gov" in url:
return {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {"event": "Tornado Warning", "severity": "Extreme"},
"geometry": {"type": "Point", "coordinates": [-78.7, 35.8]},
}],
}
return {"type": "FeatureCollection", "features": []}
monkeypatch.setattr("live_layers._get_json", fake_get)
_cache.clear()
fc = asyncio.run(fetch_weather_alerts(None, "-79.0,35.5,-78.0,36.0"))
nws_calls = [p for u, p in seen if "weather.gov" in u]
assert nws_calls, "NWS should still be fetched"
assert "bbox" not in nws_calls[0]
assert fc.get("nws_ok") is True
assert len(fc["features"]) == 1
def test_nws_alerts_failure_is_flagged(monkeypatch):
import asyncio
from live_layers import fetch_weather_alerts, _cache
async def fake_get(url, params=None):
if "weather.gov" in url:
raise RuntimeError("400 Bad Request")
return {"type": "FeatureCollection", "features": []}
monkeypatch.setattr("live_layers._get_json", fake_get)
_cache.clear()
fc = asyncio.run(fetch_weather_alerts(None, None))
assert fc.get("nws_ok") is False
def test_fetch_aircraft_get_path_does_not_persist(monkeypatch):
"""GET /api/aircraft must serve last-known without track/geofence writes."""
import asyncio
from live_layers import (
aircraft_last_known, fetch_aircraft, persist_aircraft_snapshot, _cache,
)
aircraft_last_known.clear()
aircraft_last_known["abc"] = {
"id": "abc", "lat": 35.8, "lon": -78.7, "heading": 90, "speed": 400,
"label": "ABC", "extra": {},
}
writes = {"n": 0}
async def boom(*a, **k):
writes["n"] += 1
raise AssertionError("GET path must not persist")
monkeypatch.setattr("tracks.record_position", boom)
monkeypatch.setattr("geofence.record_and_notify", boom)
_cache.clear()
rows = asyncio.run(fetch_aircraft("-79,35,-78,36", persist=False))
assert writes["n"] == 0
assert any(r["id"] == "abc" for r in rows)
def test_persist_aircraft_snapshot_writes_tracks(monkeypatch):
import asyncio
from live_layers import persist_aircraft_snapshot
recorded = []
async def fake_record(kind, marker):
recorded.append((kind, marker["id"]))
return True
async def fake_gf(**kw):
return 0
monkeypatch.setattr("tracks.record_position", fake_record)
monkeypatch.setattr("geofence.record_and_notify", fake_gf)
monkeypatch.setattr("ws_manager.manager.has_clients", lambda: False)
rows = [{
"id": "abc", "lat": 35.8, "lon": -78.7, "heading": 90, "speed": 400,
"label": "ABC", "extra": {},
}]
asyncio.run(persist_aircraft_snapshot(rows))
assert recorded == [("aircraft", "abc")]

66
tests/test_new_sources.py Normal file
View file

@ -0,0 +1,66 @@
"""NASA EONET + CISA KEV parsers (no network)."""
from __future__ import annotations
def test_parse_eonet_keeps_stable_ids_and_points():
from sources import parse_eonet_events
payload = {
"events": [
{
"id": "EONET_6363",
"title": "Etna Volcano",
"categories": [{"id": "volcanoes", "title": "Volcanoes"}],
"geometry": [
{"date": "2024-01-01T00:00:00Z", "type": "Point", "coordinates": [15.0, 37.7]},
],
"link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_6363",
},
{
"id": "EONET_skip",
"title": "No geometry",
"categories": [],
"geometry": [],
"link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_skip",
},
]
}
events = parse_eonet_events(payload)
assert len(events) == 1
ev = events[0]
assert ev["url"] == "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_6363"
assert ev["source_type"] == "disaster"
assert ev["location_lat"] == 37.7
assert ev["location_lon"] == 15.0
assert ev["raw"]["eonet_id"] == "EONET_6363"
assert "volcanoes" in ev["tags"]
def test_parse_cisa_kev_emits_cve_url_no_coords():
from sources import parse_cisa_kev
payload = {
"vulnerabilities": [
{
"cveID": "CVE-2024-1234",
"vendorProject": "Acme",
"product": "Widget",
"vulnerabilityName": "RCE",
"dateAdded": "2024-06-01",
"shortDescription": "Remote code execution",
"requiredAction": "Apply updates",
"dueDate": "2024-06-22",
"knownRansomwareCampaignUse": "Known",
}
]
}
events = parse_cisa_kev(payload)
assert len(events) == 1
ev = events[0]
assert ev["url"] == "https://nvd.nist.gov/vuln/detail/CVE-2024-1234"
assert ev["location_lat"] is None
assert ev["location_lon"] is None
assert "cisa-kev" in ev["tags"]
assert "CVE-2024-1234" in ev["tags"]
assert ev["raw"]["cveID"] == "CVE-2024-1234"

View file

@ -0,0 +1,42 @@
"""News spider/pipeline: skip audio, use pubDate, don't log dupes as errors."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
_SCRAPER = ROOT / "news/scraper"
if str(_SCRAPER) not in sys.path:
sys.path.insert(0, str(_SCRAPER))
def test_is_audio_enclosure():
from newsScraper.feed_util import is_audio_url
assert is_audio_url("https://cdn.example/podcast.mp3") is True
assert is_audio_url("https://cdn.example/show.m4a?x=1") is True
assert is_audio_url("https://www.example.com/world/story") is False
def test_article_timestamp_prefers_pubdate():
from newsScraper.feed_util import article_timestamp
ts = article_timestamp("Tue, 01 Apr 2025 12:00:00 GMT")
assert ts.tzinfo is not None
assert ts.year == 2025
assert ts.month == 4
assert ts.day == 1
def test_pipeline_does_not_wrap_dropitem_as_error():
src = (ROOT / "news/scraper/newsScraper/pipelines.py").read_text()
assert "except DropItem" in src
assert "seen_urls.add" in src or "self.seen_urls.add" in src
def test_spider_skips_audio_before_request():
src = (ROOT / "news/scraper/newsScraper/spiders/news_spider.py").read_text()
assert "is_audio_url" in src
assert "article_timestamp" in src
assert "datetime.datetime.now()" not in src

View file

@ -55,7 +55,7 @@ def test_ingest_fires_hits_http_once_within_ttl(monkeypatch):
async def fake_publish(points):
return len(points)
monkeypatch.setattr("fire_sources.publish_fire_batch", fake_publish)
monkeypatch.setattr("fire_sources.persist_hotspots", fake_publish)
assert asyncio.run(ingest_fires()) == 5
assert asyncio.run(ingest_fires()) == 5