chore: pre-existing in-tree work (event-study/research/vintages/prices + migration script + integrity docs)
Committing the prior uncommitted working-tree state that predates this session's data-source work (was already modified/untracked at session start) so the tree is clean before push. Includes: event-study + research report integrity/forward observation work, prices tests, research hash migration script, and the 2026-08-23/24 engineering-log + test-evidence notes. Verified green as part of the full 362-test suite.
This commit is contained in:
1 parent
dbb787c50a
commit
ead9aeb25c
22 files changed
+2326
-66
No files matched your search
@@ -6,6 +6,7 @@ import math
|
||||
from datetime import date, datetime, timezone
|
||||
from statistics import fmean
|
||||
from typing import Any, Mapping, Sequence
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
class EventStudyError(ValueError):
|
||||
@@ -34,6 +35,18 @@ def _canonical_timestamp(value: str) -> str:
|
||||
return parsed.astimezone(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _parse_known_at(value: Any, symbol: str) -> datetime:
|
||||
if not isinstance(value, str):
|
||||
raise EventStudyError(f"known_at is required for {symbol}")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise EventStudyError(f"invalid known_at for {symbol}") from exc
|
||||
if parsed.tzinfo is None:
|
||||
raise EventStudyError(f"known_at must include a timezone for {symbol}")
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def assess_backtest_readiness(vintages: Sequence[Mapping[str, Any]], min_events: int = 12) -> dict[str, Any]:
|
||||
if isinstance(min_events, bool) or min_events < 1:
|
||||
raise EventStudyError("min_events must be positive")
|
||||
@@ -63,13 +76,16 @@ def assess_backtest_readiness(vintages: Sequence[Mapping[str, Any]], min_events:
|
||||
}
|
||||
|
||||
|
||||
def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]]) -> dict[date, float]:
|
||||
def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]], *, require_known_at: bool = False) -> dict[date, tuple[float, datetime | None]]:
|
||||
if not rows:
|
||||
raise EventStudyError(f"missing prices for {symbol}")
|
||||
values: dict[date, float] = {}
|
||||
values: dict[date, tuple[float, datetime | None]] = {}
|
||||
for row in rows:
|
||||
try:
|
||||
trading_day = _parse_date(str(row["date"]))
|
||||
session_date_value = row.get("session_date")
|
||||
if session_date_value is None:
|
||||
session_date_value = row["date"]
|
||||
trading_day = _parse_date(str(session_date_value))
|
||||
close = float(row["close"])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise EventStudyError(f"invalid price row for {symbol}") from exc
|
||||
@@ -77,11 +93,22 @@ def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]]) -> dict[date, flo
|
||||
raise EventStudyError(f"invalid close for {symbol}")
|
||||
if trading_day in values:
|
||||
raise EventStudyError(f"duplicate price date for {symbol}")
|
||||
values[trading_day] = close
|
||||
known_at = _parse_known_at(row.get("known_at"), symbol) if require_known_at else None
|
||||
if known_at is not None:
|
||||
timezone_name = row.get("market_timezone")
|
||||
if not isinstance(timezone_name, str) or not timezone_name.strip():
|
||||
raise EventStudyError(f"market_timezone is required for {symbol}")
|
||||
try:
|
||||
market_date = known_at.astimezone(ZoneInfo(timezone_name)).date()
|
||||
except Exception as exc:
|
||||
raise EventStudyError(f"invalid market_timezone for {symbol}") from exc
|
||||
if market_date > trading_day:
|
||||
raise EventStudyError(f"known_at is after session date for {symbol}")
|
||||
values[trading_day] = (close, known_at)
|
||||
return dict(sorted(values.items()))
|
||||
|
||||
|
||||
def _window_return(series: dict[date, float], event_date: date, window: int, symbol: str, execution_lag_sessions: int) -> float:
|
||||
def _window_return(series: dict[date, tuple[float, datetime | None]], event_date: date, window: int, symbol: str, execution_lag_sessions: int) -> float:
|
||||
dates = list(series)
|
||||
anchor_candidates = [index for index, trading_day in enumerate(dates) if trading_day >= event_date]
|
||||
if not anchor_candidates:
|
||||
@@ -96,7 +123,7 @@ def _window_return(series: dict[date, float], event_date: date, window: int, sym
|
||||
end = anchor + window
|
||||
if end >= len(dates):
|
||||
raise EventStudyError(f"insufficient price history for {symbol} window {window}")
|
||||
return series[dates[end]] / series[dates[anchor]] - 1.0
|
||||
return series[dates[end]][0] / series[dates[anchor]][0] - 1.0
|
||||
|
||||
|
||||
def run_event_study(
|
||||
@@ -108,6 +135,7 @@ def run_event_study(
|
||||
cost_bps: float = 0.0,
|
||||
min_events: int = 12,
|
||||
execution_lag_sessions: int = 1,
|
||||
require_price_known_at: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Calculate weighted post-publication returns from point-in-time events."""
|
||||
|
||||
@@ -128,8 +156,13 @@ def run_event_study(
|
||||
if not math.isfinite(cost_bps) or cost_bps < 0:
|
||||
raise EventStudyError("cost_bps must be finite and non-negative")
|
||||
|
||||
normalized_prices = {str(symbol).upper(): _price_map(str(symbol).upper(), rows) for symbol, rows in prices.items()}
|
||||
normalized_benchmark = _price_map("benchmark", benchmark_prices) if benchmark_prices is not None else None
|
||||
if not isinstance(require_price_known_at, bool):
|
||||
raise EventStudyError("require_price_known_at must be boolean")
|
||||
normalized_prices = {
|
||||
str(symbol).upper(): _price_map(str(symbol).upper(), rows, require_known_at=require_price_known_at)
|
||||
for symbol, rows in prices.items()
|
||||
}
|
||||
normalized_benchmark = _price_map("benchmark", benchmark_prices, require_known_at=require_price_known_at) if benchmark_prices is not None else None
|
||||
seen_event_ids: set[str] = set()
|
||||
event_rows: list[dict[str, Any]] = []
|
||||
for event in events:
|
||||
@@ -189,4 +222,5 @@ def run_event_study(
|
||||
"event_count": len(event_rows),
|
||||
"windows": window_results,
|
||||
"min_events": min_events,
|
||||
"price_known_at_required": require_price_known_at,
|
||||
}
|
||||
+261
-37
@@ -1,8 +1,8 @@
|
||||
"""Frozen, replayable Tourism research runs.
|
||||
|
||||
A run either produces a deterministic event-study result from point-in-time
|
||||
inputs or persists a blocked report explaining the exact missing gate. It never
|
||||
falls back to revised vendor history.
|
||||
Validated runs require point-in-time inputs. Explicit exploratory runs may use
|
||||
revised vendor history, but their result is permanently labelled descriptive
|
||||
only and does not satisfy the validated backtest gate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,12 +17,15 @@ from pathlib import Path
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
from .event_study import EventStudyError, _canonical_timestamp, assess_backtest_readiness, run_event_study
|
||||
from .prices import PriceSnapshotStore, PriceSourceError
|
||||
from .prices import PIT_ARCHIVE_CONTRACT, PriceSnapshotStore, PriceSourceError
|
||||
from .tourism import compute_tourism_signal
|
||||
from .vintages import VintageStore, VintageStoreError
|
||||
|
||||
RUN_SCHEMA_VERSION = 1
|
||||
REPORT_HASH_ALGORITHM = "sha256-json-canonical-v1"
|
||||
_RUN_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
|
||||
RESEARCH_MODES = {"validated", "exploratory"}
|
||||
_OBSERVATION_RUNTIME_FIELDS = frozenset({"first_seen_at", "last_seen_at", "observation_count"})
|
||||
|
||||
|
||||
class ResearchRunError(ValueError):
|
||||
@@ -34,6 +37,20 @@ def _canonical_hash(payload: Mapping[str, Any]) -> str:
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def _report_hash(report: Mapping[str, Any]) -> str:
|
||||
payload = copy.deepcopy(dict(report))
|
||||
payload.pop("report_hash", None)
|
||||
payload.pop("report_hash_algorithm", None)
|
||||
return _canonical_hash(payload)
|
||||
|
||||
|
||||
def _manifest_entry_hash(entry: Mapping[str, Any]) -> str:
|
||||
payload = copy.deepcopy(dict(entry))
|
||||
payload.pop("manifest_entry_hash", None)
|
||||
payload.pop("manifest_entry_hash_algorithm", None)
|
||||
return _canonical_hash(payload)
|
||||
|
||||
|
||||
def _atomic_write(path: Path, payload: Mapping[str, Any]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(f".{path.name}.tmp")
|
||||
@@ -54,9 +71,13 @@ class ResearchRunStore:
|
||||
return {"schema_version": RUN_SCHEMA_VERSION, "runs": {}}
|
||||
try:
|
||||
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ResearchRunError("research run manifest is unreadable") from exc
|
||||
if manifest.get("schema_version") != RUN_SCHEMA_VERSION or not isinstance(manifest.get("runs"), dict):
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("schema_version") != RUN_SCHEMA_VERSION
|
||||
or not isinstance(manifest.get("runs"), dict)
|
||||
):
|
||||
raise ResearchRunError("unsupported research run manifest schema")
|
||||
return manifest
|
||||
|
||||
@@ -74,79 +95,235 @@ class ResearchRunStore:
|
||||
raise FileNotFoundError(run_id)
|
||||
try:
|
||||
report = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ResearchRunError("research report is unreadable") from exc
|
||||
if not isinstance(report, dict):
|
||||
raise ResearchRunError("research report is invalid")
|
||||
if report.get("run_id") != run_id or report.get("schema_version") != RUN_SCHEMA_VERSION:
|
||||
raise ResearchRunError("research report identity mismatch")
|
||||
declared_hash = report.get("report_hash")
|
||||
if (
|
||||
report.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or not isinstance(declared_hash, str)
|
||||
or _report_hash(report) != declared_hash
|
||||
):
|
||||
raise ResearchRunError("research report integrity hash mismatch")
|
||||
manifest_entry = self.load_manifest().get("runs", {}).get(run_id)
|
||||
declared_manifest_hash = manifest_entry.get("manifest_entry_hash") if isinstance(manifest_entry, dict) else None
|
||||
if (
|
||||
not isinstance(manifest_entry, dict)
|
||||
or manifest_entry.get("run_id") != run_id
|
||||
or manifest_entry.get("report_file") != path.name
|
||||
or any(manifest_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at"))
|
||||
or manifest_entry.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or manifest_entry.get("report_hash") != declared_hash
|
||||
or manifest_entry.get("manifest_entry_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or not isinstance(declared_manifest_hash, str)
|
||||
or _manifest_entry_hash(manifest_entry) != declared_manifest_hash
|
||||
):
|
||||
raise ResearchRunError("research report manifest integrity mismatch")
|
||||
return report
|
||||
|
||||
def migrate_legacy(self) -> int:
|
||||
"""Add integrity metadata to explicitly migrated pre-hash reports."""
|
||||
manifest = self.load_manifest()
|
||||
migrated = 0
|
||||
for raw_run_id, raw_entry in manifest["runs"].items():
|
||||
run_id = str(raw_run_id)
|
||||
if not _RUN_ID_RE.fullmatch(run_id) or not isinstance(raw_entry, dict):
|
||||
raise ResearchRunError("invalid research run manifest entry")
|
||||
path = self._report_path(run_id)
|
||||
if raw_entry.get("run_id") != run_id or raw_entry.get("report_file") != path.name:
|
||||
raise ResearchRunError("research run manifest entry identity mismatch")
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(run_id)
|
||||
try:
|
||||
report = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ResearchRunError("research report is unreadable") from exc
|
||||
if not isinstance(report, dict) or report.get("run_id") != run_id or report.get("schema_version") != RUN_SCHEMA_VERSION:
|
||||
raise ResearchRunError("research report identity mismatch")
|
||||
has_report_integrity = "report_hash" in report or "report_hash_algorithm" in report
|
||||
has_manifest_integrity = "manifest_entry_hash" in raw_entry or "manifest_entry_hash_algorithm" in raw_entry
|
||||
if has_manifest_integrity and not has_report_integrity:
|
||||
raise ResearchRunError("research run integrity metadata is incomplete")
|
||||
declared_report_hash = report.get("report_hash")
|
||||
report_integrity_valid = (
|
||||
report.get("report_hash_algorithm") == REPORT_HASH_ALGORITHM
|
||||
and isinstance(declared_report_hash, str)
|
||||
and _report_hash(report) == declared_report_hash
|
||||
)
|
||||
if has_report_integrity and not report_integrity_valid:
|
||||
raise ResearchRunError("research run integrity metadata is invalid")
|
||||
if not has_report_integrity or not has_manifest_integrity:
|
||||
if any(raw_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at")):
|
||||
raise ResearchRunError("research report manifest metadata mismatch")
|
||||
if not has_report_integrity:
|
||||
stored = copy.deepcopy(report)
|
||||
stored["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
stored["report_hash"] = _report_hash(stored)
|
||||
declared_report_hash = stored["report_hash"]
|
||||
_atomic_write(path, stored)
|
||||
if not has_manifest_integrity:
|
||||
migrated_entry = copy.deepcopy(raw_entry)
|
||||
migrated_entry["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
migrated_entry["report_hash"] = declared_report_hash
|
||||
migrated_entry["manifest_entry_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
migrated_entry["manifest_entry_hash"] = _manifest_entry_hash(migrated_entry)
|
||||
manifest["runs"][run_id] = migrated_entry
|
||||
migrated += 1
|
||||
continue
|
||||
declared_manifest_hash = raw_entry.get("manifest_entry_hash")
|
||||
if (
|
||||
not report_integrity_valid
|
||||
or raw_entry.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or raw_entry.get("report_hash") != declared_report_hash
|
||||
or raw_entry.get("manifest_entry_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or not isinstance(declared_manifest_hash, str)
|
||||
or _manifest_entry_hash(raw_entry) != declared_manifest_hash
|
||||
or any(raw_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at"))
|
||||
):
|
||||
raise ResearchRunError("research run integrity metadata is invalid")
|
||||
if migrated:
|
||||
_atomic_write(self.manifest_path, manifest)
|
||||
return migrated
|
||||
|
||||
def _validated_manifest_entries(self) -> list[dict[str, Any]]:
|
||||
manifest = self.load_manifest()
|
||||
entries: list[dict[str, Any]] = []
|
||||
for run_id, raw_entry in manifest["runs"].items():
|
||||
if not _RUN_ID_RE.fullmatch(str(run_id)) or not isinstance(raw_entry, dict) or raw_entry.get("run_id") != run_id:
|
||||
raise ResearchRunError("invalid research run manifest entry")
|
||||
try:
|
||||
self.load(run_id)
|
||||
except FileNotFoundError as exc:
|
||||
raise ResearchRunError("research run manifest entry report is missing") from exc
|
||||
entries.append(raw_entry)
|
||||
return entries
|
||||
|
||||
def persist(self, report: dict[str, Any]) -> dict[str, Any]:
|
||||
run_id = str(report.get("run_id", ""))
|
||||
path = self._report_path(run_id)
|
||||
manifest = self.load_manifest()
|
||||
existing = manifest["runs"].get(run_id)
|
||||
if existing:
|
||||
stored = self.load(run_id)
|
||||
if stored != report:
|
||||
raise ResearchRunError("research run id already contains a different report")
|
||||
return stored
|
||||
stored = copy.deepcopy(report)
|
||||
stored["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
stored["report_hash"] = _report_hash(stored)
|
||||
manifest = self.load_manifest()
|
||||
self._validated_manifest_entries()
|
||||
if run_id in manifest["runs"]:
|
||||
if not isinstance(manifest["runs"][run_id], dict):
|
||||
raise ResearchRunError("invalid research run manifest entry")
|
||||
existing_report = self.load(run_id)
|
||||
if existing_report != stored:
|
||||
raise ResearchRunError("research run id already contains a different report")
|
||||
return existing_report
|
||||
_atomic_write(path, stored)
|
||||
manifest["runs"][run_id] = {
|
||||
manifest_entry = {
|
||||
"run_id": run_id,
|
||||
"status": stored.get("status"),
|
||||
"reason": stored.get("reason"),
|
||||
"generated_at": stored.get("generated_at"),
|
||||
"report_file": path.name,
|
||||
"report_hash_algorithm": REPORT_HASH_ALGORITHM,
|
||||
"report_hash": stored["report_hash"],
|
||||
}
|
||||
manifest_entry["manifest_entry_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
manifest_entry["manifest_entry_hash"] = _manifest_entry_hash(manifest_entry)
|
||||
manifest["runs"][run_id] = manifest_entry
|
||||
_atomic_write(self.manifest_path, manifest)
|
||||
return stored
|
||||
|
||||
def latest(self) -> dict[str, Any]:
|
||||
entries = list(self.load_manifest().get("runs", {}).values())
|
||||
entries = self._validated_manifest_entries()
|
||||
if not entries:
|
||||
raise FileNotFoundError("no research runs")
|
||||
latest = max(entries, key=lambda item: (str(item.get("generated_at", "")), str(item.get("run_id", ""))))
|
||||
return self.load(str(latest["run_id"]))
|
||||
|
||||
def list_runs(self) -> list[dict[str, Any]]:
|
||||
entries = list(self.load_manifest().get("runs", {}).values())
|
||||
entries = self._validated_manifest_entries()
|
||||
return sorted(entries, key=lambda item: (str(item.get("generated_at", "")), str(item.get("run_id", ""))), reverse=True)
|
||||
|
||||
|
||||
def _validate_config(windows: Sequence[int], cost_bps: float, min_events: int, execution_lag_sessions: int) -> tuple[list[int], float, int, int]:
|
||||
if not windows or any(isinstance(window, bool) or int(window) != window or int(window) <= 0 for window in windows):
|
||||
raise ResearchRunError("windows must contain positive integers")
|
||||
def _parse_config_integer(value: Any, field: str, minimum: int) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ResearchRunError(f"{field} must be an integer")
|
||||
try:
|
||||
parsed = int(value)
|
||||
numeric = float(value)
|
||||
except (OverflowError, TypeError, ValueError) as exc:
|
||||
raise ResearchRunError(f"{field} must be an integer") from exc
|
||||
if not math.isfinite(numeric) or parsed != value or parsed < minimum:
|
||||
qualifier = "positive" if minimum > 0 else "non-negative"
|
||||
raise ResearchRunError(f"{field} must be a {qualifier} integer")
|
||||
return parsed
|
||||
|
||||
|
||||
def _validate_config(windows: Sequence[int], cost_bps: float, min_events: int, execution_lag_sessions: int) -> tuple[list[int], float, int, int]:
|
||||
if not isinstance(windows, (list, tuple)) or not windows:
|
||||
raise ResearchRunError("windows must contain positive integers")
|
||||
parsed_windows = [_parse_config_integer(window, "windows", 1) for window in windows]
|
||||
try:
|
||||
if isinstance(cost_bps, bool):
|
||||
raise TypeError
|
||||
parsed_cost = float(cost_bps)
|
||||
except (TypeError, ValueError) as exc:
|
||||
except (OverflowError, TypeError, ValueError) as exc:
|
||||
raise ResearchRunError("cost_bps must be finite and non-negative") from exc
|
||||
if not math.isfinite(parsed_cost) or parsed_cost < 0:
|
||||
raise ResearchRunError("cost_bps must be finite and non-negative")
|
||||
if isinstance(min_events, bool) or int(min_events) != min_events or int(min_events) < 1:
|
||||
raise ResearchRunError("min_events must be positive")
|
||||
if isinstance(execution_lag_sessions, bool) or int(execution_lag_sessions) != execution_lag_sessions or int(execution_lag_sessions) < 0:
|
||||
raise ResearchRunError("execution_lag_sessions must be a non-negative integer")
|
||||
return [int(window) for window in windows], parsed_cost, int(min_events), int(execution_lag_sessions)
|
||||
parsed_min_events = _parse_config_integer(min_events, "min_events", 1)
|
||||
parsed_execution_lag = _parse_config_integer(execution_lag_sessions, "execution_lag_sessions", 0)
|
||||
return parsed_windows, parsed_cost, parsed_min_events, parsed_execution_lag
|
||||
|
||||
|
||||
def _price_gate(price_entry: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||
def _validate_mode(mode: str) -> str:
|
||||
if not isinstance(mode, str) or mode not in RESEARCH_MODES:
|
||||
raise ResearchRunError(f"mode must be one of: {', '.join(sorted(RESEARCH_MODES))}")
|
||||
return mode
|
||||
|
||||
|
||||
def _price_gate(price_entry: Mapping[str, Any] | None, mode: str = "validated") -> dict[str, Any]:
|
||||
mode = _validate_mode(mode)
|
||||
if not price_entry:
|
||||
return {"status": "blocked", "reason": "price_snapshot_missing", "snapshot_count": 0}
|
||||
if price_entry.get("point_in_time") is not True:
|
||||
return {
|
||||
"status": "blocked",
|
||||
"status": "descriptive_only" if mode == "exploratory" else "blocked",
|
||||
"reason": "price_series_not_point_in_time",
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"point_in_time": False,
|
||||
"validated": False,
|
||||
}
|
||||
if price_entry.get("quality") != "point_in_time_archive" or price_entry.get("archive_contract") != PIT_ARCHIVE_CONTRACT:
|
||||
return {
|
||||
"status": "descriptive_only" if mode == "exploratory" else "blocked",
|
||||
"reason": "price_archive_contract_missing",
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"archive_contract": price_entry.get("archive_contract"),
|
||||
"point_in_time": True,
|
||||
"validated": False,
|
||||
}
|
||||
if mode == "exploratory":
|
||||
return {
|
||||
"status": "descriptive_only",
|
||||
"reason": "exploratory_mode_non_validated",
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"archive_contract": price_entry.get("archive_contract"),
|
||||
"provider_release_id": price_entry.get("provider_release_id"),
|
||||
"point_in_time": True,
|
||||
"validated": False,
|
||||
}
|
||||
return {
|
||||
"status": "ready",
|
||||
"reason": None,
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"archive_contract": price_entry.get("archive_contract"),
|
||||
"provider_release_id": price_entry.get("provider_release_id"),
|
||||
"point_in_time": True,
|
||||
"validated": True,
|
||||
}
|
||||
|
||||
|
||||
@@ -164,11 +341,25 @@ def _select_independent_vintages(entries: Sequence[Mapping[str, Any]]) -> list[d
|
||||
entry = dict(raw_entry)
|
||||
key = _revision_key(entry)
|
||||
current = selected.get(key)
|
||||
candidate_rank = (str(entry.get("first_seen_at", "")), str(entry.get("last_seen_at", "")), str(entry.get("vintage_id", "")))
|
||||
current_rank = (str(current.get("first_seen_at", "")), str(current.get("last_seen_at", "")), str(current.get("vintage_id", ""))) if current else ("", "", "")
|
||||
candidate_rank = (
|
||||
_canonical_timestamp(str(entry.get("first_seen_at") or "")),
|
||||
_canonical_timestamp(str(entry.get("last_seen_at") or "")),
|
||||
str(entry.get("vintage_id", "")),
|
||||
)
|
||||
current_rank = (
|
||||
_canonical_timestamp(str(current.get("first_seen_at") or "")),
|
||||
_canonical_timestamp(str(current.get("last_seen_at") or "")),
|
||||
str(current.get("vintage_id", "")),
|
||||
) if current else ("", "", "")
|
||||
if current is None or candidate_rank > current_rank:
|
||||
selected[key] = entry
|
||||
return sorted(selected.values(), key=lambda item: (str(item.get("published_at", "")), str(item.get("vintage_id", ""))))
|
||||
return sorted(
|
||||
selected.values(),
|
||||
key=lambda item: (
|
||||
_canonical_timestamp(str(item.get("published_at") or "")),
|
||||
str(item.get("vintage_id", "")),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _series_rows(series: Mapping[str, Any], price_field: str, symbol: str) -> list[dict[str, Any]]:
|
||||
@@ -179,7 +370,15 @@ def _series_rows(series: Mapping[str, Any], price_field: str, symbol: str) -> li
|
||||
for bar in bars:
|
||||
if not isinstance(bar, dict) or price_field not in bar:
|
||||
raise ResearchRunError(f"price field {price_field} missing for {symbol}")
|
||||
rows.append({"date": bar.get("date"), "close": bar.get(price_field)})
|
||||
session_date = bar.get("session_date", bar.get("date"))
|
||||
row = {"date": session_date, "close": bar.get(price_field)}
|
||||
if "session_date" in bar:
|
||||
row["session_date"] = session_date
|
||||
if "known_at" in bar:
|
||||
row["known_at"] = bar.get("known_at")
|
||||
if "timezone" in series:
|
||||
row["market_timezone"] = series.get("timezone")
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
@@ -192,13 +391,15 @@ def run_tourism_research(
|
||||
windows: Sequence[int] = (1, 3, 5, 20),
|
||||
cost_bps: float = 20.0,
|
||||
execution_lag_sessions: int = 1,
|
||||
mode: str = "validated",
|
||||
) -> dict[str, Any]:
|
||||
mode = _validate_mode(mode)
|
||||
windows, cost_bps, min_events, execution_lag_sessions = _validate_config(windows, cost_bps, min_events, execution_lag_sessions)
|
||||
try:
|
||||
vintages = _select_independent_vintages(vintage_store.list_vintages())
|
||||
price_entry = price_store.latest_snapshot_entry()
|
||||
except (VintageStoreError, PriceSourceError) as exc:
|
||||
raise ResearchRunError(str(exc)) from exc
|
||||
raise ResearchRunError(f"research input integrity validation failed: {exc}") from exc
|
||||
vintage_gate = assess_backtest_readiness(vintages, min_events=min_events)
|
||||
validated_vintage_snapshots: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
@@ -219,9 +420,11 @@ def run_tourism_research(
|
||||
**price_entry,
|
||||
"point_in_time": price_source.get("point_in_time"),
|
||||
"quality": price_source.get("quality"),
|
||||
"archive_contract": price_source.get("archive_contract"),
|
||||
"provider_release_id": price_source.get("provider_release_id"),
|
||||
"normalized_snapshot_hash": price_source.get("normalized_snapshot_hash"),
|
||||
}
|
||||
price_gate = _price_gate(price_gate_entry)
|
||||
price_gate = _price_gate(price_gate_entry, mode)
|
||||
input_vintages = [
|
||||
{
|
||||
"vintage_id": entry.get("vintage_id"),
|
||||
@@ -229,17 +432,28 @@ def run_tourism_research(
|
||||
"as_of": entry.get("as_of"),
|
||||
"published_at": entry.get("published_at"),
|
||||
"raw_payload_hash": entry.get("raw_payload_hash"),
|
||||
"normalized_snapshot_hash": entry.get("normalized_snapshot_hash"),
|
||||
"normalized_hash_algorithm": entry.get("normalized_hash_algorithm"),
|
||||
"parser_version": entry.get("parser_version"),
|
||||
"revision_status": entry.get("revision_status"),
|
||||
}
|
||||
for entry in vintages
|
||||
]
|
||||
input_price = copy.deepcopy(price_gate_entry) if price_gate_entry else None
|
||||
input_price = (
|
||||
{
|
||||
key: copy.deepcopy(value)
|
||||
for key, value in price_gate_entry.items()
|
||||
if key not in _OBSERVATION_RUNTIME_FIELDS
|
||||
}
|
||||
if price_gate_entry
|
||||
else None
|
||||
)
|
||||
config = {
|
||||
"min_events": min_events,
|
||||
"windows": windows,
|
||||
"cost_bps": cost_bps,
|
||||
"execution_lag_sessions": execution_lag_sessions,
|
||||
"mode": mode,
|
||||
}
|
||||
input_fingerprint = _canonical_hash({"theme": "tourism", "config": config, "vintages": input_vintages, "price_snapshot": input_price})
|
||||
run_id = f"tourism-run-{input_fingerprint[:16]}"
|
||||
@@ -255,6 +469,8 @@ def run_tourism_research(
|
||||
"status": "blocked",
|
||||
"reason": None,
|
||||
"generated_at": generated_at,
|
||||
"research_mode": mode,
|
||||
"result_scope": "blocked",
|
||||
"config": config,
|
||||
"gates": {"vintages": vintage_gate, "prices": price_gate},
|
||||
"inputs": {"vintages": input_vintages, "price_snapshot": input_price},
|
||||
@@ -262,7 +478,7 @@ def run_tourism_research(
|
||||
if vintage_gate["status"] != "ready":
|
||||
report["reason"] = vintage_gate["reason"]
|
||||
return run_store.persist(report)
|
||||
if price_gate["status"] != "ready":
|
||||
if price_gate["status"] == "blocked":
|
||||
report["reason"] = price_gate["reason"]
|
||||
return run_store.persist(report)
|
||||
if not price_entry or price_snapshot is None:
|
||||
@@ -294,13 +510,21 @@ def run_tourism_research(
|
||||
cost_bps=cost_bps,
|
||||
min_events=min_events,
|
||||
execution_lag_sessions=execution_lag_sessions,
|
||||
require_price_known_at=mode == "validated",
|
||||
)
|
||||
except (FileNotFoundError, VintageStoreError, EventStudyError, ResearchRunError, KeyError, TypeError, ValueError) as exc:
|
||||
report["reason"] = "research_inputs_invalid"
|
||||
report["error"] = str(exc)
|
||||
return run_store.persist(report)
|
||||
report["status"] = "ready"
|
||||
report["status"] = "descriptive_only" if mode == "exploratory" else "ready"
|
||||
report["reason"] = None
|
||||
report["result_scope"] = "validated_pit_event_study" if mode == "validated" else "non_pit_descriptive_only"
|
||||
if mode == "exploratory":
|
||||
report["limitations"] = ["This result is descriptive only and must not be used as validated backtest evidence."]
|
||||
if price_source.get("point_in_time") is not True:
|
||||
report["limitations"].insert(0, "Historical price data may be revised vendor history and is not point-in-time validated.")
|
||||
else:
|
||||
report["limitations"].insert(0, "Point-in-time-capable inputs are intentionally not promoted by exploratory mode.")
|
||||
report["result"] = result
|
||||
report["input_summary"] = {
|
||||
"event_count": len(events),
|
||||
|
||||
+10
-3
@@ -42,10 +42,12 @@ def _data_quality(snapshot: dict[str, Any], observations: list[dict[str, Any]])
|
||||
def compute_tourism_signal(snapshot: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Compute a replayable Tourism Pulse signal from a frozen snapshot."""
|
||||
|
||||
observations = list(snapshot.get("observations", []))
|
||||
if not observations:
|
||||
observations = snapshot.get("observations", [])
|
||||
if not isinstance(observations, list) or not observations:
|
||||
raise ValueError("tourism snapshot must contain observations")
|
||||
for observation in observations:
|
||||
if not isinstance(observation, dict):
|
||||
raise ValueError("tourism observation must be an object")
|
||||
_validate_observation(observation)
|
||||
|
||||
standardized = []
|
||||
@@ -58,7 +60,12 @@ def compute_tourism_signal(snapshot: dict[str, Any]) -> dict[str, Any]:
|
||||
theme_surprise = round(fmean(standardized), 8)
|
||||
|
||||
signal_rows = []
|
||||
for exposure in snapshot.get("exposures", []):
|
||||
exposures = snapshot.get("exposures", [])
|
||||
if not isinstance(exposures, list):
|
||||
raise ValueError("tourism snapshot exposures must be a list")
|
||||
for exposure in exposures:
|
||||
if not isinstance(exposure, dict):
|
||||
raise ValueError("tourism exposure must be an object")
|
||||
symbol = str(exposure.get("symbol", "")).strip().upper()
|
||||
coefficient = float(exposure.get("coefficient", 0))
|
||||
confidence = float(exposure.get("confidence", 1.0))
|
||||
|
||||
@@ -90,7 +90,7 @@ class VintageStore:
|
||||
return {"schema_version": MANIFEST_SCHEMA_VERSION, "vintages": {}}
|
||||
try:
|
||||
payload = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise VintageStoreError("vintage manifest is unreadable") from exc
|
||||
if not isinstance(payload, dict) or payload.get("schema_version") != MANIFEST_SCHEMA_VERSION:
|
||||
raise VintageStoreError("unsupported vintage manifest schema")
|
||||
@@ -174,8 +174,10 @@ class VintageStore:
|
||||
raise FileNotFoundError(vintage_id)
|
||||
try:
|
||||
snapshot = json.loads(snapshot_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise VintageStoreError("vintage snapshot is unreadable") from exc
|
||||
if not isinstance(snapshot, dict):
|
||||
raise VintageStoreError("vintage snapshot is invalid")
|
||||
source = snapshot.get("source")
|
||||
if not isinstance(source, dict) or source.get("vintage_id") != vintage_id:
|
||||
raise VintageStoreError("vintage snapshot identity mismatch")
|
||||
@@ -186,7 +188,11 @@ class VintageStore:
|
||||
raw_path = (self.raw_dir / raw_filename).resolve()
|
||||
if raw_path.parent != self.raw_dir.resolve() or not raw_path.is_file():
|
||||
raise VintageStoreError("vintage raw payload is missing")
|
||||
if hashlib.sha256(raw_path.read_bytes()).hexdigest() != source.get("raw_payload_hash"):
|
||||
try:
|
||||
raw_payload_hash = hashlib.sha256(raw_path.read_bytes()).hexdigest()
|
||||
except OSError as exc:
|
||||
raise VintageStoreError("vintage raw payload is unreadable") from exc
|
||||
if raw_payload_hash != source.get("raw_payload_hash"):
|
||||
raise VintageStoreError("vintage raw payload hash mismatch")
|
||||
manifest_entry = self.load_manifest().get("vintages", {}).get(vintage_id)
|
||||
if not isinstance(manifest_entry, dict):
|
||||
|
||||
+3
-2
@@ -6,12 +6,13 @@ import os
|
||||
|
||||
from app import create_app
|
||||
|
||||
app = create_app()
|
||||
HOST = os.getenv("HOST", os.getenv("PAPER_BIND_HOST", "127.0.0.1"))
|
||||
app = create_app({"PAPER_BIND_HOST": HOST})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(
|
||||
host=os.getenv("HOST", "127.0.0.1"),
|
||||
host=HOST,
|
||||
port=int(os.getenv("PORT", "5000")),
|
||||
debug=False,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Migrate legacy research reports into the fail-closed hashed format."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from app.research import ResearchRunStore
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--root",
|
||||
type=Path,
|
||||
default=Path(__file__).resolve().parents[1] / "data" / "research",
|
||||
help="research store root containing manifest.json and reports/",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
migrated = ResearchRunStore(args.root).migrate_legacy()
|
||||
print(json.dumps({"migrated_reports": migrated}, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -94,6 +94,39 @@ class EventStudyTests(unittest.TestCase):
|
||||
result = run_event_study(events, prices, windows=(1,), min_events=1)
|
||||
self.assertAlmostEqual(result["windows"]["1"]["gross_return"], 101 / 100 - 1, places=8)
|
||||
|
||||
def test_event_study_requires_known_at_for_point_in_time_prices(self):
|
||||
events = [{"event_id": "pit", "published_at": "2026-01-01T08:00:00+07:00", "signals": [{"symbol": "AOT", "target_weight": 1.0}]}]
|
||||
prices = {
|
||||
"AOT": [
|
||||
{"session_date": "2026-01-01", "close": 100},
|
||||
{"session_date": "2026-01-02", "close": 105, "known_at": "2026-01-02T17:00:00+07:00"},
|
||||
]
|
||||
}
|
||||
with self.assertRaisesRegex(EventStudyError, "known_at"):
|
||||
run_event_study(events, prices, windows=(1,), min_events=1, require_price_known_at=True)
|
||||
|
||||
def test_event_study_rejects_price_known_after_session_as_lookahead(self):
|
||||
events = [{"event_id": "lookahead", "published_at": "2026-01-01T08:00:00+07:00", "signals": [{"symbol": "AOT", "target_weight": 1.0}]}]
|
||||
prices = {
|
||||
"AOT": [
|
||||
{"session_date": "2026-01-01", "close": 100, "known_at": "2026-01-01T17:00:00+07:00", "market_timezone": "Asia/Bangkok"},
|
||||
{"session_date": "2026-01-02", "close": 105, "known_at": "2026-01-03T09:00:00+07:00", "market_timezone": "Asia/Bangkok"},
|
||||
]
|
||||
}
|
||||
with self.assertRaisesRegex(EventStudyError, "known_at"):
|
||||
run_event_study(events, prices, windows=(1,), min_events=1, require_price_known_at=True)
|
||||
|
||||
def test_event_study_checks_known_at_in_market_timezone(self):
|
||||
events = [{"event_id": "timezone-lookahead", "published_at": "2026-01-01T08:00:00+07:00", "signals": [{"symbol": "AOT", "target_weight": 1.0}]}]
|
||||
prices = {
|
||||
"AOT": [
|
||||
{"session_date": "2026-01-01", "close": 100, "known_at": "2026-01-01T18:30:00Z", "market_timezone": "Asia/Bangkok"},
|
||||
{"session_date": "2026-01-02", "close": 105, "known_at": "2026-01-02T17:00:00+07:00", "market_timezone": "Asia/Bangkok"},
|
||||
]
|
||||
}
|
||||
with self.assertRaisesRegex(EventStudyError, "known_at"):
|
||||
run_event_study(events, prices, windows=(1,), min_events=1, require_price_known_at=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,11 +5,15 @@ import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.prices import (
|
||||
DEFAULT_SYMBOL_MAP,
|
||||
PIT_ARCHIVE_CONTRACT,
|
||||
PriceSnapshotStore,
|
||||
PriceSourceError,
|
||||
_normalized_snapshot_hash,
|
||||
_observation_id,
|
||||
collect_price_snapshot,
|
||||
normalize_yahoo_chart,
|
||||
trading_dates,
|
||||
@@ -19,6 +23,33 @@ FIXTURE = Path(__file__).parent / "fixtures" / "yahoo_chart_aot.json"
|
||||
PAYLOAD = json.loads(FIXTURE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def valid_non_pit_snapshot(snapshot_id="prices-valid", retrieved_at="2026-02-01T00:00:00+00:00"):
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": snapshot_id,
|
||||
"retrieved_at": retrieved_at,
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-02",
|
||||
"quality": "revised_vendor_history",
|
||||
"point_in_time": False,
|
||||
"parser_version": "test-v1",
|
||||
"adjusted_prices": False,
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"provider_symbol": "AOT.BK",
|
||||
"raw_payload_hash": hashlib.sha256(b"aot").hexdigest(),
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{"date": "2026-01-01", "close": 100.0}],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class FakePriceProvider:
|
||||
def __init__(self, payload):
|
||||
self.payload = payload
|
||||
@@ -75,6 +106,43 @@ class PriceSnapshotTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(PriceSourceError, "result"):
|
||||
normalize_yahoo_chart(payload, canonical_symbol="AOT", provider_symbol="AOT.BK", retrieved_at="2026-08-23T06:00:00+00:00", raw_payload_hash="a" * 64)
|
||||
|
||||
def test_normalize_yahoo_chart_rejects_malformed_provider_shapes_and_numbers(self):
|
||||
cases = []
|
||||
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
payload["chart"]["result"][0]["meta"] = []
|
||||
cases.append(("meta", payload))
|
||||
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
payload["chart"]["result"][0]["indicators"]["quote"][0] = []
|
||||
cases.append(("quote", payload))
|
||||
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
payload["chart"]["result"][0]["timestamp"][0] = 10**100
|
||||
cases.append(("timestamp overflow", payload))
|
||||
|
||||
for label, field, value in (
|
||||
("boolean timestamp", "timestamp", True),
|
||||
("boolean close", "close", True),
|
||||
("boolean volume", "volume", True),
|
||||
):
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
if field == "timestamp":
|
||||
payload["chart"]["result"][0][field][0] = value
|
||||
else:
|
||||
payload["chart"]["result"][0]["indicators"]["quote"][0][field][0] = value
|
||||
cases.append((label, payload))
|
||||
|
||||
for label, payload in cases:
|
||||
with self.subTest(label=label), self.assertRaises(PriceSourceError):
|
||||
normalize_yahoo_chart(
|
||||
payload,
|
||||
canonical_symbol="AOT",
|
||||
provider_symbol="AOT.BK",
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
raw_payload_hash="a" * 64,
|
||||
)
|
||||
|
||||
def test_collector_persists_revised_vendor_history_snapshot(self):
|
||||
provider = FakePriceProvider(PAYLOAD)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -93,6 +161,231 @@ class PriceSnapshotTests(unittest.TestCase):
|
||||
self.assertEqual(len(manifest["snapshots"]), 1)
|
||||
self.assertEqual(len(provider.calls), 2)
|
||||
|
||||
def test_collector_records_observation_history_for_unchanged_payload(self):
|
||||
provider = FakePriceProvider(PAYLOAD)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=provider,
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=provider,
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
observations = manifest["observations"]
|
||||
self.assertEqual(len(observations), 2)
|
||||
self.assertEqual(observations[0]["revision_status"], "initial")
|
||||
self.assertEqual(observations[1]["revision_status"], "unchanged")
|
||||
self.assertEqual(observations[1]["previous_raw_payload_hash"], observations[0]["raw_payload_hash"])
|
||||
self.assertFalse(observations[1]["diff"]["normalized_content_changed"])
|
||||
entry = store.latest_snapshot_entry()
|
||||
self.assertEqual(entry["first_seen_at"], "2026-08-23T06:00:00+00:00")
|
||||
self.assertEqual(entry["last_seen_at"], "2026-08-24T06:00:00+00:00")
|
||||
self.assertEqual(entry["observation_count"], 2)
|
||||
|
||||
def test_collector_records_revision_diff_without_overwriting_previous_snapshot(self):
|
||||
changed_payload = copy.deepcopy(PAYLOAD)
|
||||
changed_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
revised = collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(changed_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
observations = manifest["observations"]
|
||||
self.assertEqual(len(manifest["snapshots"]), 2)
|
||||
self.assertEqual(len(observations), 2)
|
||||
self.assertEqual(observations[1]["revision_status"], "revised")
|
||||
self.assertTrue(observations[1]["diff"]["normalized_content_changed"])
|
||||
self.assertIn("series.AOT.bars[0].close", observations[1]["diff"]["changed_paths"])
|
||||
self.assertEqual(observations[1]["previous_snapshot_id"], observations[0]["snapshot_id"])
|
||||
self.assertNotEqual(revised["source"]["snapshot_id"], observations[0]["snapshot_id"])
|
||||
self.assertEqual(store.load_snapshot(observations[0]["snapshot_id"])["series"]["AOT"]["bars"][0]["close"], 61.5)
|
||||
|
||||
def test_price_store_rejects_tampered_observation_audit_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
manifest["observations"][0]["diff"]["changed_paths"] = ["series.AOT.bars[0].close"]
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaises(PriceSourceError):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_recomputed_observation_id_with_mismatched_predecessor(self):
|
||||
changed_payload = copy.deepcopy(PAYLOAD)
|
||||
changed_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(changed_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
tampered = manifest["observations"][1]
|
||||
tampered["previous_raw_payload_hash"] = "0" * 64
|
||||
tampered["observation_id"] = _observation_id({key: value for key, value in tampered.items() if key != "observation_id"})
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "previous.*hash|observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_recomputed_observation_id_with_tampered_diff(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
tampered = manifest["observations"][0]
|
||||
tampered["diff"]["changed_paths"] = ["series.AOT.bars[0].close"]
|
||||
tampered["observation_id"] = _observation_id({key: value for key, value in tampered.items() if key != "observation_id"})
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "diff|observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_malformed_observation_id_types_without_type_error(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
tampered = manifest["observations"][0]
|
||||
tampered["snapshot_id"] = []
|
||||
tampered["observation_id"] = _observation_id({key: value for key, value in tampered.items() if key != "observation_id"})
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_observation_history_truncation(self):
|
||||
changed_payload = copy.deepcopy(PAYLOAD)
|
||||
changed_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(changed_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
manifest["observations"] = manifest["observations"][:-1]
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_collector_rejects_out_of_order_observation_after_future_capture(self):
|
||||
revised_payload = copy.deepcopy(PAYLOAD)
|
||||
revised_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
late_payload = copy.deepcopy(PAYLOAD)
|
||||
late_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 62.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(revised_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
before = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable predecessor"):
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(late_payload),
|
||||
retrieved_at="2026-08-22T06:00:00+00:00",
|
||||
)
|
||||
after = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_price_store_rejects_snapshot_with_mismatched_raw_hash(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
@@ -100,6 +393,469 @@ class PriceSnapshotTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(PriceSourceError, "raw payload hash"):
|
||||
store.persist(snapshot, {"AOT.BK": b"different"})
|
||||
|
||||
def test_price_store_rejects_same_raw_hash_with_changed_stable_content(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"snapshot_id": "prices-same-raw",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "revised_vendor_history",
|
||||
"point_in_time": False,
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"provider_symbol": "AOT.BK",
|
||||
"raw_payload_hash": hashlib.sha256(b"aot").hexdigest(),
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{"date": "2026-01-01", "close": 100.0}],
|
||||
}
|
||||
},
|
||||
}
|
||||
raw = {"AOT.BK": b"aot"}
|
||||
store.persist(snapshot, raw)
|
||||
changed = copy.deepcopy(snapshot)
|
||||
changed["series"]["AOT"]["bars"][0]["close"] = 101.0
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable"):
|
||||
store.persist(changed, raw)
|
||||
|
||||
def test_price_store_rejects_same_raw_payload_with_changed_normalized_content(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
initial = valid_non_pit_snapshot("prices-same-raw-initial", "2026-02-01T00:00:00+00:00")
|
||||
store.persist(initial, {"AOT.BK": b"aot"})
|
||||
|
||||
revised = valid_non_pit_snapshot("prices-same-raw-revised", "2026-02-02T00:00:00+00:00")
|
||||
revised["series"]["AOT"]["bars"][0]["close"] = 101.0
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "normalized content"):
|
||||
store.persist(revised, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_point_in_time_flag_without_archive_contract(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"snapshot_id": "prices-pit-missing-contract",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-02",
|
||||
"quality": "forward_market_archive",
|
||||
"point_in_time": True,
|
||||
},
|
||||
"series": {"AOT": {"bars": [{"date": "2026-01-01", "close": 100.0}]}},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "point-in-time archive contract"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_requires_known_at_for_each_pit_bar(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": "prices-pit-missing-known-at",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "point_in_time_archive",
|
||||
"point_in_time": True,
|
||||
"archive_contract": PIT_ARCHIVE_CONTRACT,
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"parser_version": "pit-test-v1",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"release_published_at": "2026-01-01T17:00:00+07:00",
|
||||
},
|
||||
},
|
||||
"series": {"AOT": {"canonical_symbol": "AOT", "timezone": "Asia/Bangkok", "bars": [{"session_date": "2026-01-01", "close": 100.0}]}},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "known_at"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_persists_and_loads_explicit_pit_archive_contract(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": "prices-pit-valid",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "point_in_time_archive",
|
||||
"point_in_time": True,
|
||||
"archive_contract": PIT_ARCHIVE_CONTRACT,
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"parser_version": "pit-test-v1",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"release_published_at": "2026-01-01T17:00:00+07:00",
|
||||
},
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{
|
||||
"session_date": "2026-01-01",
|
||||
"open": 99.0,
|
||||
"high": 101.0,
|
||||
"low": 98.0,
|
||||
"close": 100.0,
|
||||
"adjusted_close": 100.0,
|
||||
"volume": 1000,
|
||||
"known_at": "2026-01-01T17:00:00+07:00",
|
||||
}],
|
||||
}
|
||||
},
|
||||
}
|
||||
loaded = store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
self.assertEqual(loaded["source"]["archive_contract"], PIT_ARCHIVE_CONTRACT)
|
||||
self.assertEqual(store.load_snapshot("prices-pit-valid")["source"]["provider_release_id"], "release-2026-01-01")
|
||||
manifest_entry = store.load_manifest()["snapshots"]["prices-pit-valid"]
|
||||
self.assertEqual(manifest_entry["archive_contract"], PIT_ARCHIVE_CONTRACT)
|
||||
self.assertTrue(manifest_entry["point_in_time"])
|
||||
|
||||
snapshot["series"]["AOT"]["bars"][0]["close"] = 101.0
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot-revision"})
|
||||
|
||||
manifest = store.load_manifest()
|
||||
manifest["snapshots"]["prices-pit-valid"]["period_end"] = "2026-01-02"
|
||||
(Path(temp_dir) / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(PriceSourceError, "point-in-time metadata"):
|
||||
store.load_snapshot("prices-pit-valid")
|
||||
|
||||
def test_price_store_totalizes_extreme_pit_numeric_values(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": "prices-pit-extreme-number",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "point_in_time_archive",
|
||||
"point_in_time": True,
|
||||
"archive_contract": PIT_ARCHIVE_CONTRACT,
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"parser_version": "pit-test-v1",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"release_published_at": "2026-01-01T17:00:00+07:00",
|
||||
},
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{
|
||||
"session_date": "2026-01-01",
|
||||
"open": 99.0,
|
||||
"high": 101.0,
|
||||
"low": 98.0,
|
||||
"close": 100.0,
|
||||
"adjusted_close": 100.0,
|
||||
"known_at": "2026-01-01T17:00:00+07:00",
|
||||
"volume": 10**1000,
|
||||
}],
|
||||
}
|
||||
},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "point-in-time archive volume"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_non_object_manifest_before_persist(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
(root / "manifest.json").write_text("[]", encoding="utf-8")
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {"source_id": "test.prices", "snapshot_id": "prices-malformed-manifest", "point_in_time": False},
|
||||
"series": {},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "manifest"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_invalid_raw_payload_symbol(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {"source_id": "test.prices", "snapshot_id": "prices-invalid-raw-symbol", "point_in_time": False},
|
||||
"series": {},
|
||||
}
|
||||
raw_payloads: Any = {1: b"aot"}
|
||||
with self.assertRaisesRegex(PriceSourceError, "raw payload"):
|
||||
store.persist(snapshot, raw_payloads)
|
||||
def test_price_store_rejects_series_provenance_mismatch_after_normalized_hash_refresh(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = valid_non_pit_snapshot()
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
snapshot_path = root / "snapshots" / "prices-valid.json"
|
||||
original = json.loads(snapshot_path.read_text(encoding="utf-8"))
|
||||
|
||||
for field, value in (("provider_symbol", "PTT.BK"), ("raw_payload_hash", "0" * 64)):
|
||||
tampered = copy.deepcopy(original)
|
||||
tampered["series"]["AOT"][field] = value
|
||||
tampered["source"]["normalized_snapshot_hash"] = _normalized_snapshot_hash(tampered)
|
||||
snapshot_path.write_text(json.dumps(tampered), encoding="utf-8")
|
||||
with self.subTest(field=field), self.assertRaisesRegex(PriceSourceError, "series"):
|
||||
store.load_snapshot("prices-valid")
|
||||
|
||||
def test_price_store_rejects_missing_required_metadata_and_malformed_non_pit_series(self):
|
||||
cases = []
|
||||
snapshot = valid_non_pit_snapshot("prices-missing-schema")
|
||||
snapshot.pop("schema_version")
|
||||
cases.append(("schema_version", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-missing-pit-flag")
|
||||
snapshot["source"].pop("point_in_time")
|
||||
cases.append(("point_in_time", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-missing-source-id")
|
||||
snapshot["source"].pop("source_id")
|
||||
cases.append(("source identity", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-malformed-series")
|
||||
snapshot["series"]["AOT"]["bars"] = "not-a-list"
|
||||
cases.append(("normalized series", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-duplicate-bars")
|
||||
snapshot["series"]["AOT"]["bars"].append(copy.deepcopy(snapshot["series"]["AOT"]["bars"][0]))
|
||||
cases.append(("duplicate normalized dates", snapshot))
|
||||
|
||||
for label, snapshot in cases:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
with self.subTest(label=label), self.assertRaises(PriceSourceError):
|
||||
PriceSnapshotStore(Path(temp_dir)).persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_non_pit_manifest_metadata_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
original = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
|
||||
for field, value in (("parser_version", "tampered-parser"), ("symbols", ["PTT"])):
|
||||
manifest = copy.deepcopy(original)
|
||||
manifest["snapshots"]["prices-valid"][field] = value
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.subTest(field=field), self.assertRaisesRegex(PriceSourceError, "metadata"):
|
||||
store.load_snapshot("prices-valid")
|
||||
|
||||
manifest = copy.deepcopy(original)
|
||||
manifest["snapshots"]["prices-valid"].pop("source_url")
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(PriceSourceError, "metadata"):
|
||||
store.load_snapshot("prices-valid")
|
||||
|
||||
def test_price_store_rejects_out_of_order_insertion_without_changing_manifest(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
late = valid_non_pit_snapshot("prices-late", "2026-02-01T18:30:00-07:00")
|
||||
early = valid_non_pit_snapshot("prices-early", "2026-02-02T00:00:00+00:00")
|
||||
store.persist(late, {"AOT.BK": b"aot"})
|
||||
before = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable predecessor"):
|
||||
store.persist(early, {"AOT.BK": b"aot"})
|
||||
|
||||
after = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(after, before)
|
||||
self.assertFalse((root / "snapshots" / "prices-early.json").exists())
|
||||
|
||||
def test_price_store_uses_deterministic_predecessor_for_equal_timestamps(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
timestamp = "2026-02-01T00:00:00+00:00"
|
||||
store.persist(valid_non_pit_snapshot("prices-a", timestamp), {"AOT.BK": b"aot"})
|
||||
store.persist(valid_non_pit_snapshot("prices-b", timestamp), {"AOT.BK": b"aot"})
|
||||
|
||||
observation = next(item for item in store.load_manifest()["observations"] if item["snapshot_id"] == "prices-b")
|
||||
self.assertEqual(observation["previous_snapshot_id"], "prices-a")
|
||||
|
||||
def test_price_store_rejects_reverse_arrival_for_equal_timestamp(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
timestamp = "2026-02-01T00:00:00+00:00"
|
||||
store.persist(valid_non_pit_snapshot("prices-b", timestamp), {"AOT.BK": b"aot"})
|
||||
before = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable predecessor"):
|
||||
store.persist(valid_non_pit_snapshot("prices-a", timestamp), {"AOT.BK": b"aot"})
|
||||
|
||||
after = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_price_store_treats_same_snapshot_same_timestamp_as_idempotent(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = valid_non_pit_snapshot("prices-idempotent", "2026-02-01T00:00:00+00:00")
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
store.persist(copy.deepcopy(snapshot), {"AOT.BK": b"aot"})
|
||||
|
||||
self.assertEqual(len(store.list_observations()), 1)
|
||||
|
||||
def test_price_store_rejects_equal_timestamp_initial_node_with_canonical_predecessor(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
timestamp = "2026-02-01T00:00:00+00:00"
|
||||
store.persist(valid_non_pit_snapshot("prices-a", timestamp), {"AOT.BK": b"aot"})
|
||||
store.persist(valid_non_pit_snapshot("prices-b", timestamp), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
observation = next(item for item in manifest["observations"] if item["snapshot_id"] == "prices-b")
|
||||
observation.pop("observation_id")
|
||||
observation["previous_snapshot_id"] = None
|
||||
observation["previous_raw_payload_hash"] = None
|
||||
observation["revision_status"] = "initial"
|
||||
observation["observation_id"] = _observation_id(observation)
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "predecessor chain"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_duplicate_equal_time_observations_for_one_snapshot(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot_id = "prices-duplicate-time"
|
||||
store.persist(valid_non_pit_snapshot(snapshot_id, "2026-02-01T00:00:00+00:00"), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
original = manifest["observations"][0]
|
||||
duplicate_diff = copy.deepcopy(original["diff"])
|
||||
duplicate_diff["raw_payload_changed"] = False
|
||||
observations = []
|
||||
for retrieved_at in ("2026-02-01T00:00:00+00:00", "2026-02-01T00:00:00Z"):
|
||||
observation = copy.deepcopy(original)
|
||||
observation["retrieved_at"] = retrieved_at
|
||||
observation["previous_snapshot_id"] = snapshot_id
|
||||
observation["previous_raw_payload_hash"] = original["raw_payload_hash"]
|
||||
observation["revision_status"] = "unchanged"
|
||||
observation["diff"] = copy.deepcopy(duplicate_diff)
|
||||
observation["observation_id"] = _observation_id(
|
||||
{key: value for key, value in observation.items() if key != "observation_id"}
|
||||
)
|
||||
observations.append(observation)
|
||||
manifest["observations"] = observations
|
||||
entry = manifest["snapshots"][snapshot_id]
|
||||
entry["observation_count"] = 2
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "ambiguous observation"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_orders_latest_snapshot_by_utc_time(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot("prices-early", "2026-02-02T00:00:00+00:00"), {"AOT.BK": b"aot"})
|
||||
store.persist(valid_non_pit_snapshot("prices-late", "2026-02-01T18:30:00-07:00"), {"AOT.BK": b"aot"})
|
||||
|
||||
self.assertEqual(store.latest_snapshot_entry()["snapshot_id"], "prices-late")
|
||||
|
||||
def test_price_store_validates_timing_metadata_when_observation_count_is_omitted(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
entry = manifest["snapshots"]["prices-valid"]
|
||||
entry.pop("observation_count")
|
||||
entry["first_seen_at"] = "not-a-timestamp"
|
||||
entry["last_seen_at"] = "not-a-timestamp"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "timing"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_observation_before_snapshot_first_capture(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot("prices-temporal", "2026-02-01T00:00:00+00:00"), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
observation = manifest["observations"][0]
|
||||
observation["retrieved_at"] = "2026-01-31T00:00:00+00:00"
|
||||
observation["observation_id"] = _observation_id({key: value for key, value in observation.items() if key != "observation_id"})
|
||||
entry = manifest["snapshots"]["prices-temporal"]
|
||||
entry["first_seen_at"] = "2026-01-31T00:00:00+00:00"
|
||||
entry["last_seen_at"] = "2026-01-31T00:00:00+00:00"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "before snapshot"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_unreferenced_contract_snapshot(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
unreferenced = copy.deepcopy(manifest["snapshots"]["prices-valid"])
|
||||
unreferenced["snapshot_id"] = "prices-unreferenced"
|
||||
unreferenced["snapshot_file"] = "prices-unreferenced.json"
|
||||
unreferenced.pop("observation_count")
|
||||
unreferenced.pop("first_seen_at")
|
||||
unreferenced.pop("last_seen_at")
|
||||
manifest["snapshots"]["prices-unreferenced"] = unreferenced
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "observation count"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_malformed_snapshot_manifest_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["snapshots"]["prices-malformed-entry"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "snapshot manifest entry"):
|
||||
store.load_manifest()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,11 +1,13 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from app.prices import PriceSnapshotStore, PriceSourceError
|
||||
from app.research import ResearchRunError, ResearchRunStore, run_tourism_research
|
||||
from app.research import ResearchRunError, ResearchRunStore, _manifest_entry_hash, _report_hash, _validate_config, run_tourism_research
|
||||
from app.vintages import VintageStore
|
||||
|
||||
|
||||
@@ -27,7 +29,7 @@ def tourism_snapshot(vintage_id: str, published_at: str) -> dict:
|
||||
"source_url": "https://example.test/bot",
|
||||
"vintage_id": vintage_id,
|
||||
"published_at": published_at,
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"retrieved_at": "2026-02-02T00:00:00+00:00",
|
||||
"release_status": "provisional",
|
||||
"parser_version": "test-v1",
|
||||
},
|
||||
@@ -35,23 +37,51 @@ def tourism_snapshot(vintage_id: str, published_at: str) -> dict:
|
||||
|
||||
|
||||
def price_snapshot(point_in_time: bool) -> tuple[dict, dict[str, bytes]]:
|
||||
def bar(session_date: str, close: float) -> dict:
|
||||
if not point_in_time:
|
||||
return {"date": session_date, "close": close}
|
||||
return {
|
||||
"date": session_date,
|
||||
"session_date": session_date,
|
||||
"open": close,
|
||||
"high": close + 1,
|
||||
"low": close - 1,
|
||||
"close": close,
|
||||
"adjusted_close": close,
|
||||
"volume": 1000,
|
||||
"known_at": f"{session_date}T17:00:00+07:00",
|
||||
}
|
||||
|
||||
pit_source = {
|
||||
"source_url": "https://example.test/prices",
|
||||
"parser_version": "pit-test-v1",
|
||||
"archive_contract": "pit-daily-v1",
|
||||
"provider_release_id": "release-2026-02-01",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-02-01",
|
||||
"release_published_at": "2026-02-01T17:00:00+07:00",
|
||||
},
|
||||
} if point_in_time else {}
|
||||
return (
|
||||
{
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"snapshot_id": "prices-test",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"retrieved_at": "2026-02-02T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-06",
|
||||
"quality": "forward_market_archive" if point_in_time else "revised_vendor_history",
|
||||
"quality": "point_in_time_archive" if point_in_time else "revised_vendor_history",
|
||||
"point_in_time": point_in_time,
|
||||
"adjusted_prices": False,
|
||||
**pit_source,
|
||||
},
|
||||
"series": {
|
||||
"AOT": {"bars": [{"date": "2026-01-01", "close": 100.0}, {"date": "2026-01-02", "close": 102.0}, {"date": "2026-01-05", "close": 104.0}, {"date": "2026-01-06", "close": 106.0}]},
|
||||
"PTT": {"bars": [{"date": "2026-01-01", "close": 100.0}, {"date": "2026-01-02", "close": 99.0}, {"date": "2026-01-05", "close": 98.0}, {"date": "2026-01-06", "close": 97.0}]},
|
||||
"SET50": {"bars": [{"date": "2026-01-01", "close": 100.0}, {"date": "2026-01-02", "close": 101.0}, {"date": "2026-01-05", "close": 102.0}, {"date": "2026-01-06", "close": 103.0}]},
|
||||
"AOT": {"canonical_symbol": "AOT", "provider_symbol": "AOT.BK", "raw_payload_hash": hashlib.sha256(b"aot").hexdigest(), "timezone": "Asia/Bangkok", "bars": [bar("2026-01-01", 100.0), bar("2026-01-02", 102.0), bar("2026-01-05", 104.0), bar("2026-01-06", 106.0)]},
|
||||
"PTT": {"canonical_symbol": "PTT", "provider_symbol": "PTT.BK", "raw_payload_hash": hashlib.sha256(b"ptt").hexdigest(), "timezone": "Asia/Bangkok", "bars": [bar("2026-01-01", 100.0), bar("2026-01-02", 99.0), bar("2026-01-05", 98.0), bar("2026-01-06", 97.0)]},
|
||||
"SET50": {"canonical_symbol": "SET50", "provider_symbol": "^SET.BK", "raw_payload_hash": hashlib.sha256(b"set").hexdigest(), "timezone": "Asia/Bangkok", "bars": [bar("2026-01-01", 100.0), bar("2026-01-02", 101.0), bar("2026-01-05", 102.0), bar("2026-01-06", 103.0)]},
|
||||
},
|
||||
"benchmark_symbol": "SET50",
|
||||
},
|
||||
@@ -60,6 +90,364 @@ def price_snapshot(point_in_time: bool) -> tuple[dict, dict[str, bytes]]:
|
||||
|
||||
|
||||
class ResearchRunTests(unittest.TestCase):
|
||||
def test_research_config_rejects_malformed_values_with_domain_error(self):
|
||||
cases = (
|
||||
((None,), 20.0, 1, 1),
|
||||
((float("nan"),), 20.0, 1, 1),
|
||||
((1,), float("inf"), 1, 1),
|
||||
((1,), 20.0, None, 1),
|
||||
((1,), 20.0, 1, float("inf")),
|
||||
)
|
||||
for windows, cost_bps, min_events, execution_lag in cases:
|
||||
with self.subTest(windows=windows, cost_bps=cost_bps, min_events=min_events, execution_lag=execution_lag):
|
||||
with self.assertRaises(ResearchRunError):
|
||||
_validate_config(
|
||||
cast(Any, windows),
|
||||
cast(Any, cost_bps),
|
||||
cast(Any, min_events),
|
||||
cast(Any, execution_lag),
|
||||
)
|
||||
|
||||
def test_research_run_store_binds_report_hash_and_rejects_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
|
||||
stored = store.persist(report)
|
||||
|
||||
self.assertRegex(stored["report_hash"], r"^[a-f0-9]{64}$")
|
||||
report_path = root / "reports" / "tourism-run-test.json"
|
||||
tampered = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
tampered["reason"] = "tampered"
|
||||
report_path.write_text(json.dumps(tampered), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-test")
|
||||
|
||||
def test_research_run_store_rejects_manifest_hash_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-manifest-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-manifest-test"]["report_hash"] = "0" * 64
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-manifest-test")
|
||||
|
||||
def test_research_run_store_migrates_legacy_reports_explicitly(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-legacy-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
legacy_manifest = {
|
||||
"schema_version": 1,
|
||||
"runs": {
|
||||
"tourism-run-legacy-test": {
|
||||
"run_id": "tourism-run-legacy-test",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"report_file": "tourism-run-legacy-test.json",
|
||||
}
|
||||
},
|
||||
}
|
||||
(root / "reports").mkdir(parents=True)
|
||||
(root / "reports" / "tourism-run-legacy-test.json").write_text(json.dumps(report), encoding="utf-8")
|
||||
(root / "manifest.json").write_text(json.dumps(legacy_manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-legacy-test")
|
||||
|
||||
self.assertEqual(store.migrate_legacy(), 1)
|
||||
migrated = store.load("tourism-run-legacy-test")
|
||||
manifest_entry = store.load_manifest()["runs"]["tourism-run-legacy-test"]
|
||||
self.assertEqual(migrated["report_hash_algorithm"], "sha256-json-canonical-v1")
|
||||
self.assertRegex(migrated["report_hash"], r"^[a-f0-9]{64}$")
|
||||
self.assertRegex(manifest_entry["manifest_entry_hash"], r"^[a-f0-9]{64}$")
|
||||
self.assertEqual(store.migrate_legacy(), 0)
|
||||
|
||||
def test_research_run_store_completes_interrupted_legacy_migration(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-partial-migration-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
partial_report = copy.deepcopy(report)
|
||||
partial_report["report_hash_algorithm"] = "sha256-json-canonical-v1"
|
||||
partial_report["report_hash"] = _report_hash(partial_report)
|
||||
legacy_entry = {
|
||||
"run_id": report["run_id"],
|
||||
"status": report["status"],
|
||||
"reason": report["reason"],
|
||||
"generated_at": report["generated_at"],
|
||||
"report_file": f"{report['run_id']}.json",
|
||||
}
|
||||
(root / "reports").mkdir(parents=True)
|
||||
(root / "reports" / f"{report['run_id']}.json").write_text(json.dumps(partial_report), encoding="utf-8")
|
||||
(root / "manifest.json").write_text(json.dumps({"schema_version": 1, "runs": {report["run_id"]: legacy_entry}}), encoding="utf-8")
|
||||
|
||||
self.assertEqual(store.migrate_legacy(), 1)
|
||||
self.assertEqual(store.load(report["run_id"])["report_hash"], partial_report["report_hash"])
|
||||
self.assertEqual(store.migrate_legacy(), 0)
|
||||
|
||||
def test_research_run_store_rejects_manifest_identity_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-identity-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
entry = manifest["runs"]["tourism-run-identity-test"]
|
||||
entry["run_id"] = "tourism-run-other"
|
||||
entry["manifest_entry_hash"] = _manifest_entry_hash(entry)
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-identity-test")
|
||||
|
||||
def test_research_run_store_rejects_manifest_metadata_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-metadata-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-metadata-test"]["generated_at"] = "2099-02-01T00:00:00+00:00"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-metadata-test")
|
||||
|
||||
def test_research_run_store_rejects_non_object_report(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-shape-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
report_path = root / "reports" / "tourism-run-shape-test.json"
|
||||
report_path.write_text("[\"tampered\"]", encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "invalid"):
|
||||
store.load("tourism-run-shape-test")
|
||||
|
||||
def test_research_run_store_rejects_non_object_manifest(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
(root / "manifest.json").write_text("[]", encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "schema"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_research_run_store_rejects_unreadable_manifest_bytes(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
(root / "manifest.json").write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "unreadable"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_research_run_store_rejects_unreadable_report_bytes(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-encoding-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
(root / "reports" / "tourism-run-encoding-test.json").write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "unreadable"):
|
||||
store.load("tourism-run-encoding-test")
|
||||
|
||||
def test_research_run_store_list_runs_rejects_manifest_metadata_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-list-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-list-test"]["generated_at"] = "2099-02-01T00:00:00+00:00"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.list_runs()
|
||||
|
||||
def test_research_run_store_latest_and_list_reject_malformed_manifest_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-entry-shape-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-entry-shape-test"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.list_runs()
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.latest()
|
||||
|
||||
def test_research_run_store_persist_rejects_malformed_existing_manifest_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-persist-entry-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-persist-entry-test"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.persist(report)
|
||||
|
||||
def test_research_run_store_persist_validates_unrelated_manifest_entries_before_write(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
existing_report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-persist-unrelated-existing",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
new_report = {
|
||||
**existing_report,
|
||||
"run_id": "tourism-run-persist-unrelated-new",
|
||||
}
|
||||
store.persist(existing_report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-persist-unrelated-malformed"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.persist(new_report)
|
||||
self.assertFalse((root / "reports" / "tourism-run-persist-unrelated-new.json").exists())
|
||||
|
||||
def test_price_store_loads_snapshot_and_verifies_raw_payload(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
@@ -100,6 +488,78 @@ class ResearchRunTests(unittest.TestCase):
|
||||
self.assertNotIn("result", report)
|
||||
self.assertEqual(run_store.latest()["run_id"], report["run_id"])
|
||||
|
||||
def test_runner_allows_explicit_exploratory_mode_with_revised_prices(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
vintage_store = VintageStore(root / "tourism")
|
||||
vintage_store.persist(b"tourism", tourism_snapshot("v1", "2026-01-01T08:00:00+07:00"))
|
||||
price_store = PriceSnapshotStore(root / "prices")
|
||||
snapshot, raw = price_snapshot(point_in_time=False)
|
||||
price_store.persist(snapshot, raw)
|
||||
run_store = ResearchRunStore(root / "runs")
|
||||
|
||||
report = run_tourism_research(
|
||||
vintage_store,
|
||||
price_store,
|
||||
run_store,
|
||||
mode="exploratory",
|
||||
min_events=1,
|
||||
windows=(1,),
|
||||
)
|
||||
|
||||
self.assertEqual(report["status"], "descriptive_only")
|
||||
self.assertEqual(report["research_mode"], "exploratory")
|
||||
self.assertEqual(report["result_scope"], "non_pit_descriptive_only")
|
||||
self.assertEqual(report["gates"]["prices"]["status"], "descriptive_only")
|
||||
self.assertEqual(report["gates"]["prices"]["reason"], "price_series_not_point_in_time")
|
||||
self.assertEqual(report["result"]["event_count"], 1)
|
||||
|
||||
def test_runner_keeps_exploratory_pit_inputs_descriptive_only(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
vintage_store = VintageStore(root / "tourism")
|
||||
vintage_store.persist(b"tourism", tourism_snapshot("v1", "2026-01-01T08:00:00+07:00"))
|
||||
price_store = PriceSnapshotStore(root / "prices")
|
||||
snapshot, raw = price_snapshot(point_in_time=True)
|
||||
price_store.persist(snapshot, raw)
|
||||
run_store = ResearchRunStore(root / "runs")
|
||||
|
||||
report = run_tourism_research(
|
||||
vintage_store,
|
||||
price_store,
|
||||
run_store,
|
||||
mode="exploratory",
|
||||
min_events=1,
|
||||
windows=(1,),
|
||||
)
|
||||
|
||||
self.assertEqual(report["status"], "descriptive_only")
|
||||
self.assertEqual(report["result_scope"], "non_pit_descriptive_only")
|
||||
self.assertEqual(report["gates"]["prices"]["status"], "descriptive_only")
|
||||
self.assertFalse(report["gates"]["prices"]["validated"])
|
||||
self.assertTrue(report["gates"]["prices"]["point_in_time"])
|
||||
self.assertEqual(report["gates"]["prices"]["reason"], "exploratory_mode_non_validated")
|
||||
|
||||
def test_runner_reuses_same_run_when_only_observation_time_changes(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
vintage_store = VintageStore(root / "tourism")
|
||||
vintage_store.persist(b"tourism", tourism_snapshot("v1", "2026-01-01T08:00:00+07:00"))
|
||||
price_store = PriceSnapshotStore(root / "prices")
|
||||
snapshot, raw = price_snapshot(point_in_time=False)
|
||||
price_store.persist(snapshot, raw)
|
||||
run_store = ResearchRunStore(root / "runs")
|
||||
|
||||
first = run_tourism_research(vintage_store, price_store, run_store, mode="exploratory", min_events=1, windows=(1,))
|
||||
observed_again = copy.deepcopy(snapshot)
|
||||
observed_again["source"]["retrieved_at"] = "2026-02-03T00:00:00+00:00"
|
||||
price_store.persist(observed_again, raw)
|
||||
second = run_tourism_research(vintage_store, price_store, run_store, mode="exploratory", min_events=1, windows=(1,))
|
||||
|
||||
self.assertEqual(second["run_id"], first["run_id"])
|
||||
self.assertEqual(second, first)
|
||||
self.assertEqual(len(price_store.list_observations()), 2)
|
||||
|
||||
def test_runner_computes_replayable_result_when_both_gates_pass(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
|
||||
@@ -5,11 +5,12 @@ import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from app.bot_tourism import BotTourismSource
|
||||
from app.collector import collect_bot_vintage
|
||||
from app.vintages import VintageStore, filter_vintages
|
||||
from app.vintages import VintageStore, VintageStoreError, filter_vintages
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
REPORT_HTML = (FIXTURES / "bot_tourism_report.html").read_text(encoding="utf-8")
|
||||
@@ -128,6 +129,50 @@ class VintageStoreTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "hash"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_snapshot_load_rejects_non_object_json(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
snapshot = sample_snapshot()
|
||||
store.persist(REPORT_HTML.encode("utf-8"), snapshot)
|
||||
snapshot_path = root / "snapshots" / f"{snapshot['source']['vintage_id']}.json"
|
||||
snapshot_path.write_text(json.dumps(["not", "a", "snapshot"]), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(VintageStoreError, "invalid"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_snapshot_load_rejects_unreadable_utf8(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
snapshot = sample_snapshot()
|
||||
store.persist(REPORT_HTML.encode("utf-8"), snapshot)
|
||||
snapshot_path = root / "snapshots" / f"{snapshot['source']['vintage_id']}.json"
|
||||
snapshot_path.write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(VintageStoreError, "unreadable"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_snapshot_load_rejects_unreadable_raw_payload(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
snapshot = sample_snapshot()
|
||||
store.persist(REPORT_HTML.encode("utf-8"), snapshot)
|
||||
|
||||
with patch("pathlib.Path.read_bytes", side_effect=OSError("read failed")):
|
||||
with self.assertRaisesRegex(VintageStoreError, "unreadable"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_manifest_load_rejects_unreadable_utf8(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
(root / "manifest.json").write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(VintageStoreError, "unreadable"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_collector_returns_manifested_snapshot_summary(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = collect_bot_vintage(
|
||||
|
||||
Reference in new issue
Block a user