Skip to content

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.

Fix history backfill review round 2 findings

Phoenix Agent (mac-studio)42238ff78120
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ea431c..0225c18 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -242,7 +242,9 @@ source here, and no proxy is substituted for any of these measures.
`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,
+ apart (`backfills`), and a source whose latest call had any failed
+ request reads `error` with that request's reason, whatever order the
+ requests were named in. 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
@@ -251,7 +253,19 @@ source here, and no proxy is substituted for any of these measures.
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.
+ invisible. `--start` keeps values dated on or after it: FRED dates as
+ written (a month by its first day), ECB weeks and quarters by the period
+ end the store keeps, so the ECB is asked from up to one period earlier
+ and the boundary period is cut client-side.
+- One capture per request (a FRED id, or an ECB key that may match several
+ series). Its saved body is a summary (request, start, full-response
+ hash, per-series counts and dates), not the response: the values are in
+ the observations, and a replay stays small. An ECB '+' alternative that
+ matched no series is named in `data_gaps`.
+- Values a re-run no longer finds in the response's date span (withdrawn,
+ or now a missing cell) are reported as `absent_from_response` with the
+ first and last date; the store keeps them as the earlier backfill read
+ them.
- 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
@@ -259,14 +273,23 @@ source here, and no proxy is substituted for any of these measures.
- 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.
+ The CLI exits 1 when any request failed. A store write failure names
+ the request it failed on, the requests fetched but not written, and the
+ upstream failures after it, written as error captures when the store
+ accepts them and listed as not logged when it does not.
- 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.
+ narrows the window. Older values past the series cap cannot be loaded
+ by a backfill (there is no end bound); values left out by the call
+ budget load in a call of their own.
+- Retention: a backfill prunes only backfill rows (sources `backfill:*`
+ and its own log), with this process's retention settings; collector rows
+ are left to the collector. 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, 0 keeps forever).
+ A backfill prunes before it stores, so a pruned value is stored again as
+ new. The collector's own prune still covers backfill rows, under the
+ collector's settings.
- 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
diff --git a/README.md b/README.md
index f6fc7fc..4b6b423 100644
--- a/README.md
+++ b/README.md
@@ -607,7 +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 |
+| `intel_history_backfill` | Load the history FRED (graph CSV) or the ECB Data Portal already serve into the history store: one capture per request (a FRED id, or an ECB key that may match several 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); FRED missing values skipped and counted, ECB missing values not countable (null); writes and fetches, so capped at 5 FRED series or 2 ECB keys per call |
---
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index 7005d22..98313f2 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -3150,11 +3150,18 @@ def history_health(ctx: click.Context, source: str | None) -> None:
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"last {row['last_run_at']} ({row['last_status']}"
+ + (
+ f", {row['last_run_failed']} of {row['last_run_requests']} request(s) failed"
+ if row.get("last_run_failed") else ""
+ )
+ + f"), {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 '-'))}."
)
+ if row.get("last_run_failed"):
+ console.print(f" Last run failed: {escape(str(row['last_reason']))}")
counts = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items())) or "none"
storage = data["storage"]
console.print(
@@ -3364,10 +3371,25 @@ def _run_backfill(
def _print_backfill(data: dict) -> None:
- if not data.get("requests"):
+ if data.get("error"):
console.print(f"[red]Error:[/red] {escape(str(data['error']))}")
+ # A store write failure (history_backfill._store_failure) names what it
+ # did not write; the committed requests follow as a table.
+ for label, key in (
+ ("Write failed on", "failed_request"),
+ ("Fetched but not written", "fetched_not_written"),
+ ("Upstream failures logged", "upstream_failures_logged"),
+ ("Upstream failures not logged", "upstream_failures_not_logged"),
+ ):
+ value = data.get(key)
+ if value:
+ names = value if isinstance(value, list) else [value]
+ console.print(f"{label}: {escape(', '.join(names))}")
+ if not data.get("requests"):
return
- title = f"Backfill into {data['source']} at {data['collected_at']}"
+ title = f"Backfill into {data['source']}"
+ if data.get("collected_at"):
+ title += f" at {data['collected_at']}"
if data.get("start"):
title += f" from {data['start']}"
table = Table(title=escape(title), box=box.SIMPLE_HEAVY)
@@ -3397,11 +3419,12 @@ def _print_backfill(data: dict) -> None:
_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'])}."
- )
+ totals = data.get("totals")
+ if 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)
diff --git a/src/world_intel_mcp/history.py b/src/world_intel_mcp/history.py
index d115c27..5cbe46d 100644
--- a/src/world_intel_mcp/history.py
+++ b/src/world_intel_mcp/history.py
@@ -841,16 +841,23 @@ class HistoryStore:
}
def _backfill_row(self, name: str) -> dict:
- """One backfill source: its captures and the series it stored."""
+ """One backfill source: its captures, its latest run and the series
+ it stored. Every capture of one backfill call shares one
+ collected_at, so the latest run is all captures at the latest time:
+ error if any request in it failed (with the first failure's reason),
+ whatever the order the requests were named in."""
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()
+ run = conn.execute(
+ "SELECT status, error FROM history_captures WHERE source = ? AND collected_at = ? "
+ "ORDER BY id",
+ (name, last_at),
+ ).fetchall()
+ failed = [r for r in run if r[0] == "error"]
+ last_status = "error" if failed else (run[-1][0] if run else None)
+ last_reason = failed[0][1] if failed else None
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 = ?",
@@ -862,6 +869,8 @@ class HistoryStore:
"last_run_at": _iso(last_at),
"last_status": last_status,
"last_reason": last_reason,
+ "last_run_requests": len(run),
+ "last_run_failed": len(failed),
"series": series,
"observations": points,
"first_observed_at": first_obs,
diff --git a/src/world_intel_mcp/history_backfill.py b/src/world_intel_mcp/history_backfill.py
index d0857a8..92ce658 100644
--- a/src/world_intel_mcp/history_backfill.py
+++ b/src/world_intel_mcp/history_backfill.py
@@ -9,8 +9,9 @@ the fetch and parse code the liquidity tools use (``sources/liquidity.py``:
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
+- One capture per request (one FRED series id, or one ECB series key,
+ which may match several series) 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,
@@ -20,7 +21,11 @@ writes the points into the history store (``history.py``):
- 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);
+ any other ECB period as the period end its response states). A start
+ keeps values whose ``observed_at`` is on or after it, for both
+ providers: the ECB applies ``startPeriod`` to a period's first day, so
+ the ECB request asks from one period earlier (6 days for weeks, 92 for
+ quarters, 183 for half-years) and the window is cut here;
``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
@@ -30,24 +35,40 @@ writes the points into the history store (``history.py``):
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.
+ stored as zero; non-finite values are skipped and counted apart. A
+ stored value inside the response's date span that the response no
+ longer serves is kept (the store never deletes a value) and reported as
+ ``absent_from_response``.
- 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.
+ error capture and store no values. A store write failure names the
+ request it failed on, the requests fetched but not written, and the
+ upstream failures it could or could not log.
+- Payload bodies of backfill captures hold a summary of the response
+ (series, counts, date span, the full response's hash), not the response:
+ one FRED series can carry 26,000 rows, and replaying it through
+ ``intel_capture_history`` would flood a client. The values loaded are in
+ the observations.
- 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.
+ optionally only from a start date. Values a series cap leaves out are
+ the oldest, and no later backfill can load them (there is no end bound);
+ values a call's budget leaves out load in a call of their own.
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.
+invisible. Retention: a backfill prunes only backfill rows (``backfill:*``
+captures, payload bodies and observations, and ``history_backfills``),
+using the retention settings of the process that runs it; collector rows
+are left to the collector's own prune and settings. Observations are
+pruned 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
@@ -63,8 +84,14 @@ Gaps / not covered:
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.
+- The collector's prune also deletes backfill rows, under the collector's
+ settings; it does not touch ``history_backfills``, whose rows are pruned
+ here, on the next backfill, past the observation retention.
+- No end bound: the oldest values of a series longer than ``MAX_POINTS``
+ cannot be backfilled.
+- An ECB key that matches only some of its combinations is not an error:
+ each ``+`` code that matched no series at all is named in the gaps, but
+ a combination of matched codes that is absent is not.
- 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.
@@ -78,7 +105,7 @@ import re
import sqlite3
import time
import zlib
-from datetime import date, datetime, timezone
+from datetime import date, datetime, timedelta, timezone
from typing import Any
from .fetcher import Fetcher
@@ -108,6 +135,11 @@ _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}
+# Days before the start an ECB request asks from, by frequency (the key's
+# first dimension), so a period that starts before the start but is dated
+# on or after it (weeks by their Sunday, quarters and half-years by their
+# end) is returned; the window is then cut on observed_at.
+_ECB_LOOKBACK_DAYS = {"W": 6, "Q": 92, "H": 183}
_SCHEMA = """
CREATE TABLE IF NOT EXISTS history_backfills (
@@ -132,13 +164,20 @@ VINTAGE_GAP = (
"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. "
+ "Retention: a backfill prunes only backfill rows, with this process's retention "
+ "settings; collector rows are left to the collector. Observations are pruned 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."
)
+BODY_NOTE = (
+ "Summary only: a backfill keeps this summary instead of the response, which can "
+ "hold tens of thousands of rows. The values loaded are in the history store "
+ "(intel_series_history); payload_hash is the full response's hash."
+)
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, "
@@ -254,40 +293,62 @@ class _Run:
self.now = 0.0 # set by commit()
self.budget = MAX_POINTS_PER_CALL
self.requests: list[dict] = []
- self._pending: list[tuple[Any, tuple]] = []
+ self._pending: list[tuple[str, tuple]] = []
+ self.failed_at: int | None = None # index in _pending of a failed write
def defer_fail(self, request: str, error: str, duration: float) -> None:
- self._pending.append((self.fail, (request, error, duration)))
+ self._pending.append(("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)))
+ self._pending.append(("store", (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."""
+ in its own transaction; returns what the prune removed. On a store
+ error ``failed_at`` marks the write that failed."""
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)
+ for i, (kind, args) in enumerate(self._pending):
+ try:
+ if kind == "store":
+ self.store_request(*args)
+ else:
+ self.fail(*args)
+ except sqlite3.Error:
+ self.failed_at = i
+ raise
return pruned
def prune(self) -> dict:
- """Prune before storing, so a value pruned past retention is stored
- again by this run instead of vanishing."""
+ """Prune backfill rows only, before storing, so a value pruned past
+ retention is stored again by this run instead of vanishing. Collector
+ rows are the collector's to prune, under its own settings."""
conn = self.store._conn
+ days = retention_days()
+ like = BACKFILL_PREFIX + "%"
+ pruned = {"payloads": 0, "captures": 0, "observations": 0, "backfill_log": 0}
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,),
+ if days["payload_days"] > 0:
+ pruned["payloads"] = conn.execute(
+ "DELETE FROM history_payloads WHERE source LIKE ? AND last_seen_at < ?",
+ (like, self.now - days["payload_days"] * 86400),
+ ).rowcount
+ if days["capture_days"] > 0:
+ pruned["captures"] = conn.execute(
+ "DELETE FROM history_captures WHERE source LIKE ? AND collected_at < ?",
+ (like, self.now - days["capture_days"] * 86400),
+ ).rowcount
+ if days["history_days"] > 0:
+ cutoff = self.now - days["history_days"] * 86400
+ pruned["observations"] = conn.execute(
+ "DELETE FROM history_observations WHERE source LIKE ? AND collected_at < ?",
+ (like, cutoff),
+ ).rowcount
+ pruned["backfill_log"] = conn.execute(
+ "DELETE FROM history_backfills WHERE ran_at < ?", (cutoff,)
).rowcount
- if days > 0
- else 0
- )
return pruned
def _previous(self, request: str) -> tuple[str | None, float | None]:
@@ -340,7 +401,24 @@ class _Run:
"""
conn = self.store._conn
digest = payload_hash(payload)
- body = json.dumps(payload, separators=(",", ":"), default=str).encode()
+ body = json.dumps({
+ "provider": payload.get("provider"),
+ "request": request,
+ "start": self.start_text,
+ "payload_hash": digest,
+ "body": BODY_NOTE,
+ "series": [
+ {
+ "series_key": f"{self.source}:{s['key']}",
+ "points_in_response": s["points_in_response"],
+ "in_window": s["in_window"],
+ "loaded": len(s["points"]),
+ "first_observed_at": s["points"][0][0] if s["points"] else None,
+ "last_observed_at": s["points"][-1][0] if s["points"] else None,
+ }
+ for s in series
+ ],
+ }, separators=(",", ":"), default=str).encode()
prev_hash, prev_at = self._previous(request)
changed = None if prev_hash is None else int(prev_hash != digest)
results = []
@@ -397,6 +475,14 @@ class _Run:
stored_total += stored
new = sum(1 for observed, _ in s["points"] if observed not in prior)
loaded = len(s["points"])
+ # Stored values inside the response's date span that it no
+ # longer serves (withdrawn, or now a missing cell).
+ lo, hi = s.get("span") or (None, None)
+ served = s.get("served") or set()
+ absent = sorted(
+ d for d in prior if d is not None and lo is not None
+ and lo <= d <= hi and d not in served
+ )
results.append({
"series_key": key,
"label": s["label"],
@@ -406,12 +492,19 @@ class _Run:
"missing_skipped": s["missing_skipped"],
"invalid_skipped": s["invalid_skipped"],
"truncated": s["truncated"],
+ "truncated_by": (
+ None if not s["truncated"]
+ else "call budget" if s.get("budget_limited") else "series cap"
+ ),
"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,
+ "absent_from_response": len(absent),
+ "absent_first": absent[0] if absent else None,
+ "absent_last": absent[-1] if absent else None,
**({"provisional": s["provisional"]} if "provisional" in s else {}),
})
conn.execute(
@@ -437,13 +530,17 @@ class _Run:
self.requests.append(entry)
return entry
- def window(self, points: list[tuple[str, float]]) -> tuple[list[tuple[str, float]], int]:
+ def window(
+ self, points: list[tuple[str, float]]
+ ) -> tuple[list[tuple[str, float]], int, bool]:
"""Newest points within the per-series cap and the call's budget,
- oldest first, and how many older ones were left out."""
+ oldest first, how many older ones were left out, and whether the
+ call's budget (not the series cap) left them out."""
cap = min(MAX_POINTS, self.budget)
kept = points[-cap:] if cap > 0 else []
self.budget -= len(kept)
- return kept, len(points) - len(kept)
+ truncated = len(points) - len(kept)
+ return kept, truncated, bool(truncated) and cap < MAX_POINTS
def result(self, provider: str, gaps: list[str], pruned: dict) -> dict:
failed = [r for r in self.requests if r["status"] == "error"]
@@ -455,7 +552,7 @@ class _Run:
**{
name: sum(s[name] for s in series)
for name in ("loaded", "stored_new", "stored_revised", "unchanged",
- "invalid_skipped", "truncated")
+ "invalid_skipped", "truncated", "absent_from_response")
},
# Unknown, not zero, when any series could not count them (ECB).
"missing_skipped": (
@@ -467,12 +564,32 @@ class _Run:
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."
- )
+ for s in series:
+ if not s["truncated"]:
+ continue
+ before = f"{s['truncated']:,} older value(s) before {s['first_observed_at']}"
+ if s["truncated_by"] == "call budget":
+ alone = s["loaded"] + s["truncated"]
+ gaps.append(
+ f"Point cap: {s['series_key']}: {before} were not loaded because this "
+ f"call's {MAX_POINTS_PER_CALL:,}-point budget ran out; backfill it in a "
+ "call of its own"
+ + (f", which loads its newest {MAX_POINTS:,}" if alone > MAX_POINTS else "")
+ + "."
+ )
+ else:
+ gaps.append(
+ f"Point cap: {s['series_key']}: {before} cannot be loaded by a "
+ f"backfill, which keeps only the newest {MAX_POINTS:,} values of a series."
+ )
+ for s in series:
+ if s["absent_from_response"]:
+ gaps.append(
+ f"{s['series_key']}: {s['absent_from_response']} stored value(s) from "
+ f"{s['absent_first']} to {s['absent_last']} are absent from this response "
+ "(withdrawn, or now a missing value); the store keeps them as an earlier "
+ "backfill read them."
+ )
out = {
"source": self.source,
"provider": provider,
@@ -491,6 +608,35 @@ class _Run:
return out
+def _first_day(observed: str | None) -> date | None:
+ """The date a stored observed_at is compared with a start by: the day
+ itself, or a month's or year's first day (as FRED dates a month)."""
+ if not observed:
+ return None
+ try:
+ if len(observed) == 10:
+ return date.fromisoformat(observed)
+ if len(observed) == 7:
+ return date.fromisoformat(observed + "-01")
+ if len(observed) == 4:
+ return date.fromisoformat(observed + "-01-01")
+ except ValueError:
+ return None
+ return None
+
+
+def _unmatched_codes(key: str, series: list[dict]) -> list[str]:
+ """Each '+' alternative of an ECB key that no returned series carries."""
+ returned = [str(s.get("key") or "").split(".")[1:] for s in series]
+ out = []
+ for i, dim in enumerate(key.split(".")):
+ codes = dim.split("+")
+ if len(codes) > 1:
+ present = {r[i] for r in returned if len(r) > i}
+ out += [code for code in codes if code not in present]
+ 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])
@@ -511,10 +657,33 @@ def _error_result(source: str, provider: str, error: str) -> dict:
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."""
+ requests listed were committed and the failing one was rolled back.
+
+ Names the request the write failed on, the requests fetched but not
+ written, and the upstream failures after it: their error captures are
+ written if the store now accepts them, else listed as not logged."""
+ committed = list(run.requests)
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"
+ out["error"] += f"; {len(committed)} earlier request(s) were committed"
+ out["requests"] = committed
+ out["collected_at"] = _iso(run.now) if run.now else None
+ failing = None if run.failed_at is None else run._pending[run.failed_at]
+ rest = run._pending if run.failed_at is None else run._pending[run.failed_at + 1:]
+ out["failed_request"] = failing[1][0] if failing else None
+ out["fetched_not_written"] = [args[0] for kind, args in rest if kind == "store"]
+ logged, not_logged = [], []
+ if failing and failing[0] == "fail":
+ not_logged.append(failing[1][0])
+ for kind, args in rest:
+ if kind != "fail":
+ continue
+ try:
+ run.fail(*args)
+ logged.append(args[0])
+ except sqlite3.Error:
+ not_logged.append(args[0])
+ out["upstream_failures_logged"] = logged
+ out["upstream_failures_not_logged"] = not_logged
return out
@@ -564,12 +733,13 @@ async def backfill_fred(
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)]
+ dates = [d.isoformat() for d, _ in in_window]
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)
+ points, truncated, budget_limited = 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)
@@ -599,6 +769,9 @@ async def backfill_fred(
"missing_skipped": missing,
"invalid_skipped": len(in_window) - missing - len(valid),
"truncated": truncated,
+ "budget_limited": budget_limited,
+ "served": {d for d, _ in valid},
+ "span": (min(dates), max(dates)) if dates else None,
}],
duration,
_copy_at(fetcher, f"liquidity:fred:{sid}"),
@@ -643,9 +816,14 @@ async def backfill_ecb(
gaps = [ECB_PUBLISHED_GAP, ECB_DATE_GAP, ECB_MISSING_GAP]
for dataset, key in parsed:
request = f"{dataset}.{key}"
+ fetch_d = None
+ if start_d is not None:
+ back = max(_ECB_LOOKBACK_DAYS.get(f, 0) for f in key.split(".")[0].split("+"))
+ fetch_d = start_d - timedelta(days=back)
began = time.monotonic()
res = await liquidity.fetch_ecb_series(
- fetcher, dataset=dataset, key=key, limit=0, start=run.start_text
+ fetcher, dataset=dataset, key=key, limit=0,
+ start=fetch_d.isoformat() if fetch_d else None,
)
duration = time.monotonic() - began
if res.get("error"):
@@ -656,34 +834,49 @@ async def backfill_ecb(
run.defer_fail(request, _refusal(f"ECB Data Portal {request}",
stale[0].get("cache_age_seconds")), duration)
continue
+ unmatched = _unmatched_codes(key, res["series"])
+ if unmatched:
+ gaps.append(
+ f"{request}: '+' alternative(s) that matched no series: {', '.join(unmatched)}"
+ )
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:
+ in_window: list[tuple[str | None, dict]] = []
+ for p in reversed(s["points"]): # oldest first
observed = period_date(p.get("observed_at")) or normalize_observed_at(
p.get("period_end")
)
+ first_day = _first_day(observed)
+ if start_d is not None and first_day is not None and first_day < start_d:
+ continue # asked for one period early; before the window
+ in_window.append((observed, p))
+ valid: list[tuple[str, float]] = []
+ seen: set[str] = set()
+ for observed, p in in_window:
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)
+ points, truncated, budget_limited = run.window(valid)
+ dates = [o for o, _ in in_window if o is not None]
series.append({
"key": s["key"],
"label": s.get("title") or s["key"],
"unit": s.get("units"),
"points": points,
- "points_in_response": len(in_window),
+ "points_in_response": len(s["points"]),
"in_window": len(in_window),
"missing_skipped": None,
"invalid_skipped": len(in_window) - len(valid),
"truncated": truncated,
+ "budget_limited": budget_limited,
+ "served": {o for o, _ in valid},
+ "span": (min(dates), max(dates)) if dates else None,
"provisional": sum(
- 1 for p in in_window if "provisional" in str(p.get("status") or "").lower()
+ 1 for _, p in in_window
+ if "provisional" in str(p.get("status") or "").lower()
),
})
if not any(s["points"] for s in series):
@@ -712,7 +905,7 @@ async def backfill_ecb(
)
run.defer_store(
request, payload, series, duration,
- _copy_at(fetcher, f"liquidity:ecb:{dataset}:{key}:0:{start_d}"),
+ _copy_at(fetcher, f"liquidity:ecb:{dataset}:{key}:0:{fetch_d}"),
)
try:
pruned = run.commit(now)
diff --git a/src/world_intel_mcp/tests/test_history_backfill.py b/src/world_intel_mcp/tests/test_history_backfill.py
index f62cfa4..569c816 100644
--- a/src/world_intel_mcp/tests/test_history_backfill.py
+++ b/src/world_intel_mcp/tests/test_history_backfill.py
@@ -17,6 +17,7 @@ backfill); FRED or ECB responses beyond the fixtures' size.
from __future__ import annotations
+import copy
import importlib
import json
import os
@@ -482,6 +483,7 @@ async def test_migrates_a_database_made_by_the_current_schema(db, fetcher) -> No
"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"])
+ assert health["state_counts"] == {"ok": 1} # the collector roster only
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)
@@ -525,6 +527,10 @@ async def test_store_error_is_reported_with_what_was_committed(fetcher, store, m
# ---------------------------------------------------------------------------
+def _refuse_runtime_init() -> None:
+ raise AssertionError("the test initialized the runtime (default cache DB)")
+
+
def _backfill_tools():
from .test_server_registry import _TMP_CACHE
@@ -543,8 +549,11 @@ def _backfill_tools():
@respx.mock
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)
+ # Set the runtime's attributes in its namespace: reading them first (as
+ # setattr does) would initialize the runtime and open the default DB.
+ monkeypatch.setattr(tools_mod.runtime, "_initialize", _refuse_runtime_init)
+ monkeypatch.setitem(vars(tools_mod.runtime), "cache", types.SimpleNamespace(db_path=db))
+ monkeypatch.setitem(vars(tools_mod.runtime), "fetcher", fetcher)
handler = tools_mod.HANDLERS["intel_history_backfill"]
_fred_route()
out = await handler({"provider": "FRED", "series": ["WALCL"], "start": "2026-10-01"})
@@ -607,3 +616,429 @@ def test_cli_backfill_ecb(cli_env) -> None:
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 counted
+
+
+# ---------------------------------------------------------------------------
+# Review round 2: each test names the mutant it kills
+# ---------------------------------------------------------------------------
+
+
+def _iso_at(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _ecb_honouring_start(body: dict):
+ """An ECB mock that applies startPeriod the way the Data Portal does:
+ to each period's first day (variant of a real response, made here)."""
+
+ def _respond(request: httpx.Request) -> httpx.Response:
+ start = request.url.params.get("startPeriod")
+ data = copy.deepcopy(body)
+ periods = data["structure"]["dimensions"]["observation"][0]["values"]
+ keep = {str(i) for i, v in enumerate(periods) if not start or v["start"][:10] >= start}
+ for series in data["dataSets"][0]["series"].values():
+ series["observations"] = {
+ k: v for k, v in series["observations"].items() if k in keep
+ }
+ return httpx.Response(200, json=data)
+
+ return _respond
+
+
+def _quarterly_bsi() -> dict:
+ """The real BSI response with its three months relabelled as quarters
+ (2025-Q4 to 2026-Q2, start and end as the portal writes them)."""
+ data = copy.deepcopy(_BSI)
+ data["structure"]["dimensions"]["series"][0]["values"] = [{"id": "Q", "name": "Quarterly"}]
+ data["structure"]["dimensions"]["observation"][0]["values"] = [
+ {"id": "2025-Q4", "name": "2025-Q4", "start": "2025-10-01T00:00:00.000+02:00",
+ "end": "2025-12-31T23:59:59.999+01:00"},
+ {"id": "2026-Q1", "name": "2026-Q1", "start": "2026-01-01T00:00:00.000+01:00",
+ "end": "2026-03-31T23:59:59.999+02:00"},
+ {"id": "2026-Q2", "name": "2026-Q2", "start": "2026-04-01T00:00:00.000+02:00",
+ "end": "2026-06-30T23:59:59.999+02:00"},
+ ]
+ return data
+
+
+_Q_M3 = "BSI.Q.U2.Y.V.M30.X.1.U2.2300.Z01.E"
+
+
+def _m3_rows(store: HistoryStore, key: str) -> list[tuple]:
+ return _rows(store, "SELECT observed_at, value FROM history_observations WHERE series_key = ? "
+ "ORDER BY observed_at", f"backfill:ecb:{key}")
+
+
+async def test_backfill_prunes_only_its_own_rows(fetcher, store, monkeypatch) -> None:
+ """BF-1. Kills: _Run.prune calling HistoryStore._prune (every source)."""
+ for name in ("WORLD_INTEL_HISTORY_DAYS", "WORLD_INTEL_HISTORY_CAPTURE_DAYS",
+ "WORLD_INTEL_HISTORY_PAYLOAD_DAYS"):
+ monkeypatch.setenv(name, "0") # the collector keeps everything
+ for age_days, kp in ((400, 2.0), (40, 3.0), (10, 4.0)):
+ at = NOW - age_days * 86400
+ store.record_cycle([SourceOutcome("space_weather", at, payload={
+ "kp_recent": [{"time": _iso_at(at), "kp": kp}], "alerts": []})], now=at)
+ counts = "SELECT COUNT(*) FROM {} WHERE source = 'space_weather'"
+ tables = ("history_captures", "history_payloads", "history_observations")
+ before = [_rows(store, counts.format(t))[0][0] for t in tables]
+ assert before == [3, 3, 3]
+ for name in ("WORLD_INTEL_HISTORY_DAYS", "WORLD_INTEL_HISTORY_CAPTURE_DAYS",
+ "WORLD_INTEL_HISTORY_PAYLOAD_DAYS"):
+ monkeypatch.delenv(name) # the backfill runs under the defaults
+ _fred_route()
+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ assert [_rows(store, counts.format(t))[0][0] for t in tables] == before
+ assert out["pruned"] == {"payloads": 0, "captures": 0, "observations": 0, "backfill_log": 0}
+ assert any("prunes only backfill rows" in g for g in out["data_gaps"])
+
+
+def _lock_after_first_write(db: Path, monkeypatch) -> list[sqlite3.Connection]:
+ """After the first request commits, a second connection takes the write
+ lock (BEGIN IMMEDIATE) and holds it: a real lock, not a raised error."""
+ real = hb._Run.store_request
+ holders: list[sqlite3.Connection] = []
+
+ def _then_lock(self, *args, **kwargs):
+ out = real(self, *args, **kwargs)
+ if not holders:
+ self.store._conn.execute("PRAGMA busy_timeout = 50")
+ holder = sqlite3.connect(str(db), timeout=0.05)
+ holder.execute("BEGIN IMMEDIATE")
+ holders.append(holder)
+ return out
+
+ monkeypatch.setattr(hb._Run, "store_request", _then_lock)
+ return holders
+
+
+def test_cli_store_failure_names_what_it_did_not_write(cli_env, monkeypatch) -> None:
+ """BF-2. Kills: _print_backfill reading collected_at/totals of a store
+ failure (KeyError), and _store_failure not naming the unwritten ones."""
+ _fred_route()
+ holders = _lock_after_first_write(cli_env, monkeypatch)
+ try:
+ out = _invoke("history", "backfill", "fred", "WALCL", "M2SL", "RRPONTSYD", "NOSUCHSERIES")
+ finally:
+ for h in holders:
+ h.rollback()
+ h.close()
+ assert out.exit_code == 1
+ assert ("Error: history store write failed: database is locked; "
+ "1 earlier request(s) were committed") in out.output
+ assert "Write failed on: M2SL" in out.output
+ assert "Fetched but not written: RRPONTSYD" in out.output
+ assert "Upstream failures not logged: NOSUCHSERIES" in out.output
+ assert "backfill:fred:WALCL" in out.output # the committed request's row
+ check = sqlite3.connect(str(cli_env))
+ try:
+ assert check.execute("SELECT request, status FROM history_backfills").fetchall() == [
+ ("WALCL", "ok")]
+ finally:
+ check.close()
+
+
+async def test_store_failure_logs_later_upstream_failures_when_it_can(
+ fetcher, store, monkeypatch
+) -> None:
+ """BF-2. Kills: _store_failure not writing the deferred error captures."""
+ real = hb._Run.store_request
+
+ def _m2sl_fails(self, request, *args, **kwargs):
+ if request == "M2SL":
+ raise sqlite3.OperationalError("disk I/O error")
+ return real(self, request, *args, **kwargs)
+
+ monkeypatch.setattr(hb._Run, "store_request", _m2sl_fails)
+ with respx.mock:
+ _fred_route()
+ out = await hb.backfill_fred(fetcher, store, ["WALCL", "M2SL", "NOSUCHSERIES"], now=NOW)
+ assert (out["failed_request"], out["fetched_not_written"]) == ("M2SL", [])
+ assert (out["upstream_failures_logged"], out["upstream_failures_not_logged"]) == (
+ ["NOSUCHSERIES"], [])
+ assert _rows(store, "SELECT request, status FROM history_backfills ORDER BY capture_id") == [
+ ("WALCL", "ok"), ("NOSUCHSERIES", "error")]
+ assert out["collected_at"] == NOW_ISO
+
+
+async def test_point_cap_gaps_say_which_values_no_backfill_can_load(
+ fetcher, store, monkeypatch
+) -> None:
+ """BF-3. Kills: every truncation reported as the series cap (budget flag
+ dropped), and the old "pass a later start or split the call" advice."""
+ monkeypatch.setattr(hb, "MAX_POINTS", 5)
+ with respx.mock:
+ _fred_route()
+ capped = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ assert ("Point cap: backfill:fred:WALCL: 4 older value(s) before 2026-09-16 cannot be "
+ "loaded by a backfill, which keeps only the newest 5 values of a series."
+ ) in capped["data_gaps"]
+ assert not any("later start" in g for g in capped["data_gaps"])
+ monkeypatch.setattr(hb, "MAX_POINTS", 20_000)
+ monkeypatch.setattr(hb, "MAX_POINTS_PER_CALL", 12)
+ with respx.mock:
+ _fred_route()
+ budget = await hb.backfill_fred(fetcher, store, ["WALCL", "RRPONTSYD"], now=NOW + 60)
+ assert ("Point cap: backfill:fred:RRPONTSYD: 40 older value(s) before 2026-10-14 were not "
+ "loaded because this call's 12-point budget ran out; backfill it in a call of "
+ "its own.") in budget["data_gaps"]
+ assert _series(budget, "RRPONTSYD")["truncated_by"] == "call budget"
+
+
[email protected]("order", [["NOSUCHSERIES", "WALCL"], ["WALCL", "NOSUCHSERIES"]])
+async def test_health_reports_a_partial_failure_in_either_order(fetcher, store, order) -> None:
+ """BF-4. Kills: _backfill_row taking the last-written capture's status."""
+ _fred_route()
+ await hb.backfill_fred(fetcher, store, order, now=NOW)
+ (row,) = store.collection_health([], now=NOW)["backfills"]
+ assert (row["last_status"], row["last_run_requests"], row["last_run_failed"]) == ("error", 2, 1)
+ assert "NOSUCHSERIES" in row["last_reason"]
+
+
+async def test_ecb_stale_cache_copy_is_refused(fetcher, store) -> None:
+ """BF-5 / F1. Kills: the ECB stale check (`if stale:`) switched off."""
+ fetcher.cache.set(f"liquidity:ecb:ILM:{liquidity._ECB_EUROSYSTEM_KEY}:0:None", _ILM, -60)
+ respx.get(_ILM_URL).mock(return_value=httpx.Response(503, text="maintenance"))
+ out = await hb.backfill_ecb(fetcher, store, [_ILM_KEY], 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_change_flag_compares_runs_with_the_same_start_only(fetcher, store) -> None:
+ """BF-5 / F3. Kills: `start IS ?` dropped from the previous-run lookup."""
+ _fred_route()
+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ windowed = await hb.backfill_fred(fetcher, store, ["WALCL"], "2026-10-01", now=NOW + 10)
+ assert windowed["requests"][0]["payload_changed"] is None # first run with this start
+ assert store.capture_history("backfill:fred")["captures"][0]["change"] == "first"
+ again = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 20)
+ assert again["requests"][0]["payload_changed"] is False
+ assert again["requests"][0]["previous_backfill_at"] == NOW_ISO
+
+
+async def test_ecb_quarters_are_dated_by_the_period_end(fetcher, store) -> None:
+ """BF-5 / F8. Kills: the period_end fallback for other periods dropped
+ (or reading the period id instead)."""
+ respx.route(host="data-api.ecb.europa.eu").mock(side_effect=_ecb_honouring_start(_quarterly_bsi()))
+ out = await hb.backfill_ecb(fetcher, store, [_Q_M3], now=NOW)
+ assert "error" not in out
+ assert _m3_rows(store, _Q_M3) == [
+ ("2025-12-31", 17611985.0), ("2026-03-31", 17615092.0), ("2026-06-30", 17646463.0)]
+
+
+async def test_ecb_start_keeps_periods_dated_on_or_after_it(fetcher, store) -> None:
+ """F13. Kills: no lookback (startPeriod = start), and no client-side cut."""
+ route = respx.route(host="data-api.ecb.europa.eu")
+ route.mock(side_effect=_ecb_honouring_start(_ILM))
+ # 2026-W39 runs 09-21 to 09-27 and is dated 09-27, on or after 09-22.
+ out = await hb.backfill_ecb(fetcher, store, [_ILM_KEY], "2026-09-22", now=NOW)
+ assert "startPeriod=2026-09-16" in str(route.calls.last.request.url)
+ assert [r[0] for r in _rows(store, "SELECT observed_at FROM history_observations "
+ "ORDER BY observed_at")] == [
+ "2026-09-27", "2026-10-04", "2026-10-11"]
+ assert _series(out, _ILM_KEY)["first_observed_at"] == "2026-09-27"
+ route.side_effect = _ecb_honouring_start(_quarterly_bsi())
+ # 2026-Q1 (dated 03-31) is returned for the early request, then cut.
+ q = await hb.backfill_ecb(fetcher, store, [_Q_M3], "2026-04-01", now=NOW + 10)
+ assert "startPeriod=2025-12-30" in str(route.calls.last.request.url)
+ assert _m3_rows(store, _Q_M3) == [("2026-06-30", 17646463.0)]
+ assert q["requests"][0]["status"] == "ok"
+ q2 = await hb.backfill_ecb(fetcher, store, [_Q_M3], "2026-02-15", now=NOW + 20)
+ assert [s for s in q2["requests"][0]["series"]
+ if s["series_key"] == f"backfill:ecb:{_Q_M3}"][0]["loaded"] == 2
+
+
+async def test_ecb_plus_codes_that_match_no_series_are_named(fetcher, store) -> None:
+ """BF-6. Kills: _unmatched_codes returning nothing."""
+ m30_only = copy.deepcopy(_BSI)
+ m30_only["dataSets"][0]["series"] = {
+ k: v for k, v in m30_only["dataSets"][0]["series"].items()
+ if k == "0:0:0:0:2:0:0:0:0:0:0"
+ } # variant: only the M3 stock series answers
+ route = respx.route(host="data-api.ecb.europa.eu")
+ route.mock(return_value=httpx.Response(200, json=m30_only))
+ key = "BSI.M.U2.Y.V.M30+M3Q.X.1.U2.2300.Z01.E"
+ out = await hb.backfill_ecb(fetcher, store, [key], now=NOW)
+ assert f"{key}: '+' alternative(s) that matched no series: M3Q" in out["data_gaps"]
+ assert out["requests"][0]["status"] == "ok"
+ route.return_value = httpx.Response(200, json=_BSI)
+ full = await hb.backfill_ecb(fetcher, store, [_BSI_KEY], now=NOW + 10)
+ assert not any("matched no series" in g for g in full["data_gaps"]) # all 7 codes answer
+
+
+async def test_values_the_publisher_no_longer_serves_are_reported(fetcher, store) -> None:
+ """BF-7. Kills: the absent-from-response comparison removed."""
+ route = _fred_route()
+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ # Variant of the real CSV: 2026-09-02 withdrawn, 2026-09-09 now ".".
+ body = _FRED["WALCL"].replace("2026-09-02,6737204\n", "").replace(
+ "2026-09-09,6740619", "2026-09-09,.")
+ assert body.count("\n") == _FRED["WALCL"].count("\n") - 1
+ fetcher.cache.delete("liquidity:fred:WALCL")
+ route.side_effect = _fred_responder({"WALCL": httpx.Response(200, text=body)})
+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 60)
+ s = _series(out, "WALCL")
+ assert (s["absent_from_response"], s["absent_first"], s["absent_last"]) == (
+ 2, "2026-09-02", "2026-09-09")
+ assert out["totals"]["absent_from_response"] == 2
+ assert any(g.startswith("backfill:fred:WALCL: 2 stored value(s) from 2026-09-02 to "
+ "2026-09-09 are absent") for g in out["data_gaps"])
+
+
+async def test_backfill_payload_bodies_are_a_summary(fetcher, store) -> None:
+ """BF-8. Kills: the full response stored as the body (replay size grows
+ with the series)."""
+ rows = "\n".join(f"{date_}, {i}" for i, date_ in enumerate(
+ datetime.fromtimestamp(NOW - d * 86400, tz=timezone.utc).date().isoformat()
+ for d in range(15_000, 0, -1)))
+ big = "observation_date,DFFX\n" + rows.replace(", ", ",") + "\n" # synthetic, 15,000 rows
+ _fred_route({"DFFX": httpx.Response(200, text=big)})
+ out = await hb.backfill_fred(fetcher, store, ["DFFX"], now=NOW)
+ assert _series(out, "DFFX")["loaded"] == 15_000
+ cap_id = out["requests"][0]["capture_id"]
+ replay = store.capture_history("backfill:fred", capture_id=cap_id)["capture"]["payload"]
+ assert replay["body"] == hb.BODY_NOTE and "rows" not in replay
+ assert replay["series"][0]["points_in_response"] == 15_000
+ assert len(json.dumps(replay)) < 2_000
+ (logged,) = _rows(store, "SELECT payload_hash FROM history_backfills WHERE capture_id = ?",
+ cap_id)
+ assert replay["payload_hash"] == logged[0] and len(logged[0]) == 64 # the full body's hash
+
+
+async def test_one_transaction_per_request(fetcher, store, monkeypatch) -> None:
+ """F2. Kills: a commit inside store_request before the observations."""
+
+ def _boom(*args, **kwargs):
+ raise sqlite3.OperationalError("disk I/O error")
+
+ monkeypatch.setattr(HistoryStore, "_store_observations", _boom)
+ _fred_route()
+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ assert out["error"].startswith("history store write failed")
+ for table in ("history_captures", "history_payloads", "history_backfills"):
+ assert _rows(store, f"SELECT COUNT(*) FROM {table}") == [(0,)], table
+
+
+async def test_previous_run_is_the_latest_ok_run(fetcher, store) -> None:
+ """F3. Kills: `status = 'ok'` dropped (a failed run becomes the previous
+ one), and ORDER BY ran_at ASC (the oldest run becomes the previous one)."""
+ revised = _FRED["WALCL"].replace("2026-10-07,6747560", "2026-10-07,6747561")
+ with respx.mock:
+ route = _fred_route()
+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW) # A
+ fetcher.cache.delete("liquidity:fred:WALCL")
+ route.side_effect = _fred_responder({"WALCL": httpx.Response(500, text="down")})
+ failed = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 10)
+ assert failed["requests"][0]["status"] == "error"
+ route.side_effect = _fred_responder({"WALCL": httpx.Response(200, text=revised)})
+ b1 = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 20) # B
+ b2 = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 30) # B again
+ assert b1["requests"][0]["payload_changed"] is True
+ assert b1["requests"][0]["previous_backfill_at"] == NOW_ISO # not the failed run
+ assert b2["requests"][0]["payload_changed"] is False
+ assert b2["requests"][0]["previous_backfill_at"] == _iso_at(NOW + 20)
+
+
+async def test_history_days_zero_keeps_the_backfill_log(fetcher, store, monkeypatch) -> None:
+ """F3. Kills: `history_days > 0` loosened to `>= 0` (0 = keep forever)."""
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_DAYS", "0")
+ _fred_route()
+ await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ later = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW + 400 * 86400)
+ assert later["pruned"]["backfill_log"] == 0 and later["pruned"]["observations"] == 0
+ assert later["requests"][0]["payload_changed"] is False
+
+
+async def test_copy_fetched_at_is_the_copys_own_fetch_time(fetcher, store) -> None:
+ """F4. Kills: _copy_at returning the read time instead of created_at."""
+ route = _fred_route()
+ fetcher.cache.set("liquidity:fred:WALCL", _FRED["WALCL"], 3600)
+ fetched = time.time() - 1800
+ fetcher.cache._get_conn().execute(
+ "UPDATE cache SET created_at = ? WHERE key = 'liquidity:fred:WALCL'", (fetched,))
+ fetcher.cache._get_conn().commit()
+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], now=NOW)
+ assert route.call_count == 0 # the cached copy was read
+ assert out["requests"][0]["copy_fetched_at"] == _iso_at(fetched)
+
+
+async def test_capture_row_carries_the_call_stamp(fetcher, store) -> None:
+ """F5. Kills: the ok capture stamped with time.time() instead of the
+ call's collected_at."""
+ _fred_route()
+ await hb.backfill_fred(fetcher, store, ["WALCL", "M2SL"], now=NOW)
+ caps = store.capture_history("backfill:fred")["captures"]
+ assert [c["collected_at"] for c in caps] == [NOW_ISO, NOW_ISO]
+
+
+def test_cli_partial_failure_exits_1_and_health_says_so(cli_env) -> None:
+ """F6, and BF-4 on the CLI. Kills: the exit check reduced to
+ `"error" in data`, and health printing only the last capture's status."""
+ _fred_route()
+ out = _invoke("history", "backfill", "fred", "WALCL", "NOSUCHSERIES")
+ assert out.exit_code == 1 and "backfill:fred:WALCL" in out.output
+ health = _invoke("history", "health").output
+ assert "(error, 1 of 2 request(s) failed)" in health
+ assert "Last run failed: FRED graph CSV for NOSUCHSERIES" in health
+
+
+async def test_start_on_an_observation_date_keeps_it(fetcher, store) -> None:
+ """F7. Kills: `d >= start_d` changed to `d > start_d`."""
+ _fred_route()
+ out = await hb.backfill_fred(fetcher, store, ["WALCL"], "2026-10-07", now=NOW)
+ s = _series(out, "WALCL")
+ assert (s["loaded"], s["first_observed_at"]) == (2, "2026-10-07")
+
+
+async def test_caps_accept_exactly_the_documented_maximum(fetcher, store) -> None:
+ """F9. Kills: `>` changed to `>=` for 5 FRED ids, 2 ECB keys and 20
+ combinations."""
+ _fred_route()
+ five = await hb.backfill_fred(fetcher, store, ["WALCL", "M2SL", "RRPONTSYD", "AAA", "BBB"],
+ now=NOW)
+ assert len(five["requests"]) == 5 and "at most" not in str(five.get("error"))
+ ecb = respx.route(host="data-api.ecb.europa.eu").mock(
+ return_value=httpx.Response(200, json=_ILM))
+ two = await hb.backfill_ecb(
+ fetcher, store, [_ILM_KEY, "ILM.W.U2.C.T000000.Z5.Z01+Z06"], now=NOW + 10)
+ assert len(two["requests"]) == 2 and "error" not in two
+ twenty = "BSI.M.U2.Y.V.M10+M20+M30+M3Q+M3R.X.1+4+I+X.U2.2300.Z01.E" # 5 x 4 = 20
+ out = await hb.backfill_ecb(fetcher, store, [twenty], now=NOW + 20)
+ assert out["requests"] and "combinations" not in str(out.get("error"))
+ assert ecb.call_count == 3
+
+
+async def test_ecb_keys_repeated_in_any_case_are_one_request(fetcher, store) -> None:
+ """F10. Kills: the ECB dict.fromkeys dedupe removed."""
+ route = respx.get(_ILM_URL).mock(return_value=httpx.Response(200, json=_ILM))
+ out = await hb.backfill_ecb(
+ fetcher, store, [_ILM_KEY, "ilm." + liquidity._ECB_EUROSYSTEM_KEY], now=NOW)
+ assert [r["request"] for r in out["requests"]] == [_ILM_KEY]
+ assert route.call_count == 1
+
+
+def test_tool_description_states_what_a_capture_and_missing_count_are() -> None:
+ """BF-9. Kills: the old "one capture per series" / "missing values are
+ skipped and counted" wording."""
+ (tool,) = _backfill_tools().TOOLS
+ assert "one capture per request (a FRED id, or an ECB key that may match" in tool.description
+ assert "ECB missing values cannot be counted (null)" in tool.description
+ assert "one capture per series" not in tool.description
diff --git a/src/world_intel_mcp/tools/history_backfill.py b/src/world_intel_mcp/tools/history_backfill.py
index 7db2aa6..8e47589 100644
--- a/src/world_intel_mcp/tools/history_backfill.py
+++ b/src/world_intel_mcp/tools/history_backfill.py
@@ -22,12 +22,14 @@ TOOLS: list[Tool] = [
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 "
+ "request (a FRED id, or an ECB key that may match several 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 "
+ "values, and a changed value is a revision. FRED missing values are skipped and "
+ "counted; ECB missing values cannot be counted (null). 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 "