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
Close database handles on every exit path; stop the suite leaking descriptors
Phoenix Agent (mac-studio)0120c70acb12
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 676745a..f817103 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,17 @@- Apply per-source request spacing to every HTTP retry, including JSON,text, XML and binary fetches.+### Fixed: database handles close on every exit path+- The collector (`run_once` and the daemon), standalone report generation+ and the weekly trends query now close their cache, HTTP client and SQLite+ connections when they finish or fail, instead of leaving them to garbage+ collection.+- The test suite closes every cache, fetcher and database it opens. Under+ `--cov` on Python 3.13 it held about 1,550 SQLite descriptors open (each+ unclosed connection's ResourceWarning kept it alive) and failed at the+ default 1,024 open-file limit. Test runs also no longer leave+ `wim-server-test-*` directories in the system temp directory.+### Added: liquidity and money (Phase 29)Keyless sources only: the FRED graph CSV (`fred.stlouisfed.org/graph/fredgraph.csv`,allowed by robots.txt with `Crawl-delay: 1`, honored by a 1 s `fred-graph` ratediff --git a/src/world_intel_mcp/analysis/alerts.py b/src/world_intel_mcp/analysis/alerts.pyindex d61007a..28ccfe7 100644--- a/src/world_intel_mcp/analysis/alerts.py+++ b/src/world_intel_mcp/analysis/alerts.py@@ -9,6 +9,7 @@ import asyncioimport loggingimport mathimport sqlite3+from contextlib import closingfrom datetime import datetime, timezonelogger = logging.getLogger("world-intel-mcp.analysis.alerts")@@ -261,11 +262,10 @@ async def fetch_weekly_trends(fetcher) -> dict:trends: list[dict] = []try:- conn = sqlite3.connect(_default_db_path())- rows = conn.execute(- "SELECT key, count, mean, m2, updated_at FROM baselines WHERE count >= 5"- ).fetchall()- conn.close()+ with closing(sqlite3.connect(_default_db_path())) as conn:+ rows = conn.execute(+ "SELECT key, count, mean, m2, updated_at FROM baselines WHERE count >= 5"+ ).fetchall()for key, n, mean, m2, updated_at in rows:parts = key.split(":")diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.pyindex 58978ef..a1b143e 100644--- a/src/world_intel_mcp/collector.py+++ b/src/world_intel_mcp/collector.py@@ -23,6 +23,7 @@ import signalimport sqlite3import sysimport time+from contextlib import AsyncExitStackfrom pathlib import Pathfrom dotenv import load_dotenv@@ -367,76 +368,79 @@ async def run_daemon(source_filter: str | None = None,) -> None:"""Run the collector in daemon mode with a configurable interval."""- cache = Cache()- breaker = CircuitBreaker(failure_threshold=3, cooldown_seconds=300)- vector_store = VectorStore(enabled=True)- await vector_store.start()- fetcher = Fetcher(cache=cache, breaker=breaker, vector_store=vector_store)-- resolved_filter = _resolve_source_filter(source_filter)- filter_desc = source_filter or "all"-- logger.info(- "Collector daemon starting: interval=%ds, sources=%s",- interval,- filter_desc,- )-- stop_event = asyncio.Event()-- def _handle_signal(sig, frame):- logger.info("Received signal %s, stopping...", sig)- stop_event.set()-- signal.signal(signal.SIGINT, _handle_signal)- signal.signal(signal.SIGTERM, _handle_signal)-- cycle = 0- while not stop_event.is_set():- cycle += 1- logger.info("Starting collection cycle %d", cycle)- try:- summary = await collect_once(fetcher, vector_store, resolved_filter)- logger.info("Cycle %d complete: %s", cycle, summary)- except Exception as exc:- logger.error("Cycle %d failed: %s", cycle, exc)+ async with AsyncExitStack() as resources:+ cache = Cache()+ resources.callback(cache.close)+ breaker = CircuitBreaker(failure_threshold=3, cooldown_seconds=300)+ vector_store = VectorStore(enabled=True)+ resources.push_async_callback(vector_store.stop)+ await vector_store.start()+ fetcher = Fetcher(cache=cache, breaker=breaker, vector_store=vector_store)+ resources.push_async_callback(fetcher.close)++ resolved_filter = _resolve_source_filter(source_filter)+ filter_desc = source_filter or "all"++ logger.info(+ "Collector daemon starting: interval=%ds, sources=%s",+ interval,+ filter_desc,+ )- # Evict expired cache entries periodically- if cycle % 12 == 0: # Every ~hour at 5min interval- evicted = cache.evict_expired()- if evicted:- logger.info("Evicted %d expired cache entries", evicted)+ stop_event = asyncio.Event()++ def _handle_signal(sig, frame):+ logger.info("Received signal %s, stopping...", sig)+ stop_event.set()++ signal.signal(signal.SIGINT, _handle_signal)+ signal.signal(signal.SIGTERM, _handle_signal)++ cycle = 0+ while not stop_event.is_set():+ cycle += 1+ logger.info("Starting collection cycle %d", cycle)+ try:+ summary = await collect_once(fetcher, vector_store, resolved_filter)+ logger.info("Cycle %d complete: %s", cycle, summary)+ except Exception as exc:+ logger.error("Cycle %d failed: %s", cycle, exc)++ # Evict expired cache entries periodically+ if cycle % 12 == 0: # Every ~hour at 5min interval+ evicted = cache.evict_expired()+ if evicted:+ logger.info("Evicted %d expired cache entries", evicted)++ # Wait for next cycle or stop signal+ try:+ await asyncio.wait_for(stop_event.wait(), timeout=interval)+ except asyncio.TimeoutError:+ pass- # Wait for next cycle or stop signal- try:- await asyncio.wait_for(stop_event.wait(), timeout=interval)- except asyncio.TimeoutError:- pass-- await vector_store.stop()- await fetcher.close()logger.info("Collector daemon stopped")async def run_once(source_filter: str | None = None) -> dict:"""Run a single collection cycle and exit."""- cache = Cache()- breaker = CircuitBreaker(failure_threshold=3, cooldown_seconds=300)- vector_store = VectorStore(enabled=True)- await vector_store.start()- fetcher = Fetcher(cache=cache, breaker=breaker, vector_store=vector_store)-- resolved_filter = _resolve_source_filter(source_filter)- summary = await collect_once(fetcher, vector_store, resolved_filter)-- # Wait for vector store queue to drain- if vector_store._store_queue:- await vector_store._store_queue.join()-- await vector_store.stop()- await fetcher.close()-- return summary+ async with AsyncExitStack() as resources:+ cache = Cache()+ resources.callback(cache.close)+ breaker = CircuitBreaker(failure_threshold=3, cooldown_seconds=300)+ vector_store = VectorStore(enabled=True)+ resources.push_async_callback(vector_store.stop)+ await vector_store.start()+ fetcher = Fetcher(cache=cache, breaker=breaker, vector_store=vector_store)+ resources.push_async_callback(fetcher.close)++ resolved_filter = _resolve_source_filter(source_filter)+ summary = await collect_once(fetcher, vector_store, resolved_filter)++ # Wait for vector store queue to drain+ if vector_store._store_queue:+ await vector_store._store_queue.join()++ return summarydef main():diff --git a/src/world_intel_mcp/reports.py b/src/world_intel_mcp/reports.pyindex 4d8c0a8..255385d 100644--- a/src/world_intel_mcp/reports.py+++ b/src/world_intel_mcp/reports.py@@ -785,4 +785,10 @@ async def generate_report_standalone(cache = Cache()breaker = CircuitBreaker(failure_threshold=3, cooldown_seconds=300)fetcher = Fetcher(cache=cache, breaker=breaker)- return await generate_report(fetcher, output_path, title, sections, fmt)+ try:+ return await generate_report(fetcher, output_path, title, sections, fmt)+ finally:+ try:+ await fetcher.close()+ finally:+ cache.close()diff --git a/src/world_intel_mcp/tests/conftest.py b/src/world_intel_mcp/tests/conftest.pyindex 6b84666..5b6fb69 100644--- a/src/world_intel_mcp/tests/conftest.py+++ b/src/world_intel_mcp/tests/conftest.py@@ -1,6 +1,7 @@"""Test configuration — strips proxy env vars so httpx doesn't try SOCKS."""import asyncio+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathimport pytest@@ -50,11 +51,89 @@ def _reset_fetcher_locks() -> None:@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture-def fetcher(cache: Cache) -> Fetcher:+async def fetcher(cache: Cache) -> AsyncIterator[Fetcher]:breaker = CircuitBreaker()- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()++[email protected](scope="module")+async def isolated_runtime():+ """Restore shared infrastructure after a module rebinds it."""+ from world_intel_mcp import runtime++ names = ("cache", "breaker", "fetcher", "aoi_store", "_aoi_store",+ "vector_store", "_vector_store")+ prior = {name: runtime.__dict__[name] for name in names if name in runtime.__dict__}+ try:+ yield runtime+ finally:+ if runtime.__dict__.get("fetcher") is not prior.get("fetcher"):+ await runtime.fetcher.close()+ runtime.aoi_store.close()+ runtime.cache.close()+ for name in names:+ runtime.__dict__.pop(name, None)+ runtime.__dict__.update(prior)++[email protected](scope="session", autouse=True)+async def _close_shared_infrastructure():+ """Close process-wide resources lazily opened by the tests."""+ import sys++ yield+ runtime = sys.modules.get("world_intel_mcp.runtime")+ if runtime is not None and "cache" in runtime.__dict__:+ await runtime.fetcher.close()+ runtime.aoi_store.close()+ runtime.cache.close()+ for module_name, name in (+ ("world_intel_mcp.sources.intelligence", "_temporal"),+ ("world_intel_mcp.analysis.spikes", "_detector"),+ ):+ module = sys.modules.get(module_name)+ instance = getattr(module, name, None)+ if instance is not None and instance._conn is not None:+ instance._conn.close()+++def temporal_baseline(tmp_path):+ from world_intel_mcp.analysis.temporal import TemporalBaseline++ baseline = TemporalBaseline(db_path=str(tmp_path / "t.db"))+ try:+ yield baseline+ finally:+ if baseline._conn is not None:+ baseline._conn.close()++[email protected](autouse=True)+async def _close_cli_resources(monkeypatch):+ """Close test-owned CLI singletons before monkeypatch restores them."""+ from world_intel_mcp import cli++ yield+ if cli._aoi_store is not None:+ cli._aoi_store.close()+ cli._aoi_store = None+ if cli._fetcher is not None:+ try:+ await cli._fetcher.close()+ finally:+ cli._fetcher.cache.close()+ cli._fetcher = Nonediff --git a/src/world_intel_mcp/tests/test_aoi.py b/src/world_intel_mcp/tests/test_aoi.pyindex 016083d..fc0a75e 100644--- a/src/world_intel_mcp/tests/test_aoi.py+++ b/src/world_intel_mcp/tests/test_aoi.py@@ -1108,10 +1108,8 @@ def test_segment_distance_perpendicular_pole() -> None:assert d == pytest.approx(10007, rel=0.01)-def test_store_update_missing_aoi_raises() -> None:- import tempfile as _tf-- s = AOIStore(Path(_tf.mkdtemp()) / "kx.db")+def test_store_update_missing_aoi_raises(tmp_path: Path) -> None:+ s = AOIStore(tmp_path / "kx.db")try:with pytest.raises(KeyError):s.update("Nowhere", radius_km=10.0)diff --git a/src/world_intel_mcp/tests/test_bonds.py b/src/world_intel_mcp/tests/test_bonds.pyindex 458e35d..ba854b3 100644--- a/src/world_intel_mcp/tests/test_bonds.py+++ b/src/world_intel_mcp/tests/test_bonds.py@@ -1,5 +1,6 @@"""Tests for bonds source module — uses respx to mock HTTP calls."""+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathfrom unittest.mock import patch@@ -13,14 +14,22 @@ from world_intel_mcp.fetcher import Fetcher@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture-def fetcher(cache: Cache) -> Fetcher:+async def fetcher(cache: Cache) -> AsyncIterator[Fetcher]:breaker = CircuitBreaker()- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()# ---------------------------------------------------------------------------diff --git a/src/world_intel_mcp/tests/test_cache.py b/src/world_intel_mcp/tests/test_cache.pyindex d3c6566..8e27b25 100644--- a/src/world_intel_mcp/tests/test_cache.py+++ b/src/world_intel_mcp/tests/test_cache.py@@ -2,6 +2,7 @@import tempfileimport time+from collections.abc import Iteratorfrom pathlib import Pathimport pytest@@ -10,8 +11,12 @@ from world_intel_mcp.cache import Cache@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()def test_set_and_get(cache: Cache) -> None:diff --git a/src/world_intel_mcp/tests/test_collector_runtime.py b/src/world_intel_mcp/tests/test_collector_runtime.pyindex 55b30ba..170067e 100644--- a/src/world_intel_mcp/tests/test_collector_runtime.py+++ b/src/world_intel_mcp/tests/test_collector_runtime.py@@ -55,6 +55,9 @@ class FakeCache:def __init__(self, *args, **kwargs):self.evictions = 0+ def close(self) -> None:+ pass+def evict_expired(self) -> int:self.evictions += 1return 3diff --git a/src/world_intel_mcp/tests/test_earnings.py b/src/world_intel_mcp/tests/test_earnings.pyindex 54f14a3..5e055d4 100644--- a/src/world_intel_mcp/tests/test_earnings.py+++ b/src/world_intel_mcp/tests/test_earnings.py@@ -1,5 +1,6 @@"""Tests for earnings source module — uses respx to mock HTTP calls."""+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathimport httpx@@ -12,14 +13,22 @@ from world_intel_mcp.fetcher import Fetcher@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture-def fetcher(cache: Cache) -> Fetcher:+async def fetcher(cache: Cache) -> AsyncIterator[Fetcher]:breaker = CircuitBreaker()- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()# ---------------------------------------------------------------------------diff --git a/src/world_intel_mcp/tests/test_fetcher.py b/src/world_intel_mcp/tests/test_fetcher.pyindex 3622398..0695fa8 100644--- a/src/world_intel_mcp/tests/test_fetcher.py+++ b/src/world_intel_mcp/tests/test_fetcher.py@@ -6,6 +6,7 @@ for fresh data. Prior to the fix, ``_stale_fallback`` returned the cachedvalue completely unmodified — the marker was documented but never set."""+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathimport pytest@@ -16,8 +17,12 @@ from world_intel_mcp.fetcher import Fetcher@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture@@ -26,8 +31,12 @@ def breaker() -> CircuitBreaker:@pytest.fixture-def fetcher(cache: Cache, breaker: CircuitBreaker) -> Fetcher:- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+async def fetcher(cache: Cache, breaker: CircuitBreaker) -> AsyncIterator[Fetcher]:+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()def test_stale_fallback_marks_dict_responses(fetcher: Fetcher) -> None:diff --git a/src/world_intel_mcp/tests/test_fleet_honesty.py b/src/world_intel_mcp/tests/test_fleet_honesty.pyindex 3115160..e215d7e 100644--- a/src/world_intel_mcp/tests/test_fleet_honesty.py+++ b/src/world_intel_mcp/tests/test_fleet_honesty.py@@ -401,11 +401,11 @@ def _baseline_keys(baseline: TemporalBaseline) -> list[str]:@pytest.mark.asyncioasync def test_surge_with_posture_down_is_an_error_and_records_nothing(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:"""Regression (M1): a posture outage recorded a zero in every region'ssurge baseline and reported no surges, the reading of an empty sky."""- baseline = TemporalBaseline(db_path=str(tmp_path / "t.db"))+ baseline = temporal_baselinemonkeypatch.setattr(intelligence, "_temporal", baseline)monkeypatch.setattr(military,@@ -425,9 +425,9 @@ async def test_surge_with_posture_down_is_an_error_and_records_nothing(@pytest.mark.asyncioasync def test_surge_skips_regions_whose_theater_had_no_source(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:- baseline = TemporalBaseline(db_path=str(tmp_path / "t.db"))+ baseline = temporal_baselinemonkeypatch.setattr(intelligence, "_temporal", baseline)monkeypatch.setattr(military,@@ -462,7 +462,7 @@ async def test_surge_skips_regions_whose_theater_had_no_source(@respx.mock@pytest.mark.asyncioasync def test_every_upstream_down_reads_unknown_through_the_real_components(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:"""Regression (M1, measured by the reviewer with a real Fetcher): NGA,adsb.lol and OpenSky all failing gave LOW_ACTIVITY, score 0, zero@@ -470,7 +470,7 @@ async def test_every_upstream_down_reads_unknown_through_the_real_components(zero aircraft and only the snapshot reported it."""monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)monkeypatch.setattr(- intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))+ intelligence, "_temporal", temporal_baseline)for host in (r"msi\.nga\.mil", r"api\.adsb\.lol", r"opensky-network\.org"):respx.get(url__regex=rf".*{host}.*").mock(return_value=httpx.Response(500))diff --git a/src/world_intel_mcp/tests/test_forex.py b/src/world_intel_mcp/tests/test_forex.pyindex 192b143..94a3488 100644--- a/src/world_intel_mcp/tests/test_forex.py+++ b/src/world_intel_mcp/tests/test_forex.py@@ -1,5 +1,6 @@"""Tests for forex source module — uses respx to mock HTTP calls."""+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathimport httpx@@ -12,14 +13,22 @@ from world_intel_mcp.fetcher import Fetcher@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture-def fetcher(cache: Cache) -> Fetcher:+async def fetcher(cache: Cache) -> AsyncIterator[Fetcher]:breaker = CircuitBreaker()- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()# ---------------------------------------------------------------------------diff --git a/src/world_intel_mcp/tests/test_history_backfill.py b/src/world_intel_mcp/tests/test_history_backfill.pyindex f62cfa4..8592639 100644--- a/src/world_intel_mcp/tests/test_history_backfill.py+++ b/src/world_intel_mcp/tests/test_history_backfill.py@@ -73,12 +73,15 @@ def db(tmp_path: Path) -> Path:@pytest.fixture-def fetcher(db: Path):+async def fetcher(db: Path):# The history store lives in the cache DB in production; same file here.f = Fetcher(cache=Cache(db_path=db), breaker=CircuitBreaker(),default_timeout=5.0, max_retries=0)- yield f- f.cache.close()+ try:+ yield f+ finally:+ await f.close()+ f.cache.close()@pytest.fixturediff --git a/src/world_intel_mcp/tests/test_intelligence.py b/src/world_intel_mcp/tests/test_intelligence.pyindex 562e5e5..fbad8db 100644--- a/src/world_intel_mcp/tests/test_intelligence.py+++ b/src/world_intel_mcp/tests/test_intelligence.py@@ -1,5 +1,6 @@"""Tests for sources/intelligence.py — downstream ACLED-failure honesty (issue #3)."""+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathimport pytest@@ -10,14 +11,22 @@ from world_intel_mcp.fetcher import Fetcher@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture-def fetcher(cache: Cache) -> Fetcher:+async def fetcher(cache: Cache) -> AsyncIterator[Fetcher]:breaker = CircuitBreaker()- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()@pytest.mark.asynciodiff --git a/src/world_intel_mcp/tests/test_lagged_connections.py b/src/world_intel_mcp/tests/test_lagged_connections.pyindex 256d83c..8713f77 100644--- a/src/world_intel_mcp/tests/test_lagged_connections.py+++ b/src/world_intel_mcp/tests/test_lagged_connections.py@@ -803,7 +803,7 @@ def test_user_facing_text_has_no_em_dashes() -> None:@pytest.fixture(scope="module")-def server():+def server(isolated_runtime):"""server.py imported under test_server_registry's temp cache path, theshared runtime rebound while the override is in force (that file'sfixture pattern)."""@@ -811,7 +811,7 @@ def server():os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)try:module = importlib.import_module("world_intel_mcp.server")- importlib.import_module("world_intel_mcp.runtime")._initialize()+ isolated_runtime._initialize()yield modulefinally:if prior is None:diff --git a/src/world_intel_mcp/tests/test_liquidity_surfaces.py b/src/world_intel_mcp/tests/test_liquidity_surfaces.pyindex 9652662..69e7205 100644--- a/src/world_intel_mcp/tests/test_liquidity_surfaces.py+++ b/src/world_intel_mcp/tests/test_liquidity_surfaces.py@@ -70,21 +70,25 @@ def _fetcher(tmp_path: Path) -> Fetcher:async def _build_payloads(tmp_path: Path) -> dict:f = _fetcher(tmp_path)- with respx.mock:- _mock_all()- ecb_key = "M.U2.Y.V.M10+M20+M30.X.1+4+I.U2.2300.Z01.E+A"- respx.get(f"https://data-api.ecb.europa.eu/service/data/BSI/{ecb_key}").mock(- return_value=httpx.Response(200, json=json.loads(- (Path(__file__).parent / "fixtures" / "liquidity" / "ecb_bsi_money.json").read_text()- ))- )- return {- "board": await liquidity.fetch_liquidity_board(f),- "net": await liquidity.fetch_net_liquidity(f, limit=3),- "money": await liquidity.fetch_money_supply(f, limit=2),- "fed": await liquidity.fetch_fed_liquidity_series(f, "WALCL", limit=2),- "ecb": await liquidity.fetch_ecb_series(f, key=ecb_key, limit=1),- }+ try:+ with respx.mock:+ _mock_all()+ ecb_key = "M.U2.Y.V.M10+M20+M30.X.1+4+I.U2.2300.Z01.E+A"+ respx.get(f"https://data-api.ecb.europa.eu/service/data/BSI/{ecb_key}").mock(+ return_value=httpx.Response(200, json=json.loads(+ (Path(__file__).parent / "fixtures" / "liquidity" / "ecb_bsi_money.json").read_text()+ ))+ )+ return {+ "board": await liquidity.fetch_liquidity_board(f),+ "net": await liquidity.fetch_net_liquidity(f, limit=3),+ "money": await liquidity.fetch_money_supply(f, limit=2),+ "fed": await liquidity.fetch_fed_liquidity_series(f, "WALCL", limit=2),+ "ecb": await liquidity.fetch_ecb_series(f, key=ecb_key, limit=1),+ }+ finally:+ await f.close()+ f.cache.close()def _payloads(tmp_path: Path) -> dict:diff --git a/src/world_intel_mcp/tests/test_news_market.py b/src/world_intel_mcp/tests/test_news_market.pyindex a6e241b..c80c65e 100644--- a/src/world_intel_mcp/tests/test_news_market.py+++ b/src/world_intel_mcp/tests/test_news_market.py@@ -182,12 +182,17 @@ def _item(title, published, category="technology", feed="Ars Technica"):@pytest.fixture-def fast_fetcher(tmp_path, monkeypatch):+async def fast_fetcher(tmp_path, monkeypatch):"""Fetcher without retries or Yahoo spacing so failure paths stay fast."""monkeypatch.setattr(fetcher_mod, "_YAHOO_MIN_INTERVAL", 0.0)monkeypatch.setitem(fetcher_mod._SOURCE_RATE_LIMITS, "yahoo-finance", 0.0)- return Fetcher(cache=Cache(db_path=tmp_path / "nm.db"), breaker=CircuitBreaker(),- default_timeout=5.0, max_retries=0)+ fetcher = Fetcher(cache=Cache(db_path=tmp_path / "nm.db"), breaker=CircuitBreaker(),+ default_timeout=5.0, max_retries=0)+ try:+ yield fetcher+ finally:+ await fetcher.close()+ fetcher.cache.close()def _feed(monkeypatch, items):diff --git a/src/world_intel_mcp/tests/test_resource_cleanup.py b/src/world_intel_mcp/tests/test_resource_cleanup.pynew file mode 100644index 0000000..9cfe599--- /dev/null+++ b/src/world_intel_mcp/tests/test_resource_cleanup.py@@ -0,0 +1,121 @@+"""Resource owners close connections even while callers retain references."""++import sqlite3++import pytest++from world_intel_mcp import collector, reports+from world_intel_mcp.analysis import alerts, temporal+from world_intel_mcp.sources import intelligence+from world_intel_mcp.tests.test_collector_runtime import FakeVectorStore++[email protected]("fail", [False, True])+async def test_standalone_report_closes_resources(tmp_path, monkeypatch, fail):+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "report.db"))+ opened = []++ async def generate(fetcher, *args):+ opened.append((fetcher.cache._conn, await fetcher._get_client()))+ if fail:+ raise RuntimeError("render failed")+ return {"path": "report.html"}++ monkeypatch.setattr(reports, "generate_report", generate)+ try:+ if fail:+ with pytest.raises(RuntimeError, match="render failed"):+ await reports.generate_report_standalone()+ else:+ assert await reports.generate_report_standalone() == {"path": "report.html"}+ conn, client = opened[0]+ assert client.is_closed+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ conn.execute("SELECT 1")+ finally:+ for conn, client in opened:+ conn.close()+ await client.aclose()++[email protected]("fail", [False, True])+async def test_collector_closes_cache(tmp_path, monkeypatch, fail):+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "collector.db"))+ monkeypatch.setattr(collector, "VectorStore", FakeVectorStore)+ opened = []++ async def collect(fetcher, *args):+ opened.append((fetcher.cache._conn, await fetcher._get_client()))+ if fail:+ raise RuntimeError("collection failed")+ return {"collected": 0}++ monkeypatch.setattr(collector, "collect_once", collect)+ try:+ if fail:+ with pytest.raises(RuntimeError, match="collection failed"):+ await collector.run_once()+ else:+ assert await collector.run_once() == {"collected": 0}+ conn, client = opened[0]+ assert client.is_closed+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ conn.execute("SELECT 1")+ finally:+ for conn, client in opened:+ conn.close()+ await client.aclose()+++async def test_weekly_trends_closes_database_on_query_error(tmp_path, monkeypatch):+ path = tmp_path / "no-baselines.db"+ monkeypatch.setattr(temporal, "_default_db_path", lambda: path)+ opened = []+ connect = sqlite3.connect++ def tracked_connect(*args, **kwargs):+ conn = connect(*args, **kwargs)+ opened.append(conn)+ return conn++ async def anomalies(fetcher):+ return {}++ monkeypatch.setattr(sqlite3, "connect", tracked_connect)+ monkeypatch.setattr(intelligence, "fetch_temporal_anomalies", anomalies)+ try:+ await alerts.fetch_weekly_trends(None)+ assert len(opened) == 1+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ opened[0].execute("SELECT 1")+ finally:+ for conn in opened:+ conn.close()++[email protected]("run", [collector.run_once, collector.run_daemon])+async def test_collector_closes_cache_when_start_fails(tmp_path, monkeypatch, run):+ from world_intel_mcp.cache import Cache++ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "start-failure.db"))+ opened = []++ def cache():+ instance = Cache()+ opened.append(instance._conn)+ return instance++ class FailedStart(FakeVectorStore):+ async def start(self):+ raise RuntimeError("start failed")++ monkeypatch.setattr(collector, "Cache", cache)+ monkeypatch.setattr(collector, "VectorStore", FailedStart)+ try:+ with pytest.raises(RuntimeError, match="start failed"):+ await run()+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ opened[0].execute("SELECT 1")+ finally:+ for conn in opened:+ conn.close()diff --git a/src/world_intel_mcp/tests/test_server_registry.py b/src/world_intel_mcp/tests/test_server_registry.pyindex b80bbfa..29db3b9 100644--- a/src/world_intel_mcp/tests/test_server_registry.py+++ b/src/world_intel_mcp/tests/test_server_registry.py@@ -19,11 +19,12 @@ from pathlib import Pathimport pytest-_TMP_CACHE = Path(tempfile.mkdtemp(prefix="wim-server-test-")) / "cache.db"+_TMP_DIRECTORY = tempfile.TemporaryDirectory(prefix="wim-server-test-")+_TMP_CACHE = Path(_TMP_DIRECTORY.name) / "cache.db"@pytest.fixture(scope="module")-def server():+def server(isolated_runtime):"""Import server.py exactly once, cache pointed at a temp file."""prior = os.environ.get("WORLD_INTEL_CACHE_DB")os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)@@ -33,7 +34,7 @@ def server():# and an earlier test module may already have touched it under a# different path. Rebind it here, under the override, so this# file's premise holds whatever order the modules run in.- importlib.import_module("world_intel_mcp.runtime")._initialize()+ isolated_runtime._initialize()yield modulefinally:if prior is None:diff --git a/src/world_intel_mcp/tests/test_sources.py b/src/world_intel_mcp/tests/test_sources.pyindex 051c757..ec4122a 100644--- a/src/world_intel_mcp/tests/test_sources.py+++ b/src/world_intel_mcp/tests/test_sources.py@@ -1,5 +1,6 @@"""Tests for source modules — uses respx to mock HTTP calls."""+from collections.abc import AsyncIterator, Iteratorfrom pathlib import Pathfrom unittest.mock import patch@@ -13,14 +14,22 @@ from world_intel_mcp.fetcher import Fetcher@pytest.fixture-def cache(tmp_path: Path) -> Cache:- return Cache(db_path=tmp_path / "test_cache.db")+def cache(tmp_path: Path) -> Iterator[Cache]:+ cache = Cache(db_path=tmp_path / "test_cache.db")+ try:+ yield cache+ finally:+ cache.close()@pytest.fixture-def fetcher(cache: Cache) -> Fetcher:+async def fetcher(cache: Cache) -> AsyncIterator[Fetcher]:breaker = CircuitBreaker()- return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ fetcher = Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)+ try:+ yield fetcher+ finally:+ await fetcher.close()# ---------------------------------------------------------------------------diff --git a/src/world_intel_mcp/tests/test_sources_intelligence.py b/src/world_intel_mcp/tests/test_sources_intelligence.pyindex cd06df9..426290f 100644--- a/src/world_intel_mcp/tests/test_sources_intelligence.py+++ b/src/world_intel_mcp/tests/test_sources_intelligence.py@@ -31,7 +31,6 @@ import httpximport pytestimport respx-from world_intel_mcp.analysis.temporal import TemporalBaselinefrom world_intel_mcp.fetcher import Fetcherfrom world_intel_mcp.sources import (conflict,@@ -557,10 +556,10 @@ async def test_fetch_signal_summary_discloses_acled_gaps(@pytest.mark.asyncioasync def test_fetch_temporal_anomalies_records_observations(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:monkeypatch.setattr(- intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))+ intelligence, "_temporal", temporal_baseline)monkeypatch.setattr(military,@@ -596,10 +595,10 @@ async def test_fetch_temporal_anomalies_records_observations(@pytest.mark.asyncioasync def test_fetch_temporal_anomalies_acled_outage_disclosed(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:monkeypatch.setattr(- intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))+ intelligence, "_temporal", temporal_baseline)monkeypatch.setattr(military,@@ -789,10 +788,10 @@ async def test_fetch_hotspot_escalation_attributes_nearby_events(@pytest.mark.asyncioasync def test_fetch_military_surge_detects_surge(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:monkeypatch.setattr(- intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))+ intelligence, "_temporal", temporal_baseline)# 40 US aircraft in the european theater map onto baltic_sea, whose US# baseline is 2 -> ratio 20 -> critical. black_sea has no US baseline,@@ -821,10 +820,10 @@ async def test_fetch_military_surge_detects_surge(@pytest.mark.asyncioasync def test_fetch_military_surge_quiet_posture(- fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path, temporal_baseline) -> None:monkeypatch.setattr(- intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))+ intelligence, "_temporal", temporal_baseline)monkeypatch.setattr(military, "fetch_theater_posture", _async_return({"theaters": {}})diff --git a/src/world_intel_mcp/tests/test_sources_liquidity.py b/src/world_intel_mcp/tests/test_sources_liquidity.pyindex 9adc00d..02c8d6a 100644--- a/src/world_intel_mcp/tests/test_sources_liquidity.py+++ b/src/world_intel_mcp/tests/test_sources_liquidity.py@@ -15,6 +15,7 @@ ECB responses with more than 50 series; FRED full-history downloadsfrom __future__ import annotationsimport json+from collections.abc import AsyncIteratorfrom datetime import datefrom pathlib import Path@@ -47,13 +48,18 @@ def _fixed_clock_and_no_throttle(monkeypatch: pytest.MonkeyPatch) -> None:@pytest.fixture-def fetcher(tmp_path: Path) -> Fetcher:- return Fetcher(+async def fetcher(tmp_path: Path) -> AsyncIterator[Fetcher]:+ fetcher = Fetcher(cache=Cache(db_path=tmp_path / "liq.db"),breaker=CircuitBreaker(),default_timeout=5.0,max_retries=0,)+ try:+ yield fetcher+ finally:+ await fetcher.close()+ fetcher.cache.close()def _fred_router(overrides: dict[str, httpx.Response] | None = None):@@ -532,9 +538,12 @@ async def test_net_liquidity_method_states_wednesday_levels_conversion_and_rrp_a# The method travels with an error too, so a failed call still says what it would compute.# A fresh cache, so the 503 is not hidden behind the first call's cached CSVs.respx.get(_FRED_URL).mock(side_effect=_fred_router({"WDTGAL": httpx.Response(503)}))- failed = await liquidity.fetch_net_liquidity(- Fetcher(cache=Cache(db_path=tmp_path / "cold.db"), breaker=CircuitBreaker(), max_retries=0)- )+ cold = Fetcher(cache=Cache(db_path=tmp_path / "cold.db"), breaker=CircuitBreaker(), max_retries=0)+ try:+ failed = await liquidity.fetch_net_liquidity(cold)+ finally:+ await cold.close()+ cold.cache.close()assert "error" in failed and failed["method"]["components"]["WDTGAL"]["units"] == "USD millions"diff --git a/src/world_intel_mcp/tests/test_spikes.py b/src/world_intel_mcp/tests/test_spikes.pyindex 4019ae9..2f3bb58 100644--- a/src/world_intel_mcp/tests/test_spikes.py+++ b/src/world_intel_mcp/tests/test_spikes.py@@ -6,6 +6,7 @@ from Welford's recurrence: for observations [10, 20, 30, 20] the runningstate is n=4, mean=20, M2=200, so variance=50 and stddev=sqrt(50)=7.0711."""+from collections.abc import Iteratorfrom pathlib import Pathimport pytest@@ -16,8 +17,13 @@ from world_intel_mcp.sources import news@pytest.fixture-def detector(tmp_path: Path) -> KeywordSpikeDetector:- return KeywordSpikeDetector(db_path=str(tmp_path / "spikes.db"))+def detector(tmp_path: Path) -> Iterator[KeywordSpikeDetector]:+ detector = KeywordSpikeDetector(db_path=str(tmp_path / "spikes.db"))+ try:+ yield detector+ finally:+ if detector._conn is not None:+ detector._conn.close()def _feed(detector: KeywordSpikeDetector, keyword: str, values: list[int]) -> None:@@ -84,19 +90,21 @@ def test_spikes_sorted_by_magnitude_descending(detector: KeywordSpikeDetector) -assert result[0]["z_score"] > result[1]["z_score"]-def test_baselines_persist_across_instances(tmp_path: Path) -> None:+def test_baselines_persist_across_instances(tmp_path: Path, request) -> None:db = str(tmp_path / "persist.db")first = KeywordSpikeDetector(db_path=db)+ request.addfinalizer(lambda: first._conn.close() if first._conn is not None else None)_feed(first, "coup", [10, 10, 10])second = KeywordSpikeDetector(db_path=db)+ request.addfinalizer(lambda: second._conn.close() if second._conn is not None else None)result = second.detect_spikes({"coup": 40})assert len(result) == 1 # baseline survived the restartassert result[0]["baseline_mean"] == 10.0async def test_fetch_keyword_spikes_composes_news_sources(- fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request) -> None:async def _fake_trending(fetcher, min_count=3):return {"keywords": [{"keyword": "gaza", "count": 30}]}@@ -112,9 +120,9 @@ async def test_fetch_keyword_spikes_composes_news_sources(monkeypatch.setattr(news, "fetch_trending_keywords", _fake_trending)monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)# Point the module singleton at a throwaway database.- monkeypatch.setattr(- spikes_mod, "_detector", KeywordSpikeDetector(db_path=str(tmp_path / "kw.db"))- )+ detector = KeywordSpikeDetector(db_path=str(tmp_path / "kw.db"))+ request.addfinalizer(lambda: detector._conn.close() if detector._conn is not None else None)+ monkeypatch.setattr(spikes_mod, "_detector", detector)result = await fetch_keyword_spikes(fetcher, min_count=3, z_threshold=2.0)assert result["keywords_analyzed"] == 1