Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: add data audit and PIT observe mode

Miranda5dd1194be465
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 9c584cbaf..31c091ff2 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -493,6 +493,7 @@ class BaseEngine(ABC):
data_sources=_run_card_data_sources(config, loader),
strategy_path=run_dir / "code" / "signal_engine.py",
warnings=config.get("content_filter_warnings") or None,
+ artifact_refs=config.get("_irr_artifact_refs") or None,
)
# Print scalar metrics (skip nested dicts for JSON compat)
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.py
index f9d7cf546..57d2f879b 100644
--- a/agent/backtest/engines/options_portfolio.py
+++ b/agent/backtest/engines/options_portfolio.py
@@ -530,6 +530,7 @@ def run_options_backtest(
data_sources=[str(getattr(loader, "name", config.get("source", "")))],
strategy_path=run_dir / "code" / "signal_engine.py",
warnings=config.get("content_filter_warnings") or None,
+ artifact_refs=config.get("_irr_artifact_refs") or None,
)
print(json.dumps(metrics, indent=2))
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index c1265fb56..161acdd00 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -371,6 +371,158 @@ def _get_loader(source: str):
raise
+def _maybe_audited_loader(
+ loader,
+ *,
+ config: dict,
+ requested_source: str,
+ selected_source: str,
+ codes: List[str],
+ interval: str,
+ fallback_chain: List[str] | None = None,
+):
+ """Wrap a backtest data loader with observe-mode audit metadata."""
+ try:
+ from src.reliability.config import reliability_enabled
+ except Exception:
+ return loader
+
+ if not reliability_enabled():
+ return loader
+
+ try:
+ from src.reliability.data.contracts import DataSetContract
+ from src.reliability.data.loader_wrapper import AuditedDataLoader
+ from src.reliability.data.source_manifest import SourceManifest
+ except Exception:
+ logger.exception("failed to initialize data audit wrapper; using raw loader")
+ return loader
+
+ selected = str(getattr(loader, "name", selected_source))
+ chain = _audit_fallback_chain(requested_source, codes, fallback_chain)
+ asset_class = _audit_asset_class(codes)
+ manifest = SourceManifest(
+ requested_source=requested_source,
+ selected_source=selected,
+ fallback_chain=chain,
+ attempted_sources=[selected],
+ runtime_source=selected,
+ cache_hit=False,
+ )
+ return AuditedDataLoader(
+ loader,
+ source=requested_source,
+ selected_source=selected,
+ source_manifest=manifest,
+ dataset_contract=DataSetContract(
+ dataset_id=f"{selected}:ohlcv:{interval}",
+ asset_class=asset_class,
+ frequency=interval,
+ calendar=str(config.get("calendar") or selected),
+ fields=["open", "high", "low", "close", "volume"],
+ timezone=_audit_timezone(asset_class),
+ corporate_action_policy=config.get("corporate_action_policy"),
+ survivorship_policy=config.get("survivorship_policy"),
+ ),
+ dataset_kind="ohlcv",
+ as_of=_audit_datetime(config.get("as_of")),
+ available_at=_audit_datetime(config.get("available_at")),
+ market_rule_config=_audit_market_rule_config(config, asset_class),
+ )
+
+
+def _attach_loader_audit_to_config(config: dict, loader) -> None:
+ """Attach an audited loader's report refs to config for run-card rendering."""
+ report = getattr(loader, "last_audit_report", None)
+ if report is None:
+ return
+
+ audit_ids = config.setdefault("_data_audit_ids", [])
+ if report.audit_id not in audit_ids:
+ audit_ids.append(report.audit_id)
+
+ refs = config.setdefault("_irr_artifact_refs", [])
+ existing_ids = {
+ ref.get("artifact_id")
+ for ref in refs
+ if isinstance(ref, dict)
+ }
+ for ref in report.artifact_refs:
+ payload = ref.model_dump(mode="json") if hasattr(ref, "model_dump") else dict(ref)
+ if payload.get("artifact_id") not in existing_ids:
+ refs.append(payload)
+ existing_ids.add(payload.get("artifact_id"))
+
+
+def _audit_fallback_chain(
+ source: str,
+ codes: List[str],
+ fallback_chain: List[str] | None = None,
+) -> List[str]:
+ if _audit_explicit_local(source, codes):
+ return ["local"]
+ if fallback_chain:
+ return list(fallback_chain)
+ if codes:
+ market = _detect_market(codes[0])
+ chain = list(FALLBACK_CHAINS.get(market, []))
+ if source in chain:
+ return chain[chain.index(source):]
+ return [source]
+
+
+def _audit_explicit_local(source: str, codes: List[str]) -> bool:
+ normalized = str(source).strip().lower()
+ return normalized in {"local", "local:"} or any(str(code).lower().startswith("local:") for code in codes)
+
+
+def _audit_asset_class(codes: List[str]) -> str:
+ markets = {_detect_market(code) for code in codes} if codes else set()
+ if "a_share" in markets:
+ return "ashare"
+ if "us_equity" in markets:
+ return "us_equity"
+ if "hk_equity" in markets:
+ return "hk_equity"
+ if "crypto" in markets:
+ return "crypto"
+ if "futures" in markets:
+ return "futures"
+ return "other"
+
+
+def _audit_timezone(asset_class: str) -> str:
+ if asset_class == "ashare":
+ return "Asia/Shanghai"
+ if asset_class == "hk_equity":
+ return "Asia/Hong_Kong"
+ return "UTC"
+
+
+def _audit_market_rule_config(config: dict, asset_class: str) -> dict:
+ audit_config = dict(config)
+ audit_config["asset_class"] = asset_class
+ if asset_class == "ashare":
+ audit_config.setdefault("ashare_t1", True)
+ audit_config.setdefault("ashare_limit_up_down", True)
+ audit_config.setdefault("ashare_lot_size", True)
+ return audit_config
+
+
+def _audit_datetime(value: Any):
+ if value in (None, ""):
+ return None
+ try:
+ timestamp = pd.Timestamp(value)
+ except Exception:
+ return None
+ if timestamp.tzinfo is None:
+ timestamp = timestamp.tz_localize("UTC")
+ else:
+ timestamp = timestamp.tz_convert("UTC")
+ return timestamp.to_pydatetime()
+
+
def _normalize_codes(codes: List[str], source: str) -> List[str]:
"""Normalize symbol strings for a source.
@@ -468,6 +620,14 @@ def main(run_dir: Path) -> None:
config["codes"] = codes
LoaderCls = _get_loader(source)
loader = LoaderCls()
+ loader = _maybe_audited_loader(
+ loader,
+ config=config,
+ requested_source=source,
+ selected_source=source,
+ codes=codes,
+ interval=interval,
+ )
data_map = loader.fetch(
codes,
config.get("start_date", ""),
@@ -475,6 +635,7 @@ def main(run_dir: Path) -> None:
fields=config.get("extra_fields") or None,
interval=interval,
)
+ _attach_loader_audit_to_config(config, loader)
if data_map and len(data_map) < len(codes):
missing = set(codes) - set(data_map.keys())
logger.warning(
@@ -482,7 +643,7 @@ def main(run_dir: Path) -> None:
source, len(data_map), len(codes), missing,
)
# Runtime fallback: try next sources in chain when primary returns empty
- if not data_map and codes:
+ if not data_map and codes and not _audit_explicit_local(source, codes):
market = _detect_market(codes[0])
for fb_name in FALLBACK_CHAINS.get(market, []):
if fb_name == source or fb_name not in LOADER_REGISTRY:
@@ -491,10 +652,20 @@ def main(run_dir: Path) -> None:
if not fb_loader.is_available():
continue
fb_codes = _normalize_codes(codes, fb_name)
+ fb_loader = _maybe_audited_loader(
+ fb_loader,
+ config=config,
+ requested_source=source,
+ selected_source=fb_name,
+ codes=fb_codes,
+ interval=interval,
+ fallback_chain=_audit_fallback_chain(source, codes),
+ )
data_map = fb_loader.fetch(
fb_codes, config.get("start_date", ""),
config.get("end_date", ""), interval=interval,
)
+ _attach_loader_audit_to_config(config, fb_loader)
if data_map:
logger.info("Runtime fallback: %s -> %s", source, fb_name)
source = fb_name
@@ -644,7 +815,17 @@ def _fetch_auto(codes: List[str], config: dict, interval: str = "1D") -> dict:
src_name = getattr(loader, "name", "unknown")
normalized_codes = _normalize_codes(market_codes, src_name)
fields = config.get("extra_fields") if src_name == "tushare" else None
+ loader = _maybe_audited_loader(
+ loader,
+ config=config,
+ requested_source="auto",
+ selected_source=src_name,
+ codes=normalized_codes,
+ interval=interval,
+ fallback_chain=list(FALLBACK_CHAINS.get(market, [src_name])),
+ )
result = loader.fetch(normalized_codes, start_date, end_date, fields=fields, interval=interval)
+ _attach_loader_audit_to_config(config, loader)
# Runtime fallback: try remaining sources when primary returns empty
if not result:
@@ -655,7 +836,17 @@ def _fetch_auto(codes: List[str], config: dict, interval: str = "1D") -> dict:
if not fb_loader.is_available():
continue
fb_codes = _normalize_codes(market_codes, fb_name)
+ fb_loader = _maybe_audited_loader(
+ fb_loader,
+ config=config,
+ requested_source="auto",
+ selected_source=fb_name,
+ codes=fb_codes,
+ interval=interval,
+ fallback_chain=list(FALLBACK_CHAINS.get(market, [fb_name])),
+ )
result = fb_loader.fetch(fb_codes, start_date, end_date, interval=interval)
+ _attach_loader_audit_to_config(config, fb_loader)
if result:
logger.info("Runtime fallback: %s -> %s for %s", src_name, fb_name, market)
break
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index 4b670fab6..2cca15ed6 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -74,6 +74,97 @@ def _json_safe(value: Any) -> Any:
return value
+def _maybe_audited_loader(
+ loader: Any,
+ *,
+ requested_source: str,
+ selected_source: str,
+ codes: list[str],
+ interval: str,
+):
+ """Wrap a loader with observe-mode data audit metadata when enabled."""
+ try:
+ from src.reliability.config import reliability_enabled
+ except Exception:
+ return loader
+
+ if not reliability_enabled():
+ return loader
+
+ try:
+ from src.reliability.data.contracts import DataSetContract
+ from src.reliability.data.loader_wrapper import AuditedDataLoader
+ from src.reliability.data.source_manifest import SourceManifest
+ except Exception:
+ logger.exception("failed to initialize data audit wrapper; using raw loader")
+ return loader
+
+ selected = str(getattr(loader, "name", selected_source))
+ manifest = SourceManifest(
+ requested_source=requested_source,
+ selected_source=selected,
+ fallback_chain=[selected],
+ attempted_sources=[selected],
+ runtime_source=selected,
+ cache_hit=False,
+ )
+ return AuditedDataLoader(
+ loader,
+ source=requested_source,
+ selected_source=selected,
+ source_manifest=manifest,
+ dataset_contract=DataSetContract(
+ dataset_id=f"{selected}:ohlcv:{interval}",
+ asset_class=_infer_asset_class(codes),
+ frequency=interval,
+ calendar=selected,
+ fields=["open", "high", "low", "close", "volume"],
+ timezone=_infer_timezone(codes),
+ ),
+ dataset_kind="ohlcv",
+ market_rule_config={
+ "asset_class": _infer_asset_class(codes),
+ },
+ )
+
+
+def _attach_audit_metadata(results: dict[str, Any], loader: Any) -> None:
+ report = getattr(loader, "last_audit_report", None)
+ if report is None:
+ return
+
+ metadata = results.setdefault("_metadata", {})
+ audit_ids = metadata.setdefault("data_audit_ids", [])
+ if report.audit_id not in audit_ids:
+ audit_ids.append(report.audit_id)
+
+ refs = metadata.setdefault("artifact_refs", [])
+ refs.extend(ref.model_dump(mode="json") for ref in report.artifact_refs)
+
+
+def _infer_asset_class(codes: list[str]) -> str:
+ if any(re.match(r"^\d{6}\.(SZ|SH|BJ)$", code, re.I) for code in codes):
+ return "ashare"
+ if any(re.match(r"^[A-Z]+\.US$", code, re.I) for code in codes):
+ return "us_equity"
+ if any(re.match(r"^\d{3,5}\.HK$", code, re.I) for code in codes):
+ return "hk_equity"
+ if any(re.match(r"^[A-Z]+[-/]USDT$", code, re.I) for code in codes):
+ return "crypto"
+ return "other"
+
+
+def _infer_timezone(codes: list[str]) -> str:
+ asset_class = _infer_asset_class(codes)
+ if asset_class == "ashare":
+ return "Asia/Shanghai"
+ if asset_class in {"us_equity", "crypto"}:
+ return "UTC"
+ if asset_class == "hk_equity":
+ return "Asia/Hong_Kong"
+ return "UTC"
+
+
def fetch_market_data(
*,
codes: list[str],
@@ -98,6 +189,13 @@ def fetch_market_data(
for src, src_codes in groups.items():
loader_cls = loader_resolver(src)
loader = loader_cls()
+ loader = _maybe_audited_loader(
+ loader,
+ requested_source=source,
+ selected_source=src,
+ codes=src_codes,
+ interval=interval,
+ )
try:
data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)
except Exception:
@@ -107,6 +205,7 @@ def fetch_market_data(
src_codes,
)
data_map = {}
+ _attach_audit_metadata(results, loader)
for symbol, df in data_map.items():
records = df.reset_index().to_dict(orient="records")
for row in records:
diff --git a/agent/src/reliability/data/__init__.py b/agent/src/reliability/data/__init__.py
new file mode 100644
index 000000000..c48283692
--- /dev/null
+++ b/agent/src/reliability/data/__init__.py
@@ -0,0 +1,5 @@
+"""Data reliability package."""
+
+from __future__ import annotations
+
+__all__: list[str] = []
diff --git a/agent/src/reliability/data/circuit_breaker.py b/agent/src/reliability/data/circuit_breaker.py
new file mode 100644
index 000000000..974250dbb
--- /dev/null
+++ b/agent/src/reliability/data/circuit_breaker.py
@@ -0,0 +1,150 @@
+"""SQLite-backed source-level circuit breaker."""
+
+from __future__ import annotations
+
+import sqlite3
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+
+from src.reliability.data.contracts import CircuitBreakerSnapshot, StructuredWarning
+
+
+@dataclass(frozen=True)
+class CircuitDecision:
+ """Decision before using one source."""
+
+ source: str
+ state: str
+ allowed: bool
+ warning: StructuredWarning | None = None
+
+
+class CircuitBreaker:
+ """Track source failures and skip OPEN providers."""
+
+ def __init__(
+ self,
+ path: Path,
+ *,
+ failure_threshold: int = 3,
+ open_seconds: int = 60,
+ ) -> None:
+ self.path = Path(path)
+ self.failure_threshold = max(1, int(failure_threshold))
+ self.open_seconds = max(0, int(open_seconds))
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self._init_db()
+
+ def before_request(self, source: str) -> CircuitDecision:
+ """Return whether source should be used now."""
+ snapshot = self.snapshot(source)
+ if snapshot.state == "OPEN":
+ now = time.time()
+ opened_at = snapshot.opened_at.timestamp() if snapshot.opened_at is not None else 0.0
+ if now - opened_at >= self.open_seconds:
+ self._upsert_state(source, "HALF_OPEN", snapshot.consecutive_failures, snapshot.last_error_class, opened_at)
+ return CircuitDecision(source=source, state="HALF_OPEN", allowed=True)
+ return CircuitDecision(
+ source=source,
+ state="OPEN",
+ allowed=False,
+ warning=StructuredWarning(
+ code="DATA_SOURCE_SKIPPED_BY_CIRCUIT",
+ severity="warning",
+ message="source skipped because circuit breaker is OPEN",
+ metadata={"source": source},
+ ),
+ )
+ return CircuitDecision(source=source, state=snapshot.state, allowed=True)
+
+ def record_success(self, source: str) -> None:
+ """Close source circuit after a successful request."""
+ self._upsert_state(source, "CLOSED", 0, None, None)
+
+ def record_failure(self, source: str, error: BaseException) -> None:
+ """Record a source failure and open if threshold is reached."""
+ snapshot = self.snapshot(source)
+ failures = snapshot.consecutive_failures + 1
+ state = "OPEN" if failures >= self.failure_threshold else snapshot.state
+ opened_at = time.time() if state == "OPEN" else (snapshot.opened_at.timestamp() if snapshot.opened_at else None)
+ self._upsert_state(source, state, failures, type(error).__name__, opened_at)
+
+ def snapshot(self, source: str) -> CircuitBreakerSnapshot:
+ """Return a source state snapshot."""
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT state, consecutive_failures, opened_at, last_error_class FROM circuit_state WHERE source = ?",
+ (source,),
+ ).fetchone()
+ if row is None:
+ return CircuitBreakerSnapshot(source=source, state="CLOSED", consecutive_failures=0)
+ state, failures, opened_at, error_class = row
+ opened_dt = _from_epoch(opened_at)
+ next_probe = (
+ datetime.fromtimestamp(float(opened_at) + self.open_seconds, tz=timezone.utc)
+ if opened_at is not None
+ else None
+ )
+ return CircuitBreakerSnapshot(
+ source=source,
+ state=state,
+ consecutive_failures=int(failures),
+ opened_at=opened_dt,
+ last_error_class=error_class,
+ next_probe_after=next_probe,
+ )
+
+ def snapshots(self, sources: list[str]) -> list[CircuitBreakerSnapshot]:
+ """Return snapshots for all requested sources."""
+ return [self.snapshot(source) for source in sources]
+
+ def _init_db(self) -> None:
+ with self._connect() as conn:
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS circuit_state (
+ source TEXT PRIMARY KEY,
+ state TEXT NOT NULL,
+ consecutive_failures INTEGER NOT NULL,
+ opened_at REAL,
+ last_error_class TEXT
+ )
+ """
+ )
+
+ def _connect(self) -> sqlite3.Connection:
+ conn = sqlite3.connect(str(self.path), timeout=30.0)
+ conn.execute("PRAGMA busy_timeout=30000")
+ return conn
+
+ def _upsert_state(
+ self,
+ source: str,
+ state: str,
+ failures: int,
+ error_class: str | None,
+ opened_at: float | None,
+ ) -> None:
+ with self._connect() as conn:
+ conn.execute(
+ """
+ INSERT INTO circuit_state (source, state, consecutive_failures, opened_at, last_error_class)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(source) DO UPDATE SET
+ state = excluded.state,
+ consecutive_failures = excluded.consecutive_failures,
+ opened_at = excluded.opened_at,
+ last_error_class = excluded.last_error_class
+ """,
+ (source, state, failures, opened_at, error_class),
+ )
+
+
+def _from_epoch(value: float | None) -> datetime | None:
+ if value is None:
+ return None
+ return datetime.fromtimestamp(float(value), tz=timezone.utc)
+
diff --git a/agent/src/reliability/data/contracts.py b/agent/src/reliability/data/contracts.py
new file mode 100644
index 000000000..1ba67b50f
--- /dev/null
+++ b/agent/src/reliability/data/contracts.py
@@ -0,0 +1,103 @@
+"""Pydantic contracts for Phase 2 data reliability audits."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Any, Literal
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+
+from src.reliability.artifacts.model import ArtifactRef
+from src.reliability.pit.violations import PITViolation
+
+
+class StructuredWarning(BaseModel):
+ """Stable warning or hard-failure code with metadata."""
+
+ code: str
+ severity: Literal["info", "warning", "hard_failure"] = "warning"
+ message: str
+ metadata: dict[str, Any] = Field(default_factory=dict)
+
+
+class DataSetContract(BaseModel):
+ """Dataset contract describing what was requested."""
+
+ dataset_id: str
+ asset_class: Literal["ashare", "us_equity", "hk_equity", "crypto", "futures", "macro", "other"]
+ frequency: str
+ calendar: str
+ fields: list[str]
+ timezone: str
+ corporate_action_policy: str | None = None
+ survivorship_policy: str | None = None
+
+
+class DataAccessContract(BaseModel):
+ """Access contract recording source/fallback/cache provenance."""
+
+ source: str
+ selected_source: str
+ request_params_hash: str
+ fallback_chain: list[str]
+ cache_key: str | None = None
+ fetched_at: datetime
+ source_timestamp: datetime | None = None
+ explicit_local: bool
+ source_priority_rank: int | None = None
+ fallback_chain_id: str | None = None
+ circuit_breaker_state: Literal["CLOSED", "OPEN", "HALF_OPEN"] | None = None
+ loader_latency_ms: float | None = None
+
+ @field_validator("fetched_at", "source_timestamp")
+ @classmethod
+ def _datetime_utc(cls, value: datetime | None) -> datetime | None:
+ if value is None:
+ return None
+ if value.tzinfo is None or value.utcoffset() is None:
+ raise ValueError("datetime fields must be timezone-aware")
+ return value.astimezone(timezone.utc)
+
+
+class CircuitBreakerSnapshot(BaseModel):
+ """Serializable source circuit-breaker state."""
+
+ source: str
+ state: Literal["CLOSED", "OPEN", "HALF_OPEN"]
+ consecutive_failures: int
+ opened_at: datetime | None = None
+ last_error_class: str | None = None
+ next_probe_after: datetime | None = None
+
+ @field_validator("opened_at", "next_probe_after")
+ @classmethod
+ def _datetime_utc(cls, value: datetime | None) -> datetime | None:
+ if value is None:
+ return None
+ if value.tzinfo is None or value.utcoffset() is None:
+ raise ValueError("datetime fields must be timezone-aware")
+ return value.astimezone(timezone.utc)
+
+
+class DataAuditReport(BaseModel):
+ """Data reliability audit produced by an audited loader call."""
+
+ model_config = ConfigDict(arbitrary_types_allowed=False)
+
+ audit_id: str
+ schema_version: str
+ dataset_contract: DataSetContract | None = None
+ access_contract: DataAccessContract
+ row_count: int
+ symbol_count: int
+ field_coverage: dict[str, float]
+ content_sample_hash: str | None = None
+ per_symbol_hashes: dict[str, str] = Field(default_factory=dict)
+ pit_violations: list[PITViolation] = Field(default_factory=list)
+ quality_warnings: list[StructuredWarning] = Field(default_factory=list)
+ market_rule_warnings: list[StructuredWarning] = Field(default_factory=list)
+ source_circuit_states: dict[str, Literal["CLOSED", "OPEN", "HALF_OPEN"]] = Field(default_factory=dict)
+ circuit_breaker_events: list[CircuitBreakerSnapshot] = Field(default_factory=list)
+ all_sources_open: bool = False
+ artifact_refs: list[ArtifactRef] = Field(default_factory=list)
+
diff --git a/agent/src/reliability/data/errors.py b/agent/src/reliability/data/errors.py
new file mode 100644
index 000000000..913679896
--- /dev/null
+++ b/agent/src/reliability/data/errors.py
@@ -0,0 +1,35 @@
+"""Data reliability exceptions."""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+class AllSourcesOpenError(Exception):
+ """Raised when every non-local fallback source is circuit-open."""
+
+ error_code = "DATA_ALL_SOURCES_OPEN"
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ chain: list[str],
+ breaker_states: dict[str, str],
+ audit_id: str | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.chain = chain
+ self.breaker_states = breaker_states
+ self.audit_id = audit_id
+
+ def to_dict(self) -> dict[str, Any]:
+ """Return a JSON-safe representation."""
+ return {
+ "error_code": self.error_code,
+ "message": str(self),
+ "chain": list(self.chain),
+ "breaker_states": dict(self.breaker_states),
+ "audit_id": self.audit_id,
+ }
+
diff --git a/agent/src/reliability/data/loader_wrapper.py b/agent/src/reliability/data/loader_wrapper.py
new file mode 100644
index 000000000..a754d53ff
--- /dev/null
+++ b/agent/src/reliability/data/loader_wrapper.py
@@ -0,0 +1,328 @@
+"""AuditedDataLoader wrapper for Phase 2 observe-mode data reliability."""
+
+from __future__ import annotations
+
+import time
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+import pandas as pd
+
+from src.reliability.artifacts.store import ArtifactStore
+from src.reliability.artifacts.hashing import sha256_json
+from src.reliability.config import reliability_enabled
+from src.reliability.data.circuit_breaker import CircuitBreaker
+from src.reliability.data.contracts import (
+ DataAccessContract,
+ DataAuditReport,
+ DataSetContract,
+ StructuredWarning,
+)
+from src.reliability.data.errors import AllSourcesOpenError
+from src.reliability.data.source_manifest import SourceManifest
+from src.reliability.data.validators import validate_data_map
+from src.reliability.market_rules.ashare import audit_ashare_assumptions
+from src.reliability.pit.checker import PITChecker
+from src.reliability.pit.model import PITTimestampSet
+
+
+class AuditedDataLoader:
+ """Wrapper that records data audit metadata without changing fetch output."""
+
+ def __init__(
+ self,
+ inner: Any,
+ *,
+ source: str,
+ selected_source: str | None = None,
+ source_manifest: SourceManifest | None = None,
+ dataset_contract: DataSetContract | None = None,
+ dataset_kind: str = "ohlcv",
+ as_of: datetime | None = None,
+ available_at: datetime | None = None,
+ market_rule_config: dict[str, Any] | None = None,
+ circuit_breaker: CircuitBreaker | None = None,
+ artifact_store: ArtifactStore | None = None,
+ max_sample_rows: int = 10_000,
+ ) -> None:
+ self.inner = inner
+ self.source = source
+ self.selected_source = selected_source or getattr(inner, "name", source)
+ self.source_manifest = source_manifest
+ self.dataset_contract = dataset_contract
+ self.dataset_kind = dataset_kind
+ self.as_of = _to_utc(as_of) if as_of is not None else None
+ self.available_at = _to_utc(available_at) if available_at is not None else None
+ self.market_rule_config = dict(market_rule_config or {})
+ self.circuit_breaker = circuit_breaker
+ self.artifact_store = artifact_store
+ self.max_sample_rows = max_sample_rows
+ self.last_audit_report: DataAuditReport | None = None
+
+ @property
+ def name(self) -> str:
+ return getattr(self.inner, "name", self.selected_source)
+
+ @property
+ def markets(self) -> set[str]:
+ return getattr(self.inner, "markets", set())
+
+ @property
+ def requires_auth(self) -> bool:
+ return bool(getattr(self.inner, "requires_auth", False))
+
+ def is_available(self) -> bool:
+ """Proxy availability checks to the inner loader."""
+ return self.inner.is_available()
+
+ def fetch(
+ self,
+ codes,
+ start_date,
+ end_date,
+ *,
+ interval: str = "1D",
+ fields: list[str] | None = None,
+ ) -> dict[str, pd.DataFrame]:
+ """Fetch data and record audit metadata when reliability is enabled."""
+ if not reliability_enabled():
+ return self.inner.fetch(codes, start_date, end_date, interval=interval, fields=fields)
+
+ manifest = self._manifest(codes)
+ request_hash = _request_hash(
+ source=self.source,
+ codes=list(codes),
+ start_date=str(start_date),
+ end_date=str(end_date),
+ interval=interval,
+ fields=fields,
+ )
+ decisions = self._circuit_decisions(manifest)
+ if self._all_nonlocal_sources_open(manifest, decisions):
+ report = self._build_empty_audit(
+ manifest=manifest,
+ request_hash=request_hash,
+ start_date=str(start_date),
+ end_date=str(end_date),
+ interval=interval,
+ all_sources_open=True,
+ quality_warnings=[
+ StructuredWarning(
+ code="DATA_ALL_SOURCES_OPEN",
+ severity="hard_failure",
+ message="all fallback data sources are circuit-open",
+ metadata={"chain": self._nonlocal_chain(manifest)},
+ )
+ ],
+ circuit_events=[decision_snapshot for decision_snapshot in decisions.values()],
+ )
+ self._record_audit(report)
+ states = {source: snapshot.state for source, snapshot in decisions.items()}
+ raise AllSourcesOpenError(
+ "all fallback data sources are circuit-open",
+ chain=self._nonlocal_chain(manifest),
+ breaker_states=states,
+ audit_id=report.audit_id,
+ )
+
+ start = time.perf_counter()
+ try:
+ data_map = self.inner.fetch(codes, start_date, end_date, interval=interval, fields=fields)
+ except Exception as exc:
+ if self.circuit_breaker is not None:
+ self.circuit_breaker.record_failure(manifest.selected_source, exc)
+ raise
+ latency_ms = (time.perf_counter() - start) * 1000.0
+ if self.circuit_breaker is not None:
+ self.circuit_breaker.record_success(manifest.selected_source)
+
+ validation = validate_data_map(data_map, max_sample_rows=self.max_sample_rows)
+ pit = self._pit_result(start_date=str(start_date), end_date=str(end_date))
+ quality_warnings = list(validation.quality_warnings)
+ quality_warnings.extend(pit.warnings)
+ market_rule_warnings = self._market_rule_warnings()
+ report = DataAuditReport(
+ audit_id=f"audit_{uuid.uuid4().hex}",
+ schema_version="1.0.0",
+ dataset_contract=self.dataset_contract,
+ access_contract=self._access_contract(
+ manifest=manifest,
+ request_hash=request_hash,
+ latency_ms=latency_ms,
+ circuit_state=decisions.get(manifest.selected_source).state if manifest.selected_source in decisions else None,
+ ),
+ row_count=validation.row_count,
+ symbol_count=validation.symbol_count,
+ field_coverage=validation.field_coverage,
+ content_sample_hash=validation.content_sample_hash,
+ per_symbol_hashes=validation.per_symbol_hashes,
+ pit_violations=pit.violations,
+ quality_warnings=quality_warnings,
+ market_rule_warnings=market_rule_warnings,
+ source_circuit_states={source: snapshot.state for source, snapshot in decisions.items()},
+ circuit_breaker_events=list(decisions.values()),
+ all_sources_open=False,
+ )
+ self._record_audit(report)
+ return data_map
+
+ def _manifest(self, codes: list[str]) -> SourceManifest:
+ explicit_local = _explicit_local(self.source, codes)
+ if self.source_manifest is not None:
+ return self.source_manifest
+ selected = "local" if explicit_local else self.selected_source
+ chain = ["local"] if explicit_local else [selected]
+ return SourceManifest(
+ requested_source=self.source,
+ selected_source=selected,
+ fallback_chain=chain,
+ attempted_sources=[selected],
+ runtime_source=selected,
+ cache_hit=False,
+ )
+
+ def _circuit_decisions(self, manifest: SourceManifest) -> dict[str, Any]:
+ if self.circuit_breaker is None:
+ return {}
+ snapshots = {}
+ for source in manifest.fallback_chain:
+ if source == "local":
+ snapshots[source] = self.circuit_breaker.snapshot(source)
+ continue
+ decision = self.circuit_breaker.before_request(source)
+ snapshots[source] = self.circuit_breaker.snapshot(source)
+ if decision.warning is not None:
+ # The warning is reconstructed in _build_empty_audit for all-open
+ # and captured in source_circuit_states for ordinary fetches.
+ pass
+ return snapshots
+
+ def _all_nonlocal_sources_open(self, manifest: SourceManifest, decisions: dict[str, Any]) -> bool:
+ chain = self._nonlocal_chain(manifest)
+ if not chain:
+ return False
+ return bool(decisions) and all(decisions[source].state == "OPEN" for source in chain)
+
+ def _nonlocal_chain(self, manifest: SourceManifest) -> list[str]:
+ if _explicit_local(manifest.requested_source, []):
+ return []
+ return [source for source in manifest.fallback_chain if source != "local"]
+
+ def _build_empty_audit(
+ self,
+ *,
+ manifest: SourceManifest,
+ request_hash: str,
+ start_date: str,
+ end_date: str,
+ interval: str,
+ all_sources_open: bool,
+ quality_warnings: list[StructuredWarning],
+ circuit_events: list[Any],
+ ) -> DataAuditReport:
+ return DataAuditReport(
+ audit_id=f"audit_{uuid.uuid4().hex}",
+ schema_version="1.0.0",
+ dataset_contract=self.dataset_contract,
+ access_contract=self._access_contract(
+ manifest=manifest,
+ request_hash=request_hash,
+ latency_ms=None,
+ circuit_state="OPEN" if all_sources_open else None,
+ ),
+ row_count=0,
+ symbol_count=0,
+ field_coverage={},
+ quality_warnings=quality_warnings,
+ source_circuit_states={event.source: event.state for event in circuit_events},
+ circuit_breaker_events=circuit_events,
+ all_sources_open=all_sources_open,
+ )
+
+ def _access_contract(
+ self,
+ *,
+ manifest: SourceManifest,
+ request_hash: str,
+ latency_ms: float | None,
+ circuit_state: str | None,
+ ) -> DataAccessContract:
+ return DataAccessContract(
+ source=manifest.requested_source,
+ selected_source=manifest.selected_source,
+ request_params_hash=request_hash,
+ fallback_chain=list(manifest.fallback_chain or [manifest.selected_source]),
+ fetched_at=datetime.now(timezone.utc),
+ explicit_local=_explicit_local(manifest.requested_source, []),
+ fallback_chain_id=manifest.fallback_chain_id,
+ circuit_breaker_state=circuit_state, # type: ignore[arg-type]
+ loader_latency_ms=latency_ms,
+ )
+
+ def _pit_result(self, *, start_date: str, end_date: str):
+ effective_at = _parse_date_utc(end_date) if self.dataset_kind == "ohlcv" else _parse_date_utc(start_date)
+ timestamps = PITTimestampSet(
+ effective_at=effective_at,
+ available_at=self.available_at,
+ as_of=self.as_of,
+ )
+ return PITChecker(dataset_kind=self.dataset_kind, as_of=self.as_of).check(timestamps)
+
+ def _market_rule_warnings(self) -> list[StructuredWarning]:
+ asset_class = self.dataset_contract.asset_class if self.dataset_contract is not None else self.market_rule_config.get("asset_class")
+ if asset_class == "ashare":
+ return audit_ashare_assumptions(self.market_rule_config)
+ return []
+
+ def _record_audit(self, report: DataAuditReport) -> None:
+ store = self.artifact_store or ArtifactStore()
+ try:
+ record = store.write_json(
+ report.model_dump(mode="json"),
+ artifact_type="data_audit",
+ generated_by="AuditedDataLoader",
+ metadata={"audit_id": report.audit_id, "selected_source": report.access_contract.selected_source},
+ )
+ except Exception:
+ record = None
+ if record is not None:
+ report.artifact_refs.append(record.to_ref())
+ self.last_audit_report = report
+
+
+def _request_hash(**kwargs: Any) -> str:
+ value = {
+ key: item
+ for key, item in kwargs.items()
+ if item is not None
+ }
+ if "fields" in value:
+ value["fields"] = [str(field) for field in value["fields"]]
+ value["codes"] = [str(code) for code in value.get("codes", [])]
+ return sha256_json(value)
+
+
+def _explicit_local(source: str, codes: list[str]) -> bool:
+ normalized = str(source).strip().lower()
+ return normalized in {"local", "local:"} or any(str(code).lower().startswith("local:") for code in codes)
+
+
+def _parse_date_utc(value: str) -> datetime | None:
+ try:
+ ts = pd.Timestamp(value)
+ except Exception:
+ return None
+ if ts.tzinfo is None:
+ ts = ts.tz_localize(timezone.utc)
+ else:
+ ts = ts.tz_convert(timezone.utc)
+ return ts.to_pydatetime()
+
+
+def _to_utc(value: datetime) -> datetime:
+ if value.tzinfo is None or value.utcoffset() is None:
+ raise ValueError("datetime must be timezone-aware")
+ return value.astimezone(timezone.utc)
+
diff --git a/agent/src/reliability/data/source_manifest.py b/agent/src/reliability/data/source_manifest.py
new file mode 100644
index 000000000..704de9933
--- /dev/null
+++ b/agent/src/reliability/data/source_manifest.py
@@ -0,0 +1,18 @@
+"""Source provenance manifest for audited data loads."""
+
+from __future__ import annotations
+
+from pydantic import BaseModel, Field
+
+
+class SourceManifest(BaseModel):
+ """Observed source selection/fallback metadata for one load."""
+
+ requested_source: str
+ selected_source: str
+ fallback_chain: list[str] = Field(default_factory=list)
+ attempted_sources: list[str] = Field(default_factory=list)
+ runtime_source: str | None = None
+ cache_hit: bool = False
+ fallback_chain_id: str | None = None
+
diff --git a/agent/src/reliability/data/validators.py b/agent/src/reliability/data/validators.py
new file mode 100644
index 000000000..6d0990386
--- /dev/null
+++ b/agent/src/reliability/data/validators.py
@@ -0,0 +1,140 @@
+"""Bounded DataFrame validators for data audit reports."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from typing import Any
+
+import pandas as pd
+from pydantic import BaseModel, Field
+
+from src.reliability.data.contracts import StructuredWarning
+
+
+class DataValidationResult(BaseModel):
+ """Bounded validation summary for a data map."""
+
+ row_count: int
+ symbol_count: int
+ field_coverage: dict[str, float]
+ content_sample_hash: str | None = None
+ per_symbol_hashes: dict[str, str] = Field(default_factory=dict)
+ quality_warnings: list[StructuredWarning] = Field(default_factory=list)
+ inspected_rows: int = 0
+
+
+def validate_data_map(
+ data_map: dict[str, pd.DataFrame],
+ *,
+ max_sample_rows: int = 10_000,
+ per_symbol_hash_limit: int = 20,
+) -> DataValidationResult:
+ """Validate a loader return map using bounded sampling."""
+ row_count = 0
+ sampled_rows = 0
+ field_non_null: dict[str, int] = {}
+ field_seen_rows: dict[str, int] = {}
+ sample_parts: list[dict[str, Any]] = []
+ per_symbol_hashes: dict[str, str] = {}
+ warnings: list[StructuredWarning] = []
+
+ remaining = max(0, int(max_sample_rows))
+ for symbol, frame in data_map.items():
+ if not isinstance(frame, pd.DataFrame):
+ warnings.append(
+ StructuredWarning(
+ code="DATA_NON_DATAFRAME_RESULT",
+ severity="warning",
+ message="loader returned a non-DataFrame value",
+ metadata={"symbol": symbol, "type": type(frame).__name__},
+ )
+ )
+ continue
+ row_count += len(frame)
+ sample = _sample_frame(frame, remaining)
+ remaining = max(0, remaining - len(sample))
+ sampled_rows += len(sample)
+ if len(frame) > len(sample):
+ warnings.append(
+ StructuredWarning(
+ code="DATA_VALIDATOR_SAMPLED",
+ severity="info",
+ message="large DataFrame sampled for audit validation",
+ metadata={"symbol": symbol, "rows": len(frame), "sampled_rows": len(sample)},
+ )
+ )
+ for column in frame.columns:
+ series = sample[column] if column in sample.columns else pd.Series(dtype="object")
+ field_non_null[column] = field_non_null.get(column, 0) + int(series.notna().sum())
+ field_seen_rows[column] = field_seen_rows.get(column, 0) + len(sample)
+ sample_parts.append(_frame_sample_payload(symbol, sample))
+ if len(per_symbol_hashes) < per_symbol_hash_limit:
+ per_symbol_hashes[symbol] = _hash_payload(_frame_sample_payload(symbol, sample))
+
+ field_coverage = {
+ field: (field_non_null.get(field, 0) / seen if seen else 0.0)
+ for field, seen in field_seen_rows.items()
+ }
+ content_sample_hash = _hash_payload(sample_parts) if sample_parts else None
+ return DataValidationResult(
+ row_count=row_count,
+ symbol_count=len(data_map),
+ field_coverage=field_coverage,
+ content_sample_hash=content_sample_hash,
+ per_symbol_hashes=per_symbol_hashes,
+ quality_warnings=warnings,
+ inspected_rows=sampled_rows,
+ )
+
+
+def _sample_frame(frame: pd.DataFrame, max_rows: int) -> pd.DataFrame:
+ if max_rows <= 0:
+ return frame.iloc[0:0]
+ if len(frame) <= max_rows:
+ return frame
+ if max_rows == 1:
+ return frame.iloc[[0]]
+ step = max(1, len(frame) // max_rows)
+ sample = frame.iloc[::step].head(max_rows)
+ return sample
+
+
+def _frame_sample_payload(symbol: str, frame: pd.DataFrame) -> dict[str, Any]:
+ reset = frame.reset_index()
+ records = reset.head(len(frame)).to_dict(orient="records")
+ return {
+ "symbol": symbol,
+ "columns": [str(column) for column in frame.columns],
+ "rows": [_json_safe_record(record) for record in records],
+ }
+
+
+def _json_safe_record(record: dict[str, Any]) -> dict[str, Any]:
+ safe: dict[str, Any] = {}
+ for key, value in record.items():
+ safe[str(key)] = _json_safe_value(value)
+ return safe
+
+
+def _json_safe_value(value: Any) -> Any:
+ if hasattr(value, "item"):
+ value = value.item()
+ if value is None:
+ return None
+ if isinstance(value, float) and not math.isfinite(value):
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ pass
+ if hasattr(value, "isoformat"):
+ return value.isoformat()
+ return value
+
+
+def _hash_payload(payload: Any) -> str:
+ blob = json.dumps(payload, ensure_ascii=False, sort_keys=True, allow_nan=False, default=str, separators=(",", ":"))
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()
diff --git a/agent/src/reliability/market_rules/__init__.py b/agent/src/reliability/market_rules/__init__.py
new file mode 100644
index 000000000..2a29b723d
--- /dev/null
+++ b/agent/src/reliability/market_rules/__init__.py
@@ -0,0 +1,6 @@
+"""Market-rule reliability checks."""
+
+from __future__ import annotations
+
+__all__ = []
+
diff --git a/agent/src/reliability/market_rules/ashare.py b/agent/src/reliability/market_rules/ashare.py
new file mode 100644
index 000000000..100049e20
--- /dev/null
+++ b/agent/src/reliability/market_rules/ashare.py
@@ -0,0 +1,47 @@
+"""A-share market-rule audit warnings."""
+
+from __future__ import annotations
+
+from typing import Any, Mapping
+
+from src.reliability.data.contracts import StructuredWarning
+
+_ASHARE_REQUIRED_FLAGS: tuple[tuple[str, str, str], ...] = (
+ ("ashare_t1", "ASHARE_T1_ASSUMPTION_MISSING", "A-share T+1 handling is not declared"),
+ (
+ "ashare_limit_up_down",
+ "ASHARE_LIMIT_UP_DOWN_ASSUMPTION_MISSING",
+ "A-share limit-up/down handling is not declared",
+ ),
+ ("ashare_suspension", "ASHARE_SUSPENSION_ASSUMPTION_MISSING", "A-share suspension handling is not declared"),
+ ("ashare_lot_size", "ASHARE_LOT_SIZE_ASSUMPTION_MISSING", "A-share 100-share lot handling is not declared"),
+ ("ashare_st_filter", "ASHARE_ST_FILTER_MISSING", "A-share ST filter is not declared"),
+ ("ashare_new_listing_filter", "ASHARE_NEW_LISTING_FILTER_MISSING", "A-share new-listing filter is not declared"),
+ (
+ "historical_universe",
+ "ASHARE_HISTORICAL_UNIVERSE_MISSING",
+ "A-share historical universe membership is not declared",
+ ),
+)
+
+
+def audit_ashare_assumptions(config: Mapping[str, Any]) -> list[StructuredWarning]:
+ """Return stable warnings for missing A-share assumptions."""
+ warnings: list[StructuredWarning] = []
+ for key, code, message in _ASHARE_REQUIRED_FLAGS:
+ if not config.get(key):
+ warnings.append(StructuredWarning(code=code, severity="warning", message=message))
+ if not config.get("cost_model") and not _has_inline_cost_model(config):
+ warnings.append(
+ StructuredWarning(
+ code="ASHARE_COST_MODEL_MISSING",
+ severity="warning",
+ message="A-share cost model is not declared",
+ )
+ )
+ return warnings
+
+
+def _has_inline_cost_model(config: Mapping[str, Any]) -> bool:
+ return any(key in config for key in ("commission_rate", "stamp_tax", "transfer_fee", "slippage"))
+
diff --git a/agent/src/reliability/market_rules/crypto.py b/agent/src/reliability/market_rules/crypto.py
new file mode 100644
index 000000000..a7ee11303
--- /dev/null
+++ b/agent/src/reliability/market_rules/crypto.py
@@ -0,0 +1,16 @@
+"""Crypto market-rule audit placeholder for Phase 2."""
+
+from __future__ import annotations
+
+from typing import Any, Mapping
+
+from src.reliability.data.contracts import StructuredWarning
+
+
+def audit_crypto_assumptions(_config: Mapping[str, Any]) -> list[StructuredWarning]:
+ """Return crypto market-rule warnings.
+
+ Phase 2 keeps this intentionally empty; later scorecard phases can extend it.
+ """
+ return []
+
diff --git a/agent/src/reliability/market_rules/us_equity.py b/agent/src/reliability/market_rules/us_equity.py
new file mode 100644
index 000000000..de07e4aab
--- /dev/null
+++ b/agent/src/reliability/market_rules/us_equity.py
@@ -0,0 +1,16 @@
+"""US equity market-rule audit placeholder for Phase 2."""
+
+from __future__ import annotations
+
+from typing import Any, Mapping
+
+from src.reliability.data.contracts import StructuredWarning
+
+
+def audit_us_equity_assumptions(_config: Mapping[str, Any]) -> list[StructuredWarning]:
+ """Return US equity market-rule warnings.
+
+ Phase 2 keeps this intentionally empty; later scorecard phases can extend it.
+ """
+ return []
+
diff --git a/agent/src/reliability/pit/__init__.py b/agent/src/reliability/pit/__init__.py
new file mode 100644
index 000000000..bccf8e4b5
--- /dev/null
+++ b/agent/src/reliability/pit/__init__.py
@@ -0,0 +1,5 @@
+"""Point-in-time reliability package."""
+
+from __future__ import annotations
+
+__all__: list[str] = []
diff --git a/agent/src/reliability/pit/checker.py b/agent/src/reliability/pit/checker.py
new file mode 100644
index 000000000..479f864f9
--- /dev/null
+++ b/agent/src/reliability/pit/checker.py
@@ -0,0 +1,107 @@
+"""Point-in-time checks for data availability."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from src.reliability.data.contracts import StructuredWarning
+from src.reliability.pit.model import PITTimestampSet
+from src.reliability.pit.violations import PITViolation
+
+DatasetKind = Literal["ohlcv", "event", "fundamental", "news", "macro", "sec_filing", "other"]
+_AVAILABLE_AT_REQUIRED = {"event", "fundamental", "news", "macro", "sec_filing"}
+
+
+class PITCheckResult(BaseModel):
+ """PIT check result."""
+
+ pit_safe: bool
+ warnings: list[StructuredWarning] = Field(default_factory=list)
+ violations: list[PITViolation] = Field(default_factory=list)
+ timestamps: PITTimestampSet
+
+
+class PITChecker:
+ """Check PIT timestamp sets against an optional as-of."""
+
+ def __init__(self, *, dataset_kind: DatasetKind = "ohlcv", as_of: datetime | None = None) -> None:
+ self.dataset_kind = dataset_kind
+ self.as_of = _to_utc(as_of) if as_of is not None else None
+
+ def check(self, timestamps: PITTimestampSet) -> PITCheckResult:
+ """Check timestamps for PIT warnings and hard failures."""
+ as_of = timestamps.as_of or self.as_of
+ available_at = timestamps.available_at
+ warnings: list[StructuredWarning] = []
+ violations: list[PITViolation] = []
+ pit_safe = True
+
+ if as_of is None:
+ warnings.append(
+ StructuredWarning(
+ code="PIT_MISSING_AS_OF",
+ severity="warning",
+ message="as_of timestamp is missing; PIT safety cannot be fully asserted",
+ )
+ )
+
+ if available_at is None and self.dataset_kind in _AVAILABLE_AT_REQUIRED:
+ warnings.append(
+ StructuredWarning(
+ code="PIT_AVAILABLE_AT_MISSING",
+ severity="warning",
+ message="available_at is required for event/fundamental/news/macro/filing data",
+ metadata={"dataset_kind": self.dataset_kind},
+ )
+ )
+ pit_safe = False
+
+ if available_at is None and self.dataset_kind == "ohlcv" and timestamps.effective_at is not None:
+ available_at = _infer_ohlcv_available_at(timestamps.effective_at)
+ warnings.append(
+ StructuredWarning(
+ code="PIT_AVAILABLE_AT_INFERRED",
+ severity="warning",
+ message="daily OHLCV available_at inferred from effective_at",
+ metadata={"available_at": available_at.isoformat()},
+ )
+ )
+
+ if available_at is not None and as_of is not None and available_at > as_of:
+ violations.append(
+ PITViolation(
+ code="PIT_FUTURE_DATA",
+ severity="hard_failure",
+ message="available_at is after as_of",
+ hard_failure=True,
+ metadata={"available_at": available_at.isoformat(), "as_of": as_of.isoformat()},
+ )
+ )
+ pit_safe = False
+
+ return PITCheckResult(
+ pit_safe=pit_safe,
+ warnings=warnings,
+ violations=violations,
+ timestamps=PITTimestampSet(
+ effective_at=timestamps.effective_at,
+ published_at=timestamps.published_at,
+ ingested_at=timestamps.ingested_at,
+ available_at=available_at,
+ as_of=as_of,
+ ),
+ )
+
+
+def _to_utc(value: datetime) -> datetime:
+ if value.tzinfo is None or value.utcoffset() is None:
+ raise ValueError("datetime must be timezone-aware")
+ return value.astimezone(timezone.utc)
+
+
+def _infer_ohlcv_available_at(effective_at: datetime) -> datetime:
+ return effective_at.astimezone(timezone.utc) + timedelta(days=1)
+
diff --git a/agent/src/reliability/pit/model.py b/agent/src/reliability/pit/model.py
new file mode 100644
index 000000000..c41fb322c
--- /dev/null
+++ b/agent/src/reliability/pit/model.py
@@ -0,0 +1,27 @@
+"""PIT timestamp model."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from pydantic import BaseModel, field_validator
+
+
+class PITTimestampSet(BaseModel):
+ """The five timestamps used for PIT checks."""
+
+ effective_at: datetime | None = None
+ published_at: datetime | None = None
+ ingested_at: datetime | None = None
+ available_at: datetime | None = None
+ as_of: datetime | None = None
+
+ @field_validator("effective_at", "published_at", "ingested_at", "available_at", "as_of")
+ @classmethod
+ def _datetime_utc(cls, value: datetime | None) -> datetime | None:
+ if value is None:
+ return None
+ if value.tzinfo is None or value.utcoffset() is None:
+ raise ValueError("PIT timestamps must be timezone-aware")
+ return value.astimezone(timezone.utc)
+
diff --git a/agent/src/reliability/pit/violations.py b/agent/src/reliability/pit/violations.py
new file mode 100644
index 000000000..84666559e
--- /dev/null
+++ b/agent/src/reliability/pit/violations.py
@@ -0,0 +1,18 @@
+"""PIT violation schema."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+
+class PITViolation(BaseModel):
+ """Structured PIT warning or violation."""
+
+ code: str
+ severity: Literal["info", "warning", "hard_failure"] = "warning"
+ message: str
+ hard_failure: bool = False
+ metadata: dict[str, Any] = Field(default_factory=dict)
+
diff --git a/agent/tests/reliability/test_audited_data_loader.py b/agent/tests/reliability/test_audited_data_loader.py
new file mode 100644
index 000000000..50a8697a1
--- /dev/null
+++ b/agent/tests/reliability/test_audited_data_loader.py
@@ -0,0 +1,190 @@
+"""Tests for Phase 2 audited data loader wrapper."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.reliability.data.circuit_breaker import CircuitBreaker
+from src.reliability.data.errors import AllSourcesOpenError
+from src.reliability.data.loader_wrapper import AuditedDataLoader
+from src.reliability.data.source_manifest import SourceManifest
+from backtest.runner import _attach_loader_audit_to_config
+
+
+class FakeLoader:
+ name = "yahoo"
+ markets = {"us_equity"}
+ requires_auth = False
+
+ def __init__(self, data_map: dict[str, pd.DataFrame] | None = None) -> None:
+ self.data_map = data_map or {}
+ self.calls: list[tuple] = []
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, interval="1D", fields=None):
+ self.calls.append((codes, start_date, end_date, interval, fields))
+ return self.data_map
+
+
+def _frame() -> pd.DataFrame:
+ return pd.DataFrame(
+ {
+ "open": [10.0, 11.0],
+ "high": [11.0, 12.0],
+ "low": [9.0, 10.0],
+ "close": [10.5, 11.5],
+ "volume": [1000, 1100],
+ },
+ index=pd.date_range("2026-01-01", periods=2, freq="D"),
+ )
+
+
+def test_audited_loader_preserves_fetch_return_shape(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ inner = FakeLoader({"AAPL.US": _frame()})
+ loader = AuditedDataLoader(inner, source="yahoo")
+
+ result = loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02", interval="1D")
+
+ assert result is inner.data_map
+ assert loader.last_audit_report is not None
+ assert loader.last_audit_report.row_count == 2
+
+
+def test_reliability_mode_off_uses_original_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "off")
+ inner = FakeLoader({"AAPL.US": _frame()})
+ loader = AuditedDataLoader(inner, source="yahoo")
+
+ result = loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02")
+
+ assert result is inner.data_map
+ assert loader.last_audit_report is None
+
+
+def test_auto_source_records_fallback_manifest(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ inner = FakeLoader({"AAPL.US": _frame()})
+ manifest = SourceManifest(
+ requested_source="auto",
+ selected_source="yahoo",
+ fallback_chain=["yahoo", "stooq"],
+ attempted_sources=["tencent", "yahoo"],
+ runtime_source="yahoo",
+ cache_hit=False,
+ )
+ loader = AuditedDataLoader(inner, source="auto", source_manifest=manifest)
+
+ loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02")
+
+ assert loader.last_audit_report is not None
+ access = loader.last_audit_report.access_contract
+ assert access.source == "auto"
+ assert access.selected_source == "yahoo"
+ assert access.fallback_chain == ["yahoo", "stooq"]
+
+
+def test_local_source_never_falls_back_to_network(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ inner = FakeLoader({})
+ inner.name = "local"
+ loader = AuditedDataLoader(inner, source="local")
+
+ loader.fetch(["local:AAPL.US"], "2026-01-01", "2026-01-02")
+
+ assert loader.last_audit_report is not None
+ assert loader.last_audit_report.access_contract.explicit_local is True
+ assert loader.last_audit_report.access_contract.fallback_chain == ["local"]
+
+
+def test_all_sources_open_raises_not_empty_frame(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ breaker = CircuitBreaker(tmp_path / "breaker.sqlite", failure_threshold=1, open_seconds=60)
+ breaker.record_failure("yahoo", RuntimeError("quota"))
+ breaker.record_failure("stooq", RuntimeError("quota"))
+ inner = FakeLoader({})
+ loader = AuditedDataLoader(
+ inner,
+ source="auto",
+ source_manifest=SourceManifest(
+ requested_source="auto",
+ selected_source="yahoo",
+ fallback_chain=["yahoo", "stooq"],
+ attempted_sources=[],
+ runtime_source=None,
+ cache_hit=False,
+ ),
+ circuit_breaker=breaker,
+ )
+
+ with pytest.raises(AllSourcesOpenError) as excinfo:
+ loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02")
+
+ assert excinfo.value.error_code == "DATA_ALL_SOURCES_OPEN"
+
+
+def test_all_sources_open_records_hard_failure_code(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ breaker = CircuitBreaker(tmp_path / "breaker.sqlite", failure_threshold=1, open_seconds=60)
+ breaker.record_failure("yahoo", RuntimeError("quota"))
+ inner = FakeLoader({})
+ loader = AuditedDataLoader(
+ inner,
+ source="auto",
+ source_manifest=SourceManifest(
+ requested_source="auto",
+ selected_source="yahoo",
+ fallback_chain=["yahoo"],
+ attempted_sources=[],
+ runtime_source=None,
+ cache_hit=False,
+ ),
+ circuit_breaker=breaker,
+ )
+
+ with pytest.raises(AllSourcesOpenError):
+ loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02")
+
+ assert loader.last_audit_report is not None
+ assert loader.last_audit_report.all_sources_open is True
+ assert any(w.code == "DATA_ALL_SOURCES_OPEN" for w in loader.last_audit_report.quality_warnings)
+
+
+def test_available_at_after_as_of_records_future_data_violation(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ inner = FakeLoader({"AAPL.US": _frame()})
+ loader = AuditedDataLoader(
+ inner,
+ source="yahoo",
+ as_of=datetime(2026, 1, 1, tzinfo=timezone.utc),
+ available_at=datetime(2026, 1, 2, tzinfo=timezone.utc),
+ dataset_kind="ohlcv",
+ )
+
+ loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02")
+
+ assert loader.last_audit_report is not None
+ assert any(v.code == "PIT_FUTURE_DATA" for v in loader.last_audit_report.pit_violations)
+
+
+def test_runner_config_collects_audit_refs_for_run_card(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ monkeypatch.setenv("VIBE_TRADING_ARTIFACT_ROOT", str(tmp_path / "artifacts"))
+ loader = AuditedDataLoader(FakeLoader({"AAPL.US": _frame()}), source="yahoo")
+ loader.fetch(["AAPL.US"], "2026-01-01", "2026-01-02")
+ config: dict[str, object] = {}
+
+ _attach_loader_audit_to_config(config, loader)
+
+ assert config["_data_audit_ids"] == [loader.last_audit_report.audit_id]
+ refs = config["_irr_artifact_refs"]
+ assert refs[0]["artifact_type"] == "data_audit"
diff --git a/agent/tests/reliability/test_circuit_breaker.py b/agent/tests/reliability/test_circuit_breaker.py
new file mode 100644
index 000000000..ea847f47a
--- /dev/null
+++ b/agent/tests/reliability/test_circuit_breaker.py
@@ -0,0 +1,38 @@
+"""Tests for Phase 2 source-level circuit breaker."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from src.reliability.data.circuit_breaker import CircuitBreaker
+
+
+def test_circuit_breaker_opens_after_three_failures(tmp_path: Path) -> None:
+ breaker = CircuitBreaker(tmp_path / "breaker.sqlite", failure_threshold=3, open_seconds=60)
+
+ for _ in range(3):
+ breaker.record_failure("yahoo", RuntimeError("rate limited"))
+
+ assert breaker.snapshot("yahoo").state == "OPEN"
+
+
+def test_circuit_breaker_half_open_success_closes(tmp_path: Path) -> None:
+ breaker = CircuitBreaker(tmp_path / "breaker.sqlite", failure_threshold=1, open_seconds=0)
+ breaker.record_failure("stooq", RuntimeError("timeout"))
+
+ assert breaker.before_request("stooq").state == "HALF_OPEN"
+ breaker.record_success("stooq")
+
+ assert breaker.snapshot("stooq").state == "CLOSED"
+
+
+def test_circuit_breaker_skip_records_warning(tmp_path: Path) -> None:
+ breaker = CircuitBreaker(tmp_path / "breaker.sqlite", failure_threshold=1, open_seconds=60)
+ breaker.record_failure("finnhub", RuntimeError("quota"))
+
+ decision = breaker.before_request("finnhub")
+
+ assert decision.allowed is False
+ assert decision.warning is not None
+ assert decision.warning.code == "DATA_SOURCE_SKIPPED_BY_CIRCUIT"
+
diff --git a/agent/tests/reliability/test_data_audit_models.py b/agent/tests/reliability/test_data_audit_models.py
new file mode 100644
index 000000000..d8c775cfe
--- /dev/null
+++ b/agent/tests/reliability/test_data_audit_models.py
@@ -0,0 +1,96 @@
+"""Tests for Phase 2 data audit schemas and validators."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+import pandas as pd
+
+from src.reliability.data.contracts import (
+ DataAccessContract,
+ DataAuditReport,
+ DataSetContract,
+ StructuredWarning,
+)
+from src.reliability.data.validators import validate_data_map
+
+
+def test_data_audit_report_has_stable_warning_error_codes() -> None:
+ report = DataAuditReport(
+ audit_id="audit_test",
+ schema_version="1.0.0",
+ dataset_contract=DataSetContract(
+ dataset_id="prices",
+ asset_class="us_equity",
+ frequency="1D",
+ calendar="XNYS",
+ fields=["open", "close"],
+ timezone="UTC",
+ ),
+ access_contract=DataAccessContract(
+ source="auto",
+ selected_source="yahoo",
+ request_params_hash="a" * 64,
+ fallback_chain=["yahoo", "stooq"],
+ fetched_at=datetime.now(timezone.utc),
+ explicit_local=False,
+ ),
+ row_count=10,
+ symbol_count=1,
+ field_coverage={"close": 1.0},
+ quality_warnings=[
+ StructuredWarning(
+ code="DATA_FIELD_COVERAGE_LOW",
+ severity="warning",
+ message="close coverage below threshold",
+ )
+ ],
+ all_sources_open=False,
+ )
+
+ dumped = report.model_dump(mode="json")
+
+ assert dumped["quality_warnings"][0]["code"] == "DATA_FIELD_COVERAGE_LOW"
+ assert dumped["all_sources_open"] is False
+ assert dumped["schema_version"] == "1.0.0"
+
+
+def test_validator_samples_large_dataframe() -> None:
+ rows = 50_000
+ frame = pd.DataFrame(
+ {
+ "open": range(rows),
+ "high": range(rows),
+ "low": range(rows),
+ "close": range(rows),
+ "volume": range(rows),
+ },
+ index=pd.date_range("2026-01-01", periods=rows, freq="min"),
+ )
+
+ result = validate_data_map({"AAPL.US": frame}, max_sample_rows=1000)
+
+ assert result.row_count == rows
+ assert result.symbol_count == 1
+ assert result.content_sample_hash is not None
+ assert result.inspected_rows <= 1000
+ assert any(warning.code == "DATA_VALIDATOR_SAMPLED" for warning in result.quality_warnings)
+
+
+def test_validator_hashes_nan_samples_without_throwing() -> None:
+ frame = pd.DataFrame(
+ {
+ "open": [1.0],
+ "high": [float("nan")],
+ "low": [0.9],
+ "close": [1.1],
+ "volume": [100],
+ },
+ index=pd.date_range("2026-01-01", periods=1, freq="D"),
+ )
+
+ result = validate_data_map({"AAPL.US": frame})
+
+ assert result.content_sample_hash is not None
+ assert result.per_symbol_hashes["AAPL.US"]
+ assert result.field_coverage["high"] == 0.0
diff --git a/agent/tests/reliability/test_market_rules_ashare.py b/agent/tests/reliability/test_market_rules_ashare.py
new file mode 100644
index 000000000..ecefbe357
--- /dev/null
+++ b/agent/tests/reliability/test_market_rules_ashare.py
@@ -0,0 +1,32 @@
+"""Tests for Phase 2 A-share market-rule warnings."""
+
+from __future__ import annotations
+
+from src.reliability.market_rules.ashare import audit_ashare_assumptions
+
+
+def test_ashare_missing_t1_warning() -> None:
+ warnings = audit_ashare_assumptions({"asset_class": "ashare"})
+
+ codes = {warning.code for warning in warnings}
+
+ assert "ASHARE_T1_ASSUMPTION_MISSING" in codes
+ assert "ASHARE_COST_MODEL_MISSING" in codes
+
+
+def test_ashare_complete_assumptions_do_not_warn() -> None:
+ warnings = audit_ashare_assumptions(
+ {
+ "ashare_t1": True,
+ "ashare_limit_up_down": True,
+ "ashare_suspension": True,
+ "ashare_lot_size": True,
+ "cost_model": {"commission_bps": 2.5},
+ "ashare_st_filter": True,
+ "ashare_new_listing_filter": True,
+ "historical_universe": True,
+ }
+ )
+
+ assert warnings == []
+
diff --git a/agent/tests/reliability/test_pit_checker.py b/agent/tests/reliability/test_pit_checker.py
new file mode 100644
index 000000000..08ec37282
--- /dev/null
+++ b/agent/tests/reliability/test_pit_checker.py
@@ -0,0 +1,47 @@
+"""Tests for Phase 2 PIT timestamp checks."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+from src.reliability.pit.checker import PITChecker
+from src.reliability.pit.model import PITTimestampSet
+
+
+def test_missing_available_at_warns_not_pit_safe() -> None:
+ checker = PITChecker(dataset_kind="fundamental", as_of=datetime(2026, 7, 1, tzinfo=timezone.utc))
+
+ result = checker.check(PITTimestampSet(published_at=datetime(2026, 6, 1, tzinfo=timezone.utc)))
+
+ assert any(warning.code == "PIT_AVAILABLE_AT_MISSING" for warning in result.warnings)
+ assert result.pit_safe is False
+
+
+def test_available_at_after_as_of_records_future_data_violation() -> None:
+ as_of = datetime(2026, 7, 1, tzinfo=timezone.utc)
+ checker = PITChecker(dataset_kind="news", as_of=as_of)
+
+ result = checker.check(PITTimestampSet(available_at=as_of + timedelta(days=1)))
+
+ assert any(violation.code == "PIT_FUTURE_DATA" for violation in result.violations)
+ assert any(violation.hard_failure for violation in result.violations)
+ assert result.pit_safe is False
+
+
+def test_ohlcv_available_at_inferred_warning() -> None:
+ as_of = datetime(2026, 7, 2, tzinfo=timezone.utc)
+ checker = PITChecker(dataset_kind="ohlcv", as_of=as_of)
+
+ result = checker.check(PITTimestampSet(effective_at=datetime(2026, 7, 1, tzinfo=timezone.utc)))
+
+ assert any(warning.code == "PIT_AVAILABLE_AT_INFERRED" for warning in result.warnings)
+ assert result.pit_safe is True
+
+
+def test_missing_as_of_warns() -> None:
+ checker = PITChecker(dataset_kind="ohlcv")
+
+ result = checker.check(PITTimestampSet(available_at=datetime(2026, 7, 1, tzinfo=timezone.utc)))
+
+ assert any(warning.code == "PIT_MISSING_AS_OF" for warning in result.warnings)
+
diff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.py
index 2da6576d3..f67751214 100644
--- a/agent/tests/test_market_data_tool.py
+++ b/agent/tests/test_market_data_tool.py
@@ -3,8 +3,9 @@ from __future__ import annotations
import json
import pandas as pd
+import pytest
-from src.market_data import fetch_market_data_json
+from src.market_data import fetch_market_data, fetch_market_data_json
from src.swarm.models import SwarmAgentSpec
from src.swarm.presets import list_presets, load_preset
from src.swarm.worker import build_worker_prompt
@@ -26,7 +27,7 @@ def test_market_data_json_is_strict_when_loader_returns_nan():
df.index.name = "trade_date"
class _Loader:
- def fetch(self, codes, start, end, interval="1D"):
+ def fetch(self, codes, start, end, interval="1D", fields=None):
return {"X.US": df}
text = fetch_market_data_json(
@@ -42,6 +43,44 @@ def test_market_data_json_is_strict_when_loader_returns_nan():
assert payload["X.US"][0]["high"] is None
+def test_market_data_response_includes_optional_data_audit_metadata(
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+):
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ monkeypatch.setenv("VIBE_TRADING_ARTIFACT_ROOT", str(tmp_path / "artifacts"))
+ idx = pd.date_range("2026-01-01", periods=1, freq="D")
+ df = pd.DataFrame(
+ {
+ "open": [1.0],
+ "high": [1.2],
+ "low": [0.9],
+ "close": [1.1],
+ "volume": [100],
+ },
+ index=idx,
+ )
+
+ class _Loader:
+ name = "yahoo"
+
+ def fetch(self, codes, start, end, interval="1D", fields=None):
+ return {"X.US": df}
+
+ payload = fetch_market_data(
+ codes=["X.US"],
+ start_date="2026-01-01",
+ end_date="2026-01-02",
+ source="yahoo",
+ loader_resolver=lambda source: _Loader,
+ )
+
+ assert "X.US" in payload
+ metadata = payload["_metadata"]
+ assert metadata["data_audit_ids"][0].startswith("audit_")
+ assert metadata["artifact_refs"][0]["artifact_type"] == "data_audit"
+
+
def test_swarm_registry_can_expose_local_get_market_data_tool():
registry = build_swarm_registry(["get_market_data"])