feat(notifications): Phase 2.12 SWPC space weather adapter + dedup fix

Wires the NOAA SWPC adapter into the notification EventBus and fixes a
dedup bug in its event id, following the Phase 2.7-2.11 pattern.

(A) DEDUP FIX (the regression this phase guards):
  before: event_id = f"swpc_r{r_scale}_{int(time.time())}"
  after:  event_id = f"swpc_{code}{level}"   # e.g. "swpc_g3"
The old id embedded int(time.time()), so every poll produced a unique id.
The store dedups env events on (source, event_id), so each tick during a
blackout was treated as new -> re-emitted to the bus every scales poll
(300s) and accumulated phantom entries in the store. The new id is stable
per condition: a sustained storm coalesces across ticks; only an
escalation to a new level (e.g. G3 -> G4) yields a new id and re-notifies.
Re-emit suppression is the Inhibitor's job (TTL ~1800s), not the id's.

(B) _update_events expanded R-scale-only -> all three NOAA scales:
  - R (Radio Blackout)        -> category rf_propagation_alert
  - S (Solar Radiation Storm) -> category solar_radiation_storm
  - G (Geomagnetic Storm)     -> category geomagnetic_storm
Emit threshold: level >= 1 (level 0 / quiet emits nothing). Severity is
tiered in _update_events and passed through by to_event:
  level 1-2 -> routine, 3-4 -> priority, 5 -> immediate.
(Scope/threshold approved by Matt before applying: "R/S/G at level >= 1".)
Each event carries scale/level discriminator fields for to_event.

(C) to_event(): category from scale, severity pass-through, group_key /
inhibit_keys = the stable event_id (single key; tiering -> Inhibitor).
SWPC conditions are global, so the Event carries lat=None, lon=None and
region="global" (Event.lat/lon are Optional and Event has a region field).
Defensive: missing scale, level<1, or missing event_id -> None;
try/except-guarded.

No store.py change: store already routes swpc through to_event in _ingest
(the swpc special-case) and the Phase 2.9 None-guard handles None returns.

Rule 17: no new tunable. Rule 18 N/A -- SWPC services.swpc.noaa.gov is
keyless (no .env entry; .ref credentials has no SWPC/NOAA key, confirming
none needed). Rule 16: standalone fetch path validated in-container.

Tests: tests/test_adapter_swpc.py (14 tests) mirrors the 2.11 shape --
scale->category mapping, severity pass-through, _update_events severity
tiering (1-2/3-4/5), group_key/inhibit_keys, all-three-scales-emit,
quiet-emits-nothing, field population (lat/lon None + region global), and
defensive cases (missing scale / level 0 / missing id / corrupted -> None).
Plus two dedup regression guards: test_dedup_id_stable_across_ticks
(SAME id across two ticks of the same condition -- fails on the old code)
and test_event_id_changes_with_level (escalation yields a new id). Full
suite: 214 passed.

Live smoke test (prod container, Phase 2.12 code rebuilt in): clean
startup, 7 env adapters loaded, healthy, no traceback, no SWPC errors. An
in-container standalone fetch of the noaa-scales endpoint succeeded
(scales_fetch_ok=true, is_loaded=true, last_error=null,
consecutive_errors=0) over the open API with no DNS/auth errors (Phase
2.6.6 DNS fix). Current conditions are quiet (R0/S0/G0), so no Event is
emitted -- acceptable, and it exercises the level<1 -> no-emit path live.
The emission path (active scale -> rf_propagation_alert / geomagnetic_storm
/ solar_radiation_storm) is unit-validated and uses the same store->bus
path that emitted live for NWS, traffic, and NIFC fires.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
K7ZVX 2026-05-27 23:41:30 +00:00
commit dda8b8f96f
2 changed files with 305 additions and 11 deletions

110
meshai/env/swpc.py vendored
View file

@ -3,10 +3,12 @@
import json
import logging
import time
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from meshai.notifications.events import Event, make_event
if TYPE_CHECKING:
from ..config import SWPCConfig
@ -235,22 +237,108 @@ class SWPCAdapter:
pass
def _update_events(self):
"""Generate events for significant space weather conditions."""
# Generate events for R-scale >= 3 (radio blackout)
"""Generate events for active space weather conditions (R/S/G scales).
One event per active NOAA scale (Radio blackout / Solar radiation /
Geomagnetic storm) at level >= 1. The event_id is a STABLE
"swpc_{scale}{level}" key (no timestamp), so a sustained condition
dedups across ticks and only an escalation to a new level re-notifies.
"""
self._events = []
r_scale = self._status.get("r_scale", 0)
if r_scale >= 3:
now = time.time()
scale_defs = [
("r", "r_scale", "Radio Blackout"),
("s", "s_scale", "Solar Radiation Storm"),
("g", "g_scale", "Geomagnetic Storm"),
]
for code, status_key, label in scale_defs:
level = self._status.get(status_key, 0) or 0
if level < 1:
continue
if level >= 5:
severity = "immediate"
elif level >= 3:
severity = "priority"
else:
severity = "routine"
scale_letter = code.upper()
self._events.append({
"source": "swpc",
"event_id": f"swpc_r{r_scale}_{int(time.time())}",
"event_type": f"R{r_scale} Radio Blackout",
"severity": "priority" if r_scale >= 3 else "routine",
"headline": f"R{r_scale} Radio Blackout in progress",
"expires": time.time() + 3600, # 1hr TTL
"event_id": f"swpc_{code}{level}", # STABLE: scale+level, no timestamp
"event_type": f"{scale_letter}{level} {label}",
"scale": scale_letter,
"level": level,
"severity": severity,
"headline": f"{scale_letter}{level} {label} in progress",
"expires": now + 3600, # 1hr TTL
"areas": [],
"fetched_at": time.time(),
"fetched_at": now,
})
def to_event(self, evt: dict) -> Optional["Event"]:
"""Translate a stored SWPC scale condition into a pipeline Event.
Category is chosen from the NOAA scale; severity (level-tiered) is
passed through unchanged. SWPC conditions are global, so the Event
carries no lat/lon and is tagged region="global".
Args:
evt: Internal event dict from get_events()
Returns:
Event instance ready for EventBus emission, or None if the dict is
missing its scale/level (or level < 1) or event_id.
"""
try:
scale = evt.get("scale")
if not scale:
return None # No scale discriminator
level = evt.get("level")
if level is None or level < 1:
return None # Quiet/baseline -- not actionable
event_id = evt.get("event_id")
if not event_id:
return None # No stable identity to group/inhibit on
category = {
"R": "rf_propagation_alert",
"S": "solar_radiation_storm",
"G": "geomagnetic_storm",
}.get(scale)
if category is None:
return None # Unknown scale
severity = evt.get("severity", "routine")
title = evt.get("headline") or evt.get("event_type") or f"{scale}{level} space weather"
# event_id is the stable "swpc_{scale}{level}" key. A sustained
# condition coalesces on this group_key (re-polls dedup); an
# escalation to a higher level yields a new key and re-notifies.
# Single inhibit key; severity tiering delegated to the Inhibitor.
return make_event(
source="swpc",
category=category,
severity=severity,
title=title,
summary=title,
timestamp=evt.get("fetched_at"),
expires=evt.get("expires"),
lat=None,
lon=None,
region="global",
group_key=event_id,
inhibit_keys=[event_id],
)
except Exception:
logger.exception(f"SWPC to_event failed for evt: {evt.get('event_id')}")
return None
def get_status(self) -> dict:
"""Get current SWPC status."""
return self._status