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
Add history backfill for FRED and ECB series, and three history extractors
Phoenix Agent (mac-studio)baab46c1389e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c12802f..4ea431c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -229,6 +229,60 @@ source here, and no proxy is substituted for any of these measures.history capture is an error.- Tools 139 -> 143.+### Added: history backfill and more history extractors (Phase 29)+- `intel history backfill fred SERIES... [--start YYYY-MM-DD]`,+ `intel history backfill ecb DATASET.KEY... [--start YYYY-MM-DD]` and the+ MCP tool `intel_history_backfill` load the history that FRED's keyless graph CSV+ and the ECB Data Portal (BSI and ILM datasets) already serve into the+ history store. Requests reuse the liquidity tools' fetch and parse code,+ so they go through the Fetcher (FRED rate floor, circuit breaker, cache):+ a copy cached by an earlier call (FRED 1 h, ECB 3 h) is reused without a+ request.+- Backfilled rows have their own sources, `backfill:fred` and+ `backfill:ecb` (series `backfill:fred:<ID>` and+ `backfill:ecb:<DATASET>.<KEY>`), so they never read as collector+ captures; `intel_collection_health` and `intel history health` list them+ apart (`backfills`). Every run is logged in a new table,+ `history_backfills`, created in place with `CREATE TABLE IF NOT EXISTS`+ (existing rows untouched).+- Dates: `observed_at` is the publisher's period (FRED's date; ECB months+ as written, ECB weeks as the Sunday that ends the ISO week);+ `published_at` is NULL, because neither response names a release or+ vintage date; `collected_at` is the backfill time, stamped after the+ call's last fetch. Values are the publisher's vintage on the backfill+ day, already revised, so revisions made before the first backfill are+ invisible.+- Idempotent: a re-run stores only new or changed values, and a changed+ value is a revision in `intel_revisions`. FRED's missing cells (`.` and+ blank) are skipped and counted, never stored as zero. ECB missing values+ cannot be counted (the SDMX-JSON parser drops them) and read `unknown`.+- Failures are errors, never an empty success: an HTTP error, an empty or+ malformed body, a window without values, and a response available only+ as a stale cache copy each record an error capture and store nothing.+ The CLI exits 1 when any request failed.+- Caps per call: 5 FRED series or 2 ECB keys (at most 20 series per key),+ the newest 20,000 points per series and 100,000 per call; `--start`+ narrows the window.+- Retention: observations are pruned by `collected_at`, not `observed_at`,+ so a 1962 value is kept as long as any value stored by the same backfill+ (`WORLD_INTEL_HISTORY_DAYS`, default 365). A backfill prunes before it+ stores, so a pruned value is stored again as new.+- New history extractors (`history_extractors.py`): `liquidity_board`+ (latest and previous value per indicator; the derived net liquidity row+ is left to its own source), `net_liquidity` (net liquidity and its three+ terms per Wednesday, reverse repo dated by the day it was taken from) and+ `net_migration` (World Bank SM.POP.NETM per country and year). Each+ dates a value only from the payload.+- Measured 2026-10-17, live, isolated HOME: WALCL 1,244 values+ (2002-12-18 to 2026-10-14), RRPONTSYD 3,348 (2,833 blank cells skipped),+ DGS10 16,182 (721 skipped; units unknown, it is not in this server's+ FRED catalog), euro area M3 560 months (1980-01 to 2026-08, 1+ provisional). A second run from the cached copies and a refetch of WALCL+ and M3 stored 0.+- FRED's terms of use speak of personal, non-commercial use of FRED data;+ whether a deployment fits them is the operator's call.+- Tools 152 -> 153; the `intel history` group gains `backfill fred|ecb`.+### Added: news signals (ROADMAP Phase 29)- `intel_hostility_timeline`: per UTC day, GDELT DOC 2.0 coverage of acountry or a pair of countries (`timelinevolraw`): matching articles,diff --git a/README.md b/README.mdindex 0638fe3..f6fc7fc 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@[](https://python.org)[](LICENSE)-Real-time global intelligence across **30+ domains** with **152 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.+Real-time global intelligence across **30+ domains** with **153 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, aircraft-cohort early warning, refugee and migration flows, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.@@ -66,9 +66,9 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Volcanoes** | 1 | Smithsonian GVP weekly activity report || **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere), with opt-in forecast tracks: positions, UTC valid times and intensities, plus NHC's cone of uncertainty || **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |-| **Collection History** | 4 | Collector run log (per-source health, overdue and failing sources), saved captures with change detection and replay, dated observation series, revisions |+| **Collection History** | 5 | Collector run log (per-source health, overdue and failing sources), saved captures with change detection and replay, dated observation series, revisions, and on-demand backfill of the history FRED and the ECB Data Portal already serve |-**Total: 152 tools** across 30+ intelligence domains.+**Total: 153 tools** across 30+ intelligence domains.---@@ -142,6 +142,8 @@ intel top-stories -m 4 # stories carried by 4+ outletsintel status # cache + circuit breaker healthintel guide # the research guide (also served as intel://guide)intel history health # per-source collection health from the collector's run log+intel history backfill fred WALCL RRPONTSYD --start 2020-01-01 # load FRED history into the history store+intel history backfill ecb BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E # load ECB Data Portal history (euro area M3)```---@@ -596,8 +598,8 @@ different, openly licensed data source; no ews code is used.|------|-------------|| `intel_situation_brief` | Cited situational awareness brief, generated on demand over MCP: a bounded server-side overview (earthquakes, military flights, ACLED conflict events, wildfires, cyber threats, disease outbreaks, news, space weather, strategic posture, alert digest), synthesized via local Ollama or a mechanically-cited fallback when Ollama is unreachable |-### Collection History (4)-History accrues only while the collector (`intel-collector`) runs; nothing before its first recorded cycle exists. Every observation keeps three dates: `observed_at` (the period the value describes, from the payload, or null when the payload has none), `published_at` (publisher release, when known) and `collected_at` (when this server saved it).+### Collection History (5)+History accrues only while the collector (`intel-collector`) runs; nothing before its first recorded cycle exists, except what a backfill loads (`intel_history_backfill`, `intel history backfill`): FRED graph CSV and ECB Data Portal series, stored under `backfill:fred` and `backfill:ecb` with the publisher's current vintage, so revisions made before the first backfill are invisible. Every observation keeps three dates: `observed_at` (the period the value describes, from the payload, or null when the payload has none), `published_at` (publisher release, when known) and `collected_at` (when this server saved it).| Tool | Description ||------|-------------|@@ -605,6 +607,7 @@ History accrues only while the collector (`intel-collector`) runs; nothing befor| `intel_capture_history` | A source's earlier captures (ok / degraded / error with reason, duration, record count) and whether each changed from the previous one; `capture_id` replays one stored payload || `intel_series_history` | One series' observations with all three dates, or the list of available series || `intel_revisions` | Values for the same `observed_at` that a later capture changed (USGS magnitude revisions, NOAA Kp updates) |+| `intel_history_backfill` | Load the history FRED (graph CSV) or the ECB Data Portal already serve into the history store: one capture per series under `backfill:fred` / `backfill:ecb`, `observed_at` from the publisher's dates, `published_at` null, `collected_at` the backfill time; re-runs store only new or changed values (a change is a revision); missing values skipped and counted; writes and fetches, so capped at 5 FRED series or 2 ECB keys per call |---diff --git a/ROADMAP.md b/ROADMAP.mdindex 259a553..0f1b29f 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -571,7 +571,7 @@ dashboard.| Wave | Feature | What it means here | Status ||------|---------|--------------------|--------|-| 1 | Observation history store | Every collector capture saved with `observed_at` (period the data describe), `published_at` (publisher release, when known) and `collected_at` (when we saved it); unchanged payloads stored once; bounded retention; backfill for sources that serve history (FRED CSV) | :yellow_circle: Unreleased: store, three dates, dedupe, retention and `register_extractor()` done (`history.py`; extractors for Kp, USGS magnitudes, FRED central bank rates, Yahoo quotes); backfill not done |+| 1 | Observation history store | Every collector capture saved with `observed_at` (period the data describe), `published_at` (publisher release, when known) and `collected_at` (when we saved it); unchanged payloads stored once; bounded retention; backfill for sources that serve history (FRED CSV) | :white_check_mark: Unreleased: store, three dates, dedupe, retention and `register_extractor()` done (`history.py`; extractors for Kp, USGS magnitudes, FRED central bank rates, Yahoo quotes, and in `history_extractors.py` the liquidity board, net liquidity and World Bank net migration). Backfill built 2026-10-17 (`history_backfill.py`, `intel_history_backfill`, `intel history backfill fred|ecb`) for FRED graph CSV and ECB Data Portal (BSI, ILM) series, under its own sources `backfill:fred` and `backfill:ecb`; `published_at` is NULL (neither response names a release date) and values are the vintage of the backfill day. Measured live 2026-10-17: WALCL 1,244 values (2002-12-18 to 2026-10-14), RRPONTSYD 3,348 (2,833 blank cells skipped), DGS10 16,182 (721 skipped), euro area M3 560 months (1980-01 to 2026-08); a second run and a refetch stored 0 || 1 | Capture history and revisions | Earlier saved copies of a source, and values a later copy revised | :white_check_mark: Unreleased (`intel_capture_history` with payload replay, `intel_revisions`) || 1 | Collection health | Per-source expected cadence; overdue / failing / never-run per source, measured from the run log, not inferred from cache freshness. Says what it cannot prove | :white_check_mark: Unreleased (`intel_collection_health`, `intel history health`) || 1 | Research guide over MCP | MCP resources (guide generated from the live registry and source health, measures glossary, "what this server will not do") and MCP prompts (worked research questions, each naming the tools it needs and the limit to respect). Server exposed no prompts or resources before | :white_check_mark: Built 2026-10-17, unreleased: 3 resources (`intel://guide`, `intel://guide/source-health`, `intel://guide/measures`), 29 prompts, `intel guide`; verified over a live stdio session |diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex 23e13a5..7005d22 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -3101,7 +3101,8 @@ def _with_history_store(fn: Any) -> dict:def history_group() -> None:"""Saved collector history: health, captures, series, revisions.- History accrues only while the collector (intel-collector) runs.+ History accrues only while the collector (intel-collector) runs, except+ series that intel history backfill loads from FRED or the ECB Data Portal."""@@ -3144,8 +3145,17 @@ def history_health(ctx: click.Context, source: str | None) -> None:_cell(row.get("latest_observed_at") or "-"),_cell(row.get("last_reason") or ""),)- console.print(table)- counts = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items()))+ if data["sources"]:+ console.print(table)+ for row in data.get("backfills", []):+ console.print(+ f"Backfill [bold]{escape(row['source'])}[/bold]: {row['captures']} capture(s), "+ f"last {row['last_run_at']} ({row['last_status']}), {row['observations']} "+ f"observations in {row['series']} series, observed "+ f"{escape(str(row['first_observed_at'] or '-'))} to "+ f"{escape(str(row['latest_observed_at'] or '-'))}."+ )+ counts = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items())) or "none"storage = data["storage"]console.print(f"States: {counts}. Stored: {storage['captures']} captures, "@@ -3318,5 +3328,107 @@ def history_revisions(console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")+# ---------------------------------------------------------------------------+# Backfill (history FRED and the ECB already serve, into the history store)+# ---------------------------------------------------------------------------+++@history_group.group(name="backfill")+def backfill_group() -> None:+ """Load history FRED or the ECB Data Portal already serve into the history store.++ Values are the publisher's current vintage, so revisions made before the+ first backfill are invisible. Read them back with intel history series.+ """+++def _run_backfill(+ ctx: click.Context, provider: str, requests: tuple[str, ...], start: str | None+) -> None:+ from . import history_backfill+ from .history import HistoryStore++ fetcher = _get_fetcher()+ run = history_backfill.backfill_fred if provider == "fred" else history_backfill.backfill_ecb+ store = HistoryStore(fetcher.cache.db_path)+ try:+ data = _run(run(fetcher, store, list(requests), start))+ finally:+ store.close()+ if ctx.obj.get("json"):+ _print_json(data)+ else:+ _print_backfill(data)+ if "error" in data or data["totals"]["failed"]:+ ctx.exit(1)+++def _print_backfill(data: dict) -> None:+ if not data.get("requests"):+ console.print(f"[red]Error:[/red] {escape(str(data['error']))}")+ return+ title = f"Backfill into {data['source']} at {data['collected_at']}"+ if data.get("start"):+ title += f" from {data['start']}"+ table = Table(title=escape(title), box=box.SIMPLE_HEAVY)+ table.add_column("Series", style="bold")+ table.add_column("Status")+ table.add_column("Loaded", justify="right")+ table.add_column("New", justify="right")+ table.add_column("Revised", justify="right")+ table.add_column("Unchanged", justify="right")+ table.add_column("Missing", justify="right")+ table.add_column("Observed from")+ table.add_column("Observed to")+ for req in data["requests"]:+ if req["status"] == "error":+ table.add_row(_cell(req["request"]), Text("error", style="red"), *["-"] * 7)+ continue+ for s in req["series"]:+ table.add_row(+ _cell(s["series_key"]),+ Text("ok", style="green"),+ str(s["loaded"]),+ str(s["stored_new"]),+ str(s["stored_revised"]),+ str(s["unchanged"]),+ "unknown" if s["missing_skipped"] is None else str(s["missing_skipped"]),+ _cell(s["first_observed_at"] or "-"),+ _cell(s["last_observed_at"] or "-"),+ )+ console.print(table)+ totals = data["totals"]+ console.print(+ f"Stored {totals['stored_new']} new and {totals['stored_revised']} revised values, "+ f"{totals['unchanged']} unchanged, in {escape(data['db_path'])}."+ )+ _print_data_gaps(data)+++@backfill_group.command(name="fred")[email protected]("series_ids", nargs=-1, required=True)[email protected]("--start", default=None, help="Only observations on or after YYYY-MM-DD")[email protected]_context+def backfill_fred_cmd(ctx: click.Context, series_ids: tuple[str, ...], start: str | None) -> None:+ """Load FRED graph CSV series (up to 5).++ For example: intel history backfill fred WALCL RRPONTSYD DGS10 --start 2020-01-01+ """+ _run_backfill(ctx, "fred", series_ids, start)+++@backfill_group.command(name="ecb")[email protected]("keys", nargs=-1, required=True)[email protected]("--start", default=None, help="Only observations on or after YYYY-MM-DD")[email protected]_context+def backfill_ecb_cmd(ctx: click.Context, keys: tuple[str, ...], start: str | None) -> None:+ """Load ECB Data Portal series (up to 2 keys).++ Each key is DATASET.KEY, for example BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E+ (euro area M3); a key with + alternatives loads every series it matches.+ """+ _run_backfill(ctx, "ecb", keys, start)++if __name__ == "__main__":main()diff --git a/src/world_intel_mcp/history.py b/src/world_intel_mcp/history.pyindex 260f6ef..d115c27 100644--- a/src/world_intel_mcp/history.py+++ b/src/world_intel_mcp/history.py@@ -26,8 +26,12 @@ settled on, fallback path included):stored value for the same series and ``observed_at``, so successiverows for one ``(series_key, observed_at)`` are revisions.-History accrues only while the collector runs: nothing is backfilled, and-a source the collector does not run reads ``never_run``.+History accrues while the collector runs, plus what a backfill+(``history_backfill.py``) loads on demand from FRED and the ECB Data+Portal, which serve their whole history; a source the collector does not+run reads ``never_run``. Backfills are captures under ``backfill:*``+sources, so their rows never read as collector captures, and+``collection_health`` lists them apart from the collector's roster.Registering an extractor (the public API)::@@ -70,8 +74,10 @@ Gaps / not covered:- Growth was measured on a Saturday with markets closed: the 15 Yahoo quoteseries, which have no observation date, gain a row per price change whilemarkets trade, and that rate is not measured.-- No backfill: sources that serve history (FRED CSV) are not replayed into- the store; only what the collector sees from the first recorded cycle on.+- Backfill covers FRED graph CSV and ECB Data Portal series only, and+ stores the publisher's current vintage: revisions made before a+ backfill are invisible (see ``history_backfill.py``). Every other source+ has only what the collector saw from its first recorded cycle on.- ``published_at`` is NULL for every built-in extractor: none of theirpayloads names a release time.- ``record_count`` is a size hint (the payload's longest top-level list,@@ -122,7 +128,17 @@ _MAX_LIMIT = 1000HISTORY_ACCRUAL_NOTE = ("History accrues only while the collector (intel-collector) runs; "- "nothing before its first recorded cycle exists here."+ "nothing before its first recorded cycle exists here, except series under "+ "backfill:* sources, which a backfill loaded from the publisher's current data."+)++# Source-name prefix of backfill captures (history_backfill.py). They run on+# demand, so collection_health reports them apart from the cadence roster.+BACKFILL_PREFIX = "backfill:"+BACKFILL_VINTAGE_NOTE = (+ "Backfilled: each value is the publisher's vintage on the day it was "+ "collected (collected_at is the backfill time), so revisions made before the "+ "first backfill are invisible; later backfills store changed values as revisions.")@@ -693,14 +709,16 @@ class HistoryStore:known = set(roster)conn = self._connlogged = [r[0] for r in conn.execute("SELECT DISTINCT source FROM history_captures")]- names = roster + sorted(set(logged) - known)+ backfilled = sorted(s for s in logged if s.startswith(BACKFILL_PREFIX))+ names = roster + sorted(set(logged) - known - set(backfilled))if source is not None:- if source not in names:+ if source not in names and source not in backfilled:return {"error": f"unknown source {source!r}: not a collector source and never captured",- "known_sources": sorted(names),+ "known_sources": sorted(names + backfilled),}- names = [source]+ names = [source] if source in names else []+ backfilled = [source] if source in backfilled else []rows = []for name in names:@@ -790,6 +808,8 @@ class HistoryStore:return {"sources": rows,"state_counts": states,+ # On-demand loads, not judged against a cadence.+ "backfills": [self._backfill_row(name) for name in backfilled],"checked_at": _iso(now),"default_cadence_s": default_cadence,"overdue_multiple": OVERDUE_MULTIPLE,@@ -820,6 +840,35 @@ class HistoryStore:},}+ def _backfill_row(self, name: str) -> dict:+ """One backfill source: its captures and the series it stored."""+ conn = self._conn+ captures, last_at = conn.execute(+ "SELECT COUNT(*), MAX(collected_at) FROM history_captures WHERE source = ?", (name,)+ ).fetchone()+ last_status, last_reason = conn.execute(+ "SELECT status, error FROM history_captures WHERE source = ? "+ "ORDER BY collected_at DESC, id DESC LIMIT 1",+ (name,),+ ).fetchone()+ series, points, first_obs, last_obs = conn.execute(+ "SELECT COUNT(DISTINCT series_key), COUNT(*), MIN(observed_at), MAX(observed_at) "+ "FROM history_observations WHERE source = ?",+ (name,),+ ).fetchone()+ return {+ "source": name,+ "captures": captures,+ "last_run_at": _iso(last_at),+ "last_status": last_status,+ "last_reason": last_reason,+ "series": series,+ "observations": points,+ "first_observed_at": first_obs,+ "latest_observed_at": last_obs,+ "note": BACKFILL_VINTAGE_NOTE,+ }+def capture_history(self, source: str, limit: Any = 20, capture_id: Any = None) -> dict:@@ -972,6 +1021,8 @@ class HistoryStore:)if all(o["published_at"] is None for o in observations):gaps.append("published_at unknown: this source's payload names no release time")+ if str(rows[0][7]).startswith(BACKFILL_PREFIX):+ gaps.append(BACKFILL_VINTAGE_NOTE)return {"series_key": series_key,"source": rows[0][7],@@ -1029,3 +1080,9 @@ class HistoryStore:],"note": HISTORY_ACCRUAL_NOTE,}+++# Extractors for further collector sources live in their own module. Importing+# it here registers them wherever a capture is classified, whichever module+# imported the store first.+from . import history_extractors # noqa: E402,F401 (registers on import)diff --git a/src/world_intel_mcp/history_backfill.py b/src/world_intel_mcp/history_backfill.pynew file mode 100644index 0000000..d0857a8--- /dev/null+++ b/src/world_intel_mcp/history_backfill.py@@ -0,0 +1,721 @@+"""History backfill: load the history FRED and the ECB Data Portal already+serve into the history store (ROADMAP Phase 29).++The collector records only what it sees from its first cycle on. Two of+its upstreams serve a series' whole history on every request: FRED's+keyless graph CSV and the ECB Data Portal. A backfill reads them through+the fetch and parse code the liquidity tools use (``sources/liquidity.py``:+``_fred_rows`` and ``fetch_ecb_series``), so every request goes through the+project's Fetcher with its FRED rate floor, circuit breaker and cache, and+writes the points into the history store (``history.py``):++- One capture per request (one FRED series id, or one ECB series key)+ under the source ``backfill:fred`` or ``backfill:ecb``, so a backfilled+ row never reads as a collector capture. Series keys are+ ``backfill:fred:<ID>`` and ``backfill:ecb:<DATASET>.<KEY>``. Every run is+ also logged in ``history_backfills`` (request, start, per-series counts,+ when the response was fetched), a table created here on first use with+ ``CREATE TABLE IF NOT EXISTS``: a database made before it existed gains+ it in place, its rows untouched.+- Three dates: ``observed_at`` is the period the publisher dates a value+ by (FRED dates as written, a monthly value at the first day of its month;+ ECB months as written, an ECB week as the Sunday that ends the ISO week,+ any other ECB period as the period end its response states);+ ``published_at`` is NULL because neither response names a release or+ vintage date (the FRED graph CSV carries observation dates and values+ only); ``collected_at`` is the backfill time, one stamp per call taken+ after its last fetch, so never earlier than a response it stores.+- Idempotent under the store's rule: a value is stored only when its series+ and ``observed_at`` have no stored value or a different one. A re-run+ stores nothing unless the publisher changed a value, and a changed value+ is then a revision (``intel_revisions``).+- FRED missing values ("." and blank cells) are skipped and counted, never+ stored as zero; non-finite values are skipped and counted apart.+- A failure is an error, never an empty success: an HTTP error, an empty or+ malformed body, a window without values, and a response available only+ as a stale cache copy (not the publisher's current data) each record an+ error capture and store nothing.+- Bounded: ``MAX_FRED_SERIES`` series or ``MAX_ECB_KEYS`` keys per call, at+ most ``MAX_ECB_COMBINATIONS`` series per ECB key, the newest+ ``MAX_POINTS`` points per series and ``MAX_POINTS_PER_CALL`` per call,+ optionally only from a start date.++Vintage: a backfilled value is the publisher's vintage on the backfill day,+already revised, so revisions made before the first backfill are+invisible. Retention: the store prunes observations by ``collected_at``+(``WORLD_INTEL_HISTORY_DAYS``, default 365), never by ``observed_at``, so a+1962 value is kept as long as any value stored the same day. An unchanged+value is not stored again, so its ``collected_at`` stays at the backfill+that first stored it; past retention the row is pruned, and the next+backfill (which prunes before it stores) stores it again as new.++Gaps / not covered:+- Only FRED graph CSV series and ECB Data Portal BSI and ILM series; no+ other source that serves history is wired.+- FRED vintages are not read: the graph CSV serves the current vintage+ only, so FRED revisions show up only between two backfills.+- ECB missing values cannot be counted: the shared SDMX-JSON parser drops+ null observations before this code sees them.+- Units of a FRED series outside ``liquidity.FRED_SERIES`` are unknown+ (stored NULL and reported as a data gap): the CSV carries no units.+- Couples to private parts of two modules: ``liquidity._fred_rows``, the+ liquidity cache-key formats (read for ``copy_fetched_at``) and the+ ECB key rules, and the store's ``_conn``, ``_store_observations`` and+ ``_prune``. A change there needs a matching change here; the tests pin+ the behaviour, not the coupling.+- The collector's prune does not touch ``history_backfills``; its rows are+ pruned here, on the next backfill, past the observation retention.+- FRED's terms of use speak of personal, non-commercial use of FRED data;+ whether a deployment's use fits them is the operator's call, not this+ module's.+"""++from __future__ import annotations++import json+import math+import re+import sqlite3+import time+import zlib+from datetime import date, datetime, timezone+from typing import Any++from .fetcher import Fetcher+from .history import (+ BACKFILL_PREFIX,+ HistoryStore,+ Observation,+ SourceOutcome,+ normalize_observed_at,+ payload_hash,+ retention_days,+)+from .history_extractors import period_date+from .sources import liquidity++FRED_SOURCE = BACKFILL_PREFIX + "fred"+ECB_SOURCE = BACKFILL_PREFIX + "ecb"++MAX_FRED_SERIES = 5+MAX_ECB_KEYS = 2+MAX_ECB_COMBINATIONS = 20+MAX_POINTS = 20_000+MAX_POINTS_PER_CALL = 100_000++_FRED_ID = re.compile(r"[A-Z0-9_]{1,40}")+_START = re.compile(r"\d{4}-\d{2}-\d{2}")+# Dimensions in a key of each dataset: the rule fetch_ecb_series applies,+# checked here so a bad key is refused before any request of the call.+_ECB_DIMENSIONS = {"BSI": 11, "ILM": 6}++_SCHEMA = """+CREATE TABLE IF NOT EXISTS history_backfills (+ capture_id INTEGER PRIMARY KEY,+ source TEXT NOT NULL,+ request TEXT NOT NULL,+ start TEXT,+ ran_at REAL NOT NULL,+ copy_fetched_at REAL,+ status TEXT NOT NULL CHECK (status IN ('ok', 'error')),+ payload_hash TEXT,+ detail TEXT NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_history_backfills_request+ ON history_backfills(source, request, start, ran_at);+"""++VINTAGE_GAP = (+ "Values are the publisher's current vintage as of this backfill (collected_at "+ "is the backfill time): revisions the publisher made before the first backfill "+ "are invisible, and a later backfill that reads a changed value stores it as a "+ "revision (intel_revisions)."+)+RETENTION_GAP = (+ "Retention: the store prunes observations by collected_at "+ "(WORLD_INTEL_HISTORY_DAYS, default 365, 0 keeps forever), not by observed_at. "+ "An unchanged value is not stored again, so its collected_at stays at the "+ "backfill that first stored it; once that is past retention the row is pruned "+ "and the next backfill stores it again. Capture rows (WORLD_INTEL_HISTORY_CAPTURE_DAYS, "+ "default 30) and payload bodies (WORLD_INTEL_HISTORY_PAYLOAD_DAYS, default 7) age out sooner."+)+COPY_GAP = (+ "copy_fetched_at is when the response this backfill read was fetched: a copy "+ "cached by an earlier call (FRED 1 h, ECB 3 h) is reused without a request, "+ "and a stale copy is refused."+)+FRED_PUBLISHED_GAP = (+ "published_at is NULL: the FRED graph CSV carries observation dates and values "+ "only, no release or vintage date."+)+FRED_DATE_GAP = (+ "observed_at is the date FRED gives each value: a monthly value is dated at the "+ "first day of its month, a weekly H.4.1 value at its Wednesday."+)+ECB_PUBLISHED_GAP = (+ "published_at is NULL: the ECB Data Portal response carries no release dates."+)+ECB_DATE_GAP = (+ "observed_at: monthly periods as written (2026-08); a weekly period (2026-W41) "+ "as the Sunday that ends the ISO week, the period end the ECB response states; "+ "any other period as the period end the response states."+)+ECB_MISSING_GAP = (+ "ECB missing values are not counted (missing_skipped is null): the SDMX-JSON "+ "parser drops null observations before the backfill sees them."+)+++def _iso(ts: float | None) -> str | None:+ if ts is None:+ return None+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _requests(raw: Any) -> list[str]:+ """Request strings from a list, tuple or comma/space separated string,+ in order and without repeats."""+ if isinstance(raw, str):+ items = re.split(r"[\s,]+", raw)+ elif isinstance(raw, (list, tuple)):+ items = [str(x) for x in raw]+ else:+ items = []+ out: list[str] = []+ for item in items:+ item = item.strip()+ if item and item not in out:+ out.append(item)+ return out+++def _start(start: Any) -> date | None:+ if start in (None, ""):+ return None+ if not isinstance(start, str) or not _START.fullmatch(start.strip()):+ raise ValueError(f"start must be a date YYYY-MM-DD, got {start!r}")+ try:+ day = date.fromisoformat(start.strip())+ except ValueError:+ raise ValueError(f"start must be a date YYYY-MM-DD, got {start!r}") from None+ if day > datetime.now(timezone.utc).date():+ raise ValueError(f"start {start} is in the future")+ return day+++def _ecb_request(raw: str) -> tuple[str, str]:+ """``DATASET.KEY`` -> (dataset, key), or ValueError naming the rule."""+ dataset, _, key = raw.partition(".")+ dataset = dataset.upper()+ if dataset not in _ECB_DIMENSIONS:+ raise ValueError(+ f"{raw!r}: an ECB series key starts with its dataset, one of "+ f"{sorted(_ECB_DIMENSIONS)} (for example BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E)"+ )+ if not liquidity._ECB_KEY_RE.fullmatch(key):+ raise ValueError(f"{raw!r}: key may hold letters, digits, '.', '+' and '_' only")+ dims = key.split(".")+ if len(dims) != _ECB_DIMENSIONS[dataset] or any(+ not code for dim in dims for code in dim.split("+")+ ):+ raise ValueError(+ f"{raw!r}: a {dataset} key names all {_ECB_DIMENSIONS[dataset]} dimensions, "+ "without wildcards"+ )+ combos = math.prod(len(dim.split("+")) for dim in dims)+ if combos > MAX_ECB_COMBINATIONS:+ raise ValueError(+ f"{raw!r}: {combos} series combinations, more than the {MAX_ECB_COMBINATIONS} "+ "a backfill loads per key"+ )+ return dataset, key+++def ensure_schema(store: HistoryStore) -> None:+ """Create the backfill log in place; idempotent, other tables untouched."""+ store._conn.executescript(_SCHEMA)+ store._conn.commit()+++class _Run:+ """One backfill call: point budget, then every write at one time.++ Requests are fetched first and written together by ``commit``, stamped+ after the last fetch, so ``collected_at`` is never earlier than a+ response it stores (the collector stamps a capture when its fetch+ finished, too).+ """++ def __init__(self, store: HistoryStore, source: str, start: date | None):+ self.store = store+ self.source = source+ self.start = start+ self.start_text = start.isoformat() if start else None+ self.now = 0.0 # set by commit()+ self.budget = MAX_POINTS_PER_CALL+ self.requests: list[dict] = []+ self._pending: list[tuple[Any, tuple]] = []++ def defer_fail(self, request: str, error: str, duration: float) -> None:+ self._pending.append((self.fail, (request, error, duration)))++ def defer_store(self, request: str, payload: dict, series: list[dict], duration: float,+ copy_at: float | None) -> None:+ self._pending.append((self.store_request, (request, payload, series, duration, copy_at)))++ def commit(self, now: float | None) -> dict:+ """Create the log table if needed, prune, then write each request+ in its own transaction; returns what the prune removed."""+ ensure_schema(self.store)+ self.now = time.time() if now is None else now+ pruned = self.prune()+ for write, args in self._pending:+ write(*args)+ return pruned++ def prune(self) -> dict:+ """Prune before storing, so a value pruned past retention is stored+ again by this run instead of vanishing."""+ conn = self.store._conn+ with conn:+ pruned = self.store._prune(self.now)+ days = retention_days()["history_days"]+ pruned["backfill_log"] = (+ conn.execute(+ "DELETE FROM history_backfills WHERE ran_at < ?",+ (self.now - days * 86400,),+ ).rowcount+ if days > 0+ else 0+ )+ return pruned++ def _previous(self, request: str) -> tuple[str | None, float | None]:+ row = self.store._conn.execute(+ "SELECT payload_hash, ran_at FROM history_backfills WHERE source = ? AND "+ "request = ? AND start IS ? AND status = 'ok' ORDER BY ran_at DESC, capture_id DESC "+ "LIMIT 1",+ (self.source, request, self.start_text),+ ).fetchone()+ return (row[0], row[1]) if row else (None, None)++ def fail(self, request: str, error: str, duration: float, copy_at: float | None = None) -> dict:+ conn = self.store._conn+ with conn:+ capture_id = conn.execute(+ "INSERT INTO history_captures (source, collected_at, status, duration_s, error) "+ "VALUES (?, ?, 'error', ?, ?)",+ (self.source, self.now, round(duration, 3), error[:500]),+ ).lastrowid+ conn.execute(+ "INSERT INTO history_backfills (capture_id, source, request, start, ran_at, "+ "copy_fetched_at, status, detail) VALUES (?, ?, ?, ?, ?, ?, 'error', ?)",+ (capture_id, self.source, request, self.start_text, self.now, copy_at,+ json.dumps({"error": error})),+ )+ entry = {+ "request": request,+ "status": "error",+ "error": error,+ "capture_id": capture_id,+ "copy_fetched_at": _iso(copy_at),+ "series": [],+ }+ self.requests.append(entry)+ return entry++ def store_request(+ self,+ request: str,+ payload: dict,+ series: list[dict],+ duration: float,+ copy_at: float | None,+ ) -> dict:+ """Write one request: payload body, capture, observations, log row.++ ``series`` items carry ``key`` (suffix after the source), ``label``,+ ``unit``, ``points`` (``(observed_at, value)`` oldest first, already+ valid) and their skip counts.+ """+ conn = self.store._conn+ digest = payload_hash(payload)+ body = json.dumps(payload, separators=(",", ":"), default=str).encode()+ prev_hash, prev_at = self._previous(request)+ changed = None if prev_hash is None else int(prev_hash != digest)+ results = []+ with conn:+ inserted = conn.execute(+ "INSERT OR IGNORE INTO history_payloads "+ "(source, payload_hash, first_seen_at, last_seen_at, raw_bytes, body) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ (self.source, digest, self.now, self.now, len(body), zlib.compress(body, 6)),+ ).rowcount+ if not inserted:+ conn.execute(+ "UPDATE history_payloads SET last_seen_at = MAX(last_seen_at, ?) "+ "WHERE source = ? AND payload_hash = ?",+ (self.now, self.source, digest),+ )+ notes = [+ f"{s['key']}: " + ", ".join(+ f"{n} {what}" for n, what in (+ (s["missing_skipped"], "missing value(s) skipped"),+ (s["invalid_skipped"], "invalid value(s) skipped"),+ (s["truncated"], "older value(s) past the point cap not loaded"),+ ) if n+ )+ for s in series+ if s["missing_skipped"] or s["invalid_skipped"] or s["truncated"]+ ]+ capture_id = conn.execute(+ "INSERT INTO history_captures (source, collected_at, status, duration_s, "+ "record_count, payload_hash, changed, observations_extracted, extract_error) "+ "VALUES (?, ?, 'ok', ?, ?, ?, ?, ?, ?)",+ (self.source, self.now, round(duration, 3),+ sum(s["points_in_response"] for s in series), digest, changed,+ sum(len(s["points"]) for s in series),+ "; ".join(notes)[:500] or None),+ ).lastrowid+ outcome = SourceOutcome(source=self.source, collected_at=self.now)+ stored_total = 0+ for s in series:+ key = f"{self.source}:{s['key']}"+ prior = {+ r[0] for r in conn.execute(+ "SELECT DISTINCT observed_at FROM history_observations "+ "WHERE series_key = ?",+ (key,),+ )+ }+ observations = [+ Observation(s["key"], value, observed_at=observed, unit=s["unit"],+ label=s["label"])+ for observed, value in s["points"]+ ]+ stored = self.store._store_observations(capture_id, outcome, observations)+ stored_total += stored+ new = sum(1 for observed, _ in s["points"] if observed not in prior)+ loaded = len(s["points"])+ results.append({+ "series_key": key,+ "label": s["label"],+ "unit": s["unit"],+ "points_in_response": s["points_in_response"],+ "in_window": s["in_window"],+ "missing_skipped": s["missing_skipped"],+ "invalid_skipped": s["invalid_skipped"],+ "truncated": s["truncated"],+ "loaded": loaded,+ "first_observed_at": s["points"][0][0] if loaded else None,+ "last_observed_at": s["points"][-1][0] if loaded else None,+ "stored_new": new,+ "stored_revised": stored - new,+ "unchanged": loaded - stored,+ **({"provisional": s["provisional"]} if "provisional" in s else {}),+ })+ conn.execute(+ "UPDATE history_captures SET observations_stored = ? WHERE id = ?",+ (stored_total, capture_id),+ )+ conn.execute(+ "INSERT INTO history_backfills (capture_id, source, request, start, ran_at, "+ "copy_fetched_at, status, payload_hash, detail) "+ "VALUES (?, ?, ?, ?, ?, ?, 'ok', ?, ?)",+ (capture_id, self.source, request, self.start_text, self.now, copy_at, digest,+ json.dumps({"series": results})),+ )+ entry = {+ "request": request,+ "status": "ok",+ "capture_id": capture_id,+ "copy_fetched_at": _iso(copy_at),+ "previous_backfill_at": _iso(prev_at),+ "payload_changed": None if changed is None else bool(changed),+ "series": results,+ }+ self.requests.append(entry)+ return entry++ def window(self, points: list[tuple[str, float]]) -> tuple[list[tuple[str, float]], int]:+ """Newest points within the per-series cap and the call's budget,+ oldest first, and how many older ones were left out."""+ cap = min(MAX_POINTS, self.budget)+ kept = points[-cap:] if cap > 0 else []+ self.budget -= len(kept)+ return kept, len(points) - len(kept)++ def result(self, provider: str, gaps: list[str], pruned: dict) -> dict:+ failed = [r for r in self.requests if r["status"] == "error"]+ series = [s for r in self.requests for s in r["series"]]+ totals = {+ "requests": len(self.requests),+ "failed": len(failed),+ "series": len(series),+ **{+ name: sum(s[name] for s in series)+ for name in ("loaded", "stored_new", "stored_revised", "unchanged",+ "invalid_skipped", "truncated")+ },+ # Unknown, not zero, when any series could not count them (ECB).+ "missing_skipped": (+ None if any(s["missing_skipped"] is None for s in series)+ else sum(s["missing_skipped"] for s in series)+ ),+ }+ gaps = list(gaps)+ if failed:+ gaps.insert(0, f"{len(failed)} of {len(self.requests)} request(s) failed and stored "+ "nothing: " + "; ".join(f"{r['request']}: {r['error']}" for r in failed))+ if any(s["truncated"] for s in series):+ gaps.append(+ f"Point cap: only the newest {MAX_POINTS:,} points per series and "+ f"{MAX_POINTS_PER_CALL:,} per call are loaded; pass a later start or split "+ "the call for the rest."+ )+ out = {+ "source": self.source,+ "provider": provider,+ "collected_at": _iso(self.now),+ "start": self.start_text,+ "requests": self.requests,+ "totals": totals,+ "pruned": pruned,+ "data_gaps": gaps + [VINTAGE_GAP, RETENTION_GAP, COPY_GAP],+ "db_path": str(self.store.db_path),+ }+ if failed and len(failed) == len(self.requests):+ out["error"] = "no request succeeded: " + "; ".join(+ f"{r['request']}: {r['error']}" for r in failed+ )[:500]+ return out+++def _copy_at(fetcher: Fetcher, cache_key: str) -> float | None:+ meta = fetcher.cache.get_stale_meta(cache_key)+ return None if meta is None else float(meta[1])+++def _refusal(what: str, age: Any) -> str:+ return (+ f"{what}: the upstream fetch failed and only a stale cached copy"+ + (f" ({age} s old)" if age is not None else "")+ + " was available; a backfill stores only the publisher's current data, so "+ "nothing was stored"+ )+++def _error_result(source: str, provider: str, error: str) -> dict:+ return {"error": error, "source": source, "provider": provider, "requests": []}+++def _store_failure(source: str, provider: str, exc: sqlite3.Error, run: _Run) -> dict:+ """A store error mid-commit: each request is its own transaction, so the+ requests listed were committed and the failing one was rolled back."""+ out = _error_result(source, provider, f"history store write failed: {exc}")+ out["requests"] = run.requests+ out["error"] += f"; {len(run.requests)} earlier request(s) were committed"+ return out+++async def backfill_fred(+ fetcher: Fetcher,+ store: HistoryStore,+ series_ids: Any,+ start: Any = None,+ *,+ now: float | None = None,+) -> dict:+ """Load FRED graph CSV series into the store under ``backfill:fred``."""+ provider = "FRED graph CSV (fred.stlouisfed.org/graph/fredgraph.csv)"+ ids = list(dict.fromkeys(s.upper() for s in _requests(series_ids)))+ if not ids:+ return _error_result(FRED_SOURCE, provider, "name at least one FRED series id")+ if len(ids) > MAX_FRED_SERIES:+ return _error_result(+ FRED_SOURCE, provider,+ f"{len(ids)} series requested; a backfill loads at most {MAX_FRED_SERIES} per call",+ )+ bad = [s for s in ids if not _FRED_ID.fullmatch(s)]+ if bad:+ return _error_result(+ FRED_SOURCE, provider,+ f"not a FRED series id (letters, digits and '_', up to 40): {', '.join(bad)}",+ )+ try:+ start_d = _start(start)+ except ValueError as exc:+ return _error_result(FRED_SOURCE, provider, str(exc))++ run = _Run(store, FRED_SOURCE, start_d)+ gaps = [FRED_PUBLISHED_GAP, FRED_DATE_GAP]+ for sid in ids:+ began = time.monotonic()+ rows, err, meta = await liquidity._fred_rows(fetcher, sid)+ duration = time.monotonic() - began+ if rows is None:+ run.defer_fail(sid, err or f"FRED graph CSV for {sid} unavailable", duration)+ continue+ if meta.get("served_from_stale_cache"):+ run.defer_fail(sid, _refusal(f"FRED graph CSV for {sid}",+ meta.get("cache_age_seconds")), duration)+ continue+ in_window = [(d, v) for d, v in rows if start_d is None or d >= start_d]+ missing = sum(1 for _, v in in_window if v is None)+ valid = [(d.isoformat(), v) for d, v in in_window+ if v is not None and math.isfinite(v)]+ if not valid:+ run.defer_fail(sid, f"FRED graph CSV for {sid} has no values"+ + (f" on or after {start_d}" if start_d else "")+ + (f" ({missing} missing)" if missing else ""), duration)+ continue+ points, truncated = run.window(valid)+ if not points:+ run.defer_fail(sid, f"not loaded: this call's {MAX_POINTS_PER_CALL:,}-point budget "+ "went to earlier series; backfill it in its own call", duration)+ continue+ catalog = liquidity.FRED_SERIES.get(sid)+ if catalog is None:+ gaps.append(+ f"{sid}: units unknown (stored NULL): the FRED graph CSV carries no units "+ "and the series is not in this server's FRED catalog; see its FRED page."+ )+ payload = {+ "provider": "fred",+ "series_id": sid,+ "start": run.start_text,+ "rows": [[d.isoformat(), v] for d, v in in_window],+ }+ run.defer_store(+ sid,+ payload,+ [{+ "key": sid,+ "label": f"FRED {sid}" + (f": {catalog['label']}" if catalog else ""),+ "unit": catalog["units"] if catalog else None,+ "points": points,+ "points_in_response": len(rows),+ "in_window": len(in_window),+ "missing_skipped": missing,+ "invalid_skipped": len(in_window) - missing - len(valid),+ "truncated": truncated,+ }],+ duration,+ _copy_at(fetcher, f"liquidity:fred:{sid}"),+ )+ try:+ pruned = run.commit(now)+ except sqlite3.Error as exc:+ return _store_failure(FRED_SOURCE, provider, exc, run)+ return run.result(provider, gaps, pruned)+++async def backfill_ecb(+ fetcher: Fetcher,+ store: HistoryStore,+ keys: Any,+ start: Any = None,+ *,+ now: float | None = None,+) -> dict:+ """Load ECB Data Portal series into the store under ``backfill:ecb``.++ Each key is ``DATASET.KEY`` as the series key reads (for example+ ``BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E``); a key with ``+`` alternatives+ loads every series it matches, at most ``MAX_ECB_COMBINATIONS``.+ """+ provider = "ECB Data Portal (data-api.ecb.europa.eu)"+ raw = _requests(keys)+ if not raw:+ return _error_result(ECB_SOURCE, provider, "name at least one ECB series key")+ if len(raw) > MAX_ECB_KEYS:+ return _error_result(+ ECB_SOURCE, provider,+ f"{len(raw)} keys requested; a backfill loads at most {MAX_ECB_KEYS} per call",+ )+ try:+ parsed = list(dict.fromkeys(_ecb_request(r) for r in raw))+ start_d = _start(start)+ except ValueError as exc:+ return _error_result(ECB_SOURCE, provider, str(exc))++ run = _Run(store, ECB_SOURCE, start_d)+ gaps = [ECB_PUBLISHED_GAP, ECB_DATE_GAP, ECB_MISSING_GAP]+ for dataset, key in parsed:+ request = f"{dataset}.{key}"+ began = time.monotonic()+ res = await liquidity.fetch_ecb_series(+ fetcher, dataset=dataset, key=key, limit=0, start=run.start_text+ )+ duration = time.monotonic() - began+ if res.get("error"):+ run.defer_fail(request, str(res["error"]), duration)+ continue+ stale = [s for s in res["series"] if s.get("served_from_stale_cache")]+ if stale:+ run.defer_fail(request, _refusal(f"ECB Data Portal {request}",+ stale[0].get("cache_age_seconds")), duration)+ continue+ series = []+ for s in res["series"]:+ in_window = list(reversed(s["points"])) # oldest first+ valid: list[tuple[str, float]] = []+ seen: set[str] = set()+ for p in in_window:+ observed = period_date(p.get("observed_at")) or normalize_observed_at(+ p.get("period_end")+ )+ value = p.get("value")+ if (observed is None or observed in seen or isinstance(value, bool)+ or not isinstance(value, (int, float)) or not math.isfinite(value)):+ continue+ seen.add(observed)+ valid.append((observed, float(value)))+ points, truncated = run.window(valid)+ series.append({+ "key": s["key"],+ "label": s.get("title") or s["key"],+ "unit": s.get("units"),+ "points": points,+ "points_in_response": len(in_window),+ "in_window": len(in_window),+ "missing_skipped": None,+ "invalid_skipped": len(in_window) - len(valid),+ "truncated": truncated,+ "provisional": sum(+ 1 for p in in_window if "provisional" in str(p.get("status") or "").lower()+ ),+ })+ if not any(s["points"] for s in series):+ run.defer_fail(request, f"ECB Data Portal {request}: no values loaded"+ + (" (this call's point budget went to earlier series)"+ if run.budget <= 0 else ""), duration)+ continue+ payload = {+ "provider": "ecb",+ "request": request,+ "start": run.start_text,+ "series": [+ {+ "key": s["key"], "title": s.get("title"), "units": s.get("units"),+ "frequency": s.get("frequency"),+ "points": [[p["observed_at"], p.get("period_end"), p["value"],+ p.get("status")] for p in reversed(s["points"])],+ }+ for s in res["series"]+ ],+ }+ if any(s["provisional"] for s in series):+ gaps.append(+ f"{request}: {sum(s['provisional'] for s in series)} point(s) the ECB marks "+ "provisional; a later backfill stores their final values as revisions."+ )+ run.defer_store(+ request, payload, series, duration,+ _copy_at(fetcher, f"liquidity:ecb:{dataset}:{key}:0:{start_d}"),+ )+ try:+ pruned = run.commit(now)+ except sqlite3.Error as exc:+ return _store_failure(ECB_SOURCE, provider, exc, run)+ return run.result(provider, gaps, pruned)diff --git a/src/world_intel_mcp/history_extractors.py b/src/world_intel_mcp/history_extractors.pynew file mode 100644index 0000000..0b4e351--- /dev/null+++ b/src/world_intel_mcp/history_extractors.py@@ -0,0 +1,163 @@+"""History extractors for more collector sources (ROADMAP Phase 29).++``history.py`` holds the extractor registry and its first extractors; this+module registers extractors for further collector sources whose payloads+carry dated numeric values. ``history.py`` imports it at its end, so these+are registered wherever the store classifies a capture. Every point is+dated only from a date in its payload, never from the collection time:++- ``liquidity_board``: each indicator row's latest and previous value+ (FRED WALCL, WDTGAL, RRPONTSYD and M2SL; ECB euro area M1, M2, M3 and+ Eurosystem total assets), in the row's own units. The derived net+ liquidity row is skipped: the ``net_liquidity`` source stores that series+ with its three terms.+- ``net_liquidity``: per Wednesday, net liquidity and its three terms in+ USD billions. The reverse repo term is dated by the day it was taken from+ (``reverse_repo_observed_at``), which can be the Tuesday before.+- ``net_migration``: World Bank SM.POP.NETM for every country or region in+ the payload's rankings (persons, dated by the year). The most recent+ years are UN World Population Prospects modelled values or projections,+ so a later World Bank release can revise them.++Period forms: FRED dates are kept as written (FRED dates a monthly value at+the first day of its month); ECB monthly periods (``2026-08``) are kept as+written; an ECB weekly period (``2026-W41``) is stored as the Sunday that+ends that ISO week (``2026-10-11``), the period end the ECB response itself+gives for its weekly series, because the store keeps calendar dates. A+value whose period cannot be read is emitted as written so the store skips+it and counts it in the capture's ``extract_error``, never stores it+undated.++Gaps / not covered:+- Collector sources with dated values left without an extractor:+ ``energy_prices``, ``residential_natgas`` and ``electricity_rates`` (EIA)+ need ``EIA_API_KEY``, so no real payload could be captured to build their+ tests; ``migration_surges`` and ``displacement`` (UNHCR yearly totals)+ were not examined in depth.+- Collector sources whose payloads carry no observation date and so got no+ extractor: crypto, stablecoin, ETF, sector, macro signal and shipping+ quotes (Yahoo or CoinGecko values without a quote time), AAA gas prices+ (today's average, undated), and the computed BTC technicals.+- Values served from a stale cache copy are stored like any other: the+ store's ``collected_at`` is when this server saved the value, which for a+ stale copy is later than when the copy was fetched.+"""++from __future__ import annotations++import re+from datetime import date+from typing import Any++from .history import Observation, normalize_observed_at, register_extractor++_ISO_WEEK = re.compile(r"(\d{4})-W(\d{2})")+++def period_date(value: Any) -> str | None:+ """A payload period in the store's date forms, or None if unreadable.++ Dates, months, years and offset instants go through+ ``normalize_observed_at``; an ISO week (``2026-W41``) becomes the Sunday+ that ends it.+ """+ observed = normalize_observed_at(value)+ if observed is not None:+ return observed+ match = _ISO_WEEK.fullmatch(str(value or "").strip())+ if match is None:+ return None+ try:+ return date.fromisocalendar(int(match[1]), int(match[2]), 7).isoformat()+ except ValueError:+ return None+++def _dated(entry: dict, date_key: str) -> str:+ """``observed_at`` for a point, or the raw period when it cannot be+ read: the store then skips the point and counts it, which keeps an+ undated value out of a dated series."""+ raw = entry.get(date_key)+ return period_date(raw) or ("" if raw is None else str(raw))+++# Board rows computed by this server from other rows, not read upstream.+_DERIVED_BOARD_ROWS = frozenset({"net_liquidity"})+++@register_extractor("liquidity_board")+def _extract_liquidity_board(payload: dict) -> list[Observation]:+ """Latest and previous value of each upstream indicator row."""+ points = []+ for row in payload.get("indicators") or []:+ indicator = row.get("indicator")+ if not indicator or indicator in _DERIVED_BOARD_ROWS:+ continue+ for value_key, date_key in (+ ("latest_value", "observed_at"),+ ("previous_value", "previous_observed_at"),+ ):+ if row.get(value_key) is None:+ continue+ points.append(+ Observation(indicator, row[value_key], observed_at=_dated(row, date_key),+ unit=row.get("units"), label=row.get("label"))+ )+ return points+++# (series suffix, value key, date key, label) per net liquidity point.+_NET_LIQUIDITY_TERMS = (+ ("net_liquidity", "value", "observed_at",+ "US net liquidity (WALCL - WDTGAL - RRPONTSYD)"),+ ("fed_total_assets", "fed_total_assets", "observed_at",+ "Fed total assets (WALCL, Wednesday level)"),+ ("treasury_general_account", "treasury_general_account", "observed_at",+ "Treasury General Account (WDTGAL, Wednesday level)"),+ ("reverse_repo", "reverse_repo", "reverse_repo_observed_at",+ "Fed overnight reverse repo (RRPONTSYD, the day used for the week)"),+)+++@register_extractor("net_liquidity")+def _extract_net_liquidity(payload: dict) -> list[Observation]:+ """Each week's net liquidity and the three terms it was computed from."""+ unit = payload.get("units")+ points = []+ for point in payload.get("points") or []:+ for suffix, value_key, date_key, label in _NET_LIQUIDITY_TERMS:+ if point.get(value_key) is None:+ continue+ points.append(+ Observation(suffix, point[value_key], observed_at=_dated(point, date_key),+ unit=unit, label=label)+ )+ return points+++_MIGRATION_LISTS = (+ "top_net_immigration",+ "top_net_emigration",+ "highest_rate_immigration",+ "highest_rate_emigration",+ "world_regions",+)+++@register_extractor("net_migration")+def _extract_net_migration(payload: dict) -> list[Observation]:+ """Net migration per country or region in the rankings, once each."""+ points = []+ seen: set[str] = set()+ for list_key in _MIGRATION_LISTS:+ for entry in payload.get(list_key) or []:+ iso = entry.get("iso3")+ if not iso or iso in seen or entry.get("net_migration") is None:+ continue+ seen.add(iso)+ points.append(+ Observation(iso, entry["net_migration"], observed_at=_dated(entry, "year"),+ unit="persons",+ label=f"{entry.get('name') or iso}: net migration (World Bank SM.POP.NETM)")+ )+ return pointsdiff --git a/src/world_intel_mcp/tests/fixtures/history/liquidity_board.json b/src/world_intel_mcp/tests/fixtures/history/liquidity_board.jsonnew file mode 100644index 0000000..e4f7e30--- /dev/null+++ b/src/world_intel_mcp/tests/fixtures/history/liquidity_board.json@@ -0,0 +1,253 @@+{+ "sort": "biggest_move",+ "ranking_rule": "biggest_move ranks absolute changes in billions of each row currency; no FX conversion, and observation horizons differ. Percentage changes do not affect ranking.",+ "count": 9,+ "indicators": [+ {+ "indicator": "us_m2",+ "label": "US M2 money stock",+ "dataset": "FRED M2SL",+ "source": "fred-graph",+ "measure": "amount_outstanding",+ "frequency": "monthly",+ "units": "USD billions",+ "latest_value": 23342.8,+ "status": null,+ "observed_at": "2026-08-01",+ "period_end": "2026-08-31",+ "previous_value": 23217.9,+ "previous_observed_at": "2026-07-01",+ "change": 124.9,+ "change_pct": 0.5379,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 47,+ "expected_max_age_days": 100,+ "stale": false+ }+ },+ {+ "indicator": "euro_area_m3",+ "label": "Euro area M3 (stock)",+ "dataset": "BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E",+ "source": "ecb-data-portal",+ "measure": "amount_outstanding",+ "frequency": "monthly",+ "units": "EUR millions",+ "latest_value": 17646463.0,+ "status": "Provisional value",+ "observed_at": "2026-08",+ "period_end": "2026-08-31",+ "previous_value": 17615092.0,+ "previous_observed_at": "2026-07",+ "change": 31371.0,+ "change_pct": 0.1781,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 47,+ "expected_max_age_days": 75,+ "stale": false+ }+ },+ {+ "indicator": "euro_area_m2",+ "label": "Euro area M2 (stock)",+ "dataset": "BSI.M.U2.Y.V.M20.X.1.U2.2300.Z01.E",+ "source": "ecb-data-portal",+ "measure": "amount_outstanding",+ "frequency": "monthly",+ "units": "EUR millions",+ "latest_value": 16447405.0,+ "status": "Provisional value",+ "observed_at": "2026-08",+ "period_end": "2026-08-31",+ "previous_value": 16434747.0,+ "previous_observed_at": "2026-07",+ "change": 12658.0,+ "change_pct": 0.077,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 47,+ "expected_max_age_days": 75,+ "stale": false+ }+ },+ {+ "indicator": "net_liquidity",+ "label": "US net liquidity (WALCL - WDTGAL - RRPONTSYD)",+ "dataset": "derived from FRED WALCL, WDTGAL, RRPONTSYD",+ "source": "fred-graph",+ "measure": "amount_outstanding",+ "frequency": "weekly, as of Wednesday",+ "units": "USD billions",+ "latest_value": 5869.615,+ "status": null,+ "observed_at": "2026-10-14",+ "period_end": "2026-10-14",+ "previous_value": 5859.439,+ "previous_observed_at": "2026-10-07",+ "change": 10.176,+ "change_pct": 0.1737,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 3,+ "expected_max_age_days": 10,+ "stale": false+ }+ },+ {+ "indicator": "fed_total_assets",+ "label": "Federal Reserve total assets",+ "dataset": "FRED WALCL",+ "source": "fred-graph",+ "measure": "amount_outstanding",+ "frequency": "weekly, as of Wednesday",+ "units": "USD millions",+ "latest_value": 6755639.0,+ "status": null,+ "observed_at": "2026-10-14",+ "period_end": "2026-10-14",+ "previous_value": 6747560.0,+ "previous_observed_at": "2026-10-07",+ "change": 8079.0,+ "change_pct": 0.1197,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 3,+ "expected_max_age_days": 10,+ "stale": false+ }+ },+ {+ "indicator": "eurosystem_total_assets",+ "label": "Total assets/liabilities - Eurosystem",+ "dataset": "ILM.W.U2.C.T000000.Z5.Z01",+ "source": "ecb-data-portal",+ "measure": "amount_outstanding",+ "frequency": "weekly",+ "units": "EUR millions",+ "latest_value": 5943911.0,+ "status": "Normal value",+ "observed_at": "2026-W41",+ "period_end": "2026-10-11",+ "previous_value": 5947826.0,+ "previous_observed_at": "2026-W40",+ "change": -3915.0,+ "change_pct": -0.0658,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 6,+ "expected_max_age_days": 16,+ "stale": false+ }+ },+ {+ "indicator": "euro_area_m1",+ "label": "Euro area M1 (stock)",+ "dataset": "BSI.M.U2.Y.V.M10.X.1.U2.2300.Z01.E",+ "source": "ecb-data-portal",+ "measure": "amount_outstanding",+ "frequency": "monthly",+ "units": "EUR millions",+ "latest_value": 11293328.0,+ "status": "Provisional value",+ "observed_at": "2026-08",+ "period_end": "2026-08-31",+ "previous_value": 11291831.0,+ "previous_observed_at": "2026-07",+ "change": 1497.0,+ "change_pct": 0.0133,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 47,+ "expected_max_age_days": 75,+ "stale": false+ }+ },+ {+ "indicator": "reverse_repo",+ "label": "Fed overnight reverse repo",+ "dataset": "FRED RRPONTSYD",+ "source": "fred-graph",+ "measure": "amount_outstanding",+ "frequency": "daily (business days)",+ "units": "USD billions",+ "latest_value": 0.1,+ "status": null,+ "observed_at": "2026-10-16",+ "period_end": "2026-10-16",+ "previous_value": 1.201,+ "previous_observed_at": "2026-10-15",+ "change": -1.101,+ "change_pct": -91.6736,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 1,+ "expected_max_age_days": 6,+ "stale": false+ }+ },+ {+ "indicator": "treasury_general_account",+ "label": "Treasury General Account (Wednesday level)",+ "dataset": "FRED WDTGAL",+ "source": "fred-graph",+ "measure": "amount_outstanding",+ "frequency": "weekly, as of Wednesday",+ "units": "USD millions",+ "latest_value": 885823.0,+ "status": null,+ "observed_at": "2026-10-14",+ "period_end": "2026-10-14",+ "previous_value": 885783.0,+ "previous_observed_at": "2026-10-07",+ "change": 40.0,+ "change_pct": 0.0045,+ "change_basis": "vs previous observation",+ "freshness": {+ "latest_age_days": 3,+ "expected_max_age_days": 10,+ "stale": false+ }+ }+ ],+ "unavailable": [],+ "blocked": [+ {+ "measure": "money market fund assets, weekly",+ "publisher": "ICI",+ "status": "blocked",+ "measured": "2026-10-17: HTTP 403 (Akamai 'Access Denied') on www.ici.org/research/stats/mmf and on /robots.txt"+ },+ {+ "measure": "ETF net issuance, monthly actuals and weekly estimates",+ "publisher": "ICI",+ "status": "blocked",+ "measured": "2026-10-17: HTTP 403 (Akamai 'Access Denied') on www.ici.org/research/stats/etf and on /robots.txt"+ },+ {+ "measure": "customer margin balances (debit and free credit), monthly",+ "publisher": "FINRA",+ "status": "blocked",+ "measured": "2026-10-17: the margin-statistics XLSX answers 200, but the finra.org Terms of Use (Restrictions d and e) forbid creating a database from the site and using data mining, scraping or harvesting tools, robots included"+ },+ {+ "measure": "BLS series (for example CPI-U, nonfarm payrolls)",+ "publisher": "BLS",+ "status": "blocked",+ "measured": "2026-10-17: public API v1 answers 200 without a key, but api.bls.gov/robots.txt is 'Disallow: /' and the www.bls.gov terms page answers 403 to this server's User-Agent"+ }+ ],+ "net_liquidity_formula": "net_liquidity = WALCL - WDTGAL - RRPONTSYD, in USD billions: WALCL and WDTGAL are USD millions divided by 1,000; RRPONTSYD is already USD billions",+ "note": "M1 is contained in M2 and M2 in M3: the aggregates nest, so they are never added together.",+ "sources": [+ "fred-graph",+ "ecb-data-portal"+ ],+ "data_gaps": [+ "Changes are vs each indicator's previous observation, so horizons differ (daily RRP, weekly Fed and Eurosystem data, monthly money supply).",+ "published_at is null for every row: neither FRED's keyless CSV nor the ECB payload carries release dates. FRED units come from the server's series catalog; ECB units come from the response.",+ "Not covered (see blocked): ICI money market fund assets and ETF net issuance, FINRA margin statistics and BLS series; no proxy is substituted for them."+ ],+ "timestamp": "2026-10-17T18:59:47.488802+00:00"+}diff --git a/src/world_intel_mcp/tests/fixtures/history/net_liquidity.json b/src/world_intel_mcp/tests/fixtures/history/net_liquidity.jsonnew file mode 100644index 0000000..73fbc5e--- /dev/null+++ b/src/world_intel_mcp/tests/fixtures/history/net_liquidity.json@@ -0,0 +1,153 @@+{+ "source": "fred-graph",+ "formula": "net_liquidity = WALCL - WDTGAL - RRPONTSYD, in USD billions: WALCL and WDTGAL are USD millions divided by 1,000; RRPONTSYD is already USD billions",+ "alignment": "One point per WALCL Wednesday. WDTGAL must be reported for that same Wednesday. RRPONTSYD is taken from that Wednesday, or when that day is blank on or after 2013-09-23, from Tuesday only; before that date a blank Wednesday has no fallback. Each point names the RRP date used. Weeks without an aligned TGA or RRP value are skipped and counted, never filled with zero.",+ "method": {+ "formula": "net_liquidity = WALCL - WDTGAL - RRPONTSYD, in USD billions: WALCL and WDTGAL are USD millions divided by 1,000; RRPONTSYD is already USD billions",+ "components": {+ "WALCL": {+ "term": "Federal Reserve total assets",+ "observed": "Wednesday level",+ "units": "USD millions",+ "conversion": "divided by 1,000 to USD billions"+ },+ "WDTGAL": {+ "term": "Treasury General Account",+ "observed": "Wednesday level",+ "units": "USD millions",+ "conversion": "divided by 1,000 to USD billions"+ },+ "RRPONTSYD": {+ "term": "Fed overnight reverse repo",+ "observed": "daily, business days",+ "units": "USD billions",+ "conversion": "none: already USD billions",+ "alignment": "the value for the WALCL Wednesday; when blank on or after 2013-09-23, Tuesday only; no fallback before that date. Reported per point as reverse_repo_observed_at; never a later day"+ }+ },+ "alignment": "One point per WALCL Wednesday. WDTGAL must be reported for that same Wednesday. RRPONTSYD is taken from that Wednesday, or when that day is blank on or after 2013-09-23, from Tuesday only; before that date a blank Wednesday has no fallback. Each point names the RRP date used. Weeks without an aligned TGA or RRP value are skipped and counted, never filled with zero.",+ "tga_choice": "The Treasury General Account term is WDTGAL (Wednesday level), not WTREGEN (week average), so all three terms describe the same Wednesday. WTREGEN is not a drop-in replacement: subtracting a week average from Wednesday-level total assets mixes two different measures. WTREGEN is served on its own by intel_fed_liquidity_series."+ },+ "units": "USD billions",+ "measure": "amount_outstanding",+ "frequency": "weekly, as of Wednesday",+ "latest": {+ "observed_at": "2026-10-14",+ "value": 5869.615,+ "units": "USD billions",+ "fed_total_assets": 6755.639,+ "treasury_general_account": 885.823,+ "reverse_repo": 0.201,+ "reverse_repo_observed_at": "2026-10-14"+ },+ "previous": {+ "observed_at": "2026-10-07",+ "value": 5859.439,+ "units": "USD billions",+ "fed_total_assets": 6747.56,+ "treasury_general_account": 885.783,+ "reverse_repo": 2.338,+ "reverse_repo_observed_at": "2026-10-07"+ },+ "change": {+ "absolute": 10.176,+ "units": "USD billions",+ "pct": 0.1737,+ "from": "2026-10-07",+ "to": "2026-10-14",+ "basis": "vs previous observation"+ },+ "components": {+ "WALCL": {+ "label": "Federal Reserve total assets",+ "units": "USD millions",+ "frequency": "weekly, as of Wednesday",+ "measure": "amount_outstanding",+ "release": "H.4.1 Factors Affecting Reserve Balances",+ "latest": {+ "observed_at": "2026-10-14",+ "value": 6755639.0,+ "units": "USD millions"+ },+ "freshness": {+ "latest_age_days": 3,+ "expected_max_age_days": 10,+ "stale": false+ }+ },+ "WDTGAL": {+ "label": "Treasury General Account (Wednesday level)",+ "units": "USD millions",+ "frequency": "weekly, as of Wednesday",+ "measure": "amount_outstanding",+ "release": "H.4.1 Factors Affecting Reserve Balances",+ "latest": {+ "observed_at": "2026-10-14",+ "value": 885823.0,+ "units": "USD millions"+ },+ "freshness": {+ "latest_age_days": 3,+ "expected_max_age_days": 10,+ "stale": false+ }+ },+ "RRPONTSYD": {+ "label": "Fed overnight reverse repo",+ "units": "USD billions",+ "frequency": "daily (business days)",+ "measure": "amount_outstanding",+ "release": "Temporary Open Market Operations",+ "latest": {+ "observed_at": "2026-10-16",+ "value": 0.1,+ "units": "USD billions"+ },+ "freshness": {+ "latest_age_days": 1,+ "expected_max_age_days": 6,+ "stale": false+ }+ }+ },+ "first_observed_at": "2003-03-19",+ "skipped_weeks": 539,+ "order": "newest_first",+ "count": 3,+ "points": [+ {+ "observed_at": "2026-10-14",+ "value": 5869.615,+ "units": "USD billions",+ "fed_total_assets": 6755.639,+ "treasury_general_account": 885.823,+ "reverse_repo": 0.201,+ "reverse_repo_observed_at": "2026-10-14"+ },+ {+ "observed_at": "2026-10-07",+ "value": 5859.439,+ "units": "USD billions",+ "fed_total_assets": 6747.56,+ "treasury_general_account": 885.783,+ "reverse_repo": 2.338,+ "reverse_repo_observed_at": "2026-10-07"+ },+ {+ "observed_at": "2026-09-30",+ "value": 5747.446,+ "units": "USD billions",+ "fed_total_assets": 6743.031,+ "treasury_general_account": 984.046,+ "reverse_repo": 11.539,+ "reverse_repo_observed_at": "2026-09-30"+ }+ ],+ "published_at": null,+ "data_gaps": [+ "FRED's keyless CSV carries observation dates only: published_at is null, and units/frequency come from the server's series catalog, not the payload.",+ "The Treasury General Account term is WDTGAL (Wednesday level), not WTREGEN (week average), so all three terms describe the same Wednesday.",+ "539 of 1244 WALCL weeks skipped (no aligned TGA or RRP value), first 2002-12-18, last 2018-12-05"+ ],+ "timestamp": "2026-10-17T18:59:47.502762+00:00"+}diff --git a/src/world_intel_mcp/tests/fixtures/history/net_migration.json b/src/world_intel_mcp/tests/fixtures/history/net_migration.jsonnew file mode 100644index 0000000..27a99a4--- /dev/null+++ b/src/world_intel_mcp/tests/fixtures/history/net_migration.json@@ -0,0 +1,214 @@+{+ "region_filter": null,+ "countries": 217,+ "net_total": 24459,+ "top_net_immigration": [+ {+ "name": "Ukraine",+ "iso3": "UKR",+ "year": 2025,+ "net_migration": 1702358,+ "per_1000": 43.67,+ "migrant_stock": 5064173,+ "migrant_stock_pct": 13.0,+ "region": "Europe & Central Asia"+ },+ {+ "name": "United States",+ "iso3": "USA",+ "year": 2025,+ "net_migration": 1230663,+ "per_1000": 3.6,+ "migrant_stock": 52375047,+ "migrant_stock_pct": 15.3,+ "region": "North America"+ },+ {+ "name": "Syrian Arab Republic",+ "iso3": "SYR",+ "year": 2025,+ "net_migration": 421693,+ "per_1000": 16.46,+ "migrant_stock": 896042,+ "migrant_stock_pct": 3.5,+ "region": "Middle East, North Africa, Afghanistan & Pakistan"+ },+ {+ "name": "United Kingdom",+ "iso3": "GBR",+ "year": 2025,+ "net_migration": 389911,+ "per_1000": 5.61,+ "migrant_stock": 11845479,+ "migrant_stock_pct": 17.0,+ "region": "Europe & Central Asia"+ }+ ],+ "top_net_emigration": [+ {+ "name": "Pakistan",+ "iso3": "PAK",+ "year": 2025,+ "net_migration": -1235336,+ "per_1000": -4.84,+ "migrant_stock": 4175958,+ "migrant_stock_pct": 1.6,+ "region": "Middle East, North Africa, Afghanistan & Pakistan"+ },+ {+ "name": "India",+ "iso3": "IND",+ "year": 2025,+ "net_migration": -495753,+ "per_1000": -0.34,+ "migrant_stock": 4796255,+ "migrant_stock_pct": 0.3,+ "region": "South Asia"+ },+ {+ "name": "Bangladesh",+ "iso3": "BGD",+ "year": 2025,+ "net_migration": -402100,+ "per_1000": -2.29,+ "migrant_stock": 2906338,+ "migrant_stock_pct": 1.7,+ "region": "South Asia"+ },+ {+ "name": "Nepal",+ "iso3": "NPL",+ "year": 2025,+ "net_migration": -364699,+ "per_1000": -12.31,+ "migrant_stock": 470719,+ "migrant_stock_pct": 1.6,+ "region": "South Asia"+ }+ ],+ "highest_rate_immigration": [+ {+ "name": "Ukraine",+ "iso3": "UKR",+ "year": 2025,+ "net_migration": 1702358,+ "per_1000": 43.67,+ "migrant_stock": 5064173,+ "migrant_stock_pct": 13.0,+ "region": "Europe & Central Asia"+ },+ {+ "name": "Oman",+ "iso3": "OMN",+ "year": 2025,+ "net_migration": 113734,+ "per_1000": 20.7,+ "migrant_stock": 2283366,+ "migrant_stock_pct": 41.6,+ "region": "Middle East, North Africa, Afghanistan & Pakistan"+ },+ {+ "name": "Syrian Arab Republic",+ "iso3": "SYR",+ "year": 2025,+ "net_migration": 421693,+ "per_1000": 16.46,+ "migrant_stock": 896042,+ "migrant_stock_pct": 3.5,+ "region": "Middle East, North Africa, Afghanistan & Pakistan"+ },+ {+ "name": "United Arab Emirates",+ "iso3": "ARE",+ "year": 2025,+ "net_migration": 158634,+ "per_1000": 13.78,+ "migrant_stock": 8157000,+ "migrant_stock_pct": 70.8,+ "region": "Middle East, North Africa, Afghanistan & Pakistan"+ }+ ],+ "highest_rate_emigration": [+ {+ "name": "St. Martin (French part)",+ "iso3": "MAF",+ "year": 2025,+ "net_migration": -1170,+ "per_1000": -46.91,+ "migrant_stock": null,+ "migrant_stock_pct": null,+ "region": "Latin America & Caribbean"+ },+ {+ "name": "Marshall Islands",+ "iso3": "MHL",+ "year": 2025,+ "net_migration": -1698,+ "per_1000": -46.8,+ "migrant_stock": 3309,+ "migrant_stock_pct": 9.1,+ "region": "East Asia & Pacific"+ },+ {+ "name": "Tuvalu",+ "iso3": "TUV",+ "year": 2025,+ "net_migration": -255,+ "per_1000": -26.86,+ "migrant_stock": 246,+ "migrant_stock_pct": 2.6,+ "region": "East Asia & Pacific"+ },+ {+ "name": "Jordan",+ "iso3": "JOR",+ "year": 2025,+ "net_migration": -303267,+ "per_1000": -26.32,+ "migrant_stock": 5280168,+ "migrant_stock_pct": 45.8,+ "region": "Middle East, North Africa, Afghanistan & Pakistan"+ }+ ],+ "world_regions": [+ {+ "name": "North America",+ "iso3": "NAC",+ "year": 2025,+ "net_migration": 1556865,+ "per_1000": 4.06,+ "migrant_stock": 61201057,+ "migrant_stock_pct": 16.0+ },+ {+ "name": "Europe & Central Asia",+ "iso3": "ECS",+ "year": 2025,+ "net_migration": 1180849,+ "per_1000": 1.27,+ "migrant_stock": 105627719,+ "migrant_stock_pct": 11.3+ },+ {+ "name": "World",+ "iso3": "WLD",+ "year": 2025,+ "net_migration": 0,+ "per_1000": 0.0,+ "migrant_stock": 303397238,+ "migrant_stock_pct": 3.7+ },+ {+ "name": "East Asia & Pacific",+ "iso3": "EAS",+ "year": 2025,+ "net_migration": -37630,+ "per_1000": -0.02,+ "migrant_stock": 32481305,+ "migrant_stock_pct": 1.4+ }+ ],+ "measure": "World Bank SM.POP.NETM: immigrants minus emigrants over the year, citizens and non-citizens, all reasons (work, family, study, forced). Positive = net inflow. Source is the UN World Population Prospects: modelled values, and the most recent years can be WPP projections rather than observed counts.",+ "source": "worldbank",+ "timestamp": "2026-10-17T18:59:47Z"+}diff --git a/src/world_intel_mcp/tests/test_history_backfill.py b/src/world_intel_mcp/tests/test_history_backfill.pynew file mode 100644index 0000000..f62cfa4--- /dev/null+++ b/src/world_intel_mcp/tests/test_history_backfill.py@@ -0,0 +1,609 @@+"""History backfill (history_backfill.py) into the history store.++Upstream bodies are the real responses under fixtures/liquidity/ (captured+2026-10-17, see test_sources_liquidity.py): FRED graph CSVs for WALCL (9+weeks), M2SL (14 months) and RRPONTSYD (45 business days with its two real+blank cells, 2026-09-07 and 2026-10-12), the ECB BSI money aggregates+response (12 series, 2026-06 to 2026-08, 2026-08 provisional), the ILM+Eurosystem total assets response (weeks 2026-W39 to W41) and the portal's+real 404 problem body. Variants (one changed value, a "." cell, a NaN+cell, empty and HTML bodies) are made in the test from those files and+say so. Every expected value is read off the fixture files.++Gaps / not covered: live requests (run by hand, see the CHANGELOG entry);+concurrent writers (the collector writing the same database during a+backfill); FRED or ECB responses beyond the fixtures' size.+"""++from __future__ import annotations++import importlib+import json+import os+import sqlite3+import time+import types+from datetime import datetime, timezone+from pathlib import Path++import httpx+import pytest+import respx+from click.testing import CliRunner++import world_intel_mcp.fetcher as fetcher_mod+from world_intel_mcp import cli+from world_intel_mcp import history_backfill as hb+from world_intel_mcp.cache import Cache+from world_intel_mcp.circuit_breaker import CircuitBreaker+from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.history import BACKFILL_VINTAGE_NOTE, HistoryStore, SourceOutcome+from world_intel_mcp.sources import liquidity++_FIX = Path(__file__).parent / "fixtures" / "liquidity"+_FRED = {sid: (_FIX / f"fred_{sid}.csv").read_text() for sid in ("WALCL", "RRPONTSYD", "M2SL")}+_BSI = json.loads((_FIX / "ecb_bsi_money.json").read_text())+_ILM = json.loads((_FIX / "ecb_ilm_total.json").read_text())+_ECB_404 = (_FIX / "ecb_404_problem.json").read_text()++_FRED_URL = "https://fred.stlouisfed.org/graph/fredgraph.csv"+_BSI_KEY = "BSI." + liquidity._ECB_MONEY_KEY # 18 combinations, 12 series answer+_ILM_KEY = "ILM." + liquidity._ECB_EUROSYSTEM_KEY+_BSI_URL = f"https://data-api.ecb.europa.eu/service/data/BSI/{liquidity._ECB_MONEY_KEY}"+_ILM_URL = f"https://data-api.ecb.europa.eu/service/data/ILM/{liquidity._ECB_EUROSYSTEM_KEY}"++NOW = datetime(2026, 10, 17, 20, 0, tzinfo=timezone.utc).timestamp()+NOW_ISO = "2026-10-17T20:00:00Z"++WALCL = [+ ("2026-08-19", 6745699.0), ("2026-08-26", 6730912.0), ("2026-09-02", 6737204.0),+ ("2026-09-09", 6740619.0), ("2026-09-16", 6746548.0), ("2026-09-23", 6747704.0),+ ("2026-09-30", 6743031.0), ("2026-10-07", 6747560.0), ("2026-10-14", 6755639.0),+]++[email protected](autouse=True)+def _no_fred_floor(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setitem(fetcher_mod._SOURCE_RATE_LIMITS, liquidity.FRED_SOURCE, 0.0)+++def db(tmp_path: Path) -> Path:+ return tmp_path / "cache.db"+++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()+++def store(db: Path):+ s = HistoryStore(db)+ yield s+ s.close()+++def _fred_responder(bodies: dict[str, httpx.Response] | None = None):+ bodies = bodies or {}++ def _respond(request: httpx.Request) -> httpx.Response:+ sid = request.url.params.get("id")+ if sid in bodies:+ return bodies[sid]+ if sid in _FRED:+ return httpx.Response(200, text=_FRED[sid])+ return httpx.Response(404, text="<html>Error - St. Louis Fed</html>")++ return _respond+++def _fred_route(bodies: dict[str, httpx.Response] | None = None):+ return respx.get(_FRED_URL).mock(side_effect=_fred_responder(bodies))+++def _series(result: dict, request: str) -> dict:+ (req,) = [r for r in result["requests"] if r["request"] == request]+ assert req["status"] == "ok", req+ (s,) = req["series"]+ return s+++def _rows(store: HistoryStore, sql: str, *params) -> list[tuple]:+ return store._conn.execute(sql, params).fetchall()+++# ---------------------------------------------------------------------------+# FRED+# ---------------------------------------------------------------------------+++async def test_fred_backfill_stores_every_value_with_three_dates(fetcher, store) -> None:+ route = _fred_route()+ out = await hb.backfill_fred(fetcher, store, ["walcl"], now=NOW)+ assert route.call_count == 1 and "error" not in out+ s = _series(out, "WALCL")+ assert s["series_key"] == "backfill:fred:WALCL"+ assert (s["points_in_response"], s["loaded"], s["stored_new"], s["stored_revised"],+ s["unchanged"], s["missing_skipped"], s["invalid_skipped"]) == (9, 9, 9, 0, 0, 0, 0)+ assert (s["first_observed_at"], s["last_observed_at"]) == ("2026-08-19", "2026-10-14")+ assert out["collected_at"] == NOW_ISO and out["totals"]["failed"] == 0++ hist = store.series_history("backfill:fred:WALCL")+ assert hist["source"] == "backfill:fred"+ got = [(o["observed_at"], o["value"]) for o in reversed(hist["observations"])]+ assert got == WALCL+ assert {o["published_at"] for o in hist["observations"]} == {None}+ assert {o["collected_at"] for o in hist["observations"]} == {NOW_ISO}+ assert {o["unit"] for o in hist["observations"]} == {"USD millions"}+ assert hist["observations"][0]["label"] == "FRED WALCL: Federal Reserve total assets"+ assert BACKFILL_VINTAGE_NOTE in hist["data_gaps"]+ assert any("graph CSV carries observation dates and values only" in g+ for g in out["data_gaps"])++ (cap,) = store.capture_history("backfill:fred")["captures"]+ assert (cap["status"], cap["change"], cap["observations_stored"]) == ("ok", "first", 9)+ (log,) = _rows(store, "SELECT source, request, start, status, ran_at FROM history_backfills")+ assert log == ("backfill:fred", "WALCL", None, "ok", NOW)+++async def test_fred_rerun_stores_nothing_and_reuses_the_cached_response(fetcher, store) -> None:+ route = _fred_route()+ first = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)+ second = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 60)+ assert route.call_count == 1 # second read the 1 h cache copy, no request+ s = _series(second, "WALCL")+ assert (s["stored_new"], s["stored_revised"], s["unchanged"]) == (0, 0, 9)+ req = second["requests"][0]+ assert req["payload_changed"] is False and req["previous_backfill_at"] == NOW_ISO+ assert req["copy_fetched_at"] == first["requests"][0]["copy_fetched_at"]+ copy_at = datetime.strptime(req["copy_fetched_at"], "%Y-%m-%dT%H:%M:%SZ").replace(+ tzinfo=timezone.utc).timestamp()+ assert abs(copy_at - time.time()) < 120 # the real fetch time, not the backfill clock++ # Refetched (cache expired): still nothing new.+ fetcher.cache.delete("liquidity:fred:WALCL")+ third = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 120)+ assert route.call_count == 2+ assert _series(third, "WALCL")["stored_new"] == 0+ assert _rows(store, "SELECT COUNT(*) FROM history_observations") == [(9,)]+ changes = [c["change"] for c in store.capture_history("backfill:fred")["captures"]]+ assert changes == ["unchanged", "unchanged", "first"]+++async def test_changed_upstream_value_is_exactly_one_revision(fetcher, store) -> None:+ route = _fred_route()+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)+ revised = _FRED["WALCL"].replace("2026-10-07,6747560", "2026-10-07,6747561")+ assert revised != _FRED["WALCL"] # variant of the real CSV: one value revised+ fetcher.cache.delete("liquidity:fred:WALCL")+ route.side_effect = _fred_responder({"WALCL": httpx.Response(200, text=revised)})+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 3600)+ s = _series(out, "WALCL")+ assert (s["stored_new"], s["stored_revised"], s["unchanged"]) == (0, 1, 8)+ assert out["requests"][0]["payload_changed"] is True+ revs = store.revisions(series_key="backfill:fred:WALCL")+ assert revs["count"] == 1+ (rev,) = revs["revisions"]+ assert (rev["observed_at"], rev["previous_value"], rev["revised_value"], rev["delta"]) == (+ "2026-10-07", 6747560.0, 6747561.0, 1.0)+ assert rev["previous_collected_at"] == NOW_ISO+++async def test_collected_at_is_stamped_after_the_fetches_it_stores(fetcher, store) -> None:+ """Without a fixed clock, one stamp per call taken after its last fetch:+ no stored row is dated before the response it came from."""+ _fred_route()+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "M2SL"])+ logs = _rows(store, "SELECT ran_at, copy_fetched_at FROM history_backfills")+ assert len(logs) == 2 and all(ran >= fetched for ran, fetched in logs)+ assert len({ran for ran, _ in logs}) == 1+ assert _rows(store, "SELECT DISTINCT collected_at FROM history_observations") == [(logs[0][0],)]+ assert out["collected_at"] >= max(r["copy_fetched_at"] for r in out["requests"])+++async def test_repeated_ids_in_any_case_are_one_request(fetcher, store) -> None:+ route = _fred_route()+ out = await hb.backfill_fred(fetcher, store, "walcl, WALCL M2SL", now=NOW)+ assert [r["request"] for r in out["requests"]] == ["WALCL", "M2SL"]+ assert route.call_count == 2 and out["totals"]["stored_new"] == 9 + 14+++async def test_missing_values_are_skipped_and_counted_never_zero(fetcher, store) -> None:+ _fred_route()+ out = await hb.backfill_fred(fetcher, store, ["RRPONTSYD"], now=NOW)+ s = _series(out, "RRPONTSYD")+ assert (s["points_in_response"], s["missing_skipped"], s["loaded"]) == (45, 2, 43)+ stored = dict(_rows(store, "SELECT observed_at, value FROM history_observations"))+ assert "2026-09-07" not in stored and "2026-10-12" not in stored+ assert stored["2026-10-16"] == 0.1 and 0.0 not in stored.values()+ cap = store.capture_history("backfill:fred")["captures"][0]+ assert cap["extract_error"] == "RRPONTSYD: 2 missing value(s) skipped"+ assert out["totals"]["missing_skipped"] == 2+++async def test_dot_and_nan_cells_are_counted_apart(fetcher, store) -> None:+ # Variant of the real CSV: FRED's other missing marker "." and a NaN cell.+ body = _FRED["WALCL"].replace("2026-09-02,6737204", "2026-09-02,.").replace(+ "2026-09-09,6740619", "2026-09-09,NaN")+ _fred_route({"WALCL": httpx.Response(200, text=body)})+ s = _series(await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW), "WALCL")+ assert (s["missing_skipped"], s["invalid_skipped"], s["loaded"]) == (1, 1, 7)+ observed = {r[0] for r in _rows(store, "SELECT observed_at FROM history_observations")}+ assert observed == {d for d, _ in WALCL} - {"2026-09-02", "2026-09-09"}+++ "response, reason",+ [+ (httpx.Response(500, text="upstream down"), "unavailable"),+ (httpx.Response(200, text=""), "not in the expected format"),+ (httpx.Response(200, text="<html><body>Error</body></html>"), "not in the expected format"),+ (httpx.Response(404, text="<html>Error</html>"), "unavailable"),+ (httpx.Response(200, text="observation_date,WALCL\n2026-10-14,\n"), "no observations"),+ ],+ ids=["http-500", "empty-body", "html-body", "unknown-id-404", "all-blank"],+)+async def test_fetch_failures_are_errors_never_an_empty_success(+ fetcher, store, response, reason+) -> None:+ _fred_route({"WALCL": response})+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)+ assert out["error"].startswith("no request succeeded: WALCL: ")+ (req,) = out["requests"]+ assert req["status"] == "error" and reason in req["error"]+ assert out["totals"]["failed"] == 1 and out["totals"]["loaded"] == 0+ assert _rows(store, "SELECT COUNT(*) FROM history_observations") == [(0,)]+ (cap,) = store.capture_history("backfill:fred")["captures"]+ assert cap["status"] == "error" and reason in cap["reason"]+ assert _rows(store, "SELECT status FROM history_backfills") == [("error",)]+++async def test_partial_failure_is_reported_not_hidden(fetcher, store) -> None:+ _fred_route()+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "NOSUCHSERIES"], now=NOW)+ assert "error" not in out and out["totals"]["failed"] == 1+ assert out["data_gaps"][0].startswith("1 of 2 request(s) failed and stored nothing: NOSUCHSERIES")+ assert _series(out, "WALCL")["stored_new"] == 9+++async def test_stale_cache_copy_is_refused(fetcher, store) -> None:+ fetcher.cache.set("liquidity:fred:WALCL", _FRED["WALCL"], -60) # expired copy+ _fred_route({"WALCL": httpx.Response(503, text="maintenance")})+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)+ (req,) = out["requests"]+ assert req["status"] == "error" and "only a stale cached copy" in req["error"]+ assert _rows(store, "SELECT COUNT(*) FROM history_observations") == [(0,)]+++async def test_start_window_and_unknown_units(fetcher, store) -> None:+ _fred_route({"DGS10": httpx.Response(200, text=_FRED["WALCL"].replace("WALCL", "DGS10"))})+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "DGS10"], "2026-10-01", now=NOW)+ s = _series(out, "WALCL")+ assert (s["points_in_response"], s["in_window"], s["loaded"]) == (9, 2, 2)+ assert (s["first_observed_at"], s["last_observed_at"]) == ("2026-10-07", "2026-10-14")+ other = _series(out, "DGS10")+ assert other["unit"] is None and other["label"] == "FRED DGS10"+ assert any(g.startswith("DGS10: units unknown") for g in out["data_gaps"])+ # A window with no values is an error, not an empty success.+ empty = await hb.backfill_fred(fetcher, store, ["M2SL"], "2026-09-01", now=NOW)+ assert "no values on or after 2026-09-01" in empty["requests"][0]["error"]+++ "ids, start, message",+ [+ ([], None, "at least one"),+ (["A", "B", "C", "D", "E", "F"], None, "at most 5"),+ (["WAL-CL"], None, "not a FRED series id"),+ (["WALCL"], "2026-13-01", "YYYY-MM-DD"),+ (["WALCL"], "20261001", "YYYY-MM-DD"),+ (["WALCL"], "2999-01-01", "in the future"),+ ],+)+async def test_bad_arguments_are_refused_before_any_request(fetcher, store, ids, start, message) -> None:+ route = _fred_route()+ out = await hb.backfill_fred(fetcher, store, ids, start, now=NOW)+ assert message in out["error"] and out["requests"] == []+ assert route.call_count == 0+ assert _rows(store, "SELECT COUNT(*) FROM history_captures") == [(0,)]+++async def test_point_caps_keep_the_newest_and_say_so(fetcher, store, monkeypatch) -> None:+ _fred_route()+ monkeypatch.setattr(hb, "MAX_POINTS", 5)+ monkeypatch.setattr(hb, "MAX_POINTS_PER_CALL", 10)+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "M2SL", "RRPONTSYD"], now=NOW)+ walcl, m2 = _series(out, "WALCL"), _series(out, "M2SL")+ assert (walcl["loaded"], walcl["truncated"], walcl["first_observed_at"]) == (5, 4, "2026-09-16")+ assert (m2["loaded"], m2["truncated"], m2["first_observed_at"]) == (5, 9, "2026-04-01")+ (rrp,) = [r for r in out["requests"] if r["request"] == "RRPONTSYD"]+ assert rrp["status"] == "error" and "point budget" in rrp["error"] # none of 10 left+ assert any(g.startswith("Point cap:") for g in out["data_gaps"])+++async def test_rrp_gets_what_is_left_of_the_call_budget(fetcher, store, monkeypatch) -> None:+ with respx.mock:+ _fred_route()+ monkeypatch.setattr(hb, "MAX_POINTS_PER_CALL", 12)+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "RRPONTSYD"], now=NOW)+ rrp = _series(out, "RRPONTSYD")+ assert (rrp["loaded"], rrp["truncated"], rrp["last_observed_at"]) == (3, 40, "2026-10-16")+++async def test_values_pruned_past_retention_are_stored_again(fetcher, store, monkeypatch) -> None:+ _fred_route()+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)+ later = NOW + 400 * 86400+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=later)+ assert out["pruned"]["observations"] == 9 and out["pruned"]["backfill_log"] == 1+ assert _series(out, "WALCL")["stored_new"] == 9+ assert out["requests"][0]["payload_changed"] is None # its earlier log row was pruned+ hist = store.series_history("backfill:fred:WALCL")+ assert {o["collected_at"] for o in hist["observations"]} == {+ datetime.fromtimestamp(later, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}+++# ---------------------------------------------------------------------------+# ECB Data Portal+# ---------------------------------------------------------------------------+++async def test_ecb_backfill_loads_every_series_of_the_key(fetcher, store) -> None:+ route = respx.get(_BSI_URL).mock(return_value=httpx.Response(200, json=_BSI))+ out = await hb.backfill_ecb(fetcher, store, [_BSI_KEY], now=NOW)+ assert "lastNObservations" not in str(route.calls.last.request.url) # full history+ (req,) = out["requests"]+ assert req["status"] == "ok" and len(req["series"]) == 12+ by_key = {s["series_key"]: s for s in req["series"]}+ m3 = by_key["backfill:ecb:BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E"]+ assert (m3["loaded"], m3["provisional"], m3["missing_skipped"]) == (3, 1, None)+ expected_units = {+ s["key"]: s["units"] for s in liquidity.parse_sdmx_json(_BSI, "BSI")+ }["BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E"]+ hist = store.series_history("backfill:ecb:BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E")+ assert [(o["observed_at"], o["value"], o["unit"]) for o in hist["observations"]] == [+ ("2026-08", 17646463.0, expected_units),+ ("2026-07", 17615092.0, expected_units),+ ("2026-06", 17611985.0, expected_units),+ ]+ assert out["totals"]["missing_skipped"] is None # unknown, not zero+ assert any("12 point(s) the ECB marks provisional" in g for g in out["data_gaps"])+ assert any("published_at is NULL" in g for g in out["data_gaps"])+++async def test_ecb_weeks_are_dated_by_the_sunday_that_ends_them(fetcher, store) -> None:+ route = respx.get(_ILM_URL).mock(return_value=httpx.Response(200, json=_ILM))+ out = await hb.backfill_ecb(fetcher, store, [_ILM_KEY], "2026-09-01", now=NOW)+ assert "startPeriod=2026-09-01" in str(route.calls.last.request.url)+ s = _series(out, _ILM_KEY)+ assert s["series_key"] == "backfill:ecb:ILM.W.U2.C.T000000.Z5.Z01"+ rows = _rows(store, "SELECT observed_at, value FROM history_observations ORDER BY observed_at")+ assert rows == [("2026-09-27", 5897262.0), ("2026-10-04", 5947826.0), ("2026-10-11", 5943911.0)]+ again = await hb.backfill_ecb(fetcher, store, [_ILM_KEY], "2026-09-01", now=NOW + 60)+ assert route.call_count == 1 and _series(again, _ILM_KEY)["unchanged"] == 3+ assert again["requests"][0]["payload_changed"] is False+ # Both runs read one cached copy, found under the liquidity cache key.+ assert out["requests"][0]["copy_fetched_at"] is not None+ assert again["requests"][0]["copy_fetched_at"] == out["requests"][0]["copy_fetched_at"]+++ "response, reason",+ [+ (httpx.Response(404, text=_ECB_404), "no series matches the key"),+ (httpx.Response(200, text=""), "no observations on or after"),+ (httpx.Response(200, text="{not json"), "not in the expected SDMX-JSON shape"),+ (httpx.Response(500, text="oops"), "upstream fetch failed"),+ ],+ ids=["404", "empty", "malformed", "http-500"],+)+async def test_ecb_failures_are_errors(fetcher, store, response, reason) -> None:+ respx.get(_ILM_URL).mock(return_value=response)+ out = await hb.backfill_ecb(fetcher, store, [_ILM_KEY], now=NOW)+ assert out["requests"][0]["status"] == "error" and reason in out["requests"][0]["error"]+ assert "error" in out+ assert _rows(store, "SELECT COUNT(*) FROM history_observations") == [(0,)]+++ "keys, message",+ [+ (["XYZ.M.U2"], "starts with its dataset"),+ (["BSI.M.U2.Y.V.M30"], "names all 11 dimensions"),+ (["ILM.W.U2.C..Z5.Z01"], "names all 6 dimensions"),+ (["BSI.M.U2.Y.V.M10+M20+M30.X.1+4+I.U2.2300.Z01+Z02.E+A"], "36 series combinations"),+ (["BSI.M.U2;DROP"], "letters, digits"),+ ([_BSI_KEY, _ILM_KEY, "BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E"], "at most 2"),+ ],+)+async def test_ecb_bad_keys_are_refused_before_any_request(fetcher, store, keys, message) -> None:+ route = respx.route(host="data-api.ecb.europa.eu").mock(+ return_value=httpx.Response(200, json=_ILM))+ out = await hb.backfill_ecb(fetcher, store, keys, now=NOW)+ assert message in out["error"] and route.call_count == 0+++# ---------------------------------------------------------------------------+# Store integration: migration, health, per-request change+# ---------------------------------------------------------------------------+++async def test_migrates_a_database_made_by_the_current_schema(db, fetcher) -> None:+ old = HistoryStore(db) # the schema as the store creates it, no backfill table+ old.record_cycle(+ [SourceOutcome("space_weather", NOW - 600, payload={+ "kp_recent": [{"time": "2026-10-17T18:00:00Z", "kp": 2.33}], "alerts": []})],+ now=NOW - 600,+ )+ before = _rows(old, "SELECT * FROM history_observations")+ tables = {r[0] for r in _rows(old, "SELECT name FROM sqlite_master WHERE type = 'table'")}+ assert "history_backfills" not in tables and len(before) == 1+ old.close()++ _fred_route()+ store = HistoryStore(db)+ try:+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)+ hb.ensure_schema(store) # idempotent on a migrated database+ assert _rows(store, "SELECT * FROM history_observations WHERE source = 'space_weather'") == before+ assert _rows(store, "SELECT COUNT(*) FROM history_backfills") == [(1,)]+ finally:+ store.close()+ reopened = HistoryStore(db)+ try:+ health = reopened.collection_health(["space_weather"], now=NOW)+ assert [r["source"] for r in health["sources"]] == ["space_weather"]+ (bf,) = health["backfills"]+ assert (bf["source"], bf["captures"], bf["series"], bf["observations"]) == (+ "backfill:fred", 1, 1, 9)+ assert (bf["first_observed_at"], bf["latest_observed_at"]) == ("2026-08-19", "2026-10-14")+ assert "backfill" not in json.dumps(health["state_counts"])+ one = reopened.collection_health(["space_weather"], source="backfill:fred", now=NOW)+ assert one["sources"] == [] and one["backfills"][0]["source"] == "backfill:fred"+ bad = reopened.collection_health(["space_weather"], source="nope", now=NOW)+ assert "backfill:fred" in bad["known_sources"]+ collector_series = reopened.series_history("space_weather:kp")+ assert BACKFILL_VINTAGE_NOTE not in collector_series["data_gaps"]+ finally:+ reopened.close()+++async def test_capture_change_compares_the_same_request_only(fetcher, store) -> None:+ _fred_route()+ for sid, at in (("WALCL", NOW), ("M2SL", NOW + 1), ("WALCL", NOW + 2)):+ await hb.backfill_fred(fetcher, store, [sid], now=at)+ changes = [c["change"] for c in store.capture_history("backfill:fred")["captures"]]+ assert changes == ["unchanged", "first", "first"] # newest first: WALCL, M2SL, WALCL+++async def test_store_error_is_reported_with_what_was_committed(fetcher, store, monkeypatch) -> None:+ with respx.mock:+ _fred_route()+ real = hb._Run.store_request+ calls = {"n": 0}++ def _flaky(self, *args, **kwargs):+ calls["n"] += 1+ if calls["n"] == 2:+ raise sqlite3.OperationalError("database is locked")+ return real(self, *args, **kwargs)++ monkeypatch.setattr(hb._Run, "store_request", _flaky)+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "M2SL"], now=NOW)+ assert out["error"] == ("history store write failed: database is locked; "+ "1 earlier request(s) were committed")+ assert [r["request"] for r in out["requests"]] == ["WALCL"]+++# ---------------------------------------------------------------------------+# MCP tool and CLI+# ---------------------------------------------------------------------------+++def _backfill_tools():+ from .test_server_registry import _TMP_CACHE++ prior = os.environ.get("WORLD_INTEL_CACHE_DB")+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)+ try:+ importlib.import_module("world_intel_mcp.tools")+ return importlib.import_module("world_intel_mcp.tools.history_backfill")+ finally:+ if prior is None:+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)+ else:+ os.environ["WORLD_INTEL_CACHE_DB"] = prior+++async def test_mcp_tool_writes_the_runtime_store_within_the_caps(db, fetcher, monkeypatch) -> None:+ tools_mod = _backfill_tools()+ monkeypatch.setattr(tools_mod.runtime, "cache", types.SimpleNamespace(db_path=db), raising=False)+ monkeypatch.setattr(tools_mod.runtime, "fetcher", fetcher, raising=False)+ handler = tools_mod.HANDLERS["intel_history_backfill"]+ _fred_route()+ out = await handler({"provider": "FRED", "series": ["WALCL"], "start": "2026-10-01"})+ assert _series(out, "WALCL")["loaded"] == 2 and out["db_path"] == str(db)+ assert "provider must be" in (await handler({"provider": "bls", "series": ["X"]}))["error"]+ too_many = await handler({"provider": "fred", "series": ["A", "B", "C", "D", "E", "F"]})+ assert "at most 5" in too_many["error"]+ (tool,) = tools_mod.TOOLS+ assert "at most 5 FRED series or 2 ECB keys" in tool.description+ assert "\u2014" not in tool.description # no em dash in user-facing text+++def cli_env(db, monkeypatch):+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(db))+ monkeypatch.setenv("COLUMNS", "220")+ monkeypatch.setattr(cli, "_fetcher", None)+ yield db+ if cli._fetcher is not None:+ cli._fetcher.cache.close()+++def _invoke(*args):+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)+++def test_cli_backfill_registry() -> None:+ assert set(cli.backfill_group.commands) == {"fred", "ecb"}+ assert cli.history_group.commands["backfill"] is cli.backfill_group+ assert "backfill" not in cli.main.commands # under intel history only+++def test_cli_backfill_fred_table_json_and_exit_codes(cli_env) -> None:+ _fred_route()+ first = _invoke("history", "backfill", "fred", "WALCL", "RRPONTSYD")+ assert first.exit_code == 0, first.output+ assert "backfill:fred:WALCL" in first.output and "backfill:fred:RRPONTSYD" in first.output+ assert "Stored 52 new and 0 revised values, 0 unchanged" in first.output+ again = json.loads(_invoke("--json-output", "history", "backfill", "fred", "WALCL").output)+ assert again["totals"]["unchanged"] == 9 and again["totals"]["stored_new"] == 0++ failed = _invoke("history", "backfill", "fred", "NOSUCHSERIES")+ assert failed.exit_code == 1 and "error" in failed.output+ refused = _invoke("history", "backfill", "fred", "WALCL", "--start", "yesterday")+ assert refused.exit_code == 1 and "YYYY-MM-DD" in refused.output++ series = _invoke("history", "series", "backfill:fred:WALCL").output+ assert "2026-10-14" in series and "6.75564e+06" in series and "Backfilled:" in series+ health = _invoke("history", "health").output+ assert "Backfill backfill:fred: 4 capture(s)" in health+ assert "52 observations in 2 series, observed 2026-08-17 to 2026-10-16" in health+++def test_cli_backfill_ecb(cli_env) -> None:+ respx.get(_ILM_URL).mock(return_value=httpx.Response(200, json=_ILM))+ out = _invoke("history", "backfill", "ecb", _ILM_KEY)+ assert out.exit_code == 0, out.output+ assert "backfill:ecb:ILM.W.U2.C.T000000.Z5.Z01" in out.output+ assert "2026-09-27" in out.output and "2026-10-11" in out.output+ assert "unknown" in out.output # ECB missing values cannot be counteddiff --git a/src/world_intel_mcp/tests/test_history_extractors.py b/src/world_intel_mcp/tests/test_history_extractors.pynew file mode 100644index 0000000..b821872--- /dev/null+++ b/src/world_intel_mcp/tests/test_history_extractors.py@@ -0,0 +1,167 @@+"""Extractors registered by history_extractors.py, pinned on real payloads.++Fixtures under fixtures/history/ are live payloads captured 2026-10-17+under an isolated HOME by the project's own fetch functions+(``liquidity.fetch_liquidity_board``, ``liquidity.fetch_net_liquidity``,+``migration.fetch_net_migration``), then trimmed: the board is complete;+net_liquidity keeps its newest 3 of 52 points (``count`` set to match);+net_migration keeps the first 4 entries of each ranking, so Ukraine (UKR)+and Syria (SYR) stay in two rankings each. No key or personal data is in+any of them. Every expected value below is read off those files by eye.++Gaps / not covered: payloads served from a stale cache copy (stored like+any other, see the module docstring); the EIA, UNHCR and quote sources+that got no extractor.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+from pathlib import Path++from world_intel_mcp import history_extractors+from world_intel_mcp.history import HistoryStore, SourceOutcome, classify++_FIX = Path(__file__).parent / "fixtures" / "history"+T0 = 1_792_000_000.0+++def _payload(name: str) -> dict:+ return json.loads((_FIX / f"{name}.json").read_text())+++def _points(source: str, payload: dict) -> dict[str, tuple]:+ c = classify(SourceOutcome(source, T0, payload=payload))+ assert c.status == "ok", c.reason+ out = {o.series_key: [] for o in c.observations}+ for o in c.observations:+ out[o.series_key].append((o.observed_at, o.value, o.unit))+ return out+++def test_period_date_forms() -> None:+ pd = history_extractors.period_date+ assert pd("2026-W41") == "2026-10-11" # Sunday ending ISO week 41+ assert pd("2026-W01") == "2026-01-04"+ assert pd("2020-W53") == "2021-01-03" # 2020 has 53 ISO weeks+ assert pd("2026-W54") is None and pd("2026-W00") is None+ assert pd("2026-08") == "2026-08" and pd("2026-08-01") == "2026-08-01"+ assert pd(2025) == "2025"+ assert pd("2026-Q2") is None and pd(None) is None and pd("") is None+++def test_liquidity_board_rows_latest_and_previous() -> None:+ points = _points("liquidity_board", _payload("liquidity_board"))+ assert points == {+ "us_m2": [("2026-08-01", 23342.8, "USD billions"), ("2026-07-01", 23217.9, "USD billions")],+ "euro_area_m3": [("2026-08", 17646463.0, "EUR millions"),+ ("2026-07", 17615092.0, "EUR millions")],+ "euro_area_m2": [("2026-08", 16447405.0, "EUR millions"),+ ("2026-07", 16434747.0, "EUR millions")],+ "fed_total_assets": [("2026-10-14", 6755639.0, "USD millions"),+ ("2026-10-07", 6747560.0, "USD millions")],+ # ECB weeks 41 and 40 end on these Sundays (the response's period end).+ "eurosystem_total_assets": [("2026-10-11", 5943911.0, "EUR millions"),+ ("2026-10-04", 5947826.0, "EUR millions")],+ "euro_area_m1": [("2026-08", 11293328.0, "EUR millions"),+ ("2026-07", 11291831.0, "EUR millions")],+ "reverse_repo": [("2026-10-16", 0.1, "USD billions"), ("2026-10-15", 1.201, "USD billions")],+ "treasury_general_account": [("2026-10-14", 885823.0, "USD millions"),+ ("2026-10-07", 885783.0, "USD millions")],+ }+ # The derived row is the net_liquidity source's series, not stored twice.+ assert "net_liquidity" not in points+++def test_net_liquidity_points_and_terms() -> None:+ points = _points("net_liquidity", _payload("net_liquidity"))+ usd = "USD billions"+ assert points == {+ "net_liquidity": [("2026-10-14", 5869.615, usd), ("2026-10-07", 5859.439, usd),+ ("2026-09-30", 5747.446, usd)],+ "fed_total_assets": [("2026-10-14", 6755.639, usd), ("2026-10-07", 6747.56, usd),+ ("2026-09-30", 6743.031, usd)],+ "treasury_general_account": [("2026-10-14", 885.823, usd), ("2026-10-07", 885.783, usd),+ ("2026-09-30", 984.046, usd)],+ "reverse_repo": [("2026-10-14", 0.201, usd), ("2026-10-07", 2.338, usd),+ ("2026-09-30", 11.539, usd)],+ }+++def test_reverse_repo_term_is_dated_by_the_day_it_was_taken_from() -> None:+ payload = _payload("net_liquidity")+ payload["points"][0]["reverse_repo_observed_at"] = "2026-10-13" # a Tuesday fallback+ points = _points("net_liquidity", payload)+ assert points["reverse_repo"][0] == ("2026-10-13", 0.201, "USD billions")+ assert points["net_liquidity"][0][0] == "2026-10-14"+++def test_net_migration_once_per_country_dated_by_year() -> None:+ c = classify(SourceOutcome("net_migration", T0, payload=_payload("net_migration")))+ assert c.status == "ok" and c.extract_error is None+ got = {o.series_key: (o.observed_at, o.value, o.unit) for o in c.observations}+ assert len(c.observations) == len(got) == 18 # 20 entries, UKR and SYR twice+ assert got == {+ iso: ("2025", float(value), "persons")+ for iso, value in {+ "UKR": 1702358, "USA": 1230663, "SYR": 421693, "GBR": 389911,+ "PAK": -1235336, "IND": -495753, "BGD": -402100, "NPL": -364699,+ "OMN": 113734, "ARE": 158634,+ "MAF": -1170, "MHL": -1698, "TUV": -255, "JOR": -303267,+ "NAC": 1556865, "ECS": 1180849, "WLD": 0, "EAS": -37630,+ }.items()+ }+ labels = {o.series_key: o.label for o in c.observations}+ assert labels["UKR"] == "Ukraine: net migration (World Bank SM.POP.NETM)"+++def test_unreadable_or_missing_period_is_skipped_and_counted_never_stored_undated() -> None:+ payload = _payload("liquidity_board")+ rows = {r["indicator"]: r for r in payload["indicators"]}+ rows["us_m2"]["observed_at"] = "2026-Q9"+ rows["euro_area_m1"]["previous_observed_at"] = None+ c = classify(SourceOutcome("liquidity_board", T0, payload=payload))+ assert c.extract_error == "2 invalid point(s) skipped"+ kept = {(o.series_key, o.observed_at) for o in c.observations}+ assert ("us_m2", "2026-07-01") in kept and ("euro_area_m1", "2026-08") in kept+ assert len(c.observations) == 14+ assert all(o.observed_at for o in c.observations)+++def test_record_cycle_stores_extracted_series_once(tmp_path: Path) -> None:+ store = HistoryStore(tmp_path / "h.db")+ try:+ outcomes = [+ SourceOutcome(name, T0, payload=_payload(name))+ for name in ("liquidity_board", "net_liquidity", "net_migration")+ ]+ first = store.record_cycle(outcomes, now=T0)+ assert first["observations_stored"] == 16 + 12 + 18+ again = store.record_cycle(+ [SourceOutcome(o.source, T0 + 300, payload=o.payload) for o in outcomes], now=T0 + 300+ )+ assert again["observations_stored"] == 0+ weekly = store.series_history("liquidity_board:eurosystem_total_assets")+ assert [(o["observed_at"], o["value"]) for o in weekly["observations"]] == [+ ("2026-10-11", 5943911.0), ("2026-10-04", 5947826.0),+ ]+ finally:+ store.close()+++def test_history_module_registers_these_extractors_on_import() -> None:+ """A fresh interpreter that imports only the store sees them, so the+ collector's classify finds them whatever imported history first."""+ code = (+ "import world_intel_mcp.history as h; "+ "print(sorted(set(h.registered_extractors()) & "+ "{'liquidity_board', 'net_liquidity', 'net_migration'}))"+ )+ out = subprocess.run(+ [sys.executable, "-c", code], capture_output=True, text=True, check=True,+ env=os.environ.copy(), timeout=60,+ ).stdout+ assert out.strip() == "['liquidity_board', 'net_liquidity', 'net_migration']"diff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.pyindex fc0bb4d..fb02ea6 100644--- a/src/world_intel_mcp/tools/__init__.py+++ b/src/world_intel_mcp/tools/__init__.py@@ -29,6 +29,7 @@ from . import ( # noqa: E402geospatial,hazards,history,+ history_backfill,infrastructure,intelligence,liquidity,@@ -59,6 +60,7 @@ _MODULES = [vector,aoi,history,+ history_backfill,system,]diff --git a/src/world_intel_mcp/tools/history.py b/src/world_intel_mcp/tools/history.pyindex fe93892..3f52de2 100644--- a/src/world_intel_mcp/tools/history.py+++ b/src/world_intel_mcp/tools/history.py@@ -15,7 +15,9 @@ from ..history import HistoryStore_ACCRUAL = ("History accrues only while the collector (intel-collector, or intel_collect) "- "runs; nothing before its first recorded cycle exists."+ "runs; nothing before its first recorded cycle exists, except series under "+ "backfill:fred and backfill:ecb, which intel_history_backfill loads from the "+ "publisher's current data.")TOOLS: list[Tool] = [@@ -24,16 +26,20 @@ TOOLS: list[Tool] = [description=("Per-source collection health from the collector's run log: last attempt, ""last success, consecutive failures, overdue against the expected cadence "- "(default 300 s, overdue past 3 cadences), never-run sources, and history "- "storage size. States what it cannot prove: a fresh capture does not mean "- "upstream observations are current (see latest_observed_at). " + _ACCRUAL+ "(default 300 s, overdue past 3 cadences), never-run sources, backfill runs "+ "listed apart (backfills), and history storage size. States what it cannot "+ "prove: a fresh capture does not mean upstream observations are current (see "+ "latest_observed_at). " + _ACCRUAL),inputSchema={"type": "object","properties": {"source": {"type": "string",- "description": "One collector source name (e.g. 'earthquakes'); omit for all",+ "description": (+ "One collector source name (e.g. 'earthquakes') or backfill "+ "source ('backfill:fred'); omit for all"+ ),},},},diff --git a/src/world_intel_mcp/tools/history_backfill.py b/src/world_intel_mcp/tools/history_backfill.pynew file mode 100644index 0000000..7db2aa6--- /dev/null+++ b/src/world_intel_mcp/tools/history_backfill.py@@ -0,0 +1,79 @@+"""History backfill tool: load the history FRED or the ECB Data Portal already serve into the history store.++The one history tool that fetches upstream and writes:+``world_intel_mcp.history_backfill`` reads FRED graph CSV or ECB Data+Portal series through the runtime Fetcher (rate floor, breaker, cache)+and stores the points in the cache DB's history store under+``backfill:fred`` or ``backfill:ecb``. Its caps are the module's, so the+CLI (``intel history backfill``) and this tool load at most the same per call.+"""++from typing import Any++from mcp.types import Tool++from .. import history_backfill as backfill+from .. import runtime+from ..history import HistoryStore++TOOLS: list[Tool] = [+ Tool(+ name="intel_history_backfill",+ description=(+ "Load the history FRED (graph CSV) or the ECB Data Portal already serve into the "+ "history store, for intel_series_history and intel_revisions: one capture per "+ "series under backfill:fred or backfill:ecb, observed_at from the publisher's "+ "dates, published_at null (neither names a release date), collected_at the "+ "backfill time. Values are the publisher's current vintage, so revisions made "+ "before the first backfill are invisible; a re-run stores only new or changed "+ "values, and a changed value is a revision. Missing values are skipped and "+ "counted; a failed fetch, or one answered only from a stale cache copy, is an "+ "error capture and stores no values. This tool "+ "writes to the history store and sends requests upstream, so it is capped: at "+ f"most {backfill.MAX_FRED_SERIES} FRED series or {backfill.MAX_ECB_KEYS} ECB keys "+ f"({backfill.MAX_ECB_COMBINATIONS} series each) per call, the newest "+ f"{backfill.MAX_POINTS:,} points per series and {backfill.MAX_POINTS_PER_CALL:,} "+ "per call. A repeat within the cache window (FRED 1 h, ECB 3 h) reads the cached "+ "response and sends no request."+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "provider": {+ "type": "string",+ "enum": ["fred", "ecb"],+ "description": "fred (FRED graph CSV) or ecb (ECB Data Portal, BSI and ILM)",+ },+ "series": {+ "type": "array",+ "items": {"type": "string"},+ "maxItems": backfill.MAX_FRED_SERIES,+ "description": (+ "FRED series ids (e.g. ['WALCL', 'RRPONTSYD']) or ECB series keys "+ "DATASET.KEY (e.g. ['BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E'])"+ ),+ },+ "start": {+ "type": "string",+ "description": "Only observations on or after this date, YYYY-MM-DD",+ },+ },+ "required": ["provider", "series"],+ },+ ),+]+++async def _history_backfill(arguments: dict[str, Any]) -> Any:+ provider = str(arguments.get("provider") or "").strip().lower()+ if provider not in ("fred", "ecb"):+ return {"error": f"provider must be 'fred' or 'ecb', got {arguments.get('provider')!r}"}+ run = backfill.backfill_fred if provider == "fred" else backfill.backfill_ecb+ store = HistoryStore(runtime.cache.db_path)+ try:+ return await run(runtime.fetcher, store, arguments.get("series"), arguments.get("start"))+ finally:+ store.close()+++HANDLERS = {"intel_history_backfill": _history_backfill}