160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Cyclone forecasts: no redirects, bounded reads, newer texts labelled
Phoenix Agent (mac-studio)56f7df8be321
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 19b3aad..ee52daa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,28 +26,65 @@### Data honesty: forecast tracks- `data_gaps` names every track or cone not delivered, per storm, with astatus: `fetch_failed`, `unparsed`, `refused_link`, `not_linked`,- `not_published` or `not_fetched_cap` (at most 10 storms per call; the rest are named,- never dropped). A failure marks the response `degraded`; a product the- agency does not link is a gap, not degradation. A quiet basin still- answers zero storms, not degraded, and makes no product fetches; a feed- outage keeps its existing degraded shape and makes none either.-- The text pages are per storm bin, not per issuance, so one can lag the- feed: an advisory or warning number that disagrees with the feed is- returned as `stale_advisory` or `stale_warning` with the expected- number, and its cached copy is dropped.+ `not_published`, `not_fetched_cap` (at most 10 storms per call; the rest are named,+ never dropped) or `error` (an unexpected exception while building that one+ product; the storm list and every other product still arrive). A failure+ marks the response `degraded`; a product the agency does not link is a+ gap, not degradation. A quiet basin still answers zero storms, not+ degraded, and makes no product fetches; a feed outage keeps its existing+ degraded shape and makes none either.+- The text pages are per storm bin, not per issuance, and the feeds are+ cached for 600 s, so a text and its feed entry can be out of step either+ way. Its advisory or warning number is compared with the feed's, with one+ rule for both agencies: a text older than the feed, or one whose number+ cannot be read, is `stale_advisory` or `stale_warning` (degraded, with the+ expected number, not kept); a text newer than the feed is+ `feed_lags_text` (named in `data_gaps`, not degraded, kept). Every+ forecast carries both numbers: `advisory_number` / `warning_number` from+ the text, `feed_advisory_number` / `feed_warning_number` from the feed,+ which the storm's other fields also come from.- Each product is fetched once per issuance (cache keys carry the- advisory or warning number; one-hour TTL) under its own circuit breaker+ advisory or warning number and the file or issue time; one-hour TTL;+ only an accepted text is kept) under its own circuit breaker(`nhc-forecast`, `nhc-gis`, `jtwc-warning`), so a product outage does- not trip the warning feeds' breakers.+ not trip the warning feeds' breakers. A failed text fetch is+ `fetch_failed`; it is not answered from an expired copy.- Remote KML is parsed with the standard library: strict UTF-8, any- DOCTYPE refused, size caps (KMZ 2 MB, KML 8 MB), and a cone with more- than one ring refused, never trimmed. A ring of more than 10,000- vertices is refused before simplifying, and simplifying runs off the- event loop.+ DOCTYPE refused, the KML member read only when it is stored or deflated+ and declares at most 100:1 expansion, and a cone with more than one ring+ refused, never trimmed. Size caps: text 1 MiB, KMZ 2 MiB, KML member+ 8 MiB. Texts and the KMZ are read with `Fetcher.get_bytes`, which stops+ reading once the decoded body passes its cap; one 64 KiB network read of+ gzip can still decode to about 64 MiB before that check.+- A ring of more than 3,000 vertices is refused before simplifying, and+ simplifying stops once the outline passes 500 vertices, which bounds it+ at about 1.5 million distance evaluations. Measured on one machine: a+ zig-zag ring at the cap takes 0.42 s of CPU; the same shape at the old+ 10,000-vertex cap took 15 s. An outline of fewer than 3 vertices is+ refused. Simplifying runs off the event loop.- Product links come from the agencies' feeds and are fetched only when- they are https on the agency's own host (www.nhc.noaa.gov,- www.metoc.navy.mil). Any other link is reported as `refused_link` and- never requested.+ they are strings, contain no whitespace or control characters, and are+ https on the agency's own host (www.nhc.noaa.gov, www.metoc.navy.mil).+ Any other link, and a feed record that is not an object, is reported as+ `refused_link` and never requested. No product redirect is followed:+ one is reported as `refused_link` naming its target, so `track_url` and+ `cone_url` are always where the data came from.+- `intel_cyclones` keeps the fetcher's `_stale` and `_stale_age_seconds`+ marker when CurrentStorms.json is served from an expired cached copy,+ with or without `include_forecast` (it was dropped before).+- `Fetcher.get_bytes` takes `follow_redirects` (keyword-only, default+ true); with false, a redirect is returned as its status and resolved+ `location`, never requested, retried or counted as a source failure. It+ also reads a body as it arrives and refuses it as soon as the decoded+ size passes `max_bytes`, where it used to buffer and decode the whole+ body first. Measured on one machine, a 521,844-byte gzip body that+ decodes to 512 MiB, from a local server, with a 64 MiB cap: peak RSS+ went from 40 MiB to 1,120 MiB before, to 176 MiB after (reading stopped+ at 67,244,864 decoded bytes, the first network read). The over-cap+ error now reads "body exceeds cap N: stopped after M decoded bytes".+ `get_text` and `get_json` still read whole bodies, and `get_text` has no+ cap. `Cache.delete` logs and swallows a locked or read-only database, as+ `Cache.set` does.- Measured 2026-10-17: every product used answered HTTP 200 without akey; nhc.noaa.gov robots.txt disallows nothing and the NWS disclaimerputs the products in the public domain. The JTWC home page anddiff --git a/src/world_intel_mcp/cache.py b/src/world_intel_mcp/cache.pyindex fdf1dae..f12b2f6 100644--- a/src/world_intel_mcp/cache.py+++ b/src/world_intel_mcp/cache.py@@ -136,10 +136,13 @@ class Cache:logger.warning("Cache write failed for %s: %s", key, exc)def delete(self, key: str) -> None:- """Delete a specific key."""- conn = self._get_conn()- conn.execute("DELETE FROM cache WHERE key = ?", (key,))- conn.commit()+ """Delete a specific key. Failures are logged and swallowed, as in set()."""+ try:+ conn = self._get_conn()+ conn.execute("DELETE FROM cache WHERE key = ?", (key,))+ conn.commit()+ except sqlite3.OperationalError as exc:+ logger.warning("Cache delete failed for %s: %s", key, exc)def evict_expired(self) -> int:"""Remove all expired entries. Returns count removed."""diff --git a/src/world_intel_mcp/fetcher.py b/src/world_intel_mcp/fetcher.pyindex 5b3afad..8d02345 100644--- a/src/world_intel_mcp/fetcher.py+++ b/src/world_intel_mcp/fetcher.py@@ -6,6 +6,7 @@ response is returned (marked with _stale=True) so dashboards never go blank."""import asyncio+import contextlibimport loggingimport timefrom dataclasses import dataclass@@ -54,12 +55,15 @@ class BinaryResult:``status`` is the final HTTP status (None when no response arrived),``content`` the body on 2xx, ``error`` a short reason otherwise. A404 is reported as ``status=404`` with no error so callers can tell- "not published (yet)" apart from "the fetch failed".+ "not published (yet)" apart from "the fetch failed". ``location`` is+ the absolute redirect target when ``follow_redirects=False`` and the+ URL answered with a redirect (which was not requested)."""status: int | Nonecontent: bytes | Noneerror: str | None = None+ location: str | None = None@propertydef ok(self) -> bool:@@ -277,13 +281,32 @@ class Fetcher:headers: dict[str, str] | None = None,timeout: float | None = None,max_bytes: int = 256 * 1024 * 1024,+ *,+ follow_redirects: bool = True,) -> BinaryResult:"""Fetch a binary body with rate limiting, retries and circuit breaking.Not cached here: binary payloads (multi-MB) do not belong in theSQLite TTL cache, so callers own any on-disk caching. A 404 is a- definitive answer (not retried, not a breaker failure). A body- larger than ``max_bytes`` is refused rather than buffered.+ definitive answer (not retried, not a breaker failure). The body+ is read as it arrives and refused as soon as its decoded size+ passes ``max_bytes``, so no more than ``max_bytes`` plus one+ decoded network read is held (one 64 KiB read of gzip can decode+ to about 64 MiB). With ``follow_redirects=False`` a redirect is+ also a definitive answer, and its target is never requested.++ The result (see BinaryResult), by outcome:++ - body: ``status`` 2xx, ``content`` the decoded body.+ - 404: ``status`` 404, ``content`` None, ``error`` None.+ - redirect not followed: ``status`` 3xx, ``content`` None,+ ``error`` "redirect to <location> not followed", ``location``+ the absolute target. ``location`` is None in every other case.+ - over the cap: ``status`` 2xx, ``content`` None, ``error``+ "body exceeds cap <max_bytes>: stopped after <n> decoded bytes".+ - failure (HTTP or transport error after the retries, or an open+ circuit): ``status`` the last status or None, ``content`` None,+ ``error`` a one-line reason."""if not self.breaker.is_available(source):return BinaryResult(None, None, f"circuit open for {source}")@@ -295,24 +318,40 @@ class Fetcher:for attempt in range(self.max_retries + 1):try:- resp = await client.get(- url, headers=headers, timeout=timeout or self.default_timeout- )- last_status = resp.status_code- if resp.status_code == 404:- self.breaker.record_success(source)- return BinaryResult(404, None, None)- resp.raise_for_status()- body = resp.content- if len(body) > max_bytes:- self.breaker.record_success(source)+ async with client.stream(+ "GET",+ url,+ headers=headers,+ timeout=timeout or self.default_timeout,+ follow_redirects=follow_redirects,+ ) as resp:+ last_status = resp.status_code+ if not follow_redirects and resp.next_request is not None:+ location = str(resp.next_request.url)+ self.breaker.record_success(source)+ return BinaryResult(+ resp.status_code, None, f"redirect to {location} not followed", location+ )+ if resp.status_code == 404:+ self.breaker.record_success(source)+ return BinaryResult(404, None, None)+ resp.raise_for_status()+ chunks: list[bytes] = []+ size = 0+ async with contextlib.aclosing(resp.aiter_bytes()) as decoded:+ async for chunk in decoded:+ size += len(chunk)+ if size > max_bytes:+ break+ chunks.append(chunk)+ self.breaker.record_success(source)+ if size > max_bytes:return BinaryResult(- resp.status_code,+ last_status,None,- f"body of {len(body)} bytes exceeds cap {max_bytes}",+ f"body exceeds cap {max_bytes}: stopped after {size} decoded bytes",)- self.breaker.record_success(source)- return BinaryResult(resp.status_code, body, None)+ return BinaryResult(last_status, b"".join(chunks), None)except (httpx.HTTPStatusError, httpx.RequestError) as exc:last_error = f"{type(exc).__name__}: {exc}"if attempt < self.max_retries:diff --git a/src/world_intel_mcp/sources/cyclone_forecasts.py b/src/world_intel_mcp/sources/cyclone_forecasts.pyindex 71f8e71..3488055 100644--- a/src/world_intel_mcp/sources/cyclone_forecasts.py+++ b/src/world_intel_mcp/sources/cyclone_forecasts.py@@ -43,16 +43,34 @@ answered 403 (CloudFront "Request blocked") to the same client that gotbe read.The text URLs are per bin, not per issuance (MIATCMEP1.shtml,-wp2926web.txt), so a page can lag the feed entry pointing at it. The-advisory or warning number in the text is checked against the feed; a-mismatch is returned labelled stale and its cached copy is dropped.+wp2926web.txt), so a page and the feed entry pointing at it can be out+of step either way: a bin page can lag the feed, and the feed itself is+cached for 600 s. The advisory or warning number in the text is compared+with the feed's. A text older than the feed, or one whose number cannot+be read, is labelled stale and not kept; a text newer than the feed is+labelled feed_lags_text and kept. Both numbers are in the response:+``advisory_number`` / ``warning_number`` from the text,+``feed_advisory_number`` / ``feed_warning_number`` from the feed, which+the storm's other fields also come from.++Products are fetched from the linked URL only: a redirect is never+followed (it is reported as refused_link, naming its target), so+``track_url`` and ``cone_url`` are where the data came from. The fetcher+stops reading a text or KMZ once its decoded size passes the cap below+(text 1 MiB, KMZ 2 MiB), though one network read can decode to more+before that check (about 64 MiB of gzip). A KML member is read only when+it is stored or deflated and declares at most 100:1 expansion, and its+decompressed size is capped at 8 MiB.Gaps / not covered: wind radii and seas are not parsed. Not observedlive: a Central Pacific (CPHC) forecast/advisory, potential tropicalcyclone products, a cone crossing the antimeridian (a cone with morethan one ring is refused, never trimmed), and a JTWC final warning (awarning text without forecast blocks is reported unparsed). JTWC's-danger swath is not fetched.+danger swath is not fetched. The cone is not checked against the+advisory number (its cache key carries the number and file time). A+failed text fetch is never answered from an expired copy, even one of+the same issuance."""import asyncio@@ -63,12 +81,11 @@ import mathimport reimport xml.etree.ElementTree as ETimport zipfile-import zlibfrom datetime import datetime, timezonefrom typing import Anyfrom urllib.parse import urlsplit-from ..fetcher import Fetcher+from ..fetcher import BinaryResult, Fetcherlogger = logging.getLogger("world-intel-mcp.sources.cyclone_forecasts")@@ -84,11 +101,19 @@ CONE_SIMPLIFY_TOLERANCE_DEG = 0.01# Cache keys carry the advisory/warning number, so a new issuance is a# new key; the TTL only bounds how long one issuance is reused._FORECAST_CACHE_TTL = 3600+# Body caps: the fetcher stops reading once a decoded body passes its cap.+_TEXT_MAX_BYTES = 1024 * 1024_CONE_MAX_BYTES = 2 * 1024 * 1024_KML_MAX_BYTES = 8 * 1024 * 1024-# Douglas-Peucker is quadratic in the worst case, so a ring past this is-# refused before simplifying (Trudy #17's ring has 1,167 vertices).-_CONE_MAX_VERTICES = 10_000+# Declared expansion bound for the KML member (the fixture's KML,+# deflated by zipfile, expands 2.8:1).+_KML_MAX_RATIO = 100+# Douglas-Peucker costs up to (kept vertices) x (ring vertices) distance+# evaluations, so both are capped: a ring past _CONE_MAX_VERTICES is+# refused before simplifying, an outline past _CONE_MAX_OUTLINE_VERTICES+# while simplifying. Trudy #17: 1,167 vertices in, 56 kept.+_CONE_MAX_VERTICES = 3_000+_CONE_MAX_OUTLINE_VERTICES = 500# Product links come from the agencies' feeds; one is fetched only when# it is https on the agency's own host, so a malformed or tampered feed@@ -107,7 +132,9 @@ _MONTHS = {# Track statuses meaning the caller asked for data and did not get it# (or got an older issuance). not_linked / not_published are upstream-# coverage facts: named in data_gaps, not degradation.+# coverage facts, and feed_lags_text a text newer than its feed entry:+# named in data_gaps, not degradation. error is an unexpected exception+# while building one product; the rest of the response stands._FAILED_STATUSES = frozenset({"fetch_failed",@@ -116,8 +143,11 @@ _FAILED_STATUSES = frozenset("stale_advisory","stale_warning","refused_link",+ "error",})+# Texts kept in the cache for their issuance.+_KEPT_STATUSES = frozenset({"ok", "feed_lags_text"})_CONE_NOTE = ("Outline simplified from NHC's ring (Douglas-Peucker, 0.01 degree "@@ -208,15 +238,39 @@ def _hours_between(start: datetime | None, end: datetime | None) -> int | None:return round((end - start).total_seconds() / 3600)-def _same_number(found: Any, expected: Any) -> bool:- try:- return int(found) == int(expected)- except (TypeError, ValueError):- return str(found).lstrip("0").upper() == str(expected).lstrip("0").upper()+def _issuance_number(value: Any) -> int | None:+ """An advisory or warning number as an int ("017" -> 17), or None."""+ if isinstance(value, int) and not isinstance(value, bool):+ return value+ if isinstance(value, str) and value.strip().isdecimal():+ return int(value.strip())+ return None+++def _compare_issuance(found: Any, listed: Any) -> str:+ """How the number a text shows stands against the one its feed lists:+ "same", "newer" (the text is ahead of the feed), "older", or+ "unreadable" (the text shows none). Numbers that are not plain+ integers can only match or not; a mismatch then counts as older."""+ if found is None:+ return "unreadable"+ text_number, feed_number = _issuance_number(found), _issuance_number(listed)+ if text_number is not None and feed_number is not None:+ if text_number == feed_number:+ return "same"+ return "newer" if text_number > feed_number else "older"+ same = str(found).strip().lstrip("0").upper() == str(listed).strip().lstrip("0").upper()+ return "same" if same else "older"-def _refused_link(url: str, hosts: frozenset[str]) -> str | None:+def _refused_link(url: Any, hosts: frozenset[str]) -> str | None:"""Why a feed-supplied product link is not fetched, or None if it may be."""+ if not isinstance(url, str):+ return f"link of type {type(url).__name__} is not a string; not fetched"+ # urlsplit drops tab, CR and LF before it reads the host, and httpx+ # refuses them: refuse here, so the check and the request see one URL.+ if any(ch.isspace() or not ch.isprintable() for ch in url):+ return f"link {url!r} contains whitespace or control characters; not fetched"try:parts = urlsplit(url)port = parts.port@@ -404,17 +458,28 @@ def _segment_distance(def simplify_closed_ring(- ring: list[tuple[float, float]], tolerance: float+ ring: list[tuple[float, float]], tolerance: float, max_vertices: int | None = None) -> list[tuple[float, float]]:"""Douglas-Peucker over a closed ring (first vertex repeated last),returned open. Every dropped vertex lies within ``tolerance`` (planar,- in the coordinates' own units) of the kept outline."""+ in the coordinates' own units) of the kept outline.++ With ``max_vertices``, an outline that would keep more vertices+ raises ValueError as soon as it passes the cap, so the cost stays+ under about ``max_vertices`` times the ring's length in distance+ evaluations (each kept vertex costs at most one pass over the ring).+ """count = len(ring)closed = count > 1 and ring[0] == ring[-1]+ over_cap = f"simplified outline has more than {max_vertices} vertices (over the outline cap)"if count < 4:- return list(ring[:-1]) if closed else list(ring)+ outline = list(ring[:-1]) if closed else list(ring)+ if max_vertices is not None and len(outline) > max_vertices:+ raise ValueError(over_cap)+ return outlinekeep = [False] * countkeep[0] = keep[-1] = True+ kept = 1 if closed else 2 # vertices of the open outline returnedstack = [(0, count - 1)]while stack:first, last = stack.pop()@@ -425,28 +490,44 @@ def simplify_closed_ring(worst_index, worst = i, distanceif worst_index != -1 and worst > tolerance:keep[worst_index] = True+ kept += 1+ if max_vertices is not None and kept > max_vertices:+ raise ValueError(over_cap)stack.append((first, worst_index))stack.append((worst_index, last))- kept = [vertex for vertex, flag in zip(ring, keep) if flag]- return kept[:-1] if closed else kept+ outline = [vertex for vertex, flag in zip(ring, keep) if flag]+ return outline[:-1] if closed else outlinedef parse_nhc_cone_kmz(content: bytes) -> dict:"""Parse NHC's CONE.kmz into a simplified [lat, lon] outline.- Raises zipfile.BadZipFile / ValueError / ET.ParseError (and the zip- layer's zlib.error, RuntimeError, EOFError) on anything unreadable;- the caller turns those into a named cone failure.+ Raises on anything unreadable (zipfile.BadZipFile, ValueError,+ ET.ParseError, and whatever the zip layer raises); the caller turns+ any exception into a named cone failure."""with zipfile.ZipFile(io.BytesIO(content)) as archive:members = [m for m in archive.infolist() if m.filename.lower().endswith(".kml")]if not members:raise ValueError("KMZ holds no .kml document")- if members[0].file_size > _KML_MAX_BYTES:+ member = members[0]+ # zipfile feeds bzip2 and LZMA members to decompressors with no+ # output bound, so only stored and deflated members are opened.+ if member.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):+ raise ValueError(+ f"KML member uses zip compression method {member.compress_type}; "+ "only stored (0) or deflated (8) members are read"+ )+ if member.file_size > _KML_MAX_BYTES:+ raise ValueError(f"KML of {member.file_size} bytes exceeds cap {_KML_MAX_BYTES}")+ if member.file_size > _KML_MAX_RATIO * max(member.compress_size, 1):raise ValueError(- f"KML of {members[0].file_size} bytes exceeds cap {_KML_MAX_BYTES}"+ f"KML member expands {member.compress_size} bytes to {member.file_size}, "+ f"past the {_KML_MAX_RATIO}:1 bound")- with archive.open(members[0]) as handle:+ # A header that understates the member cannot get past this read:+ # zipfile stops at the declared size, and the CRC check refuses it.+ with archive.open(member) as handle:kml = handle.read(_KML_MAX_BYTES + 1)if len(kml) > _KML_MAX_BYTES:raise ValueError(f"KML exceeds cap {_KML_MAX_BYTES}")@@ -461,7 +542,13 @@ def parse_nhc_cone_kmz(content: bytes) -> dict:extended[el.get("name")] = value.text.strip()period = extended.get("fcstpd")- outline = simplify_closed_ring(ring + [ring[0]], CONE_SIMPLIFY_TOLERANCE_DEG)+ outline = simplify_closed_ring(+ ring + [ring[0]], CONE_SIMPLIFY_TOLERANCE_DEG, max_vertices=_CONE_MAX_OUTLINE_VERTICES+ )+ if len(outline) < 3:+ raise ValueError(+ f"simplified cone outline has {len(outline)} vertices; an outline needs at least 3"+ )return {"vertices": [[lat, lon] for lat, lon in outline],"vertex_count": len(outline),@@ -569,16 +656,69 @@ def parse_jtwc_warning(text: str, fallback_anchor: datetime) -> dict:# ----------------------------------------------------------------------------async def _nhc_track(fetcher: Fetcher, storm_id: str, advisory: dict, now: datetime) -> dict:- url = advisory.get("url")- out: dict[str, Any] = {- "track_url": url,+def _fetch_reason(result: BinaryResult) -> str:+ """One line on why a product fetch gave no body."""+ if result.status is not None and result.status >= 400:+ return f"HTTP {result.status}"+ return (result.error or f"HTTP {result.status}").split("\n", 1)[0]+++def _redirect_refusal(result: BinaryResult) -> str:+ return (+ f"link answered HTTP {result.status}, a redirect to {result.location!r}; "+ "redirects are not followed, so nothing was fetched from it"+ )+++def _unexpected(exc: BaseException) -> str:+ """Name an unexpected exception from one product's task. Anything+ that is not an Exception (cancellation, exit) is raised again."""+ if not isinstance(exc, Exception):+ raise exc+ return f"{type(exc).__name__}: {exc}"+++async def _fetch_text(+ fetcher: Fetcher, url: str, source: str, key: str+) -> tuple[str | None, BinaryResult | None]:+ """A product text: this issuance's kept copy, else the body of ``url``+ itself (a redirect is not followed). Returns (text, None) for the kept+ copy, (text, result) for a fresh body, (None, result) for no body."""+ kept = fetcher.cache.get(key)+ if isinstance(kept, str):+ return kept, None+ result = await fetcher.get_bytes(+ url, source=source, max_bytes=_TEXT_MAX_BYTES, follow_redirects=False+ )+ if not result.ok:+ return None, result+ return result.content.decode("utf-8", errors="replace"), result+++def _nhc_track_base(advisory: Any) -> dict:+ record = advisory if isinstance(advisory, dict) else {}+ url = record.get("url")+ return {+ "track_url": url if isinstance(url, str) else None,"track_status": "ok","advisory_number": None,+ "feed_advisory_number": record.get("advNum"),"issued": None,"initial": None,"points": [],}+++async def _nhc_track(fetcher: Fetcher, storm_id: str, advisory: Any, now: datetime) -> dict:+ out = _nhc_track_base(advisory)+ if not isinstance(advisory, dict):+ out["track_status"] = "refused_link"+ out["track_error"] = (+ f"CurrentStorms.json forecastAdvisory is a {type(advisory).__name__}, "+ "not an object; nothing fetched"+ )+ return out+ url = advisory.get("url")if not url:out["track_status"] = "not_linked"out["track_error"] = "CurrentStorms.json links no forecast/advisory for this storm"@@ -591,34 +731,64 @@ async def _nhc_track(fetcher: Fetcher, storm_id: str, advisory: dict, now: datetexpected = advisory.get("advNum")key = f"cyclones:nhc:tcm:{storm_id}:{expected}:{advisory.get('fileUpdateTime')}"- page = await fetcher.get_text(- url, source="nhc-forecast", cache_key=key, cache_ttl=_FORECAST_CACHE_TTL- )+ page, fetched = await _fetch_text(fetcher, url, "nhc-forecast", key)if page is None:- out["track_status"] = "fetch_failed"- out["track_error"] = "NHC forecast/advisory text unavailable (no live or cached data)"+ if fetched.location is not None:+ out["track_status"] = "refused_link"+ out["track_error"] = "forecast/advisory " + _redirect_refusal(fetched)+ else:+ out["track_status"] = "fetch_failed"+ out["track_error"] = "NHC forecast/advisory text unavailable: " + _fetch_reason(fetched)return outparsed = parse_nhc_forecast_advisory(page, fallback_anchor=now)out.update(parsed)+ number = parsed["advisory_number"]+ standing = "same" if expected in (None, "") else _compare_issuance(number, expected)if not parsed["points"]:- fetcher.cache.delete(key)out["track_status"] = "unparsed"out["track_error"] = "forecast/advisory page carried no parseable forecast points"- elif expected and not _same_number(parsed["advisory_number"], expected):- fetcher.cache.delete(key)+ elif standing == "newer":+ out["track_status"] = "feed_lags_text"+ out["track_error"] = (+ f"forecast/advisory page shows advisory {number}, newer than advisory "+ f"{expected} that CurrentStorms.json lists; the track is advisory {number}, "+ "the storm's other fields are the feed's"+ )+ elif standing == "unreadable":+ out["track_status"] = "stale_advisory"+ out["expected_advisory_number"] = expected+ out["track_error"] = (+ "forecast/advisory page carries no readable advisory number, so it cannot "+ f"be matched to advisory {expected} that CurrentStorms.json lists"+ )+ elif standing == "older":out["track_status"] = "stale_advisory"out["expected_advisory_number"] = expectedout["track_error"] = (- f"forecast/advisory page shows advisory {parsed['advisory_number']}, "+ f"forecast/advisory page shows advisory {number}, "f"CurrentStorms.json lists {expected}")+ if fetched is not None and out["track_status"] in _KEPT_STATUSES:+ fetcher.cache.set(key, page, _FORECAST_CACHE_TTL)return out-async def _nhc_cone(fetcher: Fetcher, storm_id: str, cone_meta: dict) -> dict:+def _nhc_cone_base(cone_meta: Any) -> dict:+ url = cone_meta.get("kmzFile") if isinstance(cone_meta, dict) else None+ return {"cone_url": url if isinstance(url, str) else None, "cone_status": "ok", "cone": None}+++async def _nhc_cone(fetcher: Fetcher, storm_id: str, cone_meta: Any) -> dict:+ out = _nhc_cone_base(cone_meta)+ if not isinstance(cone_meta, dict):+ out["cone_status"] = "refused_link"+ out["cone_error"] = (+ f"CurrentStorms.json trackCone is a {type(cone_meta).__name__}, "+ "not an object; nothing fetched"+ )+ return outurl = cone_meta.get("kmzFile")- out: dict[str, Any] = {"cone_url": url, "cone_status": "ok", "cone": None}if not url:out["cone_status"] = "not_linked"return out@@ -634,17 +804,21 @@ async def _nhc_cone(fetcher: Fetcher, storm_id: str, cone_meta: dict) -> dict:out["cone"] = cachedreturn out- result = await fetcher.get_bytes(url, source="nhc-gis", max_bytes=_CONE_MAX_BYTES)+ result = await fetcher.get_bytes(+ url, source="nhc-gis", max_bytes=_CONE_MAX_BYTES, follow_redirects=False+ )+ if result.location is not None:+ out["cone_status"] = "refused_link"+ out["cone_error"] = "cone KMZ " + _redirect_refusal(result)+ return outif not result.ok:out["cone_status"] = "fetch_failed"- out["cone_error"] = "NHC cone KMZ fetch failed: " + (- result.error or f"HTTP {result.status}"- )+ out["cone_error"] = "NHC cone KMZ fetch failed: " + _fetch_reason(result)return outtry:# In a worker thread: simplifying is CPU work and must not stall the event loop.cone = await asyncio.to_thread(parse_nhc_cone_kmz, result.content)- except (zipfile.BadZipFile, zlib.error, ET.ParseError, ValueError, RuntimeError, EOFError) as exc:+ except Exception as exc: # any unreadable KMZ is a named gap, never a failed callout["cone_status"] = "unparsed"out["cone_error"] = f"NHC cone KMZ unreadable: {type(exc).__name__}: {exc}"return out@@ -655,20 +829,34 @@ async def _nhc_cone(fetcher: Fetcher, storm_id: str, cone_meta: dict) -> dict:async def _nhc_storm_forecast(fetcher: Fetcher, raw: dict, now: datetime) -> dict:storm_id = raw.get("id") or "unknown"+ advisory = raw.get("forecastAdvisory") or {}+ cone_meta = raw.get("trackCone") or {}+ # One product's unexpected exception is named as that product's+ # "error"; it never fails the other product, the storm or the call.track, cone = await asyncio.gather(- _nhc_track(fetcher, storm_id, raw.get("forecastAdvisory") or {}, now),- _nhc_cone(fetcher, storm_id, raw.get("trackCone") or {}),+ _nhc_track(fetcher, storm_id, advisory, now),+ _nhc_cone(fetcher, storm_id, cone_meta),+ return_exceptions=True,)+ if isinstance(track, BaseException):+ reason = _unexpected(track)+ track = _nhc_track_base(advisory)+ track.update(track_status="error", track_error="forecast track not built: " + reason)+ if isinstance(cone, BaseException):+ reason = _unexpected(cone)+ cone = _nhc_cone_base(cone_meta)+ cone.update(cone_status="error", cone_error="cone not built: " + reason)return {"agency": "NHC", **track, **cone}-async def _jtwc_storm_forecast(fetcher: Fetcher, storm: dict, now: datetime) -> dict:+def _jtwc_base(storm: dict) -> dict:url = storm.get("warning_text_url")- out: dict[str, Any] = {+ return {"agency": "JTWC",- "track_url": url,+ "track_url": url if isinstance(url, str) else None,"track_status": "ok","warning_number": None,+ "feed_warning_number": storm.get("warning_number"),"issued": None,"initial": None,"points": [],@@ -676,6 +864,11 @@ async def _jtwc_storm_forecast(fetcher: Fetcher, storm: dict, now: datetime) ->"cone_status": "not_published","cone": None,}+++async def _jtwc_storm_forecast(fetcher: Fetcher, storm: dict, now: datetime) -> dict:+ out = _jtwc_base(storm)+ url = storm.get("warning_text_url")if not url:out["track_status"] = "not_linked"out["track_error"] = "the JTWC RSS item links no warning text for this storm"@@ -688,32 +881,43 @@ async def _jtwc_storm_forecast(fetcher: Fetcher, storm: dict, now: datetime) ->expected = storm.get("warning_number")key = f"jtwc:warning:{storm.get('id')}:{expected}:{storm.get('issued_at')}"- text = await fetcher.get_text(- url, source="jtwc-warning", cache_key=key, cache_ttl=_FORECAST_CACHE_TTL- )+ text, fetched = await _fetch_text(fetcher, url, "jtwc-warning", key)if text is None:- out["track_status"] = "fetch_failed"- out["track_error"] = "JTWC warning text unavailable (no live or cached data)"+ if fetched.location is not None:+ out["track_status"] = "refused_link"+ out["track_error"] = "warning text " + _redirect_refusal(fetched)+ else:+ out["track_status"] = "fetch_failed"+ out["track_error"] = "JTWC warning text unavailable: " + _fetch_reason(fetched)return outparsed = parse_jtwc_warning(text, now)out.update(parsed)+ number = parsed["warning_number"]+ standing = "same" if expected is None else _compare_issuance(number, expected)if not parsed["points"]:- fetcher.cache.delete(key)out["track_status"] = "unparsed"out["track_error"] = "warning text carried no parseable forecast positions"- elif (- expected is not None- and parsed["warning_number"] is not None- and parsed["warning_number"] != expected- ):- fetcher.cache.delete(key)+ elif standing == "newer":+ out["track_status"] = "feed_lags_text"+ out["track_error"] = (+ f"warning text shows warning {number}, newer than warning {expected} that "+ f"the RSS lists; the track is warning {number}, the storm's other fields "+ "are the RSS's"+ )+ elif standing == "unreadable":out["track_status"] = "stale_warning"out["expected_warning_number"] = expectedout["track_error"] = (- f"warning text shows warning {parsed['warning_number']}, "- f"the RSS lists {expected}"+ "warning text carries no readable warning number, so it cannot be matched "+ f"to warning {expected} that the RSS lists")+ elif standing == "older":+ out["track_status"] = "stale_warning"+ out["expected_warning_number"] = expected+ out["track_error"] = f"warning text shows warning {number}, the RSS lists {expected}"+ if fetched is not None and out["track_status"] in _KEPT_STATUSES:+ fetcher.cache.set(key, text, _FORECAST_CACHE_TTL)return out@@ -748,7 +952,7 @@ def _summarize(storms: list[dict]) -> tuple[list[str], bool]:gaps.append(f"{label}: forecast track {status}: {forecast.get('track_error')}")degraded = degraded or status in _FAILED_STATUSEScone_status = forecast.get("cone_status")- if cone_status in ("fetch_failed", "unparsed", "refused_link"):+ if cone_status in ("fetch_failed", "unparsed", "refused_link", "error"):gaps.append(f"{label}: no cone, {forecast.get('cone_error')}")degraded = Trueelif cone_status == "not_linked":@@ -781,10 +985,17 @@ async def attach_jtwc_forecasts(Returns (data_gaps, degraded)."""now = datetime.now(timezone.utc)targets = storms[:MAX_FORECAST_STORMS]+ # One storm's unexpected exception is named as its track "error";+ # it never fails the other storms or the call.forecasts = await asyncio.gather(- *(_jtwc_storm_forecast(fetcher, storm, now) for storm in targets)+ *(_jtwc_storm_forecast(fetcher, storm, now) for storm in targets),+ return_exceptions=True,)for storm, forecast in zip(targets, forecasts):+ if isinstance(forecast, BaseException):+ reason = _unexpected(forecast)+ forecast = _jtwc_base(storm)+ forecast.update(track_status="error", track_error="forecast track not built: " + reason)storm["forecast"] = forecastfor storm in storms[MAX_FORECAST_STORMS:]:storm["forecast"] = _capped("JTWC")diff --git a/src/world_intel_mcp/sources/cyclones.py b/src/world_intel_mcp/sources/cyclones.pyindex 080e954..1ffc8a1 100644--- a/src/world_intel_mcp/sources/cyclones.py+++ b/src/world_intel_mcp/sources/cyclones.py@@ -132,6 +132,10 @@ async def fetch_cyclones(fetcher: Fetcher, include_forecast: bool = False) -> di"source": "nhc","timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),}+ if data.get("_stale"):+ # The fetcher served an expired copy of the feed: keep its marker.+ response["_stale"] = True+ response["_stale_age_seconds"] = data.get("_stale_age_seconds")if include_forecast:gaps, degraded = await cyclone_forecasts.attach_nhc_forecasts(fetcher, entries)response["data_gaps"] = gapsdiff --git a/src/world_intel_mcp/tests/test_cache_delete_locked.py b/src/world_intel_mcp/tests/test_cache_delete_locked.pynew file mode 100644index 0000000..a438bb6--- /dev/null+++ b/src/world_intel_mcp/tests/test_cache_delete_locked.py@@ -0,0 +1,48 @@+"""Cache.delete on a locked database: logged and swallowed, as Cache.set+does, never raised into the caller.++The review measured ``sqlite3.OperationalError: database is locked``+escaping Cache.delete (after the 5 s busy timeout) and failing the whole+tool call. Here the wait is set to zero so the test is instant; the+error raised is the same.+"""++import logging+import sqlite3+import time+from pathlib import Path++import pytest++from world_intel_mcp.cache import Cache+++def test_delete_on_a_locked_database_is_logged_not_raised(+ tmp_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ cache = Cache(db_path=tmp_path / "locked.db")+ cache.set("k", {"v": 1}, 60)+ cache._get_conn().execute("PRAGMA busy_timeout=0")++ other = sqlite3.connect(str(cache.db_path), isolation_level=None)+ other.execute("BEGIN IMMEDIATE")+ now = time.time()+ other.execute(+ "INSERT INTO cache (key, value, expires_at, created_at) VALUES (?, ?, ?, ?)",+ ("written-meanwhile", "2", now + 60, now),+ )+ try:+ with caplog.at_level(logging.WARNING, logger="world-intel-mcp.cache"):+ cache.delete("k")+ finally:+ other.execute("COMMIT")+ other.close()++ assert "Cache delete failed for k" in caplog.text+ assert "locked" in caplog.text+ assert cache.get("k") == {"v": 1}+ # The connection is still usable once the lock is gone.+ assert cache.get("written-meanwhile") == 2+ cache.delete("k")+ assert cache.get("k") is None+ cache.close()diff --git a/src/world_intel_mcp/tests/test_fetcher_body_cap.py b/src/world_intel_mcp/tests/test_fetcher_body_cap.pynew file mode 100644index 0000000..dcb7030--- /dev/null+++ b/src/world_intel_mcp/tests/test_fetcher_body_cap.py@@ -0,0 +1,110 @@+"""Fetcher.get_bytes reads a body as it arrives and stops as soon as the+decoded size passes ``max_bytes``.++Before, the whole body was buffered, and a gzip body fully decoded,+before the cap was checked, so a small compressed response could make+the process hold hundreds of MiB first. The bodies here are served in+compressed pieces by an iterator that counts how many the client pulls,+so "stopped reading" is observed directly, without timing or memory+measurement.++Gaps / not covered: peak memory is not measured here (the CHANGELOG+cites a one-machine measurement); one network read can still decode to+much more than ``max_bytes`` before the check runs.+"""++import gzip++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher++_URL = "https://a.test/body"+_MiB = 1024 * 1024+++class _CountingBody:+ """A streamed response body that counts the pieces read from it."""++ def __init__(self, data: bytes, piece: int) -> None:+ self.pieces = [data[i : i + piece] for i in range(0, len(data), piece)]+ self.pulled = 0++ async def __aiter__(self):+ for piece in self.pieces:+ self.pulled += 1+ yield piece+++async def test_a_gzip_body_past_the_cap_is_refused_without_reading_the_rest(+ fetcher: Fetcher,+) -> None:+ """16 MiB of zeros gzip to about 16 KB; each 512-byte piece decodes+ to about 0.5 MiB, so a 1 MiB cap is passed within the first few+ pieces and the rest is never read or decoded."""+ body = _CountingBody(gzip.compress(b"\0" * (16 * _MiB)), piece=512)+ respx.get(_URL).mock(+ return_value=httpx.Response(200, headers={"content-encoding": "gzip"}, content=body)+ )++ result = await fetcher.get_bytes(_URL, source="t", max_bytes=_MiB)++ assert result.ok is False+ assert result.status == 200+ assert result.content is None+ assert result.error.startswith(f"body exceeds cap {_MiB}: stopped after ")+ assert len(body.pieces) > 25+ assert body.pulled <= 4+ # An over-cap body is an answer, not an outage.+ assert fetcher.breaker.status()["t"]["total_failures"] == 0+++async def test_an_uncompressed_body_past_the_cap_is_not_read_to_the_end(+ fetcher: Fetcher,+) -> None:+ body = _CountingBody(b"x" * (64 * 1024), piece=4096)+ respx.get(_URL).mock(return_value=httpx.Response(200, content=body))++ result = await fetcher.get_bytes(_URL, source="t", max_bytes=10_000)++ assert result.content is None+ assert result.error.startswith("body exceeds cap 10000: stopped after ")+ assert body.pulled < len(body.pieces)++[email protected](("length", "ok"), [(10_000, True), (10_001, False)])+async def test_a_body_of_exactly_max_bytes_is_returned_whole(+ fetcher: Fetcher, length: int, ok: bool+) -> None:+ respx.get(_URL).mock(return_value=httpx.Response(200, content=b"y" * length))++ result = await fetcher.get_bytes(_URL, source="t", max_bytes=10_000)++ assert result.ok is ok+ assert result.content == (b"y" * length if ok else None)+++async def test_the_cap_counts_decoded_bytes_not_compressed_ones(fetcher: Fetcher) -> None:+ data = b"forecast track " * 1000+ respx.get(_URL).mock(+ return_value=httpx.Response(+ 200, headers={"content-encoding": "gzip"}, content=gzip.compress(data)+ )+ )++ whole = await fetcher.get_bytes(_URL, source="t", max_bytes=len(data))+ short = await fetcher.get_bytes(_URL, source="t", max_bytes=len(data) - 1)++ assert whole.content == data+ assert short.content is None+ assert short.error.startswith(f"body exceeds cap {len(data) - 1}: ")diff --git a/src/world_intel_mcp/tests/test_fetcher_redirects.py b/src/world_intel_mcp/tests/test_fetcher_redirects.pynew file mode 100644index 0000000..4e95363--- /dev/null+++ b/src/world_intel_mcp/tests/test_fetcher_redirects.py@@ -0,0 +1,95 @@+"""Tests for Fetcher.get_bytes(follow_redirects=False).++The shared client follows redirects. A caller that has checked a URL+against an allowlist passes ``follow_redirects=False`` so the body can+only come from that URL: a redirect comes back as its status and+resolved Location, the target is never requested, and the redirect is+an answer (not retried, not a source failure).++Gaps / not covered: get_text, get_json and get_xml have no such option+and keep following redirects.+"""++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+++async def test_get_bytes_without_following_reports_the_redirect_unrequested(+ fetcher: Fetcher,+) -> None:+ origin = respx.get("https://a.test/x").mock(+ return_value=httpx.Response(302, headers={"location": "http://10.0.0.5:8080/y"})+ )+ target = respx.get("http://10.0.0.5:8080/y").mock(+ return_value=httpx.Response(200, content=b"inner")+ )++ result = await fetcher.get_bytes("https://a.test/x", source="t", follow_redirects=False)++ assert result.ok is False+ assert result.status == 302+ assert result.content is None+ assert result.location == "http://10.0.0.5:8080/y"+ assert result.error == "redirect to http://10.0.0.5:8080/y not followed"+ assert target.called is False+ assert origin.call_count == 1+ assert fetcher.breaker.status()["t"]["total_failures"] == 0+++async def test_get_bytes_reports_a_relative_redirect_as_an_absolute_url(+ fetcher: Fetcher,+) -> None:+ respx.get("https://a.test/x").mock(+ return_value=httpx.Response(301, headers={"location": "/y?z=1"})+ )++ result = await fetcher.get_bytes("https://a.test/x", source="t", follow_redirects=False)++ assert result.status == 301+ assert result.location == "https://a.test/y?z=1"+++async def test_get_bytes_without_following_still_returns_a_direct_body(+ fetcher: Fetcher,+) -> None:+ respx.get("https://a.test/x").mock(return_value=httpx.Response(200, content=b"body"))++ result = await fetcher.get_bytes("https://a.test/x", source="t", follow_redirects=False)++ assert result.ok is True+ assert result.content == b"body"+ assert result.location is None+++async def test_follow_redirects_is_keyword_only(fetcher: Fetcher) -> None:+ """Keyword-only, so other keyword parameters of get_bytes can be added+ without moving it."""+ with pytest.raises(TypeError):+ await fetcher.get_bytes("https://a.test/x", "t", None, None, 10, False)+++async def test_get_bytes_follows_redirects_by_default(fetcher: Fetcher) -> None:+ respx.get("https://a.test/x").mock(+ return_value=httpx.Response(301, headers={"location": "https://a.test/y"})+ )+ moved = respx.get("https://a.test/y").mock(return_value=httpx.Response(200, content=b"moved"))++ result = await fetcher.get_bytes("https://a.test/x", source="t")++ assert result.ok is True+ assert result.status == 200+ assert result.content == b"moved"+ assert result.location is None+ assert moved.call_count == 1diff --git a/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.py b/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.pyindex 08ca24a..f6ce79d 100644--- a/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.py+++ b/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.py@@ -29,6 +29,9 @@ import asyncio as asyncio_modimport ioimport jsonimport math+import random+import struct+import threadingimport zipfilefrom datetime import datetime, timezonefrom pathlib import Path@@ -71,10 +74,15 @@ def _tcm_page() -> str:)-def _kmz(kml: str, name: str = "ep212026_017adv_CONE.kml") -> bytes:- """Zip a KML the way the live CONE.kmz is packed (one deflated member)."""+def _kmz(+ kml: str | bytes,+ name: str = "ep212026_017adv_CONE.kml",+ method: int = zipfile.ZIP_DEFLATED,+) -> bytes:+ """Zip a KML the way the live CONE.kmz is packed (one deflated member,+ unless ``method`` names another compression)."""buf = io.BytesIO()- with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:+ with zipfile.ZipFile(buf, "w", method) as zf:zf.writestr(name, kml)return buf.getvalue()@@ -97,6 +105,30 @@ def no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)+_FAR_NOW = datetime(2027, 3, 1, 12, 0, tzinfo=timezone.utc)+++class _FrozenClock(datetime):+ """Stands in for cyclone_forecasts.datetime: ``now()`` returns ``at``."""++ at = _FAR_NOW++ @classmethod+ def now(cls, tz=None):+ return cls.at++[email protected](autouse=True)+def _far_now(monkeypatch: pytest.MonkeyPatch) -> None:+ """Every test here runs with "now" fixed at 2027-03-01T12:00Z, four+ and a half months from the 2026-10-17 captures. Day-only product times+ ("18/0000Z") then reach their expected dates only through the+ products' own date lines, so the tests exercise that anchoring and+ give the same result on any day the suite runs. A test that needs a+ different "now" sets ``_FrozenClock.at`` itself."""+ monkeypatch.setattr(cf, "datetime", _FrozenClock)++def _mock_nhc(current: dict | None = None,tcm: httpx.Response | None = None,@@ -541,18 +573,28 @@ def test_cone_kml_with_doctype_is_refused() -> None:cf.parse_nhc_cone_kmz(_kmz(kml))-def _ring_kml(vertices: int) -> str:- """A closed ring of ``vertices`` distinct points in a minimal cone KML."""- points = [f"{-100 + i * 1e-4:.4f},{15 + (i % 2) * 1e-4:.4f},0" for i in range(vertices)]+def _coords_kml(tokens: list[str]) -> str:+ """A minimal cone KML around one ring of KML "lon,lat,alt" tokens."""return ('<?xml version="1.0" encoding="UTF-8"?>''<kml xmlns="http://www.opengis.net/kml/2.2"><Placemark><Polygon>'"<outerBoundaryIs><LinearRing><coordinates>"- + " ".join(points + points[:1])+ + " ".join(tokens)+ "</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark></kml>")+def _ring_kml(vertices: int) -> str:+ """A closed ring of ``vertices`` distinct points in a minimal cone KML:+ a thin band, out along 15.00N and back along 15.05N, which simplifies+ to its four corners (a cone outline needs at least three vertices)."""+ half = vertices // 2+ out = [(15.0, -100 + i * 1e-4) for i in range(half)]+ back = [(15.05, -100 + i * 1e-4) for i in reversed(range(vertices - half))]+ points = [f"{lon:.4f},{lat:.4f},0" for lat, lon in out + back]+ return _coords_kml(points + points[:1])++def test_cone_ring_over_the_vertex_cap_is_refused_before_simplifying() -> None:"""Douglas-Peucker is quadratic in the worst case; a ring past the capis refused, one at the cap is simplified."""@@ -828,14 +870,21 @@ async def test_jtwc_warning_link_off_the_jtwc_host_is_refused_not_fetched(async def test_jtwc_text_without_forecast_positions_is_unparsed_and_refetched(fetcher: Fetcher, no_sleep: None) -> None:- """Synthetic body: the first two lines of 29W's warning text, no- forecast blocks (a real JTWC final warning has not been observed).- Reported unparsed, degraded, and not kept for the next call."""+ """Synthetic body: the first two lines of 29W's warning text and its+ REMARKS date line, no forecast blocks (a real JTWC final warning has+ not been observed). Reported unparsed, degraded, and not kept for the+ next call. The date line fixes the month of "171500"; without it the+ issue time would follow the fetch time (see+ test_jtwc_text_without_a_date_line_resolves_against_the_fetch_time)."""routes = _mock_jtwc()routes["29W"].mock(return_value=httpx.Response(200,- text=_crlf("WTPN32 PGTW 171500\nSUBJ/TYPHOON 29W (CHAMPI) WARNING NR 013//\n"),+ text=_crlf(+ "WTPN32 PGTW 171500\nSUBJ/TYPHOON 29W (CHAMPI) WARNING NR 013//\n"+ "REMARKS:\n171500Z POSITION NEAR 12.7N 145.5E.\n"+ "17OCT26. TYPHOON 29W (CHAMPI), LOCATED APPROXIMATELY 96 NM\n"+ ),))@@ -922,3 +971,1032 @@ async def test_cyclone_tools_expose_and_honor_include_forecast(jtwc = await tools_pkg.ALL_HANDLERS["intel_jtwc_cyclones"]({"include_forecast": True})by_id = {s["id"]: s for s in jtwc["storms"]}assert by_id["29W"]["forecast"]["track_status"] == "ok"+++async def test_jtwc_tool_ignores_a_non_boolean_include_forecast(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ tools_pkg = _tools_registry()+ from world_intel_mcp import runtime++ monkeypatch.setattr(runtime, "fetcher", fetcher)+ routes = _mock_jtwc()++ stringly = await tools_pkg.ALL_HANDLERS["intel_jtwc_cyclones"]({"include_forecast": "false"})++ assert stringly["count"] == 3+ assert all("forecast" not in s for s in stringly["storms"])+ assert not any(routes[k].called for k in ("29W", "01P", "21E"))+++# ---------------------------------------------------------------------------+# The clock: product dates decide, not the day the suite runs+# ---------------------------------------------------------------------------+++async def test_jtwc_text_without_a_date_line_resolves_against_the_fetch_time(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, no_sleep: None+) -> None:+ """A warning text with no REMARKS date line places its day-only times+ in the month nearest the fetch time ("now", set here to the capture+ time; at the module's 2027-03-01 they would land in February)."""+ monkeypatch.setattr(+ _FrozenClock, "at", datetime(2026, 10, 17, 16, 45, tzinfo=timezone.utc)+ )+ routes = _mock_jtwc()+ routes["29W"].mock(+ return_value=httpx.Response(+ 200, text=_crlf(_fixture("jtwc_wp2926web_wrn013.txt").replace("17OCT26. ", ""))+ )+ )++ result = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ champi = next(s for s in result["storms"] if s["id"] == "29W")["forecast"]+ assert champi["track_status"] == "ok"+ assert champi["issued"] == "2026-10-17T15:00:00Z"+ assert _as_tuples(champi["points"]) == _CHAMPI_POINTS+++async def test_nhc_page_with_crlf_line_ends_parses_the_same(fetcher: Fetcher) -> None:+ """Line ends are normalised before parsing: with CRLF the issuance+ line would not match, and the times would follow "now" instead."""+ _mock_nhc(tcm=httpx.Response(200, text=_crlf(_tcm_page())))++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert fc["issued"] == "2026-10-17T15:00:00Z"+ assert _as_tuples(fc["points"]) == _TRUDY_POINTS+++# ---------------------------------------------------------------------------+# Feed and text out of step: which number came from where+# ---------------------------------------------------------------------------+++async def test_nhc_page_newer_than_the_feed_is_feed_lags_text_and_kept(+ fetcher: Fetcher,+) -> None:+ """CurrentStorms.json is cached for 600 s, so after an issuance it can+ still list advisory 016 while the bin page already serves 17. The page+ is then the newer product: labelled feed_lags_text with both numbers,+ not stale, not degraded, and kept for the next call."""+ current = _current_storms()+ current["activeStorms"][0]["forecastAdvisory"]["advNum"] = "016"+ routes = _mock_nhc(current=current)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "feed_lags_text"+ assert fc["advisory_number"] == "17"+ assert fc["feed_advisory_number"] == "016"+ assert "expected_advisory_number" not in fc+ assert _as_tuples(fc["points"]) == _TRUDY_POINTS+ assert "degraded" not in result+ [gap] = result["data_gaps"]+ assert "feed_lags_text" in gap and "advisory 17" in gap and "016" in gap++ again = await fetch_cyclones(fetcher, include_forecast=True)+ assert again["storms"][0]["forecast"]["track_status"] == "feed_lags_text"+ assert routes["tcm"].call_count == 1+++async def test_jtwc_text_newer_than_the_rss_is_feed_lags_text_and_kept(+ fetcher: Fetcher, no_sleep: None+) -> None:+ routes = _mock_jtwc()+ rss = _fixture("jtwc_rss_20261017.xml").replace(+ "Typhoon 29W (Champi) Warning #13", "Typhoon 29W (Champi) Warning #12"+ )+ routes["rss"].mock(return_value=httpx.Response(200, text=rss))++ result = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ storm = next(s for s in result["storms"] if s["id"] == "29W")+ assert storm["warning_number"] == 12 # the RSS's number, at storm level+ champi = storm["forecast"]+ assert champi["track_status"] == "feed_lags_text"+ assert champi["warning_number"] == 13+ assert champi["feed_warning_number"] == 12+ assert _as_tuples(champi["points"]) == _CHAMPI_POINTS+ gap = next(g for g in result["data_gaps"] if "Champi" in g)+ assert "feed_lags_text" in gap and "warning 13" in gap and "12" in gap++ await fetch_jtwc_cyclones(fetcher, include_forecast=True)+ assert routes["29W"].call_count == 1+++async def test_jtwc_stale_warning_text_is_not_kept(fetcher: Fetcher) -> None:+ """A lagging JTWC text is labelled stale and fetched again on the next+ call, never served from the cache."""+ routes = _mock_jtwc(+ trudy=httpx.Response(200, text=_crlf(_fixture("jtwc_wp2926web_wrn013.txt")))+ )++ await fetch_jtwc_cyclones(fetcher, include_forecast=True)+ second = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ trudy = next(s for s in second["storms"] if s["id"] == "21E")["forecast"]+ assert trudy["track_status"] == "stale_warning"+ assert trudy["expected_warning_number"] == 17+ assert routes["21E"].call_count == 2+++async def test_nhc_unparsed_page_is_not_kept(fetcher: Fetcher) -> None:+ routes = _mock_nhc(+ tcm=httpx.Response(200, text="<html><body><h1>Not Found</h1></body></html>")+ )++ await fetch_cyclones(fetcher, include_forecast=True)+ second = await fetch_cyclones(fetcher, include_forecast=True)++ assert second["storms"][0]["forecast"]["track_status"] == "unparsed"+ assert routes["tcm"].call_count == 2+++async def test_nhc_stale_feed_copy_is_marked_and_a_newer_page_is_not_called_stale(+ fetcher: Fetcher, no_sleep: None+) -> None:+ """CurrentStorms.json down, an expired copy listing advisory 016 in the+ cache: the fetcher serves the copy marked _stale, and the response+ keeps the marker, with or without forecasts. The text page (17) is+ newer than that copy, so it reads feed_lags_text, not stale."""+ old = _current_storms()+ old["activeStorms"][0]["forecastAdvisory"]["advNum"] = "016"+ fetcher.cache.set("cyclones:nhc:current", old, -1)+ routes = _mock_nhc()+ routes["current"].mock(return_value=httpx.Response(503))++ plain = await fetch_cyclones(fetcher)++ assert plain["count"] == 1+ assert plain["_stale"] is True+ assert plain["_stale_age_seconds"] >= 0+ assert "forecast" not in plain["storms"][0]++ with_forecast = await fetch_cyclones(fetcher, include_forecast=True)++ assert with_forecast["_stale"] is True+ fc = with_forecast["storms"][0]["forecast"]+ assert fc["track_status"] == "feed_lags_text"+ assert fc["feed_advisory_number"] == "016"+++# ---------------------------------------------------------------------------+# An unreadable advisory or warning number: one rule for both agencies+# ---------------------------------------------------------------------------+++async def test_an_unreadable_issuance_number_is_stale_for_both_agencies(+ fetcher: Fetcher, no_sleep: None+) -> None:+ """The number is the only check that a per-bin text belongs to the+ issuance the feed lists. A text whose number cannot be read cannot be+ shown to be current, so NHC and JTWC both label it stale (degraded,+ not kept) and say the number was unreadable."""+ nhc_routes = _mock_nhc(+ tcm=httpx.Response(+ 200, text=_tcm_page().replace("FORECAST/ADVISORY NUMBER 17", "FORECAST/ADVISORY")+ )+ )+ jtwc_routes = _mock_jtwc()+ jtwc_routes["29W"].mock(+ return_value=httpx.Response(+ 200,+ text=_crlf(+ _fixture("jtwc_wp2926web_wrn013.txt").replace("WARNING NR 013", "WARNING 013")+ ),+ )+ )++ nhc = await fetch_cyclones(fetcher, include_forecast=True)+ jtwc = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ fc = nhc["storms"][0]["forecast"]+ assert fc["track_status"] == "stale_advisory"+ assert fc["advisory_number"] is None+ assert "no readable advisory number" in fc["track_error"]+ assert len(fc["points"]) == 8+ assert nhc["degraded"] is True+ champi = next(s for s in jtwc["storms"] if s["id"] == "29W")["forecast"]+ assert champi["track_status"] == "stale_warning"+ assert champi["warning_number"] is None+ assert "no readable warning number" in champi["track_error"]+ assert len(champi["points"]) == 8++ await fetch_cyclones(fetcher, include_forecast=True)+ await fetch_jtwc_cyclones(fetcher, include_forecast=True)+ assert nhc_routes["tcm"].call_count == 2+ assert jtwc_routes["29W"].call_count == 2+++# ---------------------------------------------------------------------------+# Redirects: a product comes from its own URL or not at all+# ---------------------------------------------------------------------------+++async def test_nhc_product_redirects_are_refused_never_followed(fetcher: Fetcher) -> None:+ """The review's redirect probe: allowlisted product URLs answering 302+ to a private address and to the link-local metadata address. Neither+ target is requested, each redirect is named as a refused link, and the+ reported URLs are the only ones fetched."""+ routes = _mock_nhc(+ tcm=httpx.Response(302, headers={"location": "http://10.0.0.5:8080/tcm"}),+ cone=httpx.Response(+ 302, headers={"location": "http://169.254.169.254/latest/cone.kmz"}+ ),+ )+ inner_tcm = respx.get("http://10.0.0.5:8080/tcm").mock(+ return_value=httpx.Response(200, text=_tcm_page())+ )+ inner_cone = respx.get("http://169.254.169.254/latest/cone.kmz").mock(+ return_value=httpx.Response(200, content=_cone_kmz())+ )++ result = await fetch_cyclones(fetcher, include_forecast=True)++ assert inner_tcm.called is False+ assert inner_cone.called is False+ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "refused_link"+ assert fc["track_url"] == _TCM_URL+ assert "'http://10.0.0.5:8080/tcm'" in fc["track_error"]+ assert fc["points"] == []+ assert fc["cone_status"] == "refused_link"+ assert fc["cone_url"] == _CONE_URL+ assert "'http://169.254.169.254/latest/cone.kmz'" in fc["cone_error"]+ assert fc["cone"] is None+ assert result["degraded"] is True+ assert sum("redirect" in g for g in result["data_gaps"]) == 2+ # A redirect is an answer, not an outage: asked once, not retried.+ assert routes["tcm"].call_count == 1+ assert routes["cone"].call_count == 1+++async def test_same_host_https_product_redirect_is_not_followed_either(+ fetcher: Fetcher,+) -> None:+ """No product redirect is followed, even one that stays on+ www.nhc.noaa.gov over https, so track_url is always the URL the track+ came from."""+ _mock_nhc(+ tcm=httpx.Response(+ 301, headers={"location": "https://www.nhc.noaa.gov/text/refresh/MIATCMEP1.shtml"}+ )+ )+ moved = respx.get("https://www.nhc.noaa.gov/text/refresh/MIATCMEP1.shtml").mock(+ return_value=httpx.Response(200, text=_tcm_page())+ )++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert moved.called is False+ assert fc["track_status"] == "refused_link"+ assert "not followed" in fc["track_error"]+ assert fc["cone_status"] == "ok"+++async def test_jtwc_warning_text_redirect_is_refused_never_followed(+ fetcher: Fetcher, no_sleep: None+) -> None:+ routes = _mock_jtwc()+ routes["29W"].mock(+ return_value=httpx.Response(+ 301, headers={"location": "http://127.0.0.1:9/wp2926web.txt"}+ )+ )+ inner = respx.get("http://127.0.0.1:9/wp2926web.txt").mock(+ return_value=httpx.Response(200, text=_crlf(_fixture("jtwc_wp2926web_wrn013.txt")))+ )++ result = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ champi = next(s for s in result["storms"] if s["id"] == "29W")["forecast"]+ assert inner.called is False+ assert champi["track_status"] == "refused_link"+ assert champi["track_url"] == _JTWC_29W_URL+ assert "'http://127.0.0.1:9/wp2926web.txt'" in champi["track_error"]+ assert champi["points"] == []+ assert routes["29W"].call_count == 1+++# ---------------------------------------------------------------------------+# Feed values of the wrong type; links with whitespace or control characters+# ---------------------------------------------------------------------------+++ ("path", "value", "track_status", "cone_status"),+ [+ (("forecastAdvisory",), "n/a", "refused_link", "ok"),+ (("forecastAdvisory", "url"), 17, "refused_link", "ok"),+ (("trackCone",), [1], "ok", "refused_link"),+ (("trackCone", "kmzFile"), {"x": 1}, "ok", "refused_link"),+ (("trackCone",), [], "ok", "not_linked"),+ ],+)+async def test_malformed_feed_values_are_named_never_a_failed_call(+ fetcher: Fetcher, path: tuple, value: object, track_status: str, cone_status: str+) -> None:+ """The review's malformed CurrentStorms.json values: four raised out of+ fetch_cyclones and lost the storm list."""+ current = _current_storms()+ target = current["activeStorms"][0]+ for key in path[:-1]:+ target = target[key]+ target[path[-1]] = value+ _mock_nhc(current=current)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ assert result["count"] == 1+ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == track_status+ assert fc["cone_status"] == cone_status+++ "url",+ [+ "https://www.nhc.noaa.gov/text/MIATCM\tEP1.shtml",+ " https://www.nhc.noaa.gov/text/MIATCMEP1.shtml",+ "https://www.nhc.noaa.gov/text/MIATCMEP1.shtml\r\nHost: evil.example",+ "https://www.nhc.noaa.gov/text/MIATCMEP1.shtml\x00",+ "https://www.nhc.noaa.gov/text/MIATCM EP1.shtml",+ "https://www.nhc.noaa.gov/text/MIATCMEP1.shtml",+ ],+)+def test_links_with_whitespace_or_control_characters_are_refused(url: str) -> None:+ """urllib strips tab, CR and LF before reading the host, so the+ allowlist passed links that httpx then refused with InvalidURL."""+ reason = cf._refused_link(url, cf._NHC_PRODUCT_HOSTS)+ assert reason is not None+ assert "whitespace or control" in reason+++ "value", [17, {"x": 1}, ["https://www.nhc.noaa.gov/x"], b"https://www.nhc.noaa.gov/x"]+)+def test_links_that_are_not_strings_are_refused(value: object) -> None:+ reason = cf._refused_link(value, cf._NHC_PRODUCT_HOSTS)+ assert reason is not None+ assert "not a string" in reason+++async def test_cone_link_with_a_tab_is_refused_not_requested(fetcher: Fetcher) -> None:+ """In the review this link passed the allowlist and httpx's+ InvalidURL escaped fetch_cyclones."""+ current = _current_storms()+ current["activeStorms"][0]["trackCone"]["kmzFile"] = (+ "https://www.nhc.noaa.gov/storm_graphics/api/EP212026_017adv\t_CONE.kmz"+ )+ _mock_nhc(current=current)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert fc["cone_status"] == "refused_link"+ assert "whitespace or control" in fc["cone_error"]+++# ---------------------------------------------------------------------------+# One bad product never fails the response+# ---------------------------------------------------------------------------++[email protected]("method", [zipfile.ZIP_LZMA, zipfile.ZIP_BZIP2])+async def test_corrupt_bzip2_or_lzma_cone_is_a_named_gap_not_a_failed_call(+ fetcher: Fetcher, method: int+) -> None:+ """The review's corrupt LZMA and bzip2 members raised LZMAError and+ OSError out of fetch_cyclones, losing the storm list."""+ raw = bytearray(_kmz(_fixture("nhc_ep212026_017adv_CONE.kml"), method=method))+ start = 30 + len("ep212026_017adv_CONE.kml")+ for i in range(start + 12, start + 40):+ raw[i] ^= 0x5A+ _mock_nhc(cone=httpx.Response(200, content=bytes(raw)))++ result = await fetch_cyclones(fetcher, include_forecast=True)++ assert result["count"] == 1+ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert fc["cone_status"] == "unparsed"+ assert "compression method" in fc["cone_error"]+ assert result["degraded"] is True+++async def test_an_unexpected_error_in_one_product_keeps_the_rest(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ _mock_nhc()++ async def broken_cone(*args, **kwargs):+ raise RuntimeError("boom")++ monkeypatch.setattr(cf, "_nhc_cone", broken_cone)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ assert result["count"] == 1+ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert _as_tuples(fc["points"]) == _TRUDY_POINTS+ assert fc["cone_status"] == "error"+ assert fc["cone_url"] == _CONE_URL+ assert fc["cone"] is None+ assert "RuntimeError: boom" in fc["cone_error"]+ assert result["degraded"] is True+ assert any("Trudy" in g and "boom" in g for g in result["data_gaps"])+++async def test_an_unexpected_error_in_the_nhc_track_is_a_failure_named_per_storm(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The track side of the same net: the cone still arrives, and the+ track's error alone marks the response degraded."""+ _mock_nhc()++ def broken(*args, **kwargs):+ raise RuntimeError("boom")++ monkeypatch.setattr(cf, "parse_nhc_forecast_advisory", broken)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "error"+ assert fc["track_url"] == _TCM_URL+ assert fc["feed_advisory_number"] == "017"+ assert fc["points"] == []+ assert "RuntimeError: boom" in fc["track_error"]+ assert fc["cone_status"] == "ok"+ assert result["degraded"] is True+++async def test_any_exception_reading_the_cone_kmz_is_unparsed(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The review's corrupt bzip2 member raised OSError, which the cone's+ old exception list did not name. Any exception from the KMZ parser is+ now an unparsed cone, named with its type."""+ _mock_nhc()++ def corrupt(content: bytes) -> dict:+ raise OSError("Invalid data stream")++ monkeypatch.setattr(cf, "parse_nhc_cone_kmz", corrupt)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["cone_status"] == "unparsed"+ assert "OSError: Invalid data stream" in fc["cone_error"]+ assert fc["track_status"] == "ok"+++def test_unexpected_errors_are_named_but_cancellation_is_not_swallowed() -> None:+ assert cf._unexpected(RuntimeError("boom")) == "RuntimeError: boom"+ with pytest.raises(asyncio_mod.CancelledError):+ cf._unexpected(asyncio_mod.CancelledError())+++async def test_an_unexpected_error_in_one_jtwc_storm_keeps_the_others(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, no_sleep: None+) -> None:+ _mock_jtwc()+ real = cf.parse_jtwc_warning++ def flaky(text: str, anchor: datetime) -> dict:+ if "CHAMPI" in text:+ raise RuntimeError("boom")+ return real(text, anchor)++ monkeypatch.setattr(cf, "parse_jtwc_warning", flaky)++ result = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ assert result["count"] == 3+ by_id = {s["id"]: s["forecast"] for s in result["storms"]}+ assert by_id["29W"]["track_status"] == "error"+ assert by_id["29W"]["track_url"] == _JTWC_29W_URL+ assert "RuntimeError: boom" in by_id["29W"]["track_error"]+ assert by_id["29W"]["points"] == []+ assert by_id["29W"]["cone_status"] == "not_published"+ assert _as_tuples(by_id["01P"]["points"]) == _WATI_POINTS+ assert any("Champi" in g and "boom" in g for g in result["data_gaps"])+++# ---------------------------------------------------------------------------+# KMZ members: compression method, expansion ratio, declared size+# ---------------------------------------------------------------------------+++def _record_member_opens(monkeypatch: pytest.MonkeyPatch) -> list:+ """Record every ZipFile.open call (a member read) from here on."""+ opened: list = []+ real_open = zipfile.ZipFile.open++ def recording_open(self, *args, **kwargs):+ opened.append(args[0] if args else kwargs.get("name"))+ return real_open(self, *args, **kwargs)++ monkeypatch.setattr(zipfile.ZipFile, "open", recording_open)+ return opened++[email protected]("method", [zipfile.ZIP_BZIP2, zipfile.ZIP_LZMA])+def test_cone_kmz_member_not_stored_or_deflated_is_refused_unread(+ method: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ """zipfile runs bzip2 and LZMA members through decompressors with no+ output bound (the review measured a 621-byte bzip2 KMZ taking the+ process to 1 GiB RSS), so such a member is refused before it is+ opened."""+ kmz = _kmz(_fixture("nhc_ep212026_017adv_CONE.kml"), method=method)+ opened = _record_member_opens(monkeypatch)+ with pytest.raises(ValueError, match="compression method"):+ cf.parse_nhc_cone_kmz(kmz)+ assert opened == []+++def test_cone_kmz_with_a_stored_member_parses() -> None:+ cone = cf.parse_nhc_cone_kmz(+ _kmz(_fixture("nhc_ep212026_017adv_CONE.kml"), method=zipfile.ZIP_STORED)+ )+ assert cone["source_vertex_count"] == 1167+ assert cone["vertices"][0] == [16.33344, -103.90001]+++def test_cone_kmz_member_expanding_past_the_ratio_bound_is_refused_unread(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """4 MiB of padding inside the KML: under the 8 MiB cap, but the member+ then expands about 300:1 (the live cone's member expands 2.8:1)."""+ kml = _fixture("nhc_ep212026_017adv_CONE.kml").replace(+ "<Document>\n", "<Document>\n" + " " * (4 * 1024 * 1024), 1+ )+ kmz = _kmz(kml)+ info = zipfile.ZipFile(io.BytesIO(kmz)).infolist()[0]+ assert info.file_size <= cf._KML_MAX_BYTES+ assert info.file_size > cf._KML_MAX_RATIO * info.compress_size+ opened = _record_member_opens(monkeypatch)+ with pytest.raises(ValueError, match="expands"):+ cf.parse_nhc_cone_kmz(kmz)+ assert opened == []+++def test_cone_kmz_member_declaring_more_than_the_kml_cap_is_refused_unread(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A member over 8 MiB is refused from its declared size, before any of+ it is decompressed. Random bytes keep the compression ratio near 1:1,+ so only the size check can refuse it unopened."""+ kmz = _kmz(random.Random(0).randbytes(cf._KML_MAX_BYTES + 1))+ opened = _record_member_opens(monkeypatch)+ with pytest.raises(ValueError, match="exceeds cap"):+ cf.parse_nhc_cone_kmz(kmz)+ assert opened == []+++def test_cone_kmz_member_larger_than_it_declares_is_refused() -> None:+ """A header that understates the member (1 MiB of KML declared as+ 1,000 bytes): zipfile stops reading at the declared size, and the+ checksum then refuses the member."""+ kml = _fixture("nhc_ep212026_017adv_CONE.kml").replace(+ "<Document>\n", "<Document>\n" + " " * (1024 * 1024), 1+ )+ raw = bytearray(_kmz(kml))+ struct.pack_into("<I", raw, 22, 1000) # local file header: uncompressed size+ central = raw.rfind(b"PK\x01\x02")+ struct.pack_into("<I", raw, central + 24, 1000) # central directory entry+ with pytest.raises(zipfile.BadZipFile, match="CRC"):+ cf.parse_nhc_cone_kmz(bytes(raw))+++ "bad", ["-100.0,91.0,0", "-100.0,-90.5,0", "-100.0,nan,0", "nan,15.0,0", "inf,15.0,0"]+)+def test_cone_vertex_outside_the_coordinate_range_is_refused(bad: str) -> None:+ tokens = ["-100.0,15.0,0", "-99.0,15.0,0", bad, "-100.0,16.0,0", "-100.0,15.0,0"]+ with pytest.raises(ValueError, match="out of range"):+ cf.parse_cone_kml_ring(_coords_kml(tokens).encode())+++def test_cone_outline_under_three_vertices_is_refused() -> None:+ """The review's ring 0.004 degrees across simplified to one vertex at+ the 0.01 degree tolerance and still read ok."""+ pts = [(15.0, -100.0), (15.004, -100.0), (15.004, -100.004), (15.0, -100.004)]+ tokens = [f"{lon},{lat},0" for lat, lon in pts + pts[:1]]+ with pytest.raises(ValueError, match="at least 3"):+ cf.parse_nhc_cone_kmz(_kmz(_coords_kml(tokens)))+++# ---------------------------------------------------------------------------+# Simplifier cost and outline size+# ---------------------------------------------------------------------------+++def _zigzag_kml(vertices: int, amplitude: float) -> str:+ """The review's worst case: a ring zig-zagging ``amplitude`` degrees,+ above the 0.01 degree tolerance, so nearly every vertex is kept and+ each split peels off one vertex."""+ points = [+ f"{-100 + i * 1e-3:.4f},{15 + (i % 2) * amplitude:.4f},0" for i in range(vertices)+ ]+ return _coords_kml(points + points[:1])+++def test_cone_simplifier_cost_is_bounded_at_the_vertex_cap(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """At the old 10,000-vertex cap this ring kept 9,990 vertices and took+ 15.1 s of CPU (the review's measurement, 2026-10-17) and 49,994,955+ distance evaluations (calls to _segment_distance, counted the same way+ on the unfixed module, the same day). The bound is counted, not timed,+ so the test is deterministic; it is absolute, so raising either cap+ past it fails here; and the counter stops a regressed run early+ instead of letting it take seconds."""+ budget = 2_000_000+ calls = 0+ real = cf._segment_distance++ def counted(*args):+ nonlocal calls+ calls += 1+ if calls > budget:+ raise AssertionError(f"simplifier passed {budget:,} distance evaluations")+ return real(*args)++ kmz = _kmz(_zigzag_kml(cf._CONE_MAX_VERTICES, 0.05))+ monkeypatch.setattr(cf, "_segment_distance", counted)+ with pytest.raises(ValueError, match="over the outline cap"):+ cf.parse_nhc_cone_kmz(kmz)+ assert calls <= budget+++def test_simplified_outline_over_the_vertex_cap_is_refused() -> None:+ square = [(0.0, 0.0), (0.5, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]+ assert len(cf.simplify_closed_ring(square, 0.01, max_vertices=4)) == 4+ with pytest.raises(ValueError, match="more than 3"):+ cf.simplify_closed_ring(square, 0.01, max_vertices=3)+++async def test_cone_is_parsed_off_the_event_loop_thread(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ seen: list[int] = []+ real = cf.parse_nhc_cone_kmz++ def recording(content: bytes) -> dict:+ seen.append(threading.get_ident())+ return real(content)++ monkeypatch.setattr(cf, "parse_nhc_cone_kmz", recording)+ _mock_nhc()++ result = await fetch_cyclones(fetcher, include_forecast=True)++ assert result["storms"][0]["forecast"]["cone_status"] == "ok"+ assert len(seen) == 1+ assert seen[0] != threading.get_ident()+++# ---------------------------------------------------------------------------+# Parsers: values stay inside their own block and fix+# ---------------------------------------------------------------------------+++def test_nhc_point_without_a_wind_line_does_not_borrow_the_next_one() -> None:+ text = _fixture("nhc_tcm_ep212026_adv017.txt")+ old = "FORECAST VALID 19/0000Z 20.1N 106.4W\nMAX WIND 85 KT...GUSTS 105 KT.\n"+ assert old in text+ parsed = cf.parse_nhc_forecast_advisory(+ text.replace(old, "FORECAST VALID 19/0000Z 20.1N 106.4W\n")+ )+ by_tau = {p["tau_hours"]: p for p in parsed["points"]}+ assert by_tau[36]["max_wind_kt"] is None+ assert by_tau[36]["gust_kt"] is None+ assert by_tau[48]["max_wind_kt"] == 65+++def test_jtwc_point_without_a_wind_line_does_not_borrow_the_next_one() -> None:+ text = _fixture("jtwc_wp2926web_wrn013.txt")+ old = "181200Z --- 13.5N 141.6E\n MAX SUSTAINED WINDS - 135 KT, GUSTS 165 KT\n"+ assert old in text+ parsed = cf.parse_jtwc_warning(text.replace(old, "181200Z --- 13.5N 141.6E\n"), _FAR_NOW)+ by_tau = {p["tau_hours"]: p for p in parsed["points"]}+ assert by_tau[24]["max_wind_kt"] is None+ assert by_tau[36]["max_wind_kt"] == 140+++def test_jtwc_pressure_for_another_time_is_not_the_warning_fix_pressure() -> None:+ text = _fixture("jtwc_wp2926web_wrn013.txt")+ old = "MINIMUM CENTRAL PRESSURE AT 171200Z IS 945 MB"+ assert old in text+ parsed = cf.parse_jtwc_warning(+ text.replace(old, "MINIMUM CENTRAL PRESSURE AT 171800Z IS 945 MB"), _FAR_NOW+ )+ assert parsed["initial"]["valid_time"] == "2026-10-17T12:00:00Z"+ assert parsed["initial"]["pressure_mb"] is None+++# ---------------------------------------------------------------------------+# Per-issuance cache keys+# ---------------------------------------------------------------------------+++def _next_advisory_feed() -> dict:+ """Trudy's feed entry moved on to advisory 018 (new numbers, file times+ and cone URL; the text URL is the same bin page)."""+ current = _current_storms()+ storm = current["activeStorms"][0]+ storm["forecastAdvisory"].update(advNum="018", fileUpdateTime="2026-10-17T20:37:11.524Z")+ storm["trackCone"].update(+ advNum="018",+ fileUpdateTime="2026-10-17T20:39:40.332Z",+ kmzFile=_CONE_URL.replace("_017adv_", "_018adv_"),+ )+ return current+++def _advisory_18_cone_kml() -> str:+ kml = _fixture("nhc_ep212026_017adv_CONE.kml")+ old = '<Data name="advisoryNum">\n <value>17</value>'+ assert kml.count(old) == 1+ return kml.replace(old, old.replace(">17<", ">18<"))+++async def test_nhc_track_and_cone_are_fetched_again_for_a_new_advisory(+ fetcher: Fetcher,+) -> None:+ """The cache keys carry the advisory number and file time: a new+ advisory never reuses the previous advisory's text or cone."""+ routes = _mock_nhc()+ first = await fetch_cyclones(fetcher, include_forecast=True)+ assert first["storms"][0]["forecast"]["advisory_number"] == "17"+ assert first["storms"][0]["forecast"]["cone"]["advisory_number"] == "17"++ fetcher.cache.delete("cyclones:nhc:current") # the feed itself is cached 600 s+ routes["current"].mock(return_value=httpx.Response(200, json=_next_advisory_feed()))+ routes["tcm"].mock(+ return_value=httpx.Response(+ 200,+ text=_tcm_page().replace(+ "FORECAST/ADVISORY NUMBER 17", "FORECAST/ADVISORY NUMBER 18"+ ),+ )+ )+ cone_18 = respx.get(_CONE_URL.replace("_017adv_", "_018adv_")).mock(+ return_value=httpx.Response(200, content=_kmz(_advisory_18_cone_kml()))+ )++ second = await fetch_cyclones(fetcher, include_forecast=True)++ fc = second["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert fc["advisory_number"] == "18"+ assert fc["cone_status"] == "ok"+ assert fc["cone"]["advisory_number"] == "18"+ assert routes["tcm"].call_count == 2+ assert cone_18.call_count == 1+++async def test_nhc_products_are_fetched_again_when_only_the_advisory_number_changes(+ fetcher: Fetcher,+) -> None:+ """The keys carry the number itself, not only the file time: a feed+ entry for advisory 018 that kept 017's file times still gets fresh+ products. A key on the file time alone would serve 017's text (read+ as stale) and 017's cone."""+ routes = _mock_nhc()+ await fetch_cyclones(fetcher, include_forecast=True)++ renumbered = _current_storms()+ storm = renumbered["activeStorms"][0]+ storm["forecastAdvisory"]["advNum"] = "018"+ storm["trackCone"]["advNum"] = "018"+ fetcher.cache.delete("cyclones:nhc:current")+ routes["current"].mock(return_value=httpx.Response(200, json=renumbered))+ routes["tcm"].mock(+ return_value=httpx.Response(+ 200,+ text=_tcm_page().replace(+ "FORECAST/ADVISORY NUMBER 17", "FORECAST/ADVISORY NUMBER 18"+ ),+ )+ )+ routes["cone"].mock(return_value=httpx.Response(200, content=_kmz(_advisory_18_cone_kml())))++ second = await fetch_cyclones(fetcher, include_forecast=True)++ fc = second["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert fc["advisory_number"] == "18"+ assert fc["cone"]["advisory_number"] == "18"+ assert routes["tcm"].call_count == 2+ assert routes["cone"].call_count == 2+++async def test_nhc_corrected_product_with_the_same_number_is_fetched_again(+ fetcher: Fetcher,+) -> None:+ """Same advisory number, new file time (a corrected product): both+ products are fetched again, not served from the cache."""+ routes = _mock_nhc()+ await fetch_cyclones(fetcher, include_forecast=True)++ corrected = _current_storms()+ storm = corrected["activeStorms"][0]+ storm["forecastAdvisory"]["fileUpdateTime"] = "2026-10-17T15:10:00.000Z"+ storm["trackCone"]["fileUpdateTime"] = "2026-10-17T15:12:00.000Z"+ fetcher.cache.delete("cyclones:nhc:current")+ routes["current"].mock(return_value=httpx.Response(200, json=corrected))++ await fetch_cyclones(fetcher, include_forecast=True)++ assert routes["tcm"].call_count == 2+ assert routes["cone"].call_count == 2+++async def test_jtwc_text_is_fetched_again_when_only_the_warning_number_changes(+ fetcher: Fetcher, no_sleep: None+) -> None:+ """Warning 14 listed with warning 13's issue time still gets a fresh+ text: the key carries the number, not only the time."""+ routes = _mock_jtwc()+ await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ rss_14 = _fixture("jtwc_rss_20261017.xml").replace(+ "Typhoon 29W (Champi) Warning #13", "Typhoon 29W (Champi) Warning #14"+ )+ text_14 = _fixture("jtwc_wp2926web_wrn013.txt").replace("WARNING NR 013", "WARNING NR 014")+ fetcher.cache.delete("jtwc:rss:current")+ routes["rss"].mock(return_value=httpx.Response(200, text=rss_14))+ routes["29W"].mock(return_value=httpx.Response(200, text=_crlf(text_14)))++ second = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ champi = next(s for s in second["storms"] if s["id"] == "29W")["forecast"]+ assert champi["track_status"] == "ok"+ assert champi["warning_number"] == 14+ assert routes["29W"].call_count == 2+++async def test_jtwc_text_is_fetched_again_for_a_new_or_reissued_warning(+ fetcher: Fetcher, no_sleep: None+) -> None:+ routes = _mock_jtwc()+ await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ rss_14 = (+ _fixture("jtwc_rss_20261017.xml")+ .replace("Typhoon 29W (Champi) Warning #13", "Typhoon 29W (Champi) Warning #14")+ .replace("Issued at 17/1500Z", "Issued at 17/2100Z")+ )+ text_14 = _fixture("jtwc_wp2926web_wrn013.txt").replace("WARNING NR 013", "WARNING NR 014")+ fetcher.cache.delete("jtwc:rss:current") # the RSS itself is cached 600 s+ routes["rss"].mock(return_value=httpx.Response(200, text=rss_14))+ routes["29W"].mock(return_value=httpx.Response(200, text=_crlf(text_14)))++ second = await fetch_jtwc_cyclones(fetcher, include_forecast=True)++ champi = next(s for s in second["storms"] if s["id"] == "29W")["forecast"]+ assert champi["track_status"] == "ok"+ assert champi["warning_number"] == 14+ assert routes["29W"].call_count == 2++ # Reissued: the same warning number at a new issue time.+ fetcher.cache.delete("jtwc:rss:current")+ routes["rss"].mock(+ return_value=httpx.Response(+ 200, text=rss_14.replace("Issued at 17/2100Z", "Reissued at 17/2200Z")+ )+ )+ await fetch_jtwc_cyclones(fetcher, include_forecast=True)+ assert routes["29W"].call_count == 3+++# ---------------------------------------------------------------------------+# Small paths: number comparison, text size cap, tiny rings+# ---------------------------------------------------------------------------+++ ("found", "listed", "standing"),+ [+ ("17", "017", "same"),+ ("18", "017", "newer"),+ ("16", "017", "older"),+ (13, 12, "newer"),+ (None, "017", "unreadable"),+ ("17A", "017a", "same"), # not plain integers: equal or not, never ordered+ ("17A", "017", "older"),+ ],+)+def test_issuance_numbers_are_compared_as_integers_when_they_are_integers(+ found: object, listed: object, standing: str+) -> None:+ assert cf._compare_issuance(found, listed) == standing+++async def test_nhc_text_over_the_size_cap_is_a_named_fetch_failure(fetcher: Fetcher) -> None:+ _mock_nhc(tcm=httpx.Response(200, content=b"x" * (cf._TEXT_MAX_BYTES + 1)))++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "fetch_failed"+ assert f"exceeds cap {cf._TEXT_MAX_BYTES}" in fc["track_error"]+ assert result["degraded"] is True+++async def test_cone_kmz_over_the_size_cap_is_a_named_fetch_failure(fetcher: Fetcher) -> None:+ _mock_nhc(cone=httpx.Response(200, content=b"x" * (cf._CONE_MAX_BYTES + 1)))++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "ok"+ assert fc["cone_status"] == "fetch_failed"+ assert f"exceeds cap {cf._CONE_MAX_BYTES}" in fc["cone_error"]+++def test_the_documented_limits_are_the_enforced_ones() -> None:+ """The CHANGELOG and the module docstring state these numbers, and the+ behaviour tests above are written against the constants; this pins+ the constants to the stated values, so changing a limit means+ changing its documentation too."""+ assert cf.MAX_FORECAST_STORMS == 10+ assert cf._TEXT_MAX_BYTES == 1024 * 1024+ assert cf._CONE_MAX_BYTES == 2 * 1024 * 1024+ assert cf._KML_MAX_BYTES == 8 * 1024 * 1024+ assert cf._KML_MAX_RATIO == 100+ assert cf._CONE_MAX_VERTICES == 3_000+ assert cf._CONE_MAX_OUTLINE_VERTICES == 500+++def test_simplify_ring_too_short_to_simplify_still_honours_the_cap() -> None:+ two_point_ring = [(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)]+ assert cf.simplify_closed_ring(two_point_ring, 0.01, max_vertices=2) == [(0.0, 0.0), (1.0, 0.0)]+ with pytest.raises(ValueError, match="more than 1"):+ cf.simplify_closed_ring(two_point_ring, 0.01, max_vertices=1)