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.

Day timeline review fixes: extractor failures, coverage, pre-store days

Phoenix Agent (mac-studio)676ce37a09e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1dc2e51..f6c265d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -200,10 +200,28 @@ source here, and no proxy is substituted for any of these measures.
payload bodies are still kept. Each source gets a `day_state`:
`changed`, `unchanged`, `answered`, `degraded`, `failed`,
`not_attempted` (the collector ran that day, not this source),
- `collector_did_not_run` (no capture of any source that day), `never_run`
- (no capture of it in the retained run log) or `unknown_past_retention`.
- A collector block gives the day's capture count, first and last capture
- and the longest stretch without any capture.
+ `collector_did_not_run` (no capture of any source that day),
+ `before_run_log` (the day is before the first capture in this
+ database's run log, so whether the source ran cannot be read),
+ `never_run` (no capture of it before or after the day in the retained
+ run log) or `unknown_past_retention`. A source with an error beside ok or
+ degraded captures is flagged `partial_failure`. A collector block gives
+ the day's capture count, first and last capture, `covered_from` and the
+ longest stretch without any capture; its state is `ran`, `did_not_run`,
+ `unknown_past_retention` or `not_recorded` (the run log starts after the
+ day or is empty).
+- Extractor failures are read from the run log: captures whose history
+ extractor raised (nothing stored) and captures whose points the store
+ refused are counted per source, their errors appear among the reasons
+ (kind `extraction`), and the day gets a gap saying what the observed view
+ misses. by=observed checks captures collected from the day to the next
+ day for the same failures.
+- Coverage: a day partly or wholly past the run-log cutoff is read as
+ covered when the run log still holds an older capture (pruning cuts every
+ source at one cutoff and captures are stamped on insert), so a day the
+ last cycle has not pruned yet keeps its states; otherwise counts, states
+ and the longest gap are stated to cover only the first retained capture
+ onward.
- `by=observed`: values whose `observed_at` is the day (a date) or a UTC
instant on it, one item per series and `observed_at` with the latest
value, how many values were stored for it and the first one when it was
@@ -217,14 +235,22 @@ source here, and no proxy is substituted for any of these measures.
`unknown_past_retention`, never as a day on which nothing ran, and pruned
payload bodies and observations that outlived their capture are counted.
Output is capped (default 10 per source and 100 in all, at most 1,000
- and 5,000) with matched and returned counts per source.
+ and 5,000) with matched and returned counts per source; in by=observed
+ the day values and period values share one budget. A limit that is not
+ an integer (a bool, 2.9, infinity) gets the default.
+- One call reads one SQLite snapshot (a single read transaction), so a
+ collector cycle committing mid-call cannot mix two states. A store
+ missing some history tables is an error naming them, not an empty day.
+ Values whose `observed_at` starts with the day but sorts above
+ `T23:59:59Z` (fractional seconds, offsets) are counted on the day.
- Read-only: the store is opened with SQLite `mode=ro`, so the tool cannot
write it, and it never fetches. Queries range-scan
`idx_history_captures_time` and `idx_history_obs_time` and walk
`idx_history_obs_series` one key at a time; a test checks every
statement's query plan for a full scan of a history table. On a
synthetic store of 475,200 captures and 1.75 million observations
- (10,982 series), one call took 24 to 46 ms.
+ (10,982 series), one call took 24 to 46 ms (measured before the review
+ fixes, not re-measured).
- Tools 152 -> 153.
### Added: observation history and collection health
diff --git a/README.md b/README.md
index 274b516..56a5d19 100644
--- a/README.md
+++ b/README.md
@@ -606,7 +606,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_day_timeline` | What the history store holds for one UTC day (`YYYY-MM-DD`; a future day is an error). `by=collected` (default): per source, that day's captures (attempts, ok / degraded / error with reasons, changed vs unchanged payloads, first and last capture, observations stored), and for a source with no capture whether the collector did not run that day, ran without it, never ran it, or the day is past run-log retention. `by=observed`: values whose `observed_at` falls on the day; month and year values containing the day are listed apart as period values, and undated observations are counted and excluded. Every item carries `observed_at`, `published_at` and `collected_at`; pruned records are named, never read as a quiet day; per-source and total caps with truncation disclosed. Read-only, never fetches |
+| `intel_day_timeline` | What the history store holds for one UTC day (`YYYY-MM-DD`; a future day is an error). `by=collected` (default): per source, that day's captures (attempts, ok / degraded / error with reasons, changed vs unchanged payloads, first and last capture, observations stored), and extractor failures and partial failures, and for a source with no capture whether the collector did not run that day, ran without it, never ran it, the day is before the run log starts, or it is past run-log retention. `by=observed`: values whose `observed_at` falls on the day; month and year values containing the day are listed apart as period values, and undated observations are counted and excluded. Every item carries `observed_at`, `published_at` and `collected_at`; pruned records are named, never read as a quiet day; per-source and total caps (shared by both by=observed lists) with truncation disclosed. Read-only, one snapshot per call, never fetches |
---
diff --git a/ROADMAP.md b/ROADMAP.md
index 75608db..ddbabfc 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -581,7 +581,7 @@ dashboard.
| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :red_circle: |
| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :white_check_mark: Built 2026-10-17, unreleased: `intel_news_market_reaction` and `intel news-reaction`. Company rows: stock, benchmark (SPY, or the exchange country's index) and excess return on the story's session; country rows: index return with a trailing z-score. Session rule in the exchange's timezone (after close = next session; weekends and holidays read from the listing's own bars). Open: `^TASI` and `^TA125` (Saudi and Israel in the country-index table) return 404 on Yahoo, so those benchmarks are data gaps; story times inherit `sources/news.py`'s RSS timestamp offset until that is fixed |
| 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :red_circle: |
-| 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :white_check_mark: Built 2026-10-17, unreleased: `intel_day_timeline` and `intel history day` (`history_timeline.py`; read-only `mode=ro` connection, never fetches). by=collected: per-source run-log state (changed, unchanged, answered, degraded, failed, not_attempted, collector_did_not_run, never_run, unknown_past_retention) with attempts, status counts, reasons and payload changes; by=observed: date and UTC-instant values on the day, month and year values listed apart as period values, undated observations counted and excluded. Retention is stated per record kind for the day. Measured 2026-10-17: two live collector cycles of 6 sources four minutes apart (12 captures: ok 8, degraded 2, error 2; every payload in the second cycle matched the first) read back over a live MCP stdio session and the CLI; 2026-10-16 in the same store reads `collector_did_not_run` (context `before_first_capture`). On a synthetic store (475,200 captures, 1.75 million observations, 10,982 series) one call took 24 to 46 ms, and no statement full-scans a history table under SQLite 3.45.3, 3.53.4 and 3.54.0. Not measured: a live store with weeks of history |
+| 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :white_check_mark: Built 2026-10-17, unreleased: `intel_day_timeline` and `intel history day` (`history_timeline.py`; read-only `mode=ro` connection, never fetches). by=collected: per-source run-log state (changed, unchanged, answered, degraded, failed, not_attempted, collector_did_not_run, before_run_log, never_run, unknown_past_retention; collector ran, did_not_run, unknown_past_retention or not_recorded) with attempts, status counts, reasons, extractor failures, a partial_failure flag and payload changes; by=observed: date and UTC-instant values on the day, month and year values listed apart as period values, undated observations counted and excluded. Retention is stated per record kind for the day. Measured 2026-10-17: two live collector cycles of 6 sources four minutes apart (12 captures: ok 8, degraded 2, error 2; every payload in the second cycle matched the first) read back over a live MCP stdio session and the CLI; 2026-10-16 in the same store reads collector `not_recorded` (context `before_first_capture`) with sources `before_run_log` or `never_run` (re-measured 2026-10-18T02:16Z after the review fixes, MCP stdio and CLI). On a synthetic store (475,200 captures, 1.75 million observations, 10,982 series) one call took 24 to 46 ms (measured before the review fixes, not re-measured), and no statement full-scans a history table under SQLite 3.45.3, 3.53.4 and 3.54.0. Not measured: a live store with weeks of history |
| 3 | Dashboard views | Liquidity board, situations, top stories, collection health panels | :red_circle: |
Considered and not planned:
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index 240cf9f..0dd7629 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -3328,8 +3328,10 @@ def history_revisions(
help="collected: what was captured that day; observed: values whose observed_at is that day",
)
@click.option("--source", default=None, help="One collector source name")
[email protected]("--limit", default=None, type=int, help="Most items listed in all")
[email protected]("--per-source", "per_source", default=None, type=int, help="Most items listed per source")
[email protected]("--limit", default=None, type=int,
+ help="Most items listed in all (with --by observed, both lists together)")
[email protected]("--per-source", "per_source", default=None, type=int,
+ help="Most items listed per source (with --by observed, both lists together)")
@click.pass_context
def history_day(
ctx: click.Context,
@@ -3402,13 +3404,23 @@ def _print_day_collected(data: dict) -> None:
for row in data["sources"]:
counts = row.get("status_counts") or {}
changes = row.get("payload_changes") or {}
+ state = Text(row["day_state"], style=styles.get(row["day_state"], "yellow"))
if row["attempts"]:
top = (row.get("reasons") or [None])[0]
- context = f"{top['reason']} (x{top['count']})" if top else ""
+ context = ""
+ if top:
+ kind = "extraction: " if top.get("kind") == "extraction" else ""
+ context = f"{kind}{top['reason']} (x{top['count']})"
if row.get("more_reasons"):
context += f" +{row['more_reasons']} more"
stored = row.get("observations_stored")
- obs = "-" if stored is None else str(stored)
+ if stored is not None:
+ obs = str(stored)
+ else:
+ # An extractor that raised stored nothing: unknown, not "none".
+ obs = "?" if row.get("captures_extractor_raised") else "-"
+ if row.get("partial_failure"):
+ state = Text(f"{row['day_state']}, {counts['error']} failed", style="yellow")
else:
parts = []
if row.get("last_capture_before"):
@@ -3419,7 +3431,7 @@ def _print_day_collected(data: dict) -> None:
obs = str(row["observations_retained"]) if row["observations_retained"] else "-"
table.add_row(
_cell(row["source"]),
- Text(row["day_state"], style=styles.get(row["day_state"], "yellow")),
+ state,
str(row["attempts"]),
str(counts.get("ok", "-")),
str(counts.get("degraded", "-")),
diff --git a/src/world_intel_mcp/history_timeline.py b/src/world_intel_mcp/history_timeline.py
index 5acb95f..f502703 100644
--- a/src/world_intel_mcp/history_timeline.py
+++ b/src/world_intel_mcp/history_timeline.py
@@ -2,25 +2,32 @@
(ROADMAP Phase 29).
Two views over the store that ``history.py`` keeps in the cache database,
-both read through a read-only SQLite connection (``mode=ro``), so this
-module cannot write the store; it never fetches upstream either.
+both read through a read-only SQLite connection (``mode=ro``) inside one
+read transaction: this module cannot write the store, every statement of
+a call reads the same snapshot, and nothing here fetches upstream.
- ``by="collected"``: the run log for the day. Per source: attempts,
- ok / degraded / error counts with their reasons, captures whose payload
- changed or matched the capture before it, first and last capture time,
- observations stored, and how many of the day's payload bodies are still
- kept. A source without a capture that day says why: the collector
- recorded no capture of any source that day, it ran but not this source,
- the source has no capture in the retained run log (``never_run``), or
- the day is past run-log retention. The observations saved that day are
- listed too.
+ ok / degraded / error counts with their reasons, captures whose
+ extractor raised or whose points the store refused, captures whose
+ payload changed or matched the capture before it, first and last
+ capture time, observations stored, and how many of the day's payload
+ bodies are still kept. A source that failed some attempts and answered
+ others is flagged ``partial_failure``. A source without a capture that
+ day says why: the collector recorded no capture of any source that day,
+ it ran but not this source, the source has no capture in the retained
+ run log (``never_run``), the day is before this database's run log
+ starts (``before_run_log``), or the day is past run-log retention. The
+ observations saved that day are listed too.
- ``by="observed"``: observations whose ``observed_at`` falls on the day,
as a date (``YYYY-MM-DD``) or a UTC instant, one item per series and
observed_at with its latest stored value and how many values were
stored for it. Month (``YYYY-MM``) and year (``YYYY``) values that
- contain the day are listed separately, as period values. Observations
- without ``observed_at`` cannot be placed on any day: they are excluded,
- and the ones collected that day are counted.
+ contain the day are listed separately, as period values; the two lists
+ share one ``limit`` and ``per_source_limit``. Observations without
+ ``observed_at`` cannot be placed on any day: they are excluded, and the
+ ones collected that day are counted. Captures of the day and the day
+ after whose extractor failed are counted, since their values for the
+ day are missing.
The day is ``YYYY-MM-DD`` in UTC, the half-open window
``[day 00:00:00Z, next day 00:00:00Z)``. Collection times are compared as
@@ -28,6 +35,17 @@ epoch seconds, ``observed_at`` as stored text (the store keeps instants in
UTC as ``YYYY-MM-DDTHH:MM:SSZ``). A future day is an error; today is
allowed and reported as in progress.
+Coverage. Pruning deletes run-log captures older than one cutoff, for
+every source at once, and the history store stamps each capture with the
+time it inserts it. So a stored capture older than the day proves that
+nothing of the day was pruned, and the run log covers the whole day.
+When the run log's oldest capture falls on or after the day's start, the
+time before it is not covered: the database was not recording yet, or
+older captures were pruned, and the store cannot say which. Counts,
+states and the longest gap then cover only the part from that capture
+on, and a day before the run log starts reads ``not_recorded``, never as
+a day on which the collector did not run.
+
Retention (``history.retention_days()``) is stated per record kind for the
requested day, so a day whose records were pruned reads as pruned, never
as a day on which nothing happened.
@@ -43,12 +61,19 @@ Gaps / not covered:
- Retention windows come from this process's environment. The collector
prunes with its own, so a collector run with different
``WORLD_INTEL_HISTORY_*`` values makes the windows stated here wrong.
+- Coverage assumes captures are stamped when they are inserted and
+ removed only by the store's pruning. A capture written with an older
+ timestamp (a restored backup, a hand edit) would make a pruned day read
+ as covered.
- A date-only ``observed_at`` is the publisher's calendar date; it is
matched to the requested day by its label, not converted from the
publisher's time zone, which the payloads do not state.
- Collector cycles are not stored as such: "the collector did not run"
- means no capture of any source is recorded in the day's window of this
- database.
+ means no capture of any source is recorded in the covered part of the
+ day's window of this database.
+- The observed-date view checks for extractor failures only in captures
+ collected on the day and the day after; a failed capture outside that
+ span that held values for the day is not counted.
- The observed-date view costs one index seek per distinct series key.
USGS quakes get a series per event, so the cost grows with the event
count: about 12 ms for 11,000 series in 1.75 million rows, measured on
@@ -74,7 +99,7 @@ DEFAULT_LIMIT = 100
DEFAULT_PER_SOURCE_LIMIT = 10
MAX_LIMIT = 5000
MAX_PER_SOURCE_LIMIT = 1000
-# Distinct (status, reason) pairs shown per source; the rest are counted.
+# Distinct (kind, status, reason) entries shown per source; the rest are counted.
MAX_REASONS = 5
_DAY = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
@@ -102,13 +127,34 @@ WHERE c.collected_at >= :start AND c.collected_at < :end
GROUP BY c.source
"""
+# Capture reasons, then extraction notes the capture reason does not
+# already quote (an extractor whose points were all refused makes the
+# capture degraded with the note in its reason).
_CAPTURE_REASONS_SQL = """
-SELECT source, status, error, COUNT(*), MIN(collected_at), MAX(collected_at)
+SELECT source, 'capture', status, error, COUNT(*), MIN(collected_at), MAX(collected_at)
FROM history_captures
WHERE collected_at >= :start AND collected_at < :end AND error IS NOT NULL
AND (:source IS NULL OR source = :source)
GROUP BY source, status, error
-ORDER BY source, COUNT(*) DESC, MAX(collected_at) DESC
+UNION ALL
+SELECT source, 'extraction', status, extract_error, COUNT(*), MIN(collected_at),
+ MAX(collected_at)
+FROM history_captures
+WHERE collected_at >= :start AND collected_at < :end AND extract_error IS NOT NULL
+ AND (error IS NULL OR instr(error, extract_error) = 0)
+ AND (:source IS NULL OR source = :source)
+GROUP BY source, status, extract_error
+ORDER BY 1, 5 DESC, 7 DESC, 2, 4
+"""
+
+# history._extract leaves observations_extracted NULL when the extractor
+# raised, and sets it (with a note) when it refused some returned points.
+_EXTRACTION_SQL = """
+SELECT source, SUM(observations_extracted IS NULL), SUM(observations_extracted IS NOT NULL)
+FROM history_captures
+WHERE collected_at >= :start AND collected_at < :end AND extract_error IS NOT NULL
+ AND (:source IS NULL OR source = :source)
+GROUP BY source
"""
_COLLECTOR_DAY_SQL = """
@@ -191,18 +237,20 @@ WITH RECURSIVE keys(k) AS (
)
"""
-# Every stored string with the day as prefix sorts between :day and
-# :day_last ('<day>T23:59:59Z'); the CASE keeps the two recognized forms
-# and leaves anything else (only a writer bypassing record_cycle can
-# store it) NULL, to be counted rather than shown.
+# Every stored string with the day as prefix sorts in [:day, :day_upper),
+# :day_upper being the day with its last character incremented
+# ('2026-10-19' -> '2026-10-1:'). The CASE keeps the two recognized forms
+# (hours 00 to 23) and leaves anything else (only a writer bypassing
+# record_cycle can store it) NULL, to be counted rather than shown.
_DAY_MATCHED_CTE = """
, matched AS (
SELECT o.id, o.source, o.series_key, o.observed_at, o.published_at, o.collected_at,
o.value, o.unit, o.label, o.capture_id,
CASE WHEN o.observed_at = :day THEN 'date'
- WHEN o.observed_at GLOB :instant_glob THEN 'instant' END AS precision
+ WHEN o.observed_at GLOB :instant_glob
+ AND substr(o.observed_at, 12, 2) <= '23' THEN 'instant' END AS precision
FROM keys JOIN history_observations o
- ON o.series_key = keys.k AND o.observed_at >= :day AND o.observed_at <= :day_last
+ ON o.series_key = keys.k AND o.observed_at >= :day AND o.observed_at < :day_upper
WHERE :source IS NULL OR o.source = :source
)
"""
@@ -274,10 +322,14 @@ STATES_EXPLAINED = {
"degraded": "no ok capture that day; every delivered payload was marked stale or "
"degraded, was empty, or lacked the measures its extractor expects",
"failed": "every attempt that day was an error (reasons lists why)",
- "not_attempted": "the collector captured other sources that day but not this one; "
- "this source has captures on other days",
- "collector_did_not_run": "no capture of any source is recorded that day",
+ "not_attempted": "the collector captured other sources that day (in the part of it the "
+ "run log covers) but not this one; this source has captures on other days",
+ "collector_did_not_run": "no capture of any source is recorded that day, and the run "
+ "log covers the whole day (it still holds an older capture)",
"never_run": "no capture of this source anywhere in the retained run log",
+ "before_run_log": "the day is before the first capture in this database's run log (it "
+ "was not recording yet, or older captures were pruned): whether this source ran cannot "
+ "be read",
"unknown_past_retention": "part or all of the day is past run-log retention and no "
"capture of this source from it remains: whether it ran cannot be read",
}
@@ -317,13 +369,22 @@ def _iso(ts: float | None) -> str | None:
def _bounded(value: Any, default: int, maximum: int) -> int:
+ """A count clamped to 1..maximum. An integral float (MCP clients send
+ JSON 7 as 7.0) is that integer; a bool, a fraction, inf or nan gets
+ the default rather than a truncated or coerced value."""
+ if isinstance(value, bool) or (isinstance(value, float) and not value.is_integer()):
+ return default
try:
number = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return default
return max(1, min(maximum, number))
+def _per_source(counts: dict[str, int]) -> str:
+ return ", ".join(f"{name} {count:,}" for name, count in sorted(counts.items()))
+
+
def parse_day(value: Any, now: float) -> tuple[date | None, str | None]:
"""``YYYY-MM-DD`` -> (date, None), or (None, problem)."""
if not isinstance(value, str) or not _DAY.fullmatch(value):
@@ -373,6 +434,10 @@ class _Reader:
def __init__(self, conn: sqlite3.Connection | None):
self.conn = conn
+ @property
+ def available(self) -> bool:
+ return self.conn is not None
+
def all(self, sql: str, params: dict | None = None) -> list[tuple]:
if self.conn is None:
return []
@@ -384,23 +449,32 @@ class _Reader:
def _connect(db_path: Path) -> sqlite3.Connection | None:
- """A read-only connection, or None when the database does not exist
- (opening it read-only never creates it)."""
+ """A read-only connection inside one read transaction, or None when the
+ database does not exist (opening it read-only never creates it).
+
+ The transaction gives every statement of a call the snapshot its first
+ read saw, so a collector cycle committed mid-call cannot make the
+ answer disagree with itself; closing the connection ends it."""
path = Path(db_path).resolve()
if not path.exists():
return None
- return sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True, timeout=10)
+ conn = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True, timeout=10)
+ try:
+ conn.execute("BEGIN")
+ except sqlite3.Error:
+ conn.close()
+ raise
+ return conn
-def _has_history_tables(conn: sqlite3.Connection) -> bool:
- found = {
+def _history_tables(conn: sqlite3.Connection) -> set[str]:
+ return {
row[0]
for row in conn.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
_TABLES,
)
}
- return found == set(_TABLES)
def _retention(window: _Window) -> dict:
@@ -434,6 +508,12 @@ def _public_retention(retention: dict) -> dict:
}
+def _covers_whole_day(log_first: float | None, w: _Window) -> bool:
+ """True when the run log still holds a capture older than the day:
+ pruning cuts every source at one cutoff, so none of the day was pruned."""
+ return log_first is not None and log_first < w.start
+
+
def _item(row: tuple) -> dict:
(source, series_key, observed_at, published_at, collected_at, value, unit, label,
capture_id, capture_retained) = row[:10]
@@ -462,6 +542,20 @@ def _point(row: tuple) -> dict:
return item
+def _within_budget(items: list[dict], room: int, per_source: int, used: Counter) -> list[dict]:
+ """The leading items that fit in ``room`` more in all and in what
+ ``used`` left of ``per_source`` for each source."""
+ kept: list[dict] = []
+ taken = Counter(used)
+ for item in items:
+ if len(kept) >= room:
+ break
+ if taken[item["source"]] < per_source:
+ taken[item["source"]] += 1
+ kept.append(item)
+ return kept
+
+
def _truncation(matched_by_source: dict[str, int], items: list[dict], limit: int,
per_source: int) -> dict:
returned = Counter(item["source"] for item in items)
@@ -495,10 +589,11 @@ def _truncation_gap(what: str, block: dict, order: str) -> str | None:
# ---------------------------------------------------------------------------
-def _collector_block(r: _Reader, w: _Window, run_log: dict) -> dict:
+def _collector_block(r: _Reader, w: _Window, run_log: dict, log_first: float | None,
+ log_last: float | None) -> dict:
params = {"start": w.start, "end": w.end}
captures, sources, first, last = r.one(_COLLECTOR_DAY_SQL, params, (0, 0, None, None))
- log_first, log_last = r.one(_RUN_LOG_BOUNDS_SQL, None, (None, None))
+ whole_day = _covers_whole_day(log_first, w)
block: dict[str, Any] = {
"captures": captures,
"sources_captured": sources,
@@ -506,18 +601,17 @@ def _collector_block(r: _Reader, w: _Window, run_log: dict) -> dict:
"run_log_last_capture_at": _iso(log_last),
}
if captures:
- # The retained part of the day starts at the run-log cutoff when
- # the day straddles it; time before that is unknown, not silent.
- lower = w.start
- if run_log["day"] == "partly_past_window":
- lower = min(max(w.start, run_log["cutoff_ts"]), first)
- spans = [(lower, first), (last, min(w.end, w.now))]
+ # The run log covers the day from its oldest capture on; time
+ # before that capture is unrecorded, not a stretch without one.
+ covered_from = w.start if whole_day else log_first
+ spans = [(covered_from, first), (last, min(w.end, w.now))]
internal = r.one(_LONGEST_INTERNAL_GAP_SQL, params, (None, None))
if internal[0] is not None:
spans.append(internal)
gap_from, gap_to = max(spans, key=lambda span: span[1] - span[0])
block.update(
state="ran",
+ covered_from=_iso(covered_from),
first_capture_at=_iso(first),
last_capture_at=_iso(last),
longest_gap_s=round(max(0.0, gap_to - gap_from), 1),
@@ -526,7 +620,7 @@ def _collector_block(r: _Reader, w: _Window, run_log: dict) -> dict:
explanation=f"{captures:,} captures of {sources} source(s) are recorded that day.",
)
return block
- if run_log["day"] in ("past_window", "partly_past_window"):
+ if run_log["day"] in ("past_window", "partly_past_window") and not whole_day:
block.update(
state="unknown_past_retention",
explanation=(
@@ -537,10 +631,23 @@ def _collector_block(r: _Reader, w: _Window, run_log: dict) -> dict:
)
return block
if log_first is None:
- context, why = "empty_run_log", "the run log has no capture at all in this database"
- elif log_first >= w.end:
- context, why = "before_first_capture", f"the run log starts later, at {_iso(log_first)}"
- elif log_last < w.start:
+ block.update(
+ state="not_recorded",
+ context="empty_run_log",
+ explanation="The run log in this database has no capture at all: nothing is "
+ "recorded here, so whether the collector ran that day cannot be read.",
+ )
+ return block
+ if log_first >= w.end:
+ block.update(
+ state="not_recorded",
+ context="before_first_capture",
+ explanation=f"The run log in this database starts later, at {_iso(log_first)}: "
+ "no capture before then is recorded here, so whether the collector ran that day "
+ "cannot be read.",
+ )
+ return block
+ if log_last < w.start:
context, why = "after_last_capture", f"no capture is recorded since {_iso(log_last)}"
else:
context, why = "between_captures", "captures exist before and after this day"
@@ -564,6 +671,74 @@ def _captured_state(ok: int, degraded: int, changed: int, unchanged: int, first:
return "answered"
+def _run_log_gaps(r: _Reader, w: _Window, run_log: dict, collector: dict, whole_day: bool,
+ retained_captures: int, retained_obs: int) -> list[str]:
+ """Retention and coverage of the day's run log, most important first."""
+ gaps = []
+ oldest = collector["run_log_first_capture_at"]
+ if run_log["day"] == "past_window":
+ if retained_captures:
+ gaps.append(
+ f"This day is past the {run_log['days']:g}-day run-log retention (cutoff "
+ f"{run_log['cutoff']}); its {retained_captures:,} captures are still here only "
+ "because pruning runs at the end of a collector cycle, and the next cycle "
+ "removes them."
+ )
+ elif whole_day:
+ gaps.append(
+ f"This day is past the {run_log['days']:g}-day run-log retention (cutoff "
+ f"{run_log['cutoff']}), but the run log still holds an older capture "
+ f"({oldest}), so nothing from this day was pruned: the collector recorded no "
+ "capture of any source that day."
+ )
+ else:
+ # Observations collected that day prove it had captures; without
+ # them the day may equally predate this database.
+ what = "its captures are gone" if retained_obs else "any captures from it are gone"
+ gaps.append(
+ f"The run log keeps captures {run_log['days']:g} days (cutoff "
+ f"{run_log['cutoff']}); this day is past it, so {what}. Whether the collector "
+ "or any source ran that day cannot be read here: absence is not evidence "
+ "that nothing happened."
+ )
+ elif run_log["day"] == "partly_past_window":
+ if whole_day:
+ gaps.append(
+ f"Part of this day is past the {run_log['days']:g}-day run-log retention "
+ f"(cutoff {run_log['cutoff']}), but the run log still holds an older capture "
+ f"({oldest}), so no capture from this day has been pruned yet. Pruning runs "
+ "at the end of each collector cycle, so the next one removes this day's "
+ "captures from before the cutoff."
+ )
+ else:
+ gaps.append(
+ f"Captures before {run_log['cutoff']} (the {run_log['days']:g}-day run-log "
+ "cutoff) are pruned: this day's earlier hours may be missing from the counts "
+ "above, and a source shown as unknown_past_retention may have run then."
+ )
+ if retained_captures and not whole_day:
+ gaps.append(
+ f"The run log holds no capture before {oldest}, its oldest: this day before then "
+ "is not covered (this database was not recording yet, or older captures were "
+ f"pruned), so counts, states and the longest gap cover only {oldest} onward."
+ )
+ if collector["state"] == "not_recorded" and r.available:
+ day = w.day.isoformat()
+ if collector["context"] == "before_first_capture":
+ gaps.append(
+ f"This database's run log starts at {oldest}: no capture before then is "
+ "recorded here (the database was not recording yet, or older captures were "
+ f"pruned), so whether the collector or any source ran on {day} cannot be read. "
+ "Absence is not evidence that nothing ran."
+ )
+ else:
+ gaps.append(
+ "The run log in this database has no capture: no collector cycle is recorded "
+ f"here yet, so whether the collector or any source ran on {day} cannot be read."
+ )
+ return gaps
+
+
def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
source: str | None, limit: int, per_source: int,
retention: dict) -> dict:
@@ -573,8 +748,11 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
reasons: dict[str, list[tuple]] = {}
for row in r.all(_CAPTURE_REASONS_SQL, params):
reasons.setdefault(row[0], []).append(row[1:])
+ extraction = {row[0]: row[1:] for row in r.all(_EXTRACTION_SQL, params)}
obs_counts = dict(r.all(_COLLECTED_OBS_COUNTS_SQL, params))
- collector = _collector_block(r, w, run_log)
+ log_first, log_last = r.one(_RUN_LOG_BOUNDS_SQL, None, (None, None))
+ whole_day = _covers_whole_day(log_first, w)
+ collector = _collector_block(r, w, run_log, log_first, log_last)
if source is None:
names = names + sorted((set(summary) | set(obs_counts)) - set(names))
@@ -584,7 +762,7 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
entry: dict[str, Any] = {"source": name, "in_collector_roster": name in roster}
cap = summary.get(name)
if cap is None:
- if run_log["day"] in ("past_window", "partly_past_window"):
+ if run_log["day"] in ("past_window", "partly_past_window") and not whole_day:
state = "unknown_past_retention"
else:
before, after = r.one(
@@ -593,6 +771,8 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
)
if before is None and after is None:
state = "never_run"
+ elif log_first >= w.end:
+ state = "before_run_log"
elif collector["captures"] == 0:
state = "collector_did_not_run"
else:
@@ -604,11 +784,13 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
continue
(_, attempts, ok, degraded, error, changed, unchanged, first, not_stored,
first_at, last_at, obs_stored, with_extractor, bodies_kept, bodies_pruned) = cap
+ raised, skipped = extraction.get(name, (0, 0))
source_reasons = reasons.get(name, [])
entry.update(
day_state=_captured_state(ok, degraded, changed, unchanged, first),
attempts=attempts,
status_counts={"ok": ok, "degraded": degraded, "error": error},
+ partial_failure=bool(error and (ok or degraded)),
payload_changes={
"changed": changed, "unchanged": unchanged, "first": first,
"not_stored": not_stored,
@@ -617,14 +799,22 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
last_capture_at=_iso(last_at),
observations_stored=obs_stored if with_extractor else None,
observations_retained=retained_obs,
+ captures_extractor_raised=raised,
+ captures_points_skipped=skipped,
captures_with_body_retained=bodies_kept,
captures_with_body_pruned=bodies_pruned,
reasons=[
- {"status": status, "reason": reason, "count": count,
+ {"kind": kind, "status": status, "reason": reason, "count": count,
"first_at": _iso(r_first), "last_at": _iso(r_last)}
- for status, reason, count, r_first, r_last in source_reasons[:MAX_REASONS]
+ for kind, status, reason, count, r_first, r_last in source_reasons[:MAX_REASONS]
],
)
+ if raised:
+ entry["observations_stored_note"] = (
+ f"the extractor raised on {raised:,} capture(s), which stored nothing; "
+ + (f"this counts the {with_extractor:,} it ran on" if with_extractor
+ else "it ran on no capture that day, so the count is unknown")
+ )
if len(source_reasons) > MAX_REASONS:
entry["more_reasons"] = len(source_reasons) - MAX_REASONS
rows.append(entry)
@@ -637,36 +827,36 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
]
truncation = _truncation(obs_counts, items, limit, per_source)
- gaps = []
retained_captures = sum(row[1] for row in summary.values())
- if run_log["day"] == "past_window":
- if retained_captures:
- gaps.append(
- f"This day is past the {run_log['days']:g}-day run-log retention (cutoff "
- f"{run_log['cutoff']}); its {retained_captures:,} captures are still here only "
- "because pruning runs at the end of a collector cycle, and the next cycle "
- "removes them."
- )
- else:
- gaps.append(
- f"The run log keeps captures {run_log['days']:g} days (cutoff "
- f"{run_log['cutoff']}); this day is past it, so its captures are gone. Whether "
- "the collector or any source ran that day cannot be read here: absence is "
- "not evidence that nothing happened."
- )
- elif run_log["day"] == "partly_past_window":
+ gaps = _run_log_gaps(r, w, run_log, collector, whole_day, retained_captures,
+ sum(obs_counts.values()))
+ raised_by = {name: c[0] for name, c in extraction.items() if c[0]}
+ skipped_by = {name: c[1] for name, c in extraction.items() if c[1]}
+ if raised_by:
gaps.append(
- f"Captures before {run_log['cutoff']} (the {run_log['days']:g}-day run-log cutoff) "
- "are pruned: this day's earlier hours may be missing from the counts above, and "
- "a source shown as unknown_past_retention may have run then."
+ f"History extractors raised on {sum(raised_by.values()):,} capture(s) that day "
+ f"({_per_source(raised_by)}): those captures stored no observations, so "
+ "observations_stored and the observed-date view miss whatever they held; each "
+ "source's reasons give the error."
+ )
+ if skipped_by:
+ gaps.append(
+ f"{sum(skipped_by.values()):,} capture(s) that day had points their extractor "
+ f"returned but the store refused as invalid ({_per_source(skipped_by)}): those "
+ "points were not stored."
)
pruned_bodies = sum(row[14] for row in summary.values())
kept_bodies = sum(row[13] for row in summary.values())
if pruned_bodies:
+ body_days = retention["payload_bodies"]["days"]
+ kept = (
+ f"bodies are kept {body_days:g} days after the payload was last seen"
+ if body_days > 0 else "this server's settings keep bodies forever, so the "
+ "collector pruned them with its own WORLD_INTEL_HISTORY_PAYLOAD_DAYS"
+ )
gaps.append(
- f"Payload bodies of {pruned_bodies:,} of this day's captures were pruned (bodies "
- f"are kept {retention['payload_bodies']['days']:g} days after the payload was last "
- "seen); intel_capture_history can replay only captures whose body is retained "
+ f"Payload bodies of {pruned_bodies:,} of this day's captures were pruned ({kept}); "
+ "intel_capture_history can replay only captures whose body is retained "
f"({kept_bodies:,} of {kept_bodies + pruned_bodies:,})."
)
observations = retention["observations"]
@@ -687,6 +877,7 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
"collector": collector,
"sources": rows,
"state_counts": states,
+ "partial_failure_sources": [row["source"] for row in rows if row.get("partial_failure")],
"observations": items,
"truncation": truncation,
"data_gaps": gaps,
@@ -699,6 +890,8 @@ def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],
"upstream published new data.",
"A degraded capture with no records cannot tell a quiet period from a silent "
"upstream failure.",
+ "Coverage is inferred: a stored capture older than the day means none of the "
+ "day was pruned, because the store stamps captures when it inserts them.",
HISTORY_ACCRUAL_NOTE,
],
}
@@ -714,18 +907,30 @@ def _observed_view(r: _Reader, w: _Window, obs_sources: list[str], roster: set[s
retention: dict) -> dict:
day = w.day.isoformat()
base = {"source": source, "per_source": per_source, "limit": limit}
- day_params = {**base, "day": day, "day_last": f"{day}T23:59:59Z",
+ day_params = {**base, "day": day, "day_upper": day[:-1] + chr(ord(day[-1]) + 1),
"instant_glob": f"{day}T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]Z"}
period_params = {**base, "month": day[:7], "year": day[:4]}
+ # Captures of the day and the next can hold values observed on the day
+ # (the K-index payload spans 24 hours); failed extractions there lose them.
+ checked_to = w.end + 86400.0
+ extraction = {
+ row[0]: row[1:]
+ for row in r.all(_EXTRACTION_SQL, {"start": w.start, "end": checked_to, "source": source})
+ }
day_counts = {row[0]: row[1:] for row in r.all(_DAY_COUNTS_SQL, day_params)}
period_counts = {row[0]: row[1:] for row in r.all(_PERIOD_COUNTS_SQL, period_params)}
no_date = dict(r.all(_NO_OBSERVED_AT_SQL, {"start": w.start, "end": w.end, "source": source}))
day_items = [_point(row) for row in r.all(_DAY_ITEMS_SQL, day_params)]
- period_items = [_point(row) for row in r.all(_PERIOD_ITEMS_SQL, period_params)]
+ # One budget for both lists: period values get what the day values left,
+ # in all and per source. The query's own caps return enough rows for that.
+ period_items = _within_budget(
+ [_point(row) for row in r.all(_PERIOD_ITEMS_SQL, period_params)],
+ limit - len(day_items), per_source, Counter(item["source"] for item in day_items),
+ )
names = [source] if source is not None else sorted(
- set(obs_sources) | set(day_counts) | set(period_counts) | set(no_date)
+ set(obs_sources) | set(day_counts) | set(period_counts) | set(no_date) | set(extraction)
)
rows = []
for name in names:
@@ -751,10 +956,10 @@ def _observed_view(r: _Reader, w: _Window, obs_sources: list[str], roster: set[s
gaps = []
excluded = sum(no_date.values())
if excluded:
- by_source = ", ".join(f"{name} {count:,}" for name, count in sorted(no_date.items()))
gaps.append(
f"{excluded:,} observation(s) collected this day have no observed_at "
- f"({by_source}) and are excluded: {_NO_OBSERVED_AT_REASON}. by=collected lists them."
+ f"({_per_source(no_date)}) and are excluded: {_NO_OBSERVED_AT_REASON}. by=collected "
+ "lists them."
)
unrecognized_total = sum(c[2] for c in day_counts.values())
if unrecognized_total:
@@ -763,6 +968,22 @@ def _observed_view(r: _Reader, w: _Window, obs_sources: list[str], roster: set[s
f"recognized form ({day} or {day}THH:MM:SSZ) and are excluded; only a writer "
"that bypasses the history store's validation can store them."
)
+ raised_by = {name: c[0] for name, c in extraction.items() if c[0]}
+ skipped_by = {name: c[1] for name, c in extraction.items() if c[1]}
+ span = f"from {_iso(w.start)} to {_iso(checked_to)}"
+ if raised_by:
+ gaps.append(
+ f"History extractors raised on {sum(raised_by.values()):,} capture(s) collected "
+ f"{span} ({_per_source(raised_by)}): values for {day} that those captures held "
+ "were not stored, so day_values may miss them. Captures collected outside that "
+ "span are not checked."
+ )
+ if skipped_by:
+ gaps.append(
+ f"{sum(skipped_by.values()):,} capture(s) collected {span} had points the store "
+ f"refused as invalid ({_per_source(skipped_by)}); values for {day} among them "
+ "are missing."
+ )
observations = retention["observations"]
if observations["day"] in ("past_window", "partly_past_window"):
gaps.append(
@@ -774,13 +995,22 @@ def _observed_view(r: _Reader, w: _Window, obs_sources: list[str], roster: set[s
1 for item in day_items + period_items if not item["capture_retained"]
)
if pruned_captures:
+ log_days = retention["run_log"]["days"]
+ kept = (
+ f"the run log keeps {log_days:g} days" if log_days > 0
+ else "this server's settings keep the run log forever, so the collector pruned "
+ "it with its own WORLD_INTEL_HISTORY_CAPTURE_DAYS"
+ )
gaps.append(
f"{pruned_captures:,} listed value(s) outlived the capture that produced them "
- f"(the run log keeps {retention['run_log']['days']:g} days); capture_retained "
- "marks them."
+ f"({kept}); capture_retained marks them."
)
- for what, block in (("Day values", day_truncation), ("Period values", period_truncation)):
- truncated = _truncation_gap(what, block, "by observed_at, then series")
+ for what, block, order in (
+ ("Day values", day_truncation, "by observed_at, then series"),
+ ("Period values", period_truncation,
+ "by observed_at, then series, after the day values, which share these caps"),
+ ):
+ truncated = _truncation_gap(what, block, order)
if truncated:
gaps.append(truncated)
if w.in_progress:
@@ -798,6 +1028,15 @@ def _observed_view(r: _Reader, w: _Window, obs_sources: list[str], roster: set[s
"by_source": dict(sorted(no_date.items())),
"reason": _NO_OBSERVED_AT_REASON,
},
+ "extraction_problems": {
+ "captures_from": _iso(w.start),
+ "captures_to": _iso(checked_to),
+ "end_exclusive": True,
+ "by_source": {
+ name: {"extractor_raised": c[0], "points_skipped": c[1]}
+ for name, c in sorted(extraction.items())
+ },
+ },
"truncation": {"day_values": day_truncation, "period_values": period_truncation},
"precision_explained": PRECISION_EXPLAINED,
"data_gaps": gaps,
@@ -854,7 +1093,16 @@ def day_timeline(
except sqlite3.Error as exc:
return {"error": f"history store could not be opened read-only: {exc}"}
try:
- ready = conn is not None and _has_history_tables(conn)
+ found = _history_tables(conn) if conn is not None else set()
+ if found and found != set(_TABLES):
+ missing = sorted(set(_TABLES) - found)
+ return {
+ "error": f"history store in {Path(db_path)} is incomplete: table(s) "
+ f"{', '.join(missing)} missing, so no day can be read from it",
+ "missing_tables": missing,
+ "db_path": str(db_path),
+ }
+ ready = bool(found)
r = _Reader(conn if ready else None)
logged = [row[0] for row in r.all(_CAPTURE_SOURCES_SQL)]
obs_sources = [row[0] for row in r.all(_OBSERVATION_SOURCES_SQL)]
diff --git a/src/world_intel_mcp/tests/test_history_timeline.py b/src/world_intel_mcp/tests/test_history_timeline.py
index 07ffd0b..499ed05 100644
--- a/src/world_intel_mcp/tests/test_history_timeline.py
+++ b/src/world_intel_mcp/tests/test_history_timeline.py
@@ -16,6 +16,7 @@ import json
import os
import re
import sqlite3
+import time
import types
from datetime import datetime, timedelta, timezone
@@ -715,11 +716,29 @@ def _recent_day(days_ago: int = 2) -> str:
return (datetime.now(timezone.utc) - timedelta(days=days_ago)).date().isoformat()
-async def test_tool_through_the_real_dispatcher_never_fetches(server, tmp_path, monkeypatch) -> None:
+_LAZY_RUNTIME = ("cache", "breaker", "aoi_store", "_aoi_store", "vector_store", "_vector_store",
+ "fetcher")
+
+
+def runtime_untouched():
+ """Fails the test if it initialized the shared runtime, whose Cache and
+ AOIStore no test closes. monkeypatch.setattr(runtime, "cache", ...)
+ does: reading the old value calls runtime.__getattr__, which opens
+ them all. Only the patched "cache" may appear."""
+ from world_intel_mcp import runtime
+
+ others = set(_LAZY_RUNTIME) - {"cache"}
+ before = {name for name in others if name in vars(runtime)}
+ yield
+ assert {name for name in others if name in vars(runtime)} == before
+
+
+async def test_tool_through_the_real_dispatcher_never_fetches(runtime_untouched, server, tmp_path, monkeypatch) -> None:
from world_intel_mcp import runtime
db = tmp_path / "dispatch.db"
- monkeypatch.setattr(runtime, "cache", types.SimpleNamespace(db_path=db))
+ monkeypatch.setitem(vars(runtime), "cache", types.SimpleNamespace(db_path=db))
day = _recent_day()
s = HistoryStore(db)
s.record_cycle([
@@ -840,3 +859,725 @@ def test_cli_history_day_errors(cli_day) -> None:
assert wrong_view.exit_code == 2
unknown = _invoke("history", "day", cli_day, "--source", "nope").output
assert unknown.startswith("Error:") and "unknown source" in unknown
+
+
+def test_cli_state_cell_is_the_exact_state(cli_day) -> None:
+ text = _invoke("history", "day", cli_day).output
+ cells = {line.split()[0]: line.split() for line in text.splitlines() if line.strip()}
+ # "changed" in a row would also match "unchanged": compare the cell.
+ assert cells["space_weather"][1] == "changed"
+ assert cells["market_quotes"][1] == "changed"
+ data = json.loads(_invoke("--json-output", "history", "day", cli_day).output)
+ assert by_source(data)["market_quotes"]["day_state"] == "changed"
+
+
+def test_cli_day_before_the_run_log_reads_not_recorded(cli_day) -> None:
+ early = (datetime.fromisoformat(cli_day) - timedelta(days=1)).date().isoformat()
+ text = _invoke("history", "day", early).output
+ assert "Collector: not_recorded. The run log in this database starts later, at " in text
+ assert "Gap: This database's run log starts at" in text
+ cells = {line.split()[0]: line.split() for line in text.splitlines() if line.strip()}
+ assert cells["space_weather"][1] == "before_run_log"
+ assert cells["cyclones"][1] == "never_run"
+
+
+def cli_db(tmp_path, monkeypatch):
+ db = tmp_path / "cli-db.db"
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(db))
+ monkeypatch.setenv("COLUMNS", "220")
+ monkeypatch.setattr(cli, "_fetcher", None)
+ yield db
+ if cli._fetcher is not None:
+ cli._fetcher.cache.close()
+
+
+def test_cli_flags_partial_failure_and_unknown_observation_counts(cli_db, monkeypatch) -> None:
+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))
+
+ def _raise(payload):
+ raise ValueError("rows changed shape")
+
+ for name in ("wildfires", "cyclones"):
+ history.register_extractor(name, _raise)
+ day, before = _recent_day(), _recent_day(3)
+ fires = {"fires": [1]}
+ s = HistoryStore(cli_db)
+ try:
+ t = at(f"{before}T12:00:00Z")
+ s.record_cycle([SourceOutcome("wildfires", t, 1.0, fires)], now=t)
+ for hour in range(23):
+ t = at(f"{day}T{hour:02d}:00:00Z")
+ s.record_cycle([SourceOutcome("wildfires", t, 1.0, error="timeout (45.0s)")], now=t)
+ t = at(f"{day}T23:00:00Z")
+ s.record_cycle([SourceOutcome("wildfires", t, 1.0, fires),
+ SourceOutcome("cyclones", t, 1.0, {"storms": [1]})], now=t)
+ finally:
+ s.close()
+ text = _invoke("history", "day", day).output
+ lines = {line.split()[0]: line for line in text.splitlines() if line.strip()}
+ assert "unchanged, 23 failed" in lines["wildfires"]
+ # Its extractor raised on the one answer: the count is unknown, not none.
+ assert "?" in lines["wildfires"].split()
+ assert "timeout (45.0s) (x23)" in lines["wildfires"]
+ assert "extraction: extractor raised: ValueError: rows changed shape (x1)" in lines["cyclones"]
+ assert "Gap: History extractors raised on 2 capture(s) that day (cyclones 1, wildfires 1)" in text
+
+
+# ---------------------------------------------------------------------------
+# Review round 2: coverage of the run log
+# ---------------------------------------------------------------------------
+
+
+def iso(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def hourly(store, start: str, end: str, source: str = "space_weather") -> None:
+ """A one-source cycle every hour in [start, end), each pruned as the collector would."""
+ ts = at(start)
+ while ts < at(end):
+ when = iso(ts)
+ cycle(store, when, out(source, when, kp((when, 2.0))))
+ ts += 3600
+
+
+def coverage_gap(oldest: str) -> str:
+ return (
+ f"The run log holds no capture before {oldest}, its oldest: this day before then is "
+ "not covered (this database was not recording yet, or older captures were pruned), so "
+ f"counts, states and the longest gap cover only {oldest} onward."
+ )
+
+
+def test_day_pruned_by_the_last_cycle_counts_only_what_remains(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ # Hourly through 2026-10-12T12:00Z: that last cycle pruned captures before 2026-10-10T12:00Z.
+ hourly(store, "2026-10-10T00:00:00Z", "2026-10-12T13:00:00Z")
+ # A day later the whole of 2026-10-10 is past this reader's cutoff.
+ result = day_timeline(db, "2026-10-10", roster=["space_weather", "cyclones"],
+ now=at("2026-10-13T12:00:00Z"))
+ assert result["retention"]["run_log"]["day"] == "past_window"
+ c = result["collector"]
+ assert (c["captures"], c["covered_from"], c["first_capture_at"]) == (
+ 12, "2026-10-10T12:00:00Z", "2026-10-10T12:00:00Z"
+ )
+ # The pruned morning is not a stretch without capture.
+ assert (c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (
+ 3600.0, "2026-10-10T23:00:00Z", "2026-10-11T00:00:00Z"
+ )
+ assert result["data_gaps"][:2] == [
+ "This day is past the 2-day run-log retention (cutoff 2026-10-11T12:00:00Z); its 12 "
+ "captures are still here only because pruning runs at the end of a collector cycle, and "
+ "the next cycle removes them.",
+ coverage_gap("2026-10-10T12:00:00Z"),
+ ]
+ assert by_source(result)["cyclones"]["day_state"] == "unknown_past_retention"
+
+
+def _outage_store(store) -> None:
+ """Hourly captures on 2026-10-09, and on 2026-10-10 from 06:00Z: the
+ collector was down 00:00 to 06:00 on the 10th."""
+ hourly(store, "2026-10-09T00:00:00Z", "2026-10-10T00:00:00Z")
+ hourly(store, "2026-10-10T06:00:00Z", "2026-10-11T00:00:00Z")
+
+
+def test_outage_on_a_partly_expired_day_the_run_log_still_covers(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ _outage_store(store)
+ result = day_timeline(db, "2026-10-10", roster=["space_weather", "cyclones"],
+ now=at("2026-10-12T08:00:00Z"))
+ assert result["retention"]["run_log"]["day"] == "partly_past_window"
+ c = result["collector"]
+ assert (c["covered_from"], c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (
+ "2026-10-10T00:00:00Z", 21_600.0, "2026-10-10T00:00:00Z", "2026-10-10T06:00:00Z"
+ )
+ # Nothing of the day was pruned, so a roster source with no capture never ran.
+ assert by_source(result)["cyclones"]["day_state"] == "never_run"
+ assert result["data_gaps"][0] == (
+ "Part of this day is past the 2-day run-log retention (cutoff 2026-10-10T08:00:00Z), but "
+ "the run log still holds an older capture (2026-10-09T00:00:00Z), so no capture from "
+ "this day has been pruned yet. Pruning runs at the end of each collector cycle, so the "
+ "next one removes this day's captures from before the cutoff."
+ )
+ assert not any(g.startswith("The run log holds no capture before") for g in result["data_gaps"])
+
+
+def test_outage_on_an_expired_day_the_run_log_still_covers(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ _outage_store(store)
+ result = day_timeline(db, "2026-10-10", roster=["space_weather"], now=at("2026-10-13T00:00:00Z"))
+ assert result["retention"]["run_log"]["day"] == "past_window"
+ c = result["collector"]
+ assert (c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (
+ 21_600.0, "2026-10-10T00:00:00Z", "2026-10-10T06:00:00Z"
+ )
+ assert result["data_gaps"][0].startswith(
+ "This day is past the 2-day run-log retention (cutoff 2026-10-11T00:00:00Z); its 18 "
+ "captures are still here"
+ )
+
+
+def test_expired_day_without_captures_the_run_log_still_covers(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ cycle(store, "2026-10-09T13:00:00Z",
+ out("space_weather", "2026-10-09T13:00:00Z", kp(("2026-10-09T12:00:00Z", 2.0))))
+ cycle(store, "2026-10-11T12:00:00Z",
+ out("space_weather", "2026-10-11T12:00:00Z", kp(("2026-10-11T11:00:00Z", 3.0))))
+ result = day_timeline(db, "2026-10-10", roster=["space_weather"], now=at("2026-10-13T12:00:00Z"))
+ assert result["retention"]["run_log"]["day"] == "past_window"
+ c = result["collector"]
+ assert (c["state"], c["context"]) == ("did_not_run", "between_captures")
+ assert by_source(result)["space_weather"]["day_state"] == "collector_did_not_run"
+ assert result["data_gaps"] == [
+ "This day is past the 2-day run-log retention (cutoff 2026-10-11T12:00:00Z), but the run "
+ "log still holds an older capture (2026-10-09T13:00:00Z), so nothing from this day was "
+ "pruned: the collector recorded no capture of any source that day."
+ ]
+
+
+def test_day_before_the_run_log_starts_reads_not_recorded(store, db) -> None:
+ cycle(store, "2026-10-15T12:00:00Z",
+ out("space_weather", "2026-10-15T12:00:00Z", kp(("2026-10-15T09:00:00Z", 2.0))),
+ out("earthquakes", "2026-10-15T12:00:00Z", error="timeout (45.0s)"))
+ roster = ["space_weather", "earthquakes", "cyclones"]
+ result = day_timeline(db, "2026-10-14", roster=roster, now=LATER)
+ c = result["collector"]
+ assert (c["state"], c["context"], c["captures"]) == ("not_recorded", "before_first_capture", 0)
+ assert c["explanation"] == (
+ "The run log in this database starts later, at 2026-10-15T12:00:00Z: no capture before "
+ "then is recorded here, so whether the collector ran that day cannot be read."
+ )
+ assert {name: row["day_state"] for name, row in by_source(result).items()} == {
+ "space_weather": "before_run_log", "earthquakes": "before_run_log", "cyclones": "never_run",
+ }
+ assert set(result["state_counts"]) <= set(result["states_explained"])
+ assert result["data_gaps"] == [
+ "This database's run log starts at 2026-10-15T12:00:00Z: no capture before then is "
+ "recorded here (the database was not recording yet, or older captures were pruned), so "
+ "whether the collector or any source ran on 2026-10-14 cannot be read. Absence is not "
+ "evidence that nothing ran."
+ ]
+
+ # The store's first day is covered from its first capture: the morning is unrecorded.
+ first_day = day_timeline(db, "2026-10-15", roster=roster, now=LATER)
+ c = first_day["collector"]
+ assert (c["covered_from"], c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (
+ "2026-10-15T12:00:00Z", 43_200.0, "2026-10-15T12:00:00Z", "2026-10-16T00:00:00Z"
+ )
+ assert first_day["data_gaps"] == [coverage_gap("2026-10-15T12:00:00Z")]
+
+
+def test_empty_run_log_reads_not_recorded_and_bare_files_say_no_tables(tmp_path) -> None:
+ empty = tmp_path / "empty.db"
+ HistoryStore(empty).close()
+ result = day_timeline(empty, "2026-10-17", roster=["space_weather"], now=LATER)
+ assert (result["collector"]["state"], result["collector"]["context"]) == (
+ "not_recorded", "empty_run_log"
+ )
+ assert by_source(result)["space_weather"]["day_state"] == "never_run"
+ assert result["data_gaps"] == [
+ "The run log in this database has no capture: no collector cycle is recorded here yet, "
+ "so whether the collector or any source ran on 2026-10-17 cannot be read."
+ ]
+
+ bare = tmp_path / "bare.db"
+ sqlite3.connect(bare).close()
+ for by in ("collected", "observed"):
+ result = day_timeline(bare, "2026-10-17", by=by, roster=["space_weather"], now=LATER)
+ assert result["data_gaps"] == [
+ f"No history tables in {bare}: the collector has not recorded a cycle in this "
+ "database, so there is nothing to read for any day."
+ ]
+ assert by_source(day_timeline(bare, "2026-10-17", roster=["space_weather"], now=LATER))[
+ "space_weather"]["day_state"] == "never_run"
+
+ missing = tmp_path / "nowhere" / "missing.db"
+ result = day_timeline(missing, "2026-10-17", roster=["space_weather"], now=LATER)
+ assert result["data_gaps"][0].startswith("No history tables")
+ assert not missing.exists() and not missing.parent.exists()
+
+
+def test_pruned_day_with_nothing_left_does_not_claim_it_had_captures(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ cycle(store, "2026-10-15T12:00:00Z",
+ out("space_weather", "2026-10-15T12:00:00Z", kp(("2026-10-15T09:00:00Z", 2.0))))
+ result = day_timeline(db, "2026-10-11", roster=["space_weather"], now=at("2026-10-17T12:00:00Z"))
+ assert result["collector"]["state"] == "unknown_past_retention"
+ assert result["data_gaps"][0] == (
+ "The run log keeps captures 2 days (cutoff 2026-10-15T12:00:00Z); this day is past it, "
+ "so any captures from it are gone. Whether the collector or any source ran that day "
+ "cannot be read here: absence is not evidence that nothing happened."
+ )
+
+
+def test_day_straddling_the_cutoff_starts_coverage_at_the_first_capture(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ cycle(store, "2026-10-11T20:00:00Z",
+ out("space_weather", "2026-10-11T20:00:00Z", kp(("2026-10-11T18:00:00Z", 2.0))))
+ result = day_timeline(db, "2026-10-11", roster=["space_weather", "cyclones"],
+ now=at("2026-10-13T12:00:00Z"))
+ assert result["data_gaps"][:2] == [
+ "Captures before 2026-10-11T12:00:00Z (the 2-day run-log cutoff) are pruned: this day's "
+ "earlier hours may be missing from the counts above, and a source shown as "
+ "unknown_past_retention may have run then.",
+ coverage_gap("2026-10-11T20:00:00Z"),
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Review round 2: extraction failures, partial failure, state precedence
+# ---------------------------------------------------------------------------
+
+
+def broken_extractors(feeds):
+ """feed_crash raises on every payload; feed_flaky raises on a payload
+ marked broken and otherwise returns one value for 2026-10-17."""
+
+ def _crash(payload):
+ raise ValueError("rows changed shape")
+
+ def _flaky(payload):
+ if payload.get("broken"):
+ raise ValueError("rows changed shape")
+ return [Observation("v", 1.0, observed_at="2026-10-17")]
+
+ history.register_extractor("feed_crash", _crash)
+ history.register_extractor("feed_flaky", _flaky)
+ return feeds
+
+
+def test_extractor_failures_are_counted_and_explained(store, db, broken_extractors) -> None:
+ feeds = broken_extractors
+ nan = float("nan")
+ cycle(store, "2026-10-16T12:00:00Z",
+ out("space_weather", "2026-10-16T12:00:00Z", kp(("2026-10-16T09:00:00Z", 2.0))))
+ for when, flaky in (("2026-10-17T08:00:00Z", {"broken": True, "rows": [1]}),
+ ("2026-10-17T09:00:00Z", {"rows": [2]})):
+ cycle(store, when,
+ out("feed_crash", when, {"rows": [1]}),
+ out("feed_flaky", when, flaky),
+ out("feed_a", when, feeds(("good", 1.0, "2026-10-17"), ("bad", nan, "2026-10-17"))),
+ out("feed_b", when, feeds(("bad", nan, "2026-10-17"))))
+ # The next day's capture raises too; it may have held values for the 17th.
+ cycle(store, "2026-10-18T08:00:00Z", out("feed_crash", "2026-10-18T08:00:00Z", {"rows": [2]}))
+
+ result = day_timeline(db, "2026-10-17", now=LATER)
+ rows = by_source(result)
+ crash = rows["feed_crash"]
+ assert (crash["captures_extractor_raised"], crash["captures_points_skipped"]) == (2, 0)
+ assert crash["observations_stored"] is None
+ assert crash["observations_stored_note"] == (
+ "the extractor raised on 2 capture(s), which stored nothing; it ran on no capture that "
+ "day, so the count is unknown"
+ )
+ # The error is listed once, whichever status the store gave those captures.
+ assert [r["count"] for r in crash["reasons"]
+ if "extractor raised: ValueError: rows changed shape" in r["reason"]] == [2]
+ flaky = rows["feed_flaky"]
+ assert (flaky["captures_extractor_raised"], flaky["observations_stored"]) == (1, 1)
+ assert flaky["observations_stored_note"] == (
+ "the extractor raised on 1 capture(s), which stored nothing; this counts the 1 it ran on"
+ )
+ feed_a = rows["feed_a"]
+ assert (feed_a["captures_extractor_raised"], feed_a["captures_points_skipped"]) == (0, 2)
+ assert feed_a["observations_stored"] == 1 and "observations_stored_note" not in feed_a
+ assert [(r["kind"], r["status"], r["reason"], r["count"]) for r in feed_a["reasons"]] == [
+ ("extraction", "ok", "1 invalid point(s) skipped", 2)
+ ]
+ # Every point refused: the capture reason already quotes the note, so it is not repeated.
+ feed_b = rows["feed_b"]
+ assert (feed_b["day_state"], feed_b["captures_points_skipped"]) == ("degraded", 2)
+ assert [(r["kind"], r["status"], r["reason"], r["count"]) for r in feed_b["reasons"]] == [
+ ("capture", "degraded",
+ "registered extractor found no measures in this payload (1 invalid point(s) skipped)", 2)
+ ]
+ assert result["data_gaps"] == [
+ "History extractors raised on 3 capture(s) that day (feed_crash 2, feed_flaky 1): those "
+ "captures stored no observations, so observations_stored and the observed-date view miss "
+ "whatever they held; each source's reasons give the error.",
+ "4 capture(s) that day had points their extractor returned but the store refused as "
+ "invalid (feed_a 2, feed_b 2): those points were not stored.",
+ ]
+
+ observed = day_timeline(db, "2026-10-17", by="observed", now=LATER)
+ assert [p["series_key"] for p in observed["day_values"]] == ["feed_a:good", "feed_flaky:v"]
+ assert observed["extraction_problems"] == {
+ "captures_from": "2026-10-17T00:00:00Z", "captures_to": "2026-10-19T00:00:00Z",
+ "end_exclusive": True,
+ "by_source": {
+ "feed_a": {"extractor_raised": 0, "points_skipped": 2},
+ "feed_b": {"extractor_raised": 0, "points_skipped": 2},
+ "feed_crash": {"extractor_raised": 3, "points_skipped": 0},
+ "feed_flaky": {"extractor_raised": 1, "points_skipped": 0},
+ },
+ }
+ assert "feed_crash" in by_source(observed) # listed although it stored nothing
+ assert observed["data_gaps"] == [
+ "History extractors raised on 4 capture(s) collected from 2026-10-17T00:00:00Z to "
+ "2026-10-19T00:00:00Z (feed_crash 3, feed_flaky 1): values for 2026-10-17 that those "
+ "captures held were not stored, so day_values may miss them. Captures collected outside "
+ "that span are not checked.",
+ "4 capture(s) collected from 2026-10-17T00:00:00Z to 2026-10-19T00:00:00Z had points the "
+ "store refused as invalid (feed_a 2, feed_b 2); values for 2026-10-17 among them are "
+ "missing.",
+ ]
+
+
+def test_a_mostly_failing_source_is_flagged_partial_failure(store, db) -> None:
+ fires = {"fires": [1]}
+ cycle(store, "2026-10-16T12:00:00Z", out("wildfires", "2026-10-16T12:00:00Z", fires))
+ for hour in range(23):
+ when = f"2026-10-17T{hour:02d}:00:00Z"
+ cycle(store, when, out("wildfires", when, error="timeout (45.0s)"),
+ out("earthquakes", when, error="boom"),
+ out("gas_prices", when, {"prices": [hour]}))
+ cycle(store, "2026-10-17T23:00:00Z", out("wildfires", "2026-10-17T23:00:00Z", fires))
+ result = day_timeline(db, "2026-10-17", now=LATER)
+ rows = by_source(result)
+ fires_row = rows["wildfires"]
+ assert (fires_row["day_state"], fires_row["status_counts"]) == (
+ "unchanged", {"ok": 1, "degraded": 0, "error": 23}
+ )
+ assert fires_row["partial_failure"] is True
+ assert (rows["earthquakes"]["day_state"], rows["earthquakes"]["partial_failure"]) == ("failed", False)
+ assert rows["gas_prices"]["partial_failure"] is False
+ assert result["partial_failure_sources"] == ["wildfires"]
+
+
+def test_captured_state_precedence_on_mixed_days(store, db) -> None:
+ def quote(price):
+ return {"quotes": [{"symbol": "^GSPC", "price": price}]}
+
+ cycle(store, "2026-10-16T12:00:00Z", out("market_quotes", "2026-10-16T12:00:00Z", quote(1.0)))
+ cycle(store, "2026-10-17T01:00:00Z",
+ out("gas_prices", "2026-10-17T01:00:00Z", {"prices": [1]}),
+ out("market_quotes", "2026-10-17T01:00:00Z", quote(2.0)))
+ cycle(store, "2026-10-17T02:00:00Z",
+ out("gas_prices", "2026-10-17T02:00:00Z",
+ {"prices": [1], "_stale": True, "_stale_age_seconds": 60.0}),
+ out("market_quotes", "2026-10-17T02:00:00Z", quote(2.0)))
+ rows = by_source(day_timeline(db, "2026-10-17", now=LATER))
+ gas = rows["gas_prices"]
+ assert gas["status_counts"] == {"ok": 1, "degraded": 1, "error": 0}
+ assert gas["day_state"] == "changed" # an ok capture outranks a degraded one
+ quotes = rows["market_quotes"]
+ assert quotes["payload_changes"] == {"changed": 1, "unchanged": 1, "first": 0, "not_stored": 0}
+ assert quotes["day_state"] == "changed" # a changed payload outranks an unchanged one
+
+
+# ---------------------------------------------------------------------------
+# Review round 2: windows, filters, gaps, caps, limits, schema, snapshot
+# ---------------------------------------------------------------------------
+
+
+def test_every_window_query_is_end_exclusive(store, db, feeds) -> None:
+ nan = float("nan")
+ for when, tag in (("2026-10-16T23:59:59Z", "late"), ("2026-10-17T00:00:00Z", "early")):
+ cycle(store, when,
+ out("earthquakes", when, error=f"{tag} timeout"),
+ out("feed_a", when, feeds((f"{tag}_dated", 1.0, when), (f"{tag}_undated", 2.0, None),
+ (f"{tag}_bad", nan, when))))
+ for day, tag in (("2026-10-16", "late"), ("2026-10-17", "early")):
+ result = day_timeline(db, day, now=LATER)
+ rows = by_source(result)
+ assert [r["reason"] for r in rows["earthquakes"]["reasons"]] == [f"{tag} timeout"]
+ assert [r["reason"] for r in rows["feed_a"]["reasons"]] == ["1 invalid point(s) skipped"]
+ assert rows["feed_a"]["captures_points_skipped"] == 1
+ assert rows["feed_a"]["observations_retained"] == 2
+ assert (result["truncation"]["matched"], result["truncation"]["returned"]) == (2, 2)
+ assert [o["series_key"] for o in result["observations"]] == [
+ f"feed_a:{tag}_dated", f"feed_a:{tag}_undated"
+ ]
+ observed = day_timeline(db, day, by="observed", now=LATER)
+ assert observed["without_observed_at"]["by_source"] == {"feed_a": 1}
+ assert [p["series_key"] for p in observed["day_values"]] == [f"feed_a:{tag}_dated"]
+
+
+def test_window_and_today_are_utc_whatever_the_host_zone(store, db, monkeypatch) -> None:
+ """Sets the host zone itself, so a local-time bug fails on a UTC CI runner too."""
+ now = at("2026-10-17T02:30:00Z") # 22:30 on 2026-10-16 in New York
+ cycle(store, "2026-10-17T02:00:00Z",
+ out("space_weather", "2026-10-17T02:00:00Z", kp(("2026-10-17T01:00:00Z", 2.0))))
+ with monkeypatch.context() as m:
+ m.setenv("TZ", "America/New_York")
+ time.tzset()
+ try:
+ local_day = datetime.fromtimestamp(now).day
+ today = day_timeline(db, "2026-10-17", now=now)
+ yesterday = day_timeline(db, "2026-10-16", now=now)
+ finally:
+ m.undo()
+ time.tzset()
+ assert local_day == 16, "TZ=America/New_York did not take effect, so this test proves nothing"
+ assert "error" not in today # UTC today, although the host's date is still the 16th
+ assert today["collector"]["captures"] == 1
+ assert by_source(today)["space_weather"]["first_capture_at"] == "2026-10-17T02:00:00Z"
+ assert yesterday["collector"]["captures"] == 0
+
+
+def test_source_filter_applies_to_every_list(store, db, feeds) -> None:
+ def points(tag):
+ return feeds((f"{tag}_date", 1.0, "2026-10-17"), (f"{tag}_instant", 2.0, "2026-10-17T06:00:00Z"),
+ (f"{tag}_month", 3.0, "2026-10"), (f"{tag}_year", 4.0, "2026"),
+ (f"{tag}_undated", 5.0, None))
+
+ cycle(store, "2026-10-17T08:00:00Z",
+ out("feed_a", "2026-10-17T08:00:00Z", points("a")),
+ out("feed_b", "2026-10-17T08:00:00Z", points("b")))
+ collected = day_timeline(db, "2026-10-17", source="feed_b", now=LATER)
+ assert {o["source"] for o in collected["observations"]} == {"feed_b"}
+ assert (collected["truncation"]["matched"], collected["truncation"]["returned"]) == (5, 5)
+ observed = day_timeline(db, "2026-10-17", by="observed", source="feed_b", now=LATER)
+ assert [p["series_key"] for p in observed["day_values"]] == ["feed_b:b_date", "feed_b:b_instant"]
+ assert [p["series_key"] for p in observed["period_values"]] == ["feed_b:b_year", "feed_b:b_month"]
+ assert observed["without_observed_at"]["by_source"] == {"feed_b": 1}
+ assert observed["without_observed_at"]["collected_that_day"] == 1
+
+
+def test_never_run_means_no_capture_before_or_after(store, db) -> None:
+ for day in ("2026-10-15", "2026-10-16", "2026-10-17"):
+ cycle(store, f"{day}T12:00:00Z",
+ out("space_weather", f"{day}T12:00:00Z", kp((f"{day}T09:00:00Z", 2.0))))
+ cycle(store, "2026-10-17T13:00:00Z", out("new_source", "2026-10-17T13:00:00Z", {"rows": [1]}))
+ roster = ["space_weather", "new_source", "cyclones"]
+ rows = by_source(day_timeline(db, "2026-10-16", roster=roster, now=LATER))
+ # First captured after the day: not attempted that day, not never_run.
+ assert rows["new_source"]["day_state"] == "not_attempted"
+ assert (rows["new_source"]["last_capture_before"], rows["new_source"]["next_capture_after"]) == (
+ None, "2026-10-17T13:00:00Z"
+ )
+ assert rows["cyclones"]["day_state"] == "never_run"
+ early = by_source(day_timeline(db, "2026-10-14", roster=roster, now=LATER))
+ assert {name: row["day_state"] for name, row in early.items()} == {
+ "space_weather": "before_run_log", "new_source": "before_run_log", "cyclones": "never_run",
+ }
+
+
+def test_longest_gap_can_be_inside_the_day(store, db) -> None:
+ cycle(store, "2026-10-16T12:00:00Z",
+ out("space_weather", "2026-10-16T12:00:00Z", kp(("2026-10-16T09:00:00Z", 1.0))))
+ for when in ("2026-10-17T00:30:00Z", "2026-10-17T01:00:00Z", "2026-10-17T22:00:00Z",
+ "2026-10-17T23:30:00Z", "2026-10-18T00:10:00Z", "2026-10-18T00:20:00Z",
+ "2026-10-18T11:50:00Z"):
+ cycle(store, when, out("space_weather", when, kp((when, 2.0))))
+ c = day_timeline(db, "2026-10-17", now=LATER)["collector"]
+ assert (c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (
+ 75_600.0, "2026-10-17T01:00:00Z", "2026-10-17T22:00:00Z"
+ )
+ # In progress at noon, the longest stretch is still the one between captures.
+ c = day_timeline(db, "2026-10-18", now=at("2026-10-18T12:00:00Z"))["collector"]
+ assert (c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (
+ 41_400.0, "2026-10-18T00:20:00Z", "2026-10-18T11:50:00Z"
+ )
+
+
+def test_observation_only_source_is_known_and_listed(store, db, feeds, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ cycle(store, "2026-10-10T12:00:00Z", out("feed_a", "2026-10-10T12:00:00Z", feeds(("x", 1.0, "2026-10-10"))))
+ # The next cycle prunes feed_a's only capture; its observation stays.
+ cycle(store, "2026-10-13T12:00:00Z",
+ out("space_weather", "2026-10-13T12:00:00Z", kp(("2026-10-13T09:00:00Z", 1.0))))
+ now = at("2026-10-13T12:00:00Z")
+ filtered = day_timeline(db, "2026-10-10", source="feed_a", roster=["space_weather"], now=now)
+ assert "error" not in filtered
+ (row,) = filtered["sources"]
+ assert (row["source"], row["day_state"], row["observations_retained"], row["in_collector_roster"]) == (
+ "feed_a", "unknown_past_retention", 1, False
+ )
+ unfiltered = by_source(day_timeline(db, "2026-10-10", roster=["space_weather"], now=now))
+ assert (unfiltered["feed_a"]["day_state"], unfiltered["feed_a"]["observations_retained"]) == (
+ "unknown_past_retention", 1
+ )
+
+
+def test_sources_truncated_lists_only_truncated_sources(store, db, feeds) -> None:
+ many = [(f"a{i:02d}", float(i), f"2026-10-17T00:{i:02d}:00Z") for i in range(30)]
+ few = [(f"b{i}", float(i), f"2026-10-17T12:0{i}:00Z") for i in range(5)]
+ cycle(store, "2026-10-17T13:00:00Z",
+ out("feed_a", "2026-10-17T13:00:00Z", feeds(*many)),
+ out("feed_b", "2026-10-17T13:00:00Z", feeds(*few)))
+ defaults = day_timeline(db, "2026-10-17", now=LATER)["truncation"]
+ assert defaults["sources_truncated"] == {"feed_a": {"matched": 30, "returned": 10}}
+ full = day_timeline(db, "2026-10-17", per_source_limit=50, now=LATER)["truncation"]
+ assert full["sources_truncated"] == {}
+ observed = day_timeline(db, "2026-10-17", by="observed", now=LATER)["truncation"]["day_values"]
+ assert observed["sources_truncated"] == {"feed_a": {"matched": 30, "returned": 10}}
+
+
+def test_observed_lists_share_one_budget(store, db, feeds) -> None:
+ days = [(f"d{i:03d}", float(i), "2026-10-17") for i in range(150)]
+ months = [(f"m{i:03d}", float(i), "2026-10") for i in range(150)]
+ cycle(store, "2026-10-17T08:00:00Z",
+ out("feed_a", "2026-10-17T08:00:00Z", feeds(*days, *months)),
+ out("feed_b", "2026-10-17T08:00:00Z", feeds(*[(f"m{i}", 1.0, "2026-10") for i in range(5)])))
+ defaults = day_timeline(db, "2026-10-17", by="observed", now=LATER)
+ # feed_a's 10 per source go to its day values; feed_b's month values still fit.
+ assert [p["series_key"] for p in defaults["period_values"]] == [f"feed_b:m{i}" for i in range(5)]
+ capped = day_timeline(db, "2026-10-17", by="observed", per_source_limit=1000, now=LATER)
+ assert (len(capped["day_values"]), len(capped["period_values"])) == (100, 0)
+ rest = day_timeline(db, "2026-10-17", by="observed", limit=160, per_source_limit=1000, now=LATER)
+ assert (len(rest["day_values"]), len(rest["period_values"])) == (150, 10)
+ assert [p["series_key"] for p in rest["period_values"]] == [f"feed_a:m{i:03d}" for i in range(10)]
+ assert any(g.startswith(
+ "Period values: 10 of 155 returned (by observed_at, then series, after the day values, "
+ "which share these caps; at most 1,000 per source and 160 in all)"
+ ) for g in rest["data_gaps"])
+ per = day_timeline(db, "2026-10-17", by="observed", limit=1000, per_source_limit=120, now=LATER)
+ assert len([p for p in per["day_values"] + per["period_values"] if p["source"] == "feed_a"]) == 120
+
+
[email protected]("value", [2.9, True, False, float("inf"), float("-inf"), float("nan"), "2.9"])
+def test_non_integer_limits_get_the_defaults(store, db, value) -> None:
+ trunc = day_timeline(db, "2026-10-17", limit=value, per_source_limit=value, now=LATER)["truncation"]
+ assert (trunc["limit"], trunc["per_source_limit"]) == (100, 10)
+
+
+def test_integral_float_limits_are_their_integer(store, db) -> None:
+ # JSON 7 can arrive from an MCP client as 7.0.
+ trunc = day_timeline(db, "2026-10-17", limit=7.0, per_source_limit=3.0, now=LATER)["truncation"]
+ assert (trunc["limit"], trunc["per_source_limit"]) == (7, 3)
+
+
+def test_day_prefixed_odd_observed_at_strings_are_counted(store, db, feeds) -> None:
+ cycle(store, "2026-10-17T08:00:00Z",
+ out("feed_a", "2026-10-17T08:00:00Z", feeds(("ok", 1.0, "2026-10-17T06:00:00Z"))))
+ odd = ["2026-10-17t06:00:00z", "2026-10-17Z", "2026-10-17T24:00:00Z", "2026-10-17T29:59:59Z",
+ "2026-10-17T23:59:60Z", "2026-10-17T23:59:59Z ", "2026-10-17T23:59:59ZZ", "2026-10-17_06",
+ "2026-10-170", "2026-10-17T06:00:00.500Z", "2026-10-17 06:00:00", "2026-10-17\n"]
+ other_days = ["2026-10-16T23:59:59Z", "2026-10-18", "2026-10-18T00:00:00Z", "2026-10-1"]
+ with store._conn: # a writer that bypasses record_cycle's validation
+ for i, value in enumerate(odd + other_days):
+ store._conn.execute(
+ "INSERT INTO history_observations (capture_id, source, series_key, observed_at, "
+ "collected_at, value) VALUES (1, 'feed_a', ?, ?, ?, 1.0)",
+ (f"feed_a:odd{i:02d}", value, at("2026-10-17T08:00:00Z")),
+ )
+ result = day_timeline(db, "2026-10-17", by="observed", now=LATER)
+ assert [p["series_key"] for p in result["day_values"]] == ["feed_a:ok"]
+ assert by_source(result)["feed_a"]["unrecognized_observed_at"] == len(odd)
+
+
+def test_forever_payload_setting_never_prints_a_zero_day_window(store, db, monkeypatch) -> None:
+ # The collector pruned a body with the 7-day default; this server says forever.
+ cycle(store, "2026-10-01T12:00:00Z",
+ out("space_weather", "2026-10-01T12:00:00Z", kp(("2026-10-01T09:00:00Z", 2.0))),
+ out("election_calendar", "2026-10-01T12:00:00Z", {"elections": [1]}))
+ cycle(store, "2026-10-09T12:00:00Z",
+ out("space_weather", "2026-10-09T12:00:00Z", kp(("2026-10-09T09:00:00Z", 3.0))),
+ out("election_calendar", "2026-10-09T12:00:00Z", {"elections": [1]}))
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_PAYLOAD_DAYS", "0")
+ result = day_timeline(db, "2026-10-01", now=at("2026-10-09T12:00:00Z"))
+ assert result["data_gaps"][-1] == (
+ "Payload bodies of 1 of this day's captures were pruned (this server's settings keep "
+ "bodies forever, so the collector pruned them with its own "
+ "WORLD_INTEL_HISTORY_PAYLOAD_DAYS); intel_capture_history can replay only captures whose "
+ "body is retained (1 of 2)."
+ )
+
+
+def test_forever_run_log_setting_never_prints_a_zero_day_window(store, db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")
+ cycle(store, "2026-10-10T12:00:00Z",
+ out("space_weather", "2026-10-10T12:00:00Z", kp(("2026-10-10T09:00:00Z", 2.0))))
+ cycle(store, "2026-10-13T12:00:00Z",
+ out("space_weather", "2026-10-13T12:00:00Z", kp(("2026-10-13T09:00:00Z", 1.0))))
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "0")
+ observed = day_timeline(db, "2026-10-10", by="observed", now=at("2026-10-13T12:00:00Z"))
+ assert (
+ "1 listed value(s) outlived the capture that produced them (this server's settings keep "
+ "the run log forever, so the collector pruned it with its own "
+ "WORLD_INTEL_HISTORY_CAPTURE_DAYS); capture_retained marks them."
+ ) in observed["data_gaps"]
+
+
+def test_partial_history_schema_is_an_error_naming_the_missing_tables(tmp_path) -> None:
+ full = tmp_path / "full.db"
+ HistoryStore(full).close()
+ with contextlib.closing(sqlite3.connect(full)) as conn:
+ schema = [sql for (sql,) in conn.execute(
+ "SELECT sql FROM sqlite_master WHERE tbl_name = 'history_captures' AND sql IS NOT NULL"
+ )]
+ partial = tmp_path / "partial.db"
+ with contextlib.closing(sqlite3.connect(partial)) as conn:
+ for sql in schema:
+ conn.execute(sql)
+ conn.execute(
+ "INSERT INTO history_captures (source, collected_at, status) VALUES ('space_weather', ?, 'ok')",
+ (at("2026-10-17T01:00:00Z"),),
+ )
+ conn.commit()
+ for by in ("collected", "observed"):
+ assert day_timeline(partial, "2026-10-17", by=by, roster=["space_weather"], now=LATER) == {
+ "error": f"history store in {partial} is incomplete: table(s) history_observations, "
+ "history_payloads missing, so no day can be read from it",
+ "missing_tables": ["history_observations", "history_payloads"],
+ "db_path": str(partial),
+ }
+
+
+def test_exactly_max_reasons_has_no_more_reasons(store, db) -> None:
+ for minute in range(5):
+ when = f"2026-10-17T01:{minute:02d}:00Z"
+ cycle(store, when, out("earthquakes", when, error=f"failure {minute}"))
+ row = by_source(day_timeline(db, "2026-10-17", source="earthquakes", now=LATER))["earthquakes"]
+ assert len(row["reasons"]) == 5 and "more_reasons" not in row
+
+
+def test_a_day_ending_exactly_at_the_cutoff_is_past_the_window(db, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "3")
+ result = day_timeline(db, "2026-10-16", now=at("2026-10-20T00:00:00Z"))
+ assert result["retention"]["run_log"] == {
+ "days": 3.0, "cutoff": "2026-10-17T00:00:00Z", "day": "past_window"
+ }
+
+
+class _CommitAfterSummary:
+ """Connection wrapper: once the capture summary has been read, a
+ collector cycle commits through the store's own connection before the
+ timeline's next statement runs."""
+
+ def __init__(self, conn, write):
+ self._conn, self._write, self.wrote = conn, write, False
+
+ def execute(self, sql, params=()):
+ cursor = self._conn.execute(sql, params)
+ if sql == history_timeline._CAPTURE_SUMMARY_SQL and not self.wrote:
+ rows = cursor.fetchall()
+ self._write()
+ self.wrote = True
+ return types.SimpleNamespace(fetchall=lambda: rows)
+ return cursor
+
+ def close(self):
+ self._conn.close()
+
+
+def test_one_call_reads_one_snapshot(store, db, monkeypatch) -> None:
+ cycle(store, "2026-10-17T01:00:00Z",
+ out("space_weather", "2026-10-17T01:00:00Z", kp(("2026-10-17T00:00:00Z", 2.0))))
+ real = history_timeline._connect
+ opened = []
+
+ def connect(path):
+ opened.append(_CommitAfterSummary(real(path), lambda: cycle(
+ store, "2026-10-17T02:00:00Z", out("earthquakes", "2026-10-17T02:00:00Z", error="boom"))))
+ return opened[-1]
+
+ monkeypatch.setattr(history_timeline, "_connect", connect)
+ result = day_timeline(db, "2026-10-17", now=LATER)
+ assert opened[0].wrote
+ assert sum(row["attempts"] for row in result["sources"]) == result["collector"]["captures"] == 1
+ monkeypatch.setattr(history_timeline, "_connect", real)
+ assert day_timeline(db, "2026-10-17", now=LATER)["collector"]["captures"] == 2 # it committed
+
+
+def test_tool_schema_day_pattern_rejects_other_strings(server) -> None:
+ import jsonschema # an mcp requirement
+
+ (tool,) = [t for t in server.TOOLS if t.name == "intel_day_timeline"]
+ jsonschema.validate({"day": "2026-10-17"}, tool.inputSchema)
+ for bad in ("2026/10/17", "17-10-2026", "2026-10-17T00:00:00Z", "x2026-10-17x", "yesterday", ""):
+ with pytest.raises(jsonschema.ValidationError):
+ jsonschema.validate({"day": bad}, tool.inputSchema)
diff --git a/src/world_intel_mcp/tools/day_timeline.py b/src/world_intel_mcp/tools/day_timeline.py
index a087ae4..c312e9b 100644
--- a/src/world_intel_mcp/tools/day_timeline.py
+++ b/src/world_intel_mcp/tools/day_timeline.py
@@ -27,16 +27,18 @@ TOOLS: list[Tool] = [
"What the history store recorded for one UTC calendar day (YYYY-MM-DD; today "
"allowed, a future day refused). by=collected (default): per source, that day's "
"collector captures from the run log (attempts; ok / degraded / error counts with "
- "reasons; changed vs unchanged payloads; first and last capture; observations "
- "stored), sources with no capture that day and why, whether the collector ran at "
- "all, and the observations saved that day. by=observed: values whose observed_at "
- "falls on the day (dates and UTC instants); month and year values containing the "
- "day are listed apart as period values; values without observed_at are excluded "
- "and counted. Items carry observed_at, published_at and collected_at where known. "
- "Says which records are past retention (payload bodies 7 days, run log 30, "
- "observations 365 by default) instead of reading them as a quiet day. Output is "
- "capped and truncation is stated. Read-only: never fetches. History accrues only "
- "while the collector (intel-collector, or intel_collect) runs."
+ "reasons; extractor failures; partial failures; changed vs unchanged payloads; "
+ "first and last capture; observations stored), sources with no capture that day "
+ "and why, whether the collector ran or the day is before this database's run log "
+ "starts (not_recorded), and the observations saved that day. by=observed: values "
+ "whose observed_at falls on the day (dates and UTC instants); month and year values "
+ "containing the day are listed apart as period values; values without observed_at "
+ "are excluded and counted. Items carry observed_at, published_at and collected_at "
+ "where known. Says which records are past retention (payload bodies 7 days, run "
+ "log 30, observations 365 by default) or before the run log starts, instead of "
+ "reading them as a quiet day. Output is capped (in by=observed both lists share "
+ "the caps) and truncation is stated. Read-only: never fetches. History accrues "
+ "only while the collector (intel-collector, or intel_collect) runs."
),
inputSchema={
"type": "object",
@@ -59,14 +61,15 @@ TOOLS: list[Tool] = [
},
"limit": {
"type": "integer",
- "description": f"Most items listed in all (default {DEFAULT_LIMIT}, "
- f"max {MAX_LIMIT})",
+ "description": "Most items listed in all, across both lists of "
+ f"by=observed (default {DEFAULT_LIMIT}, max {MAX_LIMIT})",
"default": DEFAULT_LIMIT,
},
"per_source_limit": {
"type": "integer",
- "description": f"Most items listed per source (default "
- f"{DEFAULT_PER_SOURCE_LIMIT}, max {MAX_PER_SOURCE_LIMIT})",
+ "description": "Most items listed per source, across both lists of "
+ f"by=observed (default {DEFAULT_PER_SOURCE_LIMIT}, max "
+ f"{MAX_PER_SOURCE_LIMIT})",
"default": DEFAULT_PER_SOURCE_LIMIT,
},
},