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.

History honesty: stale serves, live-only health, caps, lost-cycle record

Phoenix Agent (mac-studio)c9f01c164152
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 739fd6a..b772e54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,8 +9,24 @@
with its reason and no record count, never an ok capture with zero
records. An empty payload is degraded, because a quiet period and a
silent upstream failure look the same.
+- A run that any upstream fetch answered from an expired cached copy is a
+ stale-cache replay: degraded, with the reason `served stale cache` and
+ the copy's age. The collector reads this from a per-task log the fetcher
+ keeps (`fetcher.recording_stale_serves()`, opened once per source task),
+ because most source modules rebuild their payload and drop the fetcher's
+ `_stale` marker. A replay's observations are counted but not stored: a
+ stale replay is not a new observation. A live capture that is degraded
+ for another reason (empty, partial, marked degraded) still stores the
+ points it has.
- Payload bodies are kept once per distinct payload as compressed JSON
- (top-level fetch-time stamps are ignored when hashing). Retention, each
+ (top-level fetch-time stamps and the stale markers are ignored when
+ hashing, so a fresh and a stale copy of the same data read unchanged).
+ A body over `WORLD_INTEL_HISTORY_MAX_BODY_BYTES` (default 4 MiB of
+ JSON, 0 = no cap) is not stored: its capture keeps the hash and says
+ why. Replay returns at most `WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES`
+ (default 256 KiB, 0 = no cap) and an outline of the top-level keys
+ beyond that; replaying a capture whose body an earlier capture stored
+ names that capture's time. Retention, each
0 = keep forever: `WORLD_INTEL_HISTORY_PAYLOAD_DAYS` (default 7) for
bodies, `WORLD_INTEL_HISTORY_CAPTURE_DAYS` (default 30) for the run log,
`WORLD_INTEL_HISTORY_DAYS` (default 365) for observations. Measured over
@@ -26,20 +42,52 @@
NOAA Kp, USGS per-event magnitude, FRED-sourced central bank rates
(curated rows are skipped), Yahoo index and commodity quotes (null
`observed_at`: the payload carries no quote time).
- `history.register_extractor()` is the public API for new sources.
+ `history.register_extractor()` is the public API for new sources; its
+ `expected=N` declares how many points a complete payload yields. The
+ Yahoo quote sources declare one per default symbol, so a run where some
+ symbols did not answer is degraded as `partial: X of N expected series`.
+ Observation dates must name a real calendar period (`2026-02-30` and
+ `0000` are rejected).
- MCP tools `intel_collection_health`, `intel_capture_history`,
`intel_series_history` and `intel_revisions`, and the CLI group
`intel history health|captures|series|revisions`. History accrues only
while the collector runs.
+- Collection health counts a success only from a live capture. A source
+ served from stale cache reads `stale`, keeps its last live success time
+ and goes overdue on schedule; consecutive failures count errors and
+ stale replays since the last live capture. Health also reports the last
+ fully ok capture (`last_ok_at`, `last_ok_age_s`; a Last ok column in
+ `intel history health`), `data_gaps` (an empty run log names the file
+ it read), lost history writes and what it cannot prove.
+ `intel_revisions` reports how many observations and dated series it
+ checked, and its data gaps.
- The collector records every source outcome of a cycle in one
transaction. Its summary gains a `history` key (and the CLI summary a
- History line); a history write failure is reported there and in the
- log, and never fails the cycle.
+ History line). A failed history write is retried once; when the retry
+ fails too, the lost cycle is appended to
+ `<cache db>-history-write-failures.jsonl` beside the DB (newest 500
+ kept), and collection health reports it with the sources it covered. A
+ history write failure never fails the cycle.
- Expected cadence for health is 300 s (the shipped plist interval);
`WORLD_INTEL_HISTORY_CADENCE_S` and
`WORLD_INTEL_HISTORY_CADENCES=source=seconds,...` override it.
+### Fixed
+- A collector source task that ended in a `BaseException` that is not an
+ `Exception` (for example a cancelled task) made the cycle raise a
+ `TypeError` while tallying results, after the fetches finished, so that
+ cycle returned no summary and recorded no history. It now counts as a
+ failure and is recorded as an error capture.
+
### Notes
+- Known limits, stated in `intel_collection_health`'s `cannot_prove` and
+ the `history` module docs: stale data are seen only through the
+ fetcher's expired-cache fallback or a top-level `_stale` marker (a
+ source that awaits a fetch another task started reads live);
+ observation retention prunes by collection time, so a value unchanged
+ for longer than `WORLD_INTEL_HISTORY_DAYS` is stored again and its first
+ sighting reads as that later capture; a collector and a server that
+ resolve different cache paths keep different run logs.
- The cycle summary's `successes` still counts a source that returned
`{"error": ...}` (unchanged, pinned by an existing test); that run's
history capture is an error.
diff --git a/README.md b/README.md
index 6cf9025..0ac37f6 100644
--- a/README.md
+++ b/README.md
@@ -513,14 +513,14 @@ 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).
+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). A run answered from an expired cached copy is recorded as a stale-cache replay: it never counts as a success, and its observations are not stored, because a replay is not a new observation.
| Tool | Description |
|------|-------------|
-| `intel_collection_health` | Per-source health from the collector's run log: last attempt, last success, consecutive failures, overdue against the expected cadence, never-run sources, history storage size; states what it cannot prove (a fresh capture does not mean upstream observations are current) |
-| `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_collection_health` | Per-source health from the collector's run log: last attempt, last live success (a source served from stale cache reads `stale` and goes overdue), last fully ok capture, consecutive failures, overdue against the expected cadence, never-run sources, lost history writes, history storage size; states its data gaps and what it cannot prove (a fresh capture does not mean upstream observations are current) |
+| `intel_capture_history` | A source's earlier captures (ok / degraded / error with reason, such as `served stale cache`, duration, record count) and whether each changed from the previous one; `capture_id` replays one stored payload (an outline of its keys past the replay cap) |
| `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_revisions` | Values for the same `observed_at` that a later capture changed (USGS magnitude revisions, NOAA Kp updates), with how many observations and dated series were checked |
---
diff --git a/ROADMAP.md b/ROADMAP.md
index c22ef24..4c79a55 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -571,9 +571,9 @@ 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 | 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 | 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, body and replay size caps, and `register_extractor()` done (`history.py`; extractors for Kp, USGS magnitudes, FRED central bank rates, Yahoo quotes); points from stale-cache replays are not stored; backfill not done |
+| 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`); a replay names the capture that stored its body, revisions say what they checked |
+| 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`): a success counts only from a live capture, so a source the fetcher answers from expired cache reads `stale` and goes overdue on schedule; lost history writes are recorded and reported. Stale data that bypass the fetcher's expired-cache fallback are not seen, and health says so |
| 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 | :red_circle: |
| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :red_circle: |
| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :red_circle: |
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index 00a29ce..6de2132 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -2674,18 +2674,21 @@ def history_health(ctx: click.Context, source: str | None) -> None:
table.add_column("State")
table.add_column("Last attempt")
table.add_column("Last success")
+ table.add_column("Last ok")
table.add_column("Fails", justify="right")
table.add_column("Latest observed")
table.add_column("Reason")
styles = {"ok": "green", "degraded": "yellow", "never_run": "dim"}
for row in data["sources"]:
state = row["state"]
- label = f"{state}, overdue" if state == "failing" and row.get("overdue") else state
+ overdue = state in ("failing", "stale") and row.get("overdue")
+ label = f"{state}, overdue" if overdue else state
table.add_row(
_cell(row["source"]),
Text(label, style=styles.get(state, "red")),
_cell(row.get("last_attempt_at") or "-"),
_cell(row.get("last_success_at") or "-"),
+ _cell(row.get("last_ok_at") or "-"),
str(row.get("consecutive_failures", "-")),
_cell(row.get("latest_observed_at") or "-"),
_cell(row.get("last_reason") or ""),
@@ -2699,6 +2702,7 @@ def history_health(ctx: click.Context, source: str | None) -> None:
f"({storage['payload_bytes_compressed']:,} bytes compressed), "
f"{storage['observations']} observations in {storage['series']} series."
)
+ _print_data_gaps(data)
for line in data["cannot_prove"]:
console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")
@@ -2732,6 +2736,8 @@ def history_captures(
console.print(f"[yellow]Gap:[/yellow] {escape(cap['payload_note'])}")
if cap.get("payload") is not None:
_print_json(cap["payload"])
+ elif cap.get("payload_outline") is not None:
+ _print_json(cap["payload_outline"])
return
captures = data["captures"]
@@ -2860,6 +2866,7 @@ def history_revisions(
rev["revised_collected_at"],
)
console.print(table)
+ _print_data_gaps(data)
for line in data["cannot_prove"]:
console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")
diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.py
index b9ed67f..4224d9c 100644
--- a/src/world_intel_mcp/collector.py
+++ b/src/world_intel_mcp/collector.py
@@ -7,7 +7,11 @@ ensuring data accumulates 24/7 for semantic search and historical analysis.
Every source outcome of a cycle (ok, degraded or error, with duration and
payload hash) is also written to the history store (``history.py``) in the
cache DB, in one transaction per cycle. That run log is what
-``intel_collection_health`` and the other history tools read.
+``intel_collection_health`` and the other history tools read. Each source
+runs inside ``fetcher.recording_stale_serves()``, so a run answered from
+expired cache is recorded as a stale-cache replay even when the source
+module dropped the fetcher's ``_stale`` marker. A failed write is retried
+once, then kept as a lost-cycle record beside the DB.
Usage:
intel-collector # Single collection cycle
@@ -37,8 +41,8 @@ logger = logging.getLogger("world-intel-collector")
from .cache import Cache
from .circuit_breaker import CircuitBreaker
-from .fetcher import Fetcher
-from .history import HistoryStore, SourceOutcome
+from .fetcher import Fetcher, recording_stale_serves
+from .history import HistoryStore, SourceOutcome, record_write_failure
from .vector_store import VectorStore
# All fetchable sources grouped by domain.
@@ -218,8 +222,9 @@ def _import_fetch_fn(module_path: str, fn_name: str):
def _record_history(fetcher: Fetcher, outcomes: list) -> dict:
"""Write one cycle's outcomes to the history store in the fetcher's
- cache DB. A history failure is reported in the cycle summary and the
- log; it never fails the cycle itself."""
+ cache DB. A history failure never fails the cycle itself: it is
+ reported in the cycle summary and the log, and kept as a lost-cycle
+ record beside the DB that ``intel_collection_health`` reports."""
db_path = getattr(getattr(fetcher, "cache", None), "db_path", None)
if db_path is None:
logger.warning("History not recorded: fetcher has no cache db_path")
@@ -227,21 +232,34 @@ def _record_history(fetcher: Fetcher, outcomes: list) -> dict:
"recorded": 0,
"error": "fetcher has no cache db_path; history not recorded",
}
- try:
- store = HistoryStore(db_path)
+ for attempt in (1, 2):
try:
- return store.record_cycle(outcomes)
- finally:
- store.close()
- except (sqlite3.Error, OSError) as exc:
- logger.warning("History write failed: %s", exc)
- return {"recorded": 0, "error": f"history write failed: {exc}"}
- except Exception as exc: # a history bug must not cost the cycle
- logger.exception("History write failed unexpectedly")
- return {
- "recorded": 0,
- "error": f"history write failed: {type(exc).__name__}: {exc}",
- }
+ store = HistoryStore(db_path)
+ try:
+ return store.record_cycle(outcomes)
+ finally:
+ store.close()
+ except sqlite3.OperationalError as exc:
+ # Usually another writer held the lock past the busy timeout.
+ # The cycle's transaction rolled back, so a retry cannot write
+ # it twice.
+ if attempt == 1:
+ logger.warning("History write failed (%s); retrying once", exc)
+ continue
+ logger.warning("History write failed: %s", exc)
+ failure = {"recorded": 0, "error": f"history write failed: {exc}"}
+ except (sqlite3.Error, OSError) as exc:
+ logger.warning("History write failed: %s", exc)
+ failure = {"recorded": 0, "error": f"history write failed: {exc}"}
+ except Exception as exc: # a history bug must not cost the cycle
+ logger.exception("History write failed unexpectedly")
+ failure = {
+ "recorded": 0,
+ "error": f"history write failed: {type(exc).__name__}: {exc}",
+ }
+ break
+ record_write_failure(db_path, outcomes, failure["error"])
+ return failure
async def collect_once(
@@ -261,20 +279,26 @@ async def collect_once(
# Per-source wall time and finish time, for the history run log.
timings: dict[str, tuple[float, float]] = {}
+ # Per-source stale-cache serves. Sources run concurrently and name
+ # their fetches differently ("usgs" for earthquakes), so each run gets
+ # its own task-scoped log rather than a per-fetch-source counter.
+ stale_serves: dict[str, list] = {}
async def _fetch_one(name: str, module_path: str, fn_name: str, kwargs: dict):
budget = SOURCE_TIMEOUTS.get(name, timeout)
t0 = time.monotonic()
- try:
- fn = _import_fetch_fn(module_path, fn_name)
- result = await asyncio.wait_for(fn(fetcher, **kwargs), timeout=budget)
- return name, result, None
- except asyncio.TimeoutError:
- return name, None, f"timeout ({budget}s)"
- except Exception as exc:
- return name, None, str(exc)[:120]
- finally:
- timings[name] = (time.monotonic() - t0, time.time())
+ with recording_stale_serves() as served:
+ stale_serves[name] = served
+ try:
+ fn = _import_fetch_fn(module_path, fn_name)
+ result = await asyncio.wait_for(fn(fetcher, **kwargs), timeout=budget)
+ return name, result, None
+ except asyncio.TimeoutError:
+ return name, None, f"timeout ({budget}s)"
+ except Exception as exc:
+ return name, None, str(exc)[:120]
+ finally:
+ timings[name] = (time.monotonic() - t0, time.time())
tasks = [_fetch_one(name, mod, fn, kw) for name, mod, fn, kw in sources_to_run]
@@ -287,20 +311,25 @@ async def collect_once(
for (source_name, _, _, _), item in zip(sources_to_run, results):
duration, finished = timings.get(source_name, (None, time.time()))
+ served = tuple(stale_serves.get(source_name, ()))
if isinstance(item, BaseException):
reason = str(item)[:500] or repr(item)
outcomes.append(
- SourceOutcome(source_name, finished, duration, error=reason)
+ SourceOutcome(source_name, finished, duration, error=reason,
+ stale_serves=served)
)
else:
outcomes.append(
SourceOutcome(
- source_name, finished, duration, payload=item[1], error=item[2]
+ source_name, finished, duration, payload=item[1], error=item[2],
+ stale_serves=served,
)
)
for item in results:
- if isinstance(item, Exception):
+ # BaseException, not Exception: gather() also returns a source's
+ # CancelledError or other BaseException, which cannot be unpacked.
+ if isinstance(item, BaseException):
failures += 1
errors.append(str(item)[:100])
continue
diff --git a/src/world_intel_mcp/fetcher.py b/src/world_intel_mcp/fetcher.py
index 5b3afad..a3f7f52 100644
--- a/src/world_intel_mcp/fetcher.py
+++ b/src/world_intel_mcp/fetcher.py
@@ -3,13 +3,18 @@
All external HTTP calls in world-intel-mcp go through this module.
Stale-data fallback: when an API call fails, the last-known-good cached
response is returned (marked with _stale=True) so dashboards never go blank.
+Source modules that rebuild their response drop that marker, so every
+stale serve is also appended to the caller's ``recording_stale_serves()``
+log, which the collector reads per source run.
"""
import asyncio
+import contextlib
+import contextvars
import logging
import time
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Iterator
import httpx
@@ -64,6 +69,45 @@ class BinaryResult:
@property
def ok(self) -> bool:
return self.content is not None
+
+
+@dataclass(frozen=True)
+class StaleServe:
+ """One expired cache entry served because the live fetch failed."""
+
+ source: str
+ cache_key: str
+ age_seconds: float
+
+
+# The logs of every recording_stale_serves() block active in this context.
+# asyncio tasks inherit a copy of the context, so a task started inside a
+# block (asyncio.gather of sub-fetches) appends to the same lists.
+_STALE_SERVE_LOGS: contextvars.ContextVar[tuple[list[StaleServe], ...]] = (
+ contextvars.ContextVar("world_intel_stale_serve_logs", default=())
+)
+
+
+def recording_stale_serves() -> Iterator[list[StaleServe]]:
+ """Collect the stale-cache serves made while the block runs.
+
+ Scoped to the current task and the tasks it starts, so concurrent
+ callers (one per collector source, one per MCP tool call) each see
+ only their own serves, whatever ``source`` name the fetches used.
+ Blocks nest: an outer block also sees an inner block's serves. A
+ caller that awaits a fetch another task started does not see that
+ task's serves.
+ """
+ served: list[StaleServe] = []
+ outer = _STALE_SERVE_LOGS.get()
+ reset_point = _STALE_SERVE_LOGS.set(outer + (served,))
+ try:
+ yield served
+ finally:
+ _STALE_SERVE_LOGS.reset(reset_point)
+
+
_source_locks: dict[str, asyncio.Lock] = {}
_source_last_call: dict[str, float] = {}
@@ -331,7 +375,8 @@ class Fetcher:
response instead of receiving it silently. Non-dict responses
(raw text/XML, lists) can't carry an inline marker the same way,
so the circuit breaker's per-source stale-serve count is the
- signal there.
+ signal there. Every serve, whatever its type, is also appended to
+ each active ``recording_stale_serves()`` log.
"""
meta = self.cache.get_stale_meta(cache_key)
if meta is None:
@@ -344,6 +389,9 @@ class Fetcher:
cache_key,
age_seconds,
)
+ serve = StaleServe(source, cache_key, round(age_seconds, 1))
+ for log in _STALE_SERVE_LOGS.get():
+ log.append(serve)
if isinstance(value, dict):
value["_stale"] = True
value["_stale_age_seconds"] = round(age_seconds, 1)
diff --git a/src/world_intel_mcp/history.py b/src/world_intel_mcp/history.py
index 260f6ef..09fd47f 100644
--- a/src/world_intel_mcp/history.py
+++ b/src/world_intel_mcp/history.py
@@ -12,10 +12,21 @@ settled on, fallback path included):
``error`` row with a reason and a null record count, never an ``ok``
row with zero records. A payload with no records is ``degraded``,
because a quiet period and a silent upstream failure look the same.
+ A run that was served an expired cached copy for any upstream fetch is
+ a stale-cache replay: ``degraded`` with a reason starting ``served
+ stale cache`` (with the copy's age). The collector reads that from the
+ fetcher's per-task log (``fetcher.recording_stale_serves``), because
+ most source modules rebuild their dict and drop the fetcher's
+ ``_stale`` marker; a top-level ``_stale`` marker counts too.
- ``history_payloads``: the payload body as zlib-compressed JSON, stored
once per ``(source, payload_hash)``. The hash ignores the top-level
fetch-time stamps in ``VOLATILE_KEYS`` (they change on every call while
- the data do not); the body kept is the first capture's.
+ the data do not); the body kept is the first capture's, and replaying a
+ later capture says so. A body over ``WORLD_INTEL_HISTORY_MAX_BODY_BYTES``
+ (default 4 MiB of JSON, ``0`` = no cap) is not stored: the capture keeps
+ its hash and a reason. Replay returns at most
+ ``WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES`` (default 256 KiB, ``0`` = no
+ cap) and an outline of the top-level keys beyond that.
- ``history_observations``: dated numeric points pulled out of payloads by
per-source extractors, each with three dates. ``observed_at`` is the
period or instant the value describes, taken from the payload; when a
@@ -24,10 +35,19 @@ settled on, fallback path included):
one, else NULL. ``collected_at`` is when this server saved the capture.
A point is stored when it is new or its value differs from the last
stored value for the same series and ``observed_at``, so successive
- rows for one ``(series_key, observed_at)`` are revisions.
+ rows for one ``(series_key, observed_at)`` are revisions. Points are
+ stored from live captures only: a stale-cache replay is not a new
+ observation, so its points are extracted and counted but not stored. A
+ live capture that is degraded for another reason (empty, partial,
+ marked degraded) still stores the points it has.
History accrues only while the collector runs: nothing is backfilled, and
-a source the collector does not run reads ``never_run``.
+a source the collector does not run reads ``never_run``. Health counts a
+success only from a live capture, so a source served from stale cache
+reads ``stale`` and goes overdue on schedule. When a cycle's write fails
+twice (a locked or unwritable DB), the collector appends a record of the
+lost cycle to ``<db>-history-write-failures.jsonl`` beside the DB (newest
+500 kept), which ``collection_health`` reports.
Registering an extractor (the public API)::
@@ -46,7 +66,9 @@ or a non-finite value is skipped and counted in the capture's
``extract_error``. Register at import time of your source module: the
collector imports a source's module before it records that source's
capture. A registered extractor that finds nothing in a non-error payload
-marks the capture ``degraded``.
+marks the capture ``degraded``; pass ``expected=N`` when a
+complete payload yields N points (one per requested symbol), and a
+capture with fewer is ``degraded`` as partial.
Retention, each ``0`` = keep forever, pruned at the end of every recorded
cycle in the same transaction:
@@ -77,9 +99,18 @@ Gaps / not covered:
- ``record_count`` is a size hint (the payload's longest top-level list,
else its integer ``count``), not a semantic count; payloads shaped as
nested dicts read NULL.
-- Degradation is read from top-level ``_stale`` / ``degraded`` markers;
- a source that degrades without marking its payload reads ``ok`` unless
- it is empty or its extractor finds nothing.
+- Stale data are seen only through the fetcher's stale fallback or a
+ top-level ``_stale`` marker. A source that serves old data by other
+ means, or awaits a fetch that another task started, reads live; one
+ that drops part of a failed answer without marking it reads ``ok``
+ unless it is empty, its extractor finds nothing, or fewer points than
+ ``expected`` arrive.
+- Observation retention prunes by ``collected_at``: a value unchanged for
+ longer than ``WORLD_INTEL_HISTORY_DAYS`` is pruned and then stored again
+ at its next capture, so its first sighting reads as that capture.
+- A collector and a server that resolve different cache paths keep
+ different run logs; health then reads ``never_run`` for every source and
+ says where it looked.
"""
from __future__ import annotations
@@ -91,17 +122,35 @@ import math
import os
import re
import sqlite3
+import tempfile
import time
import zlib
from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any, Callable, Iterable
+from .sources.markets import _COMMODITY_SYMBOLS, _DEFAULT_INDEX_SYMBOLS
+
logger = logging.getLogger("world-intel-mcp.history")
-# Top-level keys that carry this server's fetch time, not upstream data.
-VOLATILE_KEYS = frozenset({"timestamp", "fetched_at", "generated_at", "_stale_age_seconds"})
+# Top-level keys that carry this server's fetch time or fetch path, not
+# upstream data.
+VOLATILE_KEYS = frozenset(
+ {"timestamp", "fetched_at", "generated_at", "_stale", "_stale_age_seconds"}
+)
+
+# Reason prefix of a stale-cache replay. Health reads it back from the run
+# log, so stale captures need no column of their own.
+STALE_REASON = "served stale cache"
+# A capture whose payload came live from the upstream: ok, or degraded for
+# any reason but a stale-cache replay. Binds (len(STALE_REASON), STALE_REASON).
+_LIVE_CAPTURE = "status IN ('ok', 'degraded') AND (error IS NULL OR substr(error, 1, ?) != ?)"
+_RAISED = "extractor raised"
+_BODY_NOT_STORED = "payload body not stored"
+
+# How long a history write waits on another writer's lock before failing.
+BUSY_TIMEOUT_S = 5.0
# Expected seconds between collector attempts. The shipped launchd plist
# and the daemon default both run every 300 s; an operator running a
@@ -118,8 +167,16 @@ OVERDUE_MULTIPLE = 3.0
_DEFAULT_PAYLOAD_DAYS = 7.0
_DEFAULT_CAPTURE_DAYS = 30.0
_DEFAULT_HISTORY_DAYS = 365.0
+# No body in the 2026-10-17 three-cycle measurement can have exceeded
+# 1 MiB of JSON (the largest cycle added 958,424 bytes across 10 bodies),
+# so the cap stops a runaway payload, not a real one.
+_DEFAULT_MAX_BODY_BYTES = 4 * 1024 * 1024
+_DEFAULT_REPLAY_MAX_BYTES = 256 * 1024
_MAX_LIMIT = 1000
+_WRITE_FAILURES_SUFFIX = "-history-write-failures.jsonl"
+_WRITE_FAILURES_KEPT = 500
+
HISTORY_ACCRUAL_NOTE = (
"History accrues only while the collector (intel-collector) runs; "
"nothing before its first recorded cycle exists here."
@@ -145,15 +202,22 @@ class Observation:
Extractor = Callable[[Any], Iterable[Observation]]
_EXTRACTORS: dict[str, Extractor] = {}
+_EXPECTED: dict[str, int] = {}
def register_extractor(
- source: str, fn: Extractor | None = None, *, replace: bool = False
+ source: str,
+ fn: Extractor | None = None,
+ *,
+ replace: bool = False,
+ expected: int | None = None,
) -> Any:
"""Register ``fn`` as the extractor for collector source ``source``.
Usable as ``register_extractor("src", fn)`` or as a decorator. A second
registration for the same source raises unless ``replace=True``.
+ ``expected`` is how many valid points a complete payload yields; a
+ capture with fewer is ``degraded`` as partial (its points are stored).
"""
def _register(f: Extractor) -> Extractor:
@@ -161,6 +225,10 @@ def register_extractor(
if existing is not None and existing is not f and not replace:
raise ValueError(f"an extractor is already registered for {source!r}")
_EXTRACTORS[source] = f
+ if expected is None:
+ _EXPECTED.pop(source, None)
+ else:
+ _EXPECTED[source] = expected
return f
return _register(fn) if fn is not None else _register
@@ -171,23 +239,37 @@ def registered_extractors() -> dict[str, Extractor]:
return dict(_EXTRACTORS)
-_DATE_PERIOD = re.compile(r"\d{4}(-\d{2}(-\d{2})?)?")
+_DATE_PERIOD = re.compile(r"(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?")
+
+
+def _valid_period(match: re.Match) -> bool:
+ year, month, day = match.groups()
+ if day is not None:
+ try:
+ date.fromisoformat(match.group(0))
+ except ValueError:
+ return False
+ return True
+ return int(year) >= 1 and (month is None or 1 <= int(month) <= 12)
def normalize_observed_at(value: Any, *, assume_utc: bool = False) -> str | None:
"""Payload date -> stored form, or None when it cannot be read.
- ``YYYY``, ``YYYY-MM`` and ``YYYY-MM-DD`` periods are kept as written.
- An ISO 8601 instant becomes ``YYYY-MM-DDTHH:MM:SSZ`` in UTC. A naive
- instant (no offset) is only accepted with ``assume_utc=True``.
+ ``YYYY``, ``YYYY-MM`` and ``YYYY-MM-DD`` periods are kept as written
+ when they name a real calendar period (year 0001 on, month 01-12, a
+ day that exists). An ISO 8601 instant becomes ``YYYY-MM-DDTHH:MM:SSZ``
+ in UTC. A naive instant (no offset) is only accepted with
+ ``assume_utc=True``.
"""
if value is None or isinstance(value, bool):
return None
text = str(value).strip()
if not text:
return None
- if _DATE_PERIOD.fullmatch(text):
- return text
+ period = _DATE_PERIOD.fullmatch(text)
+ if period:
+ return text if _valid_period(period) else None
try:
parsed = datetime.fromisoformat(text.replace("Z", "+00:00").replace(" ", "T", 1))
except ValueError:
@@ -285,8 +367,15 @@ def _quote_extractor(list_key: str, label_key: str, unit_key: str | None):
return _extract
-register_extractor("market_quotes", _quote_extractor("quotes", "symbol", "currency"))
-register_extractor("commodity_quotes", _quote_extractor("commodities", "name", None))
+# The collector runs both with their defaults: one point per symbol.
+register_extractor(
+ "market_quotes", _quote_extractor("quotes", "symbol", "currency"),
+ expected=len(_DEFAULT_INDEX_SYMBOLS),
+)
+register_extractor(
+ "commodity_quotes", _quote_extractor("commodities", "name", None),
+ expected=len(_COMMODITY_SYMBOLS),
+)
# ---------------------------------------------------------------------------
@@ -296,13 +385,19 @@ register_extractor("commodity_quotes", _quote_extractor("commodities", "name", N
@dataclass
class SourceOutcome:
- """What one collector source run produced, handed to ``record_cycle``."""
+ """What one collector source run produced, handed to ``record_cycle``.
+
+ ``stale_serves`` holds what ``fetcher.recording_stale_serves()`` logged
+ during the run (items with an ``age_seconds``); any entry makes the
+ capture a stale-cache replay.
+ """
source: str
collected_at: float
duration_s: float | None = None
payload: Any = None
error: str | None = None
+ stale_serves: tuple[Any, ...] = ()
@dataclass
@@ -346,7 +441,7 @@ def _extract(source: str, payload: Any) -> tuple[list[Observation], str | None,
raw = list(extractor(payload))
except Exception as exc: # an extractor bug must not lose the capture
logger.warning("History extractor for %s failed: %s", source, exc)
- return [], f"extractor raised: {type(exc).__name__}: {str(exc)[:200]}", None
+ return [], f"{_RAISED}: {type(exc).__name__}: {str(exc)[:200]}", None
valid: list[Observation] = []
skipped = 0
for obs in raw:
@@ -365,8 +460,33 @@ def _extract(source: str, payload: Any) -> tuple[list[Observation], str | None,
return valid, note, len(raw)
+def _stale_reason(outcome: SourceOutcome) -> str | None:
+ """``served stale cache ...`` when any upstream fetch of this run was
+ answered from an expired cached copy, else None."""
+ serves = list(outcome.stale_serves or ())
+ payload = outcome.payload
+ marked = isinstance(payload, dict) and bool(payload.get("_stale"))
+ if not serves and not marked:
+ return None
+ ages = [_finite(getattr(serve, "age_seconds", None)) for serve in serves]
+ if marked:
+ ages.append(_finite(payload.get("_stale_age_seconds")))
+ known = [age for age in ages if age is not None]
+ if len(serves) > 1:
+ return f"{STALE_REASON} for {len(serves)} upstream fetches" + (
+ f" (oldest {max(known)} s)" if known else ""
+ )
+ return f"{STALE_REASON} (age {max(known)} s)" if known else STALE_REASON
+
+
def classify(outcome: SourceOutcome) -> _Classified:
- """Status, reason and observations for one source run."""
+ """Status, reason and observations for one source run.
+
+ ``error`` when the run produced no usable payload. ``degraded`` when it
+ was a stale-cache replay, or live but marked degraded, empty, partial,
+ or without the measures its extractor expects. Otherwise ``ok``. A
+ stale-cache replay keeps its extracted count but no observations.
+ """
if outcome.error is not None:
return _Classified("error", outcome.error[:500], None)
payload = outcome.payload
@@ -377,26 +497,33 @@ def classify(outcome: SourceOutcome) -> _Classified:
count = record_count(payload)
observations, extract_error, extracted = _extract(outcome.source, payload)
- status, reason = "ok", None
- if isinstance(payload, dict) and payload.get("_stale"):
- age = payload.get("_stale_age_seconds")
- status, reason = "degraded", (
- f"served stale cache (age {age} s)" if age is not None else "served stale cache"
- )
- elif isinstance(payload, dict) and (
+ notes = []
+ stale = _stale_reason(outcome)
+ if stale:
+ notes.append(stale)
+ if isinstance(payload, dict) and (
payload.get("degraded") is True or payload.get("status") == "degraded"
):
- status, reason = "degraded", "payload marked degraded"
- elif count == 0:
- status, reason = "degraded", (
+ notes.append("payload marked degraded")
+ expected = _EXPECTED.get(outcome.source)
+ if count == 0:
+ notes.append(
"payload has no records: a quiet period and a silent upstream "
"failure look the same here"
)
elif extracted is not None and not observations:
- status, reason = "degraded", "registered extractor found no measures in this payload" + (
+ notes.append("registered extractor found no measures in this payload" + (
f" ({extract_error})" if extract_error else ""
- )
- return _Classified(status, reason, count, observations, extract_error, extracted)
+ ))
+ elif extracted is not None and expected is not None and len(observations) < expected:
+ notes.append(f"partial: {len(observations)} of {expected} expected series")
+ if stale and observations:
+ notes.append("observations not stored: a stale-cache replay is not a new observation")
+ observations = []
+ reason = "; ".join(notes)[:500] if notes else None
+ return _Classified(
+ "degraded" if notes else "ok", reason, count, observations, extract_error, extracted
+ )
# ---------------------------------------------------------------------------
@@ -428,6 +555,31 @@ def retention_days() -> dict[str, float]:
}
+def _env_bytes(name: str, default: int) -> int:
+ raw = os.environ.get(name)
+ if raw is None or not raw.strip():
+ return default
+ try:
+ value = int(raw)
+ except ValueError:
+ logger.warning("%s=%r is not an integer; using %s", name, raw, default)
+ return default
+ if value < 0:
+ logger.warning("%s=%r must be >= 0; using %s", name, raw, default)
+ return default
+ return value
+
+
+def size_caps() -> dict[str, int]:
+ """Stored-body and replay caps in bytes of JSON; 0 = no cap."""
+ return {
+ "max_body_bytes": _env_bytes("WORLD_INTEL_HISTORY_MAX_BODY_BYTES", _DEFAULT_MAX_BODY_BYTES),
+ "replay_max_bytes": _env_bytes(
+ "WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES", _DEFAULT_REPLAY_MAX_BYTES
+ ),
+ }
+
+
def cadence_config() -> tuple[float, dict[str, float]]:
"""(default cadence, per-source overrides) after env overrides."""
default = DEFAULT_CADENCE_S
@@ -470,15 +622,121 @@ def _clamp(limit: Any, default: int) -> int:
return max(1, min(_MAX_LIMIT, value))
+def write_failures_path(db_path: Path | str) -> Path:
+ """The lost-cycle record file kept beside the history DB."""
+ db_path = Path(db_path)
+ return db_path.with_name(db_path.name + _WRITE_FAILURES_SUFFIX)
+
+
+def record_write_failure(
+ db_path: Path | str, outcomes: Iterable[SourceOutcome], error: str,
+ now: float | None = None,
+) -> Path | None:
+ """Keep a lasting record of a cycle whose history write failed.
+
+ Written beside the DB, not in it (the DB may be what failed), newest
+ ``_WRITE_FAILURES_KEPT`` records kept. Returns the file, or None when
+ it could not be written either; that is logged, and the collector log
+ is then the only trace of the lost cycle.
+ """
+ now = time.time() if now is None else now
+ path = write_failures_path(db_path)
+ record = {
+ "failed_at": _iso(now),
+ "failed_at_ts": round(now, 3),
+ "error": str(error)[:500],
+ "sources": sorted({outcome.source for outcome in outcomes}),
+ }
+ try:
+ lines = path.read_text().splitlines() if path.exists() else []
+ lines = (lines + [json.dumps(record, separators=(",", ":"))])[-_WRITE_FAILURES_KEPT:]
+ partial = path.with_name(path.name + ".tmp")
+ partial.write_text("\n".join(lines) + "\n")
+ os.chmod(partial, 0o600)
+ os.replace(partial, path)
+ except OSError as exc:
+ logger.error("Could not record the history write failure at %s: %s", path, exc)
+ return None
+ return path
+
+
+def read_write_failures(db_path: Path | str, now: float | None = None) -> tuple[list[dict], int]:
+ """(lost-cycle records inside the run-log retention window, unreadable count)."""
+ path = write_failures_path(db_path)
+ try:
+ text = path.read_text()
+ except FileNotFoundError:
+ return [], 0
+ except OSError as exc:
+ logger.warning("Could not read %s: %s", path, exc)
+ return [], 1
+ keep_days = retention_days()["capture_days"]
+ now = time.time() if now is None else now
+ cutoff = now - keep_days * 86400 if keep_days > 0 else None
+ records, unreadable = [], 0
+ for line in text.splitlines():
+ if not line.strip():
+ continue
+ try:
+ record = json.loads(line)
+ failed_at = float(record["failed_at_ts"])
+ except (ValueError, KeyError, TypeError):
+ unreadable += 1
+ continue
+ if cutoff is None or failed_at >= cutoff:
+ records.append(record)
+ return records, unreadable
+
+
+def _unrecorded_attempts(failures: list[dict], source: str, after: float | None) -> int:
+ """Lost cycles that ran ``source`` after its last recorded capture."""
+ count = 0
+ for record in failures:
+ sources = record.get("sources")
+ if not isinstance(sources, list) or source not in sources:
+ continue
+ if after is None or float(record.get("failed_at_ts") or 0) > after:
+ count += 1
+ return count
+
+
+def _temp_fallback_db() -> Path:
+ """Where ``Cache`` falls back when its default path is unusable."""
+ return Path(tempfile.gettempdir()) / "world-intel-mcp" / "cache.db"
+
+
+def _same_path(a: Path, b: Path) -> bool:
+ try:
+ return Path(a).resolve() == Path(b).resolve()
+ except OSError:
+ return False
+
+
+def _outline(payload: Any) -> Any:
+ """Top-level shape of a payload too large to replay."""
+
+ def _shape(value: Any) -> str:
+ if isinstance(value, list):
+ return f"list of {len(value)}"
+ if isinstance(value, dict):
+ return f"object with {len(value)} keys"
+ return type(value).__name__
+
+ if isinstance(payload, dict):
+ return {str(key): _shape(value) for key, value in list(payload.items())[:100]}
+ return _shape(payload)
+
+
class HistoryStore:
"""Capture log, payload bodies and observations in the cache DB."""
def __init__(self, db_path: Path | str):
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
- self._conn = sqlite3.connect(str(self.db_path), timeout=10)
+ # The connect timeout is SQLite's busy timeout: how long a write
+ # waits on another writer's lock before "database is locked".
+ self._conn = sqlite3.connect(str(self.db_path), timeout=BUSY_TIMEOUT_S)
self._conn.execute("PRAGMA journal_mode=WAL")
- self._conn.execute("PRAGMA busy_timeout=5000")
self._conn.execute("PRAGMA synchronous=NORMAL")
self._conn.executescript(
"""
@@ -545,6 +803,7 @@ class HistoryStore:
counts = {"ok": 0, "degraded": 0, "error": 0}
payloads_stored = 0
observations_stored = 0
+ max_body = size_caps()["max_body_bytes"]
with conn:
for outcome in outcomes:
c = classify(outcome)
@@ -563,7 +822,15 @@ class HistoryStore:
digest = body = None
note = f"payload not stored in history: {type(exc).__name__}: {exc}"
c.reason = (f"{c.reason}; {note}" if c.reason else note)[:500]
- if digest is not None and body is not None:
+ if body is not None and max_body and len(body) > max_body:
+ # The hash still dates changes; only the body is lost.
+ note = (
+ f"{_BODY_NOT_STORED}: {len(body):,} bytes of JSON, over the "
+ f"{max_body:,}-byte cap (WORLD_INTEL_HISTORY_MAX_BODY_BYTES)"
+ )
+ c.reason = (f"{c.reason}; {note}" if c.reason else note)[:500]
+ body = None
+ if digest is not None:
prev = conn.execute(
"SELECT payload_hash FROM history_captures "
"WHERE source = ? AND payload_hash IS NOT NULL "
@@ -571,6 +838,7 @@ class HistoryStore:
(outcome.source,),
).fetchone()
changed = None if prev is None else int(prev[0] != digest)
+ if digest is not None and body is not None:
inserted = conn.execute(
"INSERT OR IGNORE INTO history_payloads "
"(source, payload_hash, first_seen_at, last_seen_at, raw_bytes, body) "
@@ -680,6 +948,7 @@ class HistoryStore:
"series": series,
"first_capture_at": _iso(first),
"retention": retention_days(),
+ "size_caps": size_caps(),
"db_path": str(self.db_path),
}
@@ -702,6 +971,8 @@ class HistoryStore:
}
names = [source]
+ failures, unreadable_failures = read_write_failures(self.db_path, now)
+ live_args = (len(STALE_REASON), STALE_REASON)
rows = []
for name in names:
cadence = overrides.get(name, default_cadence)
@@ -720,6 +991,9 @@ class HistoryStore:
if last is None:
entry.update(state="never_run", attempts=0, overdue=None,
last_attempt_at=None, last_success_at=None)
+ unrecorded = _unrecorded_attempts(failures, name, None)
+ if unrecorded:
+ entry["unrecorded_attempts"] = unrecorded
rows.append(entry)
continue
last_at, last_status, last_reason, last_extract_error = last
@@ -727,21 +1001,21 @@ class HistoryStore:
"SELECT COUNT(*) FROM history_captures WHERE source = ?", (name,)
).fetchone()[0]
last_success = conn.execute(
- "SELECT MAX(collected_at) FROM history_captures "
- "WHERE source = ? AND status IN ('ok', 'degraded')",
- (name,),
+ "SELECT MAX(collected_at) FROM history_captures WHERE source = ? AND "
+ + _LIVE_CAPTURE,
+ (name, *live_args),
).fetchone()[0]
last_ok = conn.execute(
"SELECT MAX(collected_at) FROM history_captures WHERE source = ? AND status = 'ok'",
(name,),
).fetchone()[0]
- # Errors recorded after the last non-error capture, in insertion
- # order (robust to a clock that stepped backwards).
+ # Captures after the last live one (errors and stale replays), in
+ # insertion order (robust to a clock that stepped backwards).
consecutive = conn.execute(
- "SELECT COUNT(*) FROM history_captures WHERE source = ? AND status = 'error' "
+ "SELECT COUNT(*) FROM history_captures WHERE source = ? "
"AND id > COALESCE((SELECT MAX(id) FROM history_captures "
- "WHERE source = ? AND status != 'error'), 0)",
- (name, name),
+ "WHERE source = ? AND " + _LIVE_CAPTURE + "), 0)",
+ (name, name, *live_args),
).fetchone()[0]
obs = conn.execute(
"SELECT MAX(observed_at), COUNT(DISTINCT series_key), "
@@ -750,15 +1024,18 @@ class HistoryStore:
).fetchone()
age_attempt = now - last_at
age_success = None if last_success is None else now - last_success
+ age_ok = None if last_ok is None else now - last_ok
overdue = age_success is None or age_success > overdue_after
attempt_overdue = age_attempt > overdue_after
- # A non-error last capture is itself the last success, so overdue
- # can differ from attempt_overdue only for a failing source; it is
- # reported there as the overdue flag, not as a state of its own.
+ # A live last capture is itself the last success, so overdue can
+ # differ from attempt_overdue only for a failing or stale source;
+ # it is reported there as the overdue flag, not as a state.
if attempt_overdue:
state = "not_attempted_recently"
elif last_status == "error":
state = "failing"
+ elif (last_reason or "").startswith(STALE_REASON):
+ state = "stale"
else:
state = last_status
entry.update(
@@ -771,10 +1048,14 @@ class HistoryStore:
last_success_at=_iso(last_success),
last_success_age_s=None if age_success is None else round(age_success, 1),
last_ok_at=_iso(last_ok),
+ last_ok_age_s=None if age_ok is None else round(age_ok, 1),
consecutive_failures=consecutive,
overdue=overdue,
attempt_overdue=attempt_overdue,
)
+ unrecorded = _unrecorded_attempts(failures, name, last_at)
+ if unrecorded:
+ entry["unrecorded_attempts"] = unrecorded
if last_extract_error:
entry["last_extract_error"] = last_extract_error
if obs[1]:
@@ -787,13 +1068,49 @@ class HistoryStore:
states: dict[str, int] = {}
for entry in rows:
states[entry["state"]] = states.get(entry["state"], 0) + 1
+ storage = self.storage_stats()
+ record_file = write_failures_path(self.db_path)
+ gaps = []
+ if storage["captures"] == 0:
+ gaps.append(
+ f"no captures in this run log ({self.db_path}): the collector has not "
+ "written to this database. A collector that resolved another cache path "
+ "(WORLD_INTEL_CACHE_DB, XDG_CACHE_HOME, the temp-directory fallback) keeps "
+ "its own log."
+ )
+ elif states.get("never_run"):
+ gaps.append(f"{states['never_run']} source(s) have no capture in this run log")
+ if _same_path(self.db_path, _temp_fallback_db()):
+ gaps.append(
+ f"this run log is the temp-directory fallback ({self.db_path}): the default "
+ "cache path was unusable when this process started, so a collector writing "
+ "to the default path is not visible here"
+ )
+ if failures:
+ gaps.append(
+ f"{len(failures)} collector cycle(s) were not written to this run log (last "
+ f"at {failures[-1].get('failed_at')}: {failures[-1].get('error')}); their "
+ "attempts, failures and payloads are missing, so ages and failure counts "
+ "can be off (unrecorded_attempts per source)"
+ )
+ if unreadable_failures:
+ gaps.append(
+ f"{unreadable_failures} lost-cycle record(s) in {record_file} could not be read"
+ )
return {
"sources": rows,
"state_counts": states,
"checked_at": _iso(now),
"default_cadence_s": default_cadence,
"overdue_multiple": OVERDUE_MULTIPLE,
- "storage": self.storage_stats(),
+ "storage": storage,
+ "history_write_failures": {
+ "count": len(failures),
+ "last_failed_at": failures[-1].get("failed_at") if failures else None,
+ "last_error": failures[-1].get("error") if failures else None,
+ "record_file": str(record_file),
+ },
+ "data_gaps": gaps,
"cannot_prove": [
"A recent capture shows the collector reached the upstream and saved a "
"payload; it does not show the upstream's observations are current. "
@@ -804,20 +1121,43 @@ class HistoryStore:
"real period is longer by the cycle's own duration.",
"A degraded capture with no records cannot tell a quiet period from a "
"silent upstream failure.",
+ "A stale-cache replay is seen through the fetcher's stale fallback (logged "
+ "per source run) or a top-level _stale marker. A source that serves old "
+ "data by other means, or awaits a fetch another task started, reads live.",
+ "This is the run log in storage.db_path, wherever this process's cache "
+ "resolved (WORLD_INTEL_CACHE_DB, else XDG_CACHE_HOME, else ~/.cache, or the "
+ "temp-directory fallback). A collector that resolved another path writes a "
+ "log this does not read, and its sources read never_run here.",
+ "A cycle whose history write failed is counted in history_write_failures; "
+ "one whose failure record could not be written either (a full disk, an "
+ "unwritable directory) leaves no trace here.",
HISTORY_ACCRUAL_NOTE + " A source the collector never ran reads never_run, "
"not healthy.",
],
"states_explained": {
- "ok": "last capture delivered records with no degradation marker",
- "degraded": "last capture delivered a payload marked stale/degraded, empty, "
- "or without the measures its extractor expects",
- "failing": "last capture was an error (consecutive_failures counts the run; "
- f"overdue is true when no payload arrived within {OVERDUE_MULTIPLE:g} "
- "cadences)",
+ "ok": "last capture was live and complete: records, every upstream fetch "
+ "answered, no degradation marker",
+ "degraded": "last capture was live but degraded: marked degraded, empty, "
+ "partial (fewer series than expected), or its extractor found nothing",
+ "stale": "last capture replayed an expired cached copy because an upstream "
+ "fetch failed; that is not a success, so overdue counts from the last live "
+ "capture",
+ "failing": "last capture was an error (overdue is true when no live payload "
+ f"arrived within {OVERDUE_MULTIPLE:g} cadences)",
"not_attempted_recently": f"the collector has not attempted it within "
- f"{OVERDUE_MULTIPLE:g} cadences (overdue is then always true)",
+ f"{OVERDUE_MULTIPLE:g} cadences, or its attempts were not recorded (see "
+ "unrecorded_attempts); overdue is then always true",
"never_run": "no capture recorded",
},
+ "fields_explained": {
+ "last_success_at": "last live capture: ok, or degraded for any reason but a "
+ "stale-cache replay; overdue and last_success_age_s count from it",
+ "last_ok_at": "last ok capture: live, complete and unmarked",
+ "consecutive_failures": "errors and stale-cache replays recorded since the "
+ "last live capture",
+ "unrecorded_attempts": "cycles after this source's last recorded capture "
+ "whose history write failed",
+ },
}
def capture_history(
@@ -840,17 +1180,48 @@ class HistoryStore:
except (TypeError, ValueError):
return {"error": f"capture_id must be an integer, got {capture_id!r}"}
row = conn.execute(
- f"SELECT {columns}, p.body {join} WHERE c.id = ? AND c.source = ?",
+ f"SELECT {columns}, p.raw_bytes, p.first_seen_at, p.body {join} "
+ "WHERE c.id = ? AND c.source = ?",
(cid, source),
).fetchone()
if row is None:
return {"error": f"no capture {cid} for source {source!r}"}
- capture = self._capture_row(row[:-1])
- if row[-1] is not None:
- capture["payload"] = json.loads(zlib.decompress(row[-1]))
- elif capture["payload_hash"]:
- capture["payload"] = None
- capture["payload_note"] = "body pruned past WORLD_INTEL_HISTORY_PAYLOAD_DAYS"
+ capture = self._capture_row(row[:-3])
+ raw_bytes, stored_at, body = row[-3:]
+ notes = []
+ if body is None:
+ if capture["payload_hash"]:
+ capture["payload"] = None
+ notes.append(
+ "body not stored: it was over WORLD_INTEL_HISTORY_MAX_BODY_BYTES "
+ "when captured (see reason)"
+ if _BODY_NOT_STORED in (capture["reason"] or "")
+ else "body pruned past WORLD_INTEL_HISTORY_PAYLOAD_DAYS"
+ )
+ else:
+ payload = json.loads(zlib.decompress(body))
+ replay_cap = size_caps()["replay_max_bytes"]
+ if replay_cap and raw_bytes > replay_cap:
+ capture["payload"] = None
+ capture["payload_outline"] = _outline(payload)
+ notes.append(
+ f"body is {raw_bytes:,} bytes of JSON, over the {replay_cap:,}-byte "
+ "replay cap (WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES, 0 = no cap); "
+ "payload_outline lists its top-level keys"
+ )
+ else:
+ capture["payload"] = payload
+ if stored_at != row[1]:
+ # Dedupe keeps one body per hash: this one is another
+ # capture's, identical except for the volatile keys.
+ capture["payload_stored_at"] = _iso(stored_at)
+ notes.append(
+ f"body stored by the capture at {_iso(stored_at)} with the same "
+ f"payload hash; its top-level {', '.join(sorted(VOLATILE_KEYS))} "
+ "are from that capture, not this one"
+ )
+ if notes:
+ capture["payload_note"] = "; ".join(notes)
return {"source": source, "capture": capture, "note": HISTORY_ACCRUAL_NOTE}
n = _clamp(limit, 20)
@@ -979,7 +1350,10 @@ class HistoryStore:
"data_gaps": gaps,
"note": (
"Rows for the same observed_at are successive values this server saw "
- "(revisions); a row is stored only when new or changed. "
+ "(revisions); a row is stored only when new or changed, and never from a "
+ "stale-cache replay. Rows older than WORLD_INTEL_HISTORY_DAYS are pruned by "
+ "collected_at, so a value unchanged for longer is stored again at its next "
+ "capture and its first sighting then reads as that capture. "
+ HISTORY_ACCRUAL_NOTE
),
}
@@ -1008,7 +1382,34 @@ class HistoryStore:
"ORDER BY collected_at DESC, id DESC LIMIT ?",
(*params, _clamp(limit, 100)),
).fetchall()
+ # What was searched: the same source / series filters, every point.
+ scope = filters[1:]
+ observations, series, dated = self._conn.execute(
+ "SELECT COUNT(*), COUNT(DISTINCT series_key), "
+ "COUNT(DISTINCT CASE WHEN observed_at IS NOT NULL THEN series_key END) "
+ "FROM history_observations" + (" WHERE " + " AND ".join(scope) if scope else ""),
+ params,
+ ).fetchone()
+ gaps = []
+ if observations == 0:
+ gaps.append("no observations recorded yet" + (
+ f" for source {source!r}" if source else ""
+ ) + (f" for series {series_key!r}" if series_key else "") + (
+ ", so no revision can be seen"
+ ))
+ elif dated == 0:
+ gaps.append(
+ f"none of the {series} series checked has an observed_at, so none can be "
+ "checked for revisions"
+ )
+ elif dated < series:
+ gaps.append(
+ f"{series - dated} of {series} series have no observed_at and cannot be "
+ "checked for revisions"
+ )
return {
+ "checked": {"observations": observations, "series": series, "dated_series": dated},
+ "data_gaps": gaps,
"revisions": [
{
"series_key": r[0], "source": r[1], "observed_at": r[2],
@@ -1026,6 +1427,8 @@ class HistoryStore:
"running, is not.",
"Series without observed_at (for example Yahoo quotes) cannot be checked "
"for revisions: there is no observation date to hold fixed.",
+ "Observations older than WORLD_INTEL_HISTORY_DAYS are pruned by collected_at: "
+ "a revision of a value whose earlier row was pruned is not seen.",
],
"note": HISTORY_ACCRUAL_NOTE,
}
diff --git a/src/world_intel_mcp/tests/test_history_honesty.py b/src/world_intel_mcp/tests/test_history_honesty.py
new file mode 100644
index 0000000..6c08caf
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_history_honesty.py
@@ -0,0 +1,678 @@
+"""History honesty: stale-cache attribution, live-success health, caps,
+lasting write-failure records and the rules the run log must keep.
+
+The stale-cache tests drive a real ``Fetcher`` with a real ``Cache`` and
+real source modules (``fetch_earthquakes``, ``fetch_market_quotes``)
+against respx, because the failure they guard is a source module
+rebuilding its dict and dropping the fetcher's ``_stale`` marker: a
+hand-built ``{"_stale": True}`` payload would not exercise it. The health
+tests then feed ``SourceOutcome`` values with the same ``stale_serves``
+the collector attaches, at fixed times.
+"""
+
+import asyncio
+import json
+import sqlite3
+import tempfile
+import time
+import types
+from urllib.parse import unquote
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp import cli, collector, history
+from world_intel_mcp import fetcher as fetcher_mod
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import StaleServe, recording_stale_serves
+from world_intel_mcp.history import HistoryStore, Observation, SourceOutcome
+
+from .test_history import T0, _history_tools, _importer, _invoke, _kp, _record, _VS
+
+_USGS = "https://earthquake.usgs.gov/fdsnws/event/1/query"
+_YAHOO = r"https://query1\.finance\.yahoo\.com/v8/finance/chart/.*"
+
+
[email protected](autouse=True)
+def _default_history_env(monkeypatch):
+ for var in (
+ "WORLD_INTEL_HISTORY_DAYS",
+ "WORLD_INTEL_HISTORY_PAYLOAD_DAYS",
+ "WORLD_INTEL_HISTORY_CAPTURE_DAYS",
+ "WORLD_INTEL_HISTORY_CADENCE_S",
+ "WORLD_INTEL_HISTORY_CADENCES",
+ "WORLD_INTEL_HISTORY_MAX_BODY_BYTES",
+ "WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES",
+ ):
+ monkeypatch.delenv(var, raising=False)
+
+
+def store(tmp_path):
+ s = HistoryStore(tmp_path / "history.db")
+ yield s
+ s.close()
+
+
+def cli_db(tmp_path, monkeypatch):
+ """A cache DB for CLI commands; closes the cache the CLI opens on it."""
+ db = tmp_path / "cli.db"
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(db))
+ monkeypatch.setattr(cli, "_fetcher", None)
+ yield db
+ if cli._fetcher is not None:
+ cli._fetcher.cache.close()
+
+
+def _stale(age: float = 812.0) -> tuple:
+ return (StaleServe("firms", "wildfire:firms:world", age),)
+
+
+def _replay(store, source, at, payload, age: float = 812.0) -> dict:
+ """Record a capture the fetcher answered from expired cache."""
+ return store.record_cycle(
+ [SourceOutcome(source, at, 1.0, payload, stale_serves=_stale(age))], now=at
+ )
+
+
+def _quotes(*prices) -> dict:
+ return {"quotes": [{"symbol": f"^Q{i}", "price": p} for i, p in enumerate(prices)]}
+
+
+FIRES = {"fires": [1]}
+
+
+# ---------------------------------------------------------------------------
+# H1: stale-cache serves are attributed to the collector source
+# ---------------------------------------------------------------------------
+
+
+def _geojson(magnitude: float) -> dict:
+ return {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "id": "us7000hst1",
+ "properties": {"mag": magnitude, "place": "Test Ridge", "time": 1_760_000_000_000},
+ "geometry": {"type": "Point", "coordinates": [-120.5, 35.2, 10.0]},
+ }
+ ],
+ }
+
+
+def _real_fetcher(tmp_path, monkeypatch) -> fetcher_mod.Fetcher:
+ # No retries and no rate floors: the test controls every response.
+ monkeypatch.delitem(fetcher_mod._SOURCE_RATE_LIMITS, "usgs")
+ monkeypatch.delitem(fetcher_mod._SOURCE_RATE_LIMITS, "yahoo-finance")
+ monkeypatch.setattr(fetcher_mod, "_YAHOO_MIN_INTERVAL", 0.0)
+ cache = Cache(db_path=tmp_path / "cache.db")
+ return fetcher_mod.Fetcher(
+ cache=cache, breaker=CircuitBreaker(), default_timeout=5.0, max_retries=0
+ )
+
+
+def _expire_cache(db_path, key: str | None = None) -> None:
+ conn = sqlite3.connect(str(db_path))
+ try:
+ with conn:
+ if key is None:
+ conn.execute("UPDATE cache SET expires_at = 0")
+ else:
+ conn.execute("UPDATE cache SET expires_at = 0 WHERE key = ?", (key,))
+ finally:
+ conn.close()
+
+
+async def test_stale_serve_through_a_real_source_is_a_stale_capture(tmp_path, monkeypatch):
+ """USGS answers, the cached copy expires, then USGS returns 503. The
+ fetcher serves the expired copy and fetch_earthquakes rebuilds its dict
+ without the _stale marker. The capture must still read as a stale-cache
+ replay, and health must keep the live capture as the last success."""
+ real = _real_fetcher(tmp_path, monkeypatch)
+ route = respx.get(_USGS)
+ route.mock(return_value=httpx.Response(200, json=_geojson(5.2)))
+ await collector.collect_once(real, _VS(), source_filter={"earthquakes"})
+
+ _expire_cache(real.cache.db_path)
+ route.mock(return_value=httpx.Response(503))
+ summary = await collector.collect_once(real, _VS(), source_filter={"earthquakes"})
+ await real.close()
+ real.cache.close()
+ assert route.call_count == 2 # the second cycle did try USGS live
+ assert summary["history"]["status_counts"] == {"ok": 0, "degraded": 1, "error": 0}
+
+ store = HistoryStore(real.cache.db_path)
+ try:
+ stale, live = store.capture_history("earthquakes")["captures"]
+ health = store.collection_health(["earthquakes"])["sources"][0]
+ finally:
+ store.close()
+ assert live["status"] == "ok" and live["observations_stored"] == 1
+ assert stale["status"] == "degraded"
+ assert stale["reason"].startswith(history.STALE_REASON)
+ assert stale["change"] == "unchanged" # same upstream data, replayed
+ assert stale["observations_stored"] == 0
+ assert health["state"] == "stale"
+ assert health["last_success_at"] == live["collected_at"]
+ assert health["last_ok_at"] == live["collected_at"]
+ assert health["consecutive_failures"] == 1
+
+
+async def test_stale_serve_inside_a_gathered_sub_fetch_is_attributed(tmp_path, monkeypatch):
+ """fetch_market_quotes gathers one Yahoo fetch per symbol in sub-tasks;
+ a stale serve in one of them still lands in market_quotes' log, and a
+ concurrently running source that stayed live is not marked."""
+ real = _real_fetcher(tmp_path, monkeypatch)
+ failing = {"symbol": None}
+
+ def _chart(request):
+ if unquote(request.url.path.rsplit("/", 1)[-1]) == failing["symbol"]:
+ return httpx.Response(503)
+ return httpx.Response(200, json={"chart": {"result": [{"meta": {
+ "regularMarketPrice": 100.0, "previousClose": 99.0, "currency": "USD",
+ }}]}})
+
+ respx.get(url__regex=_YAHOO).mock(side_effect=_chart)
+ respx.get(_USGS).mock(return_value=httpx.Response(200, json=_geojson(5.2)))
+ both = {"market_quotes", "earthquakes"}
+ first = await collector.collect_once(real, _VS(), source_filter=both)
+ assert first["history"]["status_counts"] == {"ok": 2, "degraded": 0, "error": 0}
+
+ _expire_cache(real.cache.db_path, "markets:quotes:^N225")
+ _expire_cache(real.cache.db_path, "seismology:quakes:4.5:24")
+ failing["symbol"] = "^N225"
+ await collector.collect_once(real, _VS(), source_filter=both)
+ await real.close()
+ real.cache.close()
+
+ store = HistoryStore(real.cache.db_path)
+ try:
+ quotes = store.capture_history("market_quotes")["captures"][0]
+ quakes = store.capture_history("earthquakes")["captures"][0]
+ finally:
+ store.close()
+ assert quotes["status"] == "degraded"
+ assert quotes["reason"].startswith(history.STALE_REASON)
+ assert (quotes["observations_extracted"], quotes["observations_stored"]) == (7, 0)
+ assert (quakes["status"], quakes["reason"]) == ("ok", None)
+
+
+def test_stale_serve_log_is_task_scoped_and_nests(tmp_path) -> None:
+ cache = Cache(db_path=tmp_path / "c.db")
+ real = fetcher_mod.Fetcher(cache=cache, breaker=CircuitBreaker())
+ cache.set("k:dict", {"v": 1}, ttl_seconds=-10)
+ cache.set("k:list", [1, 2], ttl_seconds=-10)
+
+ async def _serve(key):
+ with recording_stale_serves() as served:
+ await asyncio.sleep(0)
+ real._stale_fallback(key, "src")
+ await asyncio.sleep(0)
+ return [s.cache_key for s in served]
+
+ async def _main():
+ with recording_stale_serves() as outer:
+ a, b = await asyncio.gather(_serve("k:dict"), _serve("k:list"))
+ real._stale_fallback("k:missing", "src") # nothing cached: no serve
+ return a, b, [s.cache_key for s in outer], fetcher_mod._STALE_SERVE_LOGS.get()
+
+ a, b, outer, after = asyncio.run(_main())
+ cache.close()
+ assert a == ["k:dict"] and b == ["k:list"] # each task sees only its own
+ assert sorted(outer) == ["k:dict", "k:list"] # the outer block sees both
+ assert after == () # the block reset its log on exit
+
+
+def test_several_stale_serves_and_a_bare_top_level_marker_read_stale(store) -> None:
+ serves = tuple(StaleServe("polymarket", f"k{i}", age) for i, age in enumerate((30.0, 812.5)))
+ store.record_cycle([
+ SourceOutcome("prediction_markets", T0, 1.0, {"markets": [1]}, stale_serves=serves),
+ SourceOutcome("gas_prices", T0, 1.0, {"prices": [1], "_stale": True}),
+ ], now=T0)
+ for source in ("prediction_markets", "gas_prices"):
+ (cap,) = store.capture_history(source)["captures"]
+ assert cap["status"] == "degraded"
+ assert cap["reason"].startswith(history.STALE_REASON)
+
+
+# ---------------------------------------------------------------------------
+# M1: health counts success only from live captures
+# ---------------------------------------------------------------------------
+
+
+def test_stale_captures_do_not_clear_overdue_or_the_success_time(store) -> None:
+ now = T0 + 10_000
+ _record(store, "wildfires", now - 5000, FIRES)
+ for ago in (600, 300, 10):
+ _replay(store, "wildfires", now - ago, FIRES)
+ row = store.collection_health(["wildfires"], now=now)["sources"][0]
+ assert row["state"] == "stale"
+ assert row["overdue"] is True and row["attempt_overdue"] is False
+ assert row["last_success_at"] == history._iso(now - 5000)
+ assert row["last_success_age_s"] == 5000.0
+ assert (row["last_ok_at"], row["last_ok_age_s"]) == (history._iso(now - 5000), 5000.0)
+ assert row["consecutive_failures"] == 3
+ assert row["last_attempt_age_s"] == 10.0
+ assert row["last_reason"].startswith(history.STALE_REASON)
+
+
+def test_a_live_degraded_capture_still_counts_as_success(store) -> None:
+ now = T0 + 10_000
+ _record(store, "wildfires", now - 5000, FIRES)
+ _record(store, "wildfires", now - 10, {"fires": [], "count": 0})
+ row = store.collection_health(["wildfires"], now=now)["sources"][0]
+ assert (row["state"], row["overdue"], row["consecutive_failures"]) == ("degraded", False, 0)
+ assert row["last_success_age_s"] == 10.0
+ assert row["last_ok_age_s"] == 5000.0
+
+
+def test_consecutive_failures_reset_only_by_a_live_capture(store) -> None:
+ """ok, error, ok, error reads 1 (counted from the LAST live capture);
+ a stale replay does not reset the count."""
+ for i, (payload, error) in enumerate([(FIRES, None), (None, "boom"), (FIRES, None), (None, "boom")]):
+ _record(store, "wildfires", T0 + i, payload, error)
+ row = store.collection_health(["wildfires"], now=T0 + 5)["sources"][0]
+ assert row["consecutive_failures"] == 1
+ _replay(store, "wildfires", T0 + 6, FIRES)
+ _record(store, "wildfires", T0 + 7, None, "boom")
+ row = store.collection_health(["wildfires"], now=T0 + 8)["sources"][0]
+ assert (row["state"], row["consecutive_failures"]) == ("failing", 3)
+
+
+def test_states_and_fields_are_explained(store) -> None:
+ _replay(store, "wildfires", T0, FIRES)
+ health = store.collection_health(["wildfires"], now=T0)
+ assert {r["state"] for r in health["sources"]} == {"stale"}
+ assert set(health["states_explained"]) == {
+ "ok", "degraded", "stale", "failing", "not_attempted_recently", "never_run"
+ }
+ assert "stale-cache replay" in health["fields_explained"]["last_success_at"]
+
+
+def test_cli_health_shows_stale_overdue_and_last_ok(cli_db, monkeypatch) -> None:
+ monkeypatch.setenv("COLUMNS", "260")
+ now = time.time()
+ s = HistoryStore(cli_db)
+ _record(s, "wildfires", now - 5000, FIRES)
+ _replay(s, "wildfires", now - 30, FIRES)
+ s.close()
+ out = _invoke("history", "health").output
+ row = next(line for line in out.splitlines() if line.strip().startswith("wildfires"))
+ assert "stale, overdue" in row
+ assert row.count(history._iso(now - 5000)) == 2 # Last success and Last ok
+ assert "Last ok" in out
+ assert "served stale cache (age 812.0 s)" in row
+
+
+# ---------------------------------------------------------------------------
+# M2: a stale replay is not a new observation
+# ---------------------------------------------------------------------------
+
+
+def test_stale_replay_stores_no_observations(store) -> None:
+ _record(store, "market_quotes", T0 + 10, _quotes(100.0))
+ _record(store, "market_quotes", T0 + 20, _quotes(101.0))
+ _replay(store, "market_quotes", T0 + 30, _quotes(100.0))
+ store.record_cycle([SourceOutcome("market_quotes", T0 + 40, 1.0,
+ dict(_quotes(99.0), _stale=True))], now=T0 + 40)
+ points = store.series_history("market_quotes:^Q0:price")["observations"]
+ assert [p["value"] for p in points] == [101.0, 100.0] # newest first
+ caps = store.capture_history("market_quotes")["captures"]
+ for cap in caps[:2]:
+ assert (cap["observations_extracted"], cap["observations_stored"]) == (1, 0)
+ assert "observations not stored: a stale-cache replay" in cap["reason"]
+
+
+def test_a_live_partial_capture_is_degraded_and_keeps_its_points(store) -> None:
+ """6 of the 7 default index quotes answer: degraded as partial, and the
+ six live points are stored."""
+ symbols = history._DEFAULT_INDEX_SYMBOLS
+ quotes = [{"symbol": sym, "price": 100.0 + i} for i, sym in enumerate(symbols)]
+ _record(store, "market_quotes", T0, {"quotes": quotes[:-1]})
+ (cap,) = store.capture_history("market_quotes")["captures"]
+ assert cap["status"] == "degraded"
+ assert cap["reason"] == "partial: 6 of 7 expected series"
+ assert cap["observations_stored"] == 6
+ _record(store, "market_quotes", T0 + 300, {"quotes": quotes})
+ assert store.capture_history("market_quotes")["captures"][0]["status"] == "ok"
+ commodities = {"commodities": [{"symbol": "GC=F", "name": "Gold", "price": 1.0}]}
+ _record(store, "commodity_quotes", T0, commodities)
+ assert store.capture_history("commodity_quotes")["captures"][0]["reason"] == (
+ "partial: 1 of 8 expected series"
+ )
+
+
+# ---------------------------------------------------------------------------
+# M3 + L3 + L5: replay says whose body it is, and both sizes are capped
+# ---------------------------------------------------------------------------
+
+
+def test_replay_of_a_deduped_capture_names_the_capture_that_stored_the_body(store) -> None:
+ first = dict(_kp(("2026-10-17T00:00:00Z", 2.0)), timestamp="2026-10-17T16:00:00Z")
+ _record(store, "space_weather", T0, first)
+ _record(store, "space_weather", T0 + 300, dict(first, timestamp="2026-10-17T16:05:00Z"))
+ own = store.capture_history("space_weather", capture_id=1)["capture"]
+ assert "payload_note" not in own and "payload_stored_at" not in own
+ later = store.capture_history("space_weather", capture_id=2)["capture"]
+ assert later["payload"]["timestamp"] == "2026-10-17T16:00:00Z"
+ assert later["payload_stored_at"] == history._iso(T0)
+ assert later["payload_note"].startswith(f"body stored by the capture at {history._iso(T0)}")
+ assert "timestamp" in later["payload_note"] and "_stale_age_seconds" in later["payload_note"]
+
+
+def test_fresh_then_stale_flip_of_the_same_data_is_unchanged(store) -> None:
+ data = {"prices": [3.1], "region": "US"}
+ _record(store, "gas_prices", T0, data)
+ _record(store, "gas_prices", T0 + 300, dict(data, _stale=True, _stale_age_seconds=300.0))
+ caps = store.capture_history("gas_prices")["captures"]
+ assert [c["change"] for c in caps] == ["unchanged", "first"]
+ assert store.storage_stats()["payload_bodies"] == 1
+
+
+def test_body_over_the_cap_keeps_its_hash_and_says_why(store, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_MAX_BODY_BYTES", "1000")
+ big = {"rows": ["x" * 50] * 40}
+ raw = len(json.dumps(big, separators=(",", ":")))
+ summary = _record(store, "news_feed", T0, big)
+ _record(store, "news_feed", T0 + 300, big)
+ assert summary["payloads_stored"] == 0
+ caps = store.capture_history("news_feed")["captures"]
+ assert [c["change"] for c in caps] == ["unchanged", "first"] # the hash still dates changes
+ for cap in caps:
+ assert cap["status"] == "ok" # the fetch was fine; only the body was not kept
+ assert cap["payload_hash"] is not None and cap["body_retained"] is False
+ assert cap["reason"] == (
+ f"payload body not stored: {raw:,} bytes of JSON, over the 1,000-byte cap "
+ "(WORLD_INTEL_HISTORY_MAX_BODY_BYTES)"
+ )
+ replay = store.capture_history("news_feed", capture_id=1)["capture"]
+ assert replay["payload"] is None
+ assert "over WORLD_INTEL_HISTORY_MAX_BODY_BYTES" in replay["payload_note"]
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_MAX_BODY_BYTES", "0") # 0 = no cap
+ assert _record(store, "news_feed", T0 + 600, big)["payloads_stored"] == 1
+
+
+def test_replay_over_the_replay_cap_returns_an_outline(store, monkeypatch) -> None:
+ payload = {"rows": list(range(500)), "source": "x", "meta": {"a": 1, "b": 2}}
+ _record(store, "news_feed", T0, payload)
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES", "100")
+ capped = store.capture_history("news_feed", capture_id=1)["capture"]
+ assert capped["payload"] is None
+ assert capped["payload_outline"] == {
+ "rows": "list of 500", "source": "str", "meta": "object with 2 keys"
+ }
+ raw = len(json.dumps(payload, separators=(",", ":")))
+ assert capped["payload_note"].startswith(f"body is {raw:,} bytes of JSON, over the 100-byte")
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES", "0")
+ assert store.capture_history("news_feed", capture_id=1)["capture"]["payload"] == payload
+
+
+def test_cli_replay_prints_the_outline(cli_db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES", "10")
+ s = HistoryStore(cli_db)
+ _record(s, "news_feed", T0, {"rows": list(range(50))})
+ s.close()
+ out = _invoke("history", "captures", "news_feed", "--capture-id", "1").output
+ assert "replay cap" in out and "list of 50" in out
+
+
+def test_size_caps_defaults_and_bad_values(monkeypatch) -> None:
+ defaults = {"max_body_bytes": 4_194_304, "replay_max_bytes": 262_144}
+ assert history.size_caps() == defaults
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_MAX_BODY_BYTES", "-1")
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_REPLAY_MAX_BYTES", "lots")
+ assert history.size_caps() == defaults
+
+
+# ---------------------------------------------------------------------------
+# L1 + L9: empty results name what was checked and where
+# ---------------------------------------------------------------------------
+
+
+def test_revisions_name_what_was_checked(store) -> None:
+ empty = store.revisions()
+ assert empty["checked"] == {"observations": 0, "series": 0, "dated_series": 0}
+ assert empty["data_gaps"] == ["no observations recorded yet, so no revision can be seen"]
+ _record(store, "market_quotes", T0, _quotes(1.0))
+ undated = store.revisions()
+ assert undated["checked"] == {"observations": 1, "series": 1, "dated_series": 0}
+ assert undated["data_gaps"] == [
+ "none of the 1 series checked has an observed_at, so none can be checked for revisions"
+ ]
+ _record(store, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.0)))
+ mixed = store.revisions()
+ assert mixed["data_gaps"] == [
+ "1 of 2 series have no observed_at and cannot be checked for revisions"
+ ]
+ scoped = store.revisions(source="space_weather")
+ assert (scoped["checked"]["series"], scoped["data_gaps"]) == (1, [])
+ assert store.revisions(source="cyclones")["data_gaps"] == [
+ "no observations recorded yet for source 'cyclones', so no revision can be seen"
+ ]
+
+
+def test_cli_revisions_prints_gaps(cli_db) -> None:
+ out = _invoke("history", "revisions").output
+ assert "Gap:" in out and "no observations recorded yet" in out
+
+
+def test_empty_run_log_names_its_path_and_the_other_path_risk(store) -> None:
+ health = store.collection_health(["wildfires", "earthquakes"], now=T0)
+ assert health["data_gaps"][0].startswith(f"no captures in this run log ({store.db_path})")
+ assert any("never_run here" in line for line in health["cannot_prove"])
+ _record(store, "wildfires", T0, FIRES)
+ health = store.collection_health(["wildfires", "earthquakes"], now=T0)
+ assert health["data_gaps"] == ["1 source(s) have no capture in this run log"]
+
+
+def test_temp_fallback_run_log_is_named(tmp_path, monkeypatch) -> None:
+ """A Cache whose default path is unusable falls back to the temp dir;
+ health on that file says so."""
+ blocker = tmp_path / "not-a-dir"
+ blocker.write_text("")
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(blocker / "cache.db"))
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path / "tmp"))
+ cache = Cache()
+ try:
+ assert cache.db_path == tmp_path / "tmp" / "world-intel-mcp" / "cache.db"
+ s = HistoryStore(cache.db_path)
+ try:
+ gaps = s.collection_health(["wildfires"], now=T0)["data_gaps"]
+ finally:
+ s.close()
+ finally:
+ cache.close()
+ assert any(gap.startswith("this run log is the temp-directory fallback") for gap in gaps)
+
+
+async def test_history_tools_pass_gaps_through(tmp_path, monkeypatch) -> None:
+ tools_mod = _history_tools()
+ monkeypatch.setattr(tools_mod.runtime, "cache", types.SimpleNamespace(db_path=tmp_path / "t.db"))
+ out = await tools_mod.HANDLERS["intel_revisions"]({})
+ assert out["data_gaps"] == ["no observations recorded yet, so no revision can be seen"]
+ health = await tools_mod.HANDLERS["intel_collection_health"]({"source": "wildfires"})
+ assert health["history_write_failures"]["count"] == 0
+ assert health["data_gaps"][0].startswith("no captures in this run log")
+
+
+# ---------------------------------------------------------------------------
+# L4: observation dates must name real calendar periods
+# ---------------------------------------------------------------------------
+
+
+ "text,expected",
+ [
+ ("2026-13-45", None), ("2026-02-30", None), ("2026-02-29", None), ("0000", None),
+ ("2026-00", None), ("2026-13", None), ("0000-01-01", None),
+ ("2028-02-29", "2028-02-29"), ("2026-12", "2026-12"), ("0001", "0001"),
+ ],
+)
+def test_observed_at_periods_are_calendar_checked(text, expected) -> None:
+ assert history.normalize_observed_at(text) == expected
+
+
+# ---------------------------------------------------------------------------
+# L6: a failed history write leaves a lasting, visible record
+# ---------------------------------------------------------------------------
+
+
+async def _ok_fires(fetcher, **kw):
+ return dict(FIRES)
+
+
+async def test_locked_db_is_retried_then_recorded_as_a_lost_cycle(tmp_path, monkeypatch):
+ db = tmp_path / "cache.db"
+ s = HistoryStore(db)
+ _record(s, "wildfires", T0, FIRES)
+ s.close()
+ monkeypatch.setattr(history, "BUSY_TIMEOUT_S", 0.05)
+ monkeypatch.setattr(collector, "_import_fetch_fn", _importer({"wildfires": _ok_fires}))
+ holder = sqlite3.connect(str(db), timeout=0.05)
+ holder.execute("BEGIN IMMEDIATE") # another writer holds the lock
+ fetcher = types.SimpleNamespace(cache=types.SimpleNamespace(db_path=db))
+ try:
+ summary = await collector.collect_once(fetcher, _VS(), source_filter={"wildfires"})
+ finally:
+ holder.rollback()
+ holder.close()
+ assert summary["history"] == {
+ "recorded": 0, "error": "history write failed: database is locked"
+ }
+ (line,) = history.write_failures_path(db).read_text().splitlines()
+ record = json.loads(line)
+ assert (record["error"], record["sources"]) == (
+ "history write failed: database is locked", ["wildfires"]
+ )
+
+ s = HistoryStore(db)
+ try:
+ assert s.capture_history("wildfires")["total_captures"] == 1 # the cycle was lost
+ health = s.collection_health(["wildfires", "earthquakes"])
+ finally:
+ s.close()
+ failures = health["history_write_failures"]
+ assert failures["count"] == 1
+ assert failures["last_error"] == "history write failed: database is locked"
+ assert failures["record_file"] == str(history.write_failures_path(db))
+ assert any(gap.startswith("1 collector cycle(s) were not written") for gap in health["data_gaps"])
+ rows = {r["source"]: r for r in health["sources"]}
+ assert rows["wildfires"]["unrecorded_attempts"] == 1
+ assert "unrecorded_attempts" not in rows["earthquakes"] # not in the lost cycle
+
+
+async def test_a_write_that_fails_once_is_retried(tmp_path, monkeypatch):
+ real_record = HistoryStore.record_cycle
+ calls = {"n": 0}
+
+ def _flaky(self, outcomes, now=None):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise sqlite3.OperationalError("database is locked")
+ return real_record(self, outcomes, now)
+
+ monkeypatch.setattr(HistoryStore, "record_cycle", _flaky)
+ monkeypatch.setattr(collector, "_import_fetch_fn", _importer({"wildfires": _ok_fires}))
+ db = tmp_path / "cache.db"
+ fetcher = types.SimpleNamespace(cache=types.SimpleNamespace(db_path=db))
+ summary = await collector.collect_once(fetcher, _VS(), source_filter={"wildfires"})
+ assert calls["n"] == 2 and summary["history"]["recorded"] == 1
+ assert not history.write_failures_path(db).exists()
+
+
+def test_lost_cycle_records_are_capped_retained_and_parsed(tmp_path, monkeypatch) -> None:
+ db = tmp_path / "cache.db"
+ outcome = [SourceOutcome("wildfires", T0)]
+ for i in range(505):
+ history.record_write_failure(db, outcome, f"e{i}", now=T0 + i)
+ lines = history.write_failures_path(db).read_text().splitlines()
+ assert len(lines) == 500 and json.loads(lines[0])["error"] == "e5"
+ with history.write_failures_path(db).open("a") as fh:
+ fh.write("not json\n[1, 2]\n")
+ records, unreadable = history.read_write_failures(db, now=T0 + 600)
+ assert (len(records), unreadable) == (500, 2)
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "1")
+ records, _ = history.read_write_failures(db, now=T0 + 86400 + 300)
+ assert records[0]["error"] == "e300" # older ones aged out with the run log
+ s = HistoryStore(db)
+ try:
+ gaps = s.collection_health(["wildfires"], now=T0 + 600)["data_gaps"]
+ finally:
+ s.close()
+ assert f"2 lost-cycle record(s) in {history.write_failures_path(db)} could not be read" in gaps
+
+
+def test_unwritable_failure_record_is_logged_not_raised(tmp_path, caplog) -> None:
+ missing_dir = tmp_path / "gone" / "cache.db"
+ assert history.record_write_failure(missing_dir, [], "boom") is None
+ assert "Could not record the history write failure" in caplog.text
+
+
+# ---------------------------------------------------------------------------
+# Surviving mutants from the review
+# ---------------------------------------------------------------------------
+
+
+def test_a_body_seen_continuously_outlives_payload_retention(store, monkeypatch) -> None:
+ """Payload retention counts from the LAST sighting: a body first stored
+ 1.5 days ago but seen again 0.6 days ago survives a 1-day window."""
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_PAYLOAD_DAYS", "1")
+ payload = _kp(("2026-10-17T00:00:00Z", 2.0))
+ _record(store, "space_weather", T0, payload)
+ _record(store, "space_weather", T0 + 0.9 * 86400, payload) # unchanged: bumps last_seen_at
+ summary = _record(store, "wildfires", T0 + 1.5 * 86400, FIRES)
+ assert summary["pruned"]["payloads"] == 0
+ assert store.capture_history("space_weather", capture_id=2)["capture"]["payload"] == payload
+ summary = _record(store, "wildfires", T0 + 2 * 86400, FIRES)
+ assert summary["pruned"]["payloads"] == 1 # 1.1 days after its last sighting
+
+
+def test_replace_true_swaps_in_a_different_extractor(store, monkeypatch) -> None:
+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))
+ monkeypatch.setattr(history, "_EXPECTED", dict(history._EXPECTED))
+ history.register_extractor("test_feed", lambda p: [Observation("a", 1.0)])
+ history.register_extractor("test_feed", lambda p: [Observation("b", 2.0)], replace=True)
+ _record(store, "test_feed", T0, {"rows": [1]})
+ assert [s["series_key"] for s in store.series_history()["series"]] == ["test_feed:b"]
+
+
+def test_expected_count_is_per_registration(monkeypatch) -> None:
+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))
+ monkeypatch.setattr(history, "_EXPECTED", dict(history._EXPECTED))
+ history.register_extractor("test_feed", lambda p: [], expected=3)
+ assert history._EXPECTED["test_feed"] == 3
+ history.register_extractor("test_feed", lambda p: [], replace=True)
+ assert "test_feed" not in history._EXPECTED
+
+
+class _Abort(BaseException):
+ """Not an Exception: gather() returns it, and nothing above catches it."""
+
+
+async def test_collector_records_a_source_that_raised_a_base_exception(tmp_path, monkeypatch):
+ async def _aborts(fetcher, **kw):
+ raise _Abort("source aborted")
+
+ monkeypatch.setattr(collector, "_import_fetch_fn", _importer({
+ "wildfires": _ok_fires, "acled_events": _aborts,
+ }))
+ db = tmp_path / "cache.db"
+ fetcher = types.SimpleNamespace(cache=types.SimpleNamespace(db_path=db))
+ summary = await collector.collect_once(
+ fetcher, _VS(), source_filter={"wildfires", "acled_events"}
+ )
+ assert (summary["successes"], summary["failures"]) == (1, 1)
+ assert summary["history"]["status_counts"] == {"ok": 1, "degraded": 0, "error": 1}
+ s = HistoryStore(db)
+ try:
+ (cap,) = s.capture_history("acled_events")["captures"]
+ finally:
+ s.close()
+ assert (cap["status"], cap["reason"], cap["record_count"]) == ("error", "source aborted", None)
+ assert cap["duration_s"] is not None
diff --git a/src/world_intel_mcp/tools/history.py b/src/world_intel_mcp/tools/history.py
index fe93892..555d358 100644
--- a/src/world_intel_mcp/tools/history.py
+++ b/src/world_intel_mcp/tools/history.py
@@ -23,10 +23,12 @@ TOOLS: list[Tool] = [
name="intel_collection_health",
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
+ "last live success (a stale-cache replay never counts; such a source reads "
+ "stale), last fully ok capture, consecutive failures, overdue against the "
+ "expected cadence (default 300 s, overdue past 3 cadences), never-run "
+ "sources, cycles whose history write failed, and history storage size. "
+ "States its data gaps and what it cannot prove: a fresh capture does not "
+ "mean upstream observations are current (see latest_observed_at). " + _ACCRUAL
),
inputSchema={
"type": "object",
@@ -42,9 +44,11 @@ TOOLS: list[Tool] = [
name="intel_capture_history",
description=(
"A source's earlier collector captures, newest first: status (ok / degraded / "
- "error with reason), duration, record count, payload hash and whether it "
- "changed from the previous capture. Pass capture_id to replay one stored "
- "payload. " + _ACCRUAL
+ "error with reason; a run answered from expired cache is degraded with "
+ "reason 'served stale cache'), duration, record count, payload hash and "
+ "whether it changed from the previous capture. Pass capture_id to replay one "
+ "stored payload (over the replay cap, an outline of its top-level keys). "
+ + _ACCRUAL
),
inputSchema={
"type": "object",
@@ -97,8 +101,8 @@ TOOLS: list[Tool] = [
description=(
"Values for the same observed_at that a later capture changed (for example "
"USGS magnitude revisions, NOAA Kp updates), with both values and both "
- "collection times. Only changes between this server's own captures are "
- "visible. " + _ACCRUAL
+ "collection times, and how many observations and dated series were checked. "
+ "Only changes between this server's own captures are visible. " + _ACCRUAL
),
inputSchema={
"type": "object",