Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(loaders): let the health lane report why a source is empty

cgycorey712f861648b3
diff --git a/agent/backtest/loader_health.py b/agent/backtest/loader_health.py
index 15b2e3598..dedfccafe 100644
--- a/agent/backtest/loader_health.py
+++ b/agent/backtest/loader_health.py
@@ -2,6 +2,8 @@
Run ``python -m backtest.loader_health --output report.json`` from agent/.
Every non-healthy source fails the lane; connectivity is never a passing skip.
+A row also carries the loader's own warnings as ``evidence``, so an empty frame
+says whether the source refused this runner or the loader itself is broken.
"""
from __future__ import annotations
@@ -12,9 +14,11 @@ from contextlib import redirect_stderr, redirect_stdout
from datetime import date, datetime, timedelta, timezone
import importlib.util
import json
+import logging
import math
import os
from pathlib import Path
+import re
import subprocess
import sys
import tempfile
@@ -51,6 +55,61 @@ DEPENDENCIES = {
FRESHNESS_DAYS = 14
WINDOW_DAYS = 21
+#: A row carries at most this many loader warnings, each capped and sanitized.
+MAX_EVIDENCE = 3
+EVIDENCE_TEXT_LIMIT = 200
+
+_URL_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://\S+")
+_PATH_RE = re.compile(r"(?:[A-Za-z]:\\[^\s]+)|(?:\\\\[^\s]+)|(?:/[\w.@+.-]+)+/?")
+_CREDENTIAL_RE = re.compile(
+ r"\b[\w-]*(?:token|secret|password|passwd|api[-_]?key|private[-_]?key)[\w-]*\s*[=:]\s*\S+"
+ r"|\bbearer\s+\S+"
+ r"|\b(?:gh[pousr]_|github_pat_|sk-|xox[baprs]-)[\w-]{8,}",
+ re.IGNORECASE,
+)
+
+
+def sanitize_evidence(text: str) -> str | None:
+ """Redact URLs, paths and credential-shaped tokens from a loader warning.
+
+ Args:
+ text: A log message emitted by a loader.
+
+ Returns:
+ The message with URLs, filesystem paths (single-segment included) and
+ credential-shaped values replaced by placeholders and whitespace
+ collapsed, or ``None`` when the result still carries a URL or path
+ separator — an unclassifiable message is dropped rather than reported,
+ because this artifact is public.
+ """
+ cleaned = " ".join(_CREDENTIAL_RE.sub("<redacted>", _URL_RE.sub("<url>", text or "")).split())
+ cleaned = _PATH_RE.sub("<path>", cleaned)[:EVIDENCE_TEXT_LIMIT].strip()
+ if not cleaned or any(marker in cleaned for marker in ("://", "/", "\\")):
+ return None
+ return cleaned
+
+
+class _LoaderWarningCollector(logging.Handler):
+ """Collect a loader's own warnings so an empty frame can explain itself.
+
+ The child process suppresses the loader's log output (this lane exists to
+ separate a blocked source from a broken one, and both reach the report as
+ the same empty frame), so the reason is carried in the report instead.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(level=logging.WARNING)
+ self.messages: list[str] = []
+
+ def emit(self, record: logging.LogRecord) -> None:
+ if not (record.name == "backtest.loaders" or record.name.startswith("backtest.loaders.")):
+ return
+ if len(self.messages) >= MAX_EVIDENCE:
+ return
+ text = sanitize_evidence(record.getMessage())
+ if text and text not in self.messages:
+ self.messages.append(text)
+
def coverage_errors() -> list[str]:
"""Return catalog drift without probing network or credentials."""
@@ -128,26 +187,34 @@ def probe(source: str, today: date) -> dict:
return {"status": "invalid", "reason": "not_public_canary"}
symbol = CANARY_SYMBOLS[source]
result = {"status": "unavailable", "reason": "availability_probe_failed"}
- for attempt in range(1, 3):
- try:
- loader = cls()
- if not loader.is_available():
- result = {"status": "unavailable", "reason": "availability_probe_failed"}
- else:
- frames = loader.fetch(
- [symbol], (today - timedelta(days=WINDOW_DAYS)).isoformat(), today.isoformat(), interval="1D"
- )
- result = check_frame(frames.get(symbol) if isinstance(frames, dict) else None, today)
- except (ConnectionError, TimeoutError, requests.exceptions.ConnectionError, requests.exceptions.Timeout):
- result = {"status": "unreachable", "reason": "network_error"}
- except ImportError:
- result = {"status": "missing_dependency", "reason": "loader_import_failed"}
- except Exception:
- # Exception messages can contain URLs, local paths or credentials.
- result = {"status": "error", "reason": "fetch_failed"}
- result["attempts"] = attempt
- if result["status"] == "healthy":
- break
+ collector = _LoaderWarningCollector()
+ loaders_logger = logging.getLogger("backtest.loaders")
+ loaders_logger.addHandler(collector)
+ try:
+ for attempt in range(1, 3):
+ try:
+ loader = cls()
+ if not loader.is_available():
+ result = {"status": "unavailable", "reason": "availability_probe_failed"}
+ else:
+ frames = loader.fetch(
+ [symbol], (today - timedelta(days=WINDOW_DAYS)).isoformat(), today.isoformat(), interval="1D"
+ )
+ result = check_frame(frames.get(symbol) if isinstance(frames, dict) else None, today)
+ except (ConnectionError, TimeoutError, requests.exceptions.ConnectionError, requests.exceptions.Timeout):
+ result = {"status": "unreachable", "reason": "network_error"}
+ except ImportError:
+ result = {"status": "missing_dependency", "reason": "loader_import_failed"}
+ except Exception:
+ # Exception messages can contain URLs, local paths or credentials.
+ result = {"status": "error", "reason": "fetch_failed"}
+ result["attempts"] = attempt
+ if result["status"] == "healthy":
+ break
+ finally:
+ loaders_logger.removeHandler(collector)
+ if collector.messages and result["status"] != "healthy":
+ result["evidence"] = collector.messages
return result
diff --git a/agent/tests/test_loader_health.py b/agent/tests/test_loader_health.py
index 2664080a4..18f97befe 100644
--- a/agent/tests/test_loader_health.py
+++ b/agent/tests/test_loader_health.py
@@ -2,6 +2,7 @@
from datetime import date, timedelta
import json
+import logging
import subprocess
import pandas as pd
@@ -94,6 +95,7 @@ def test_network_error_is_sanitized_and_retried(monkeypatch):
def fetch(self, *args, **kwargs):
calls.append(args)
+ logging.getLogger("backtest.loaders.tencent_loader").warning("GET https://secret:[email protected] failed")
raise requests.exceptions.ConnectionError("https://secret:[email protected]")
monkeypatch.setitem(
@@ -111,6 +113,7 @@ def test_network_error_is_sanitized_and_retried(monkeypatch):
)
result = health.probe("tencent", TODAY)
assert result["status"] == "unreachable" and len(calls) == 2
+ assert result["evidence"] == ["GET <url> failed"]
assert "secret" not in json.dumps(result)
@@ -141,17 +144,24 @@ def test_lane_exit_and_report(monkeypatch, tmp_path, status, coverage, exit_code
monkeypatch.setattr(health.sys, "argv", ["health", "--output", str(output)])
monkeypatch.setattr(health, "CANARY_SYMBOLS", {"test": "TEST"})
monkeypatch.setattr(health, "coverage_errors", lambda: coverage)
- monkeypatch.setattr(health, "run_source", lambda *args: {"source": "test", "status": status})
+ monkeypatch.setattr(
+ health, "run_source", lambda *args: {"source": "test", "status": status, "evidence": ["a loader warning"]}
+ )
assert health.main() == exit_code
report = json.loads(output.read_text())
assert report["coverage_errors"] == coverage
- assert report["sources"] == [{"source": "test", "status": status}]
+ assert report["sources"] == [{"source": "test", "status": status, "evidence": ["a loader warning"]}]
@pytest.mark.parametrize(
"payload,status",
[
('{"status":"healthy","rows":2}', "healthy"),
+ ('{"status":"stale","reason":"last_bar_too_old"}', "stale"),
+ ('{"status":"unavailable","reason":"availability_probe_failed"}', "unavailable"),
+ ('{"status":"unreachable","reason":"network_error"}', "unreachable"),
+ ('{"status":"missing_dependency","reason":"install_canary_dependencies"}', "missing_dependency"),
+ ('{"status":"error","reason":"fetch_failed"}', "error"),
("not json", "error"),
("[]", "error"),
('{"status":"skip"}', "error"),
@@ -163,7 +173,7 @@ def test_child_report_handling(monkeypatch, payload, status):
def child(command, **kwargs):
if payload is not None:
- Path(command[-1]).write_text(payload)
+ Path(command[command.index("--output") + 1]).write_text(payload)
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(health.subprocess, "run", child)
@@ -197,3 +207,160 @@ def test_second_attempt_recovers_without_fallback(monkeypatch):
result = health.probe("tencent", TODAY)
assert result["status"] == "healthy" and result["attempts"] == 2
assert calls == [["601398.SH"], ["601398.SH"]]
+
+
+def _stub_loader(monkeypatch, source, *, fetch):
+ from backtest.loaders.registry import LOADER_REGISTRY
+
+ monkeypatch.setitem(
+ LOADER_REGISTRY,
+ source,
+ type("Loader", (), {"requires_auth": False, "is_available": lambda self: True, "fetch": fetch}),
+ )
+
+
+def test_empty_frame_carries_the_loaders_own_reason(monkeypatch):
+ """A blocked source must not report as a bare broken loader (#1621 item 2)."""
+
+ def fetch(self, codes, start, end, *, interval):
+ logging.getLogger("backtest.loaders.stooq_loader").warning(
+ "stooq is serving an anti-bot challenge page instead of CSV data; "
+ "treating it as unavailable for the rest of this process."
+ )
+ return {}
+
+ _stub_loader(monkeypatch, "stooq", fetch=fetch)
+ result = health.probe("stooq", TODAY)
+ assert result["status"] == "invalid" and result["reason"] == "empty_frame"
+ assert result["evidence"] == [
+ "stooq is serving an anti-bot challenge page instead of CSV data; "
+ "treating it as unavailable for the rest of this process."
+ ]
+
+
+def test_loader_evidence_is_sanitized(monkeypatch):
+ def fetch(self, codes, start, end, *, interval):
+ logging.getLogger("backtest.loaders.stooq_loader").warning(
+ "GET https://api.example.com/v3/klines failed for /home/runner/.cache/vibe "
+ "with api_key=abc123 from \\\\fileserver\\share"
+ )
+ return {}
+
+ _stub_loader(monkeypatch, "stooq", fetch=fetch)
+ result = health.probe("stooq", TODAY)
+ report = json.dumps(result)
+ assert result["evidence"] == ["GET <url> failed for <path> with <redacted> from <path>"]
+ assert "example.com" not in report and "abc123" not in report and "/home/" not in report
+
+
+def test_a_loader_that_logs_then_raises_still_reports_its_reason(monkeypatch):
+ """The generic handler path must keep the row (and the reason) alive."""
+
+ def fetch(self, codes, start, end, *, interval):
+ logging.getLogger("backtest.loaders.tencent_loader").warning("tencent returned an unparsable body")
+ raise ValueError("boom")
+
+ _stub_loader(monkeypatch, "tencent", fetch=fetch)
+ result = health.probe("tencent", TODAY)
+ assert result["status"] == "error" and result["reason"] == "fetch_failed" and result["attempts"] == 2
+ assert result["evidence"] == ["tencent returned an unparsable body"]
+
+
+def test_sanitizer_keeps_single_segment_paths_instead_of_dropping_the_message():
+ """ccxt, mootdx and tushare warn with a lone slash; dropping the line loses the cause."""
+ assert (
+ health.sanitize_evidence("CCXT failed for BTC-USDT: binance does not have market symbol BTC/USDT")
+ == "CCXT failed for BTC-USDT: binance does not have market symbol BTC<path>"
+ )
+ assert health.sanitize_evidence("cache file /tmp missing, refetching") == "cache file <path> missing, refetching"
+ assert health.sanitize_evidence("retry 2/3 failed") == "retry 2<path> failed"
+
+
+def test_sanitizer_redacts_header_and_token_shaped_credentials():
+ assert (
+ health.sanitize_evidence("request rejected, Authorization: Bearer ghp_abcdef123456")
+ == "request rejected, Authorization: <redacted>"
+ )
+ assert health.sanitize_evidence("x-api-key: abc123 rejected") == "<redacted> rejected"
+ assert health.sanitize_evidence("api_key=abc123 in query") == "<redacted> in query"
+ assert health.sanitize_evidence("token sk-abcdefghijklmnop rejected") == "token <redacted> rejected"
+
+
+def test_sanitizer_truncates_and_collapses_whitespace():
+ assert len(health.sanitize_evidence("x" * 500)) == health.EVIDENCE_TEXT_LIMIT
+ assert health.sanitize_evidence("two\n\tlines here ") == "two lines here"
+
+
+def test_sanitizer_drops_a_body_it_cannot_classify():
+ assert health.sanitize_evidence(r"retry via proxy \ gateway") is None
+ assert health.sanitize_evidence("fetch failed at http://") is None
+ assert health.sanitize_evidence(" ") is None
+
+
+def test_evidence_is_capped_and_deduplicated(monkeypatch):
+ def fetch(self, codes, start, end, *, interval):
+ logger = logging.getLogger("backtest.loaders.stooq_loader")
+ for index in range(5):
+ logger.warning("attempt %s failed", index)
+ logger.warning("attempt 0 failed")
+ return {}
+
+ _stub_loader(monkeypatch, "stooq", fetch=fetch)
+ evidence = health.probe("stooq", TODAY)["evidence"]
+ assert evidence == ["attempt 0 failed", "attempt 1 failed", "attempt 2 failed"]
+ assert len(evidence) == health.MAX_EVIDENCE
+
+
+def test_healthy_probe_carries_no_evidence_even_when_the_loader_warns(monkeypatch):
+ """A warning during a fetch that then succeeds is not a reason for the row."""
+
+ def fetch(self, codes, start, end, *, interval):
+ logging.getLogger("backtest.loaders.ccxt_loader").warning(
+ "Unknown CCXT exchange binance, falling back to binance"
+ )
+ return {codes[0]: frame()}
+
+ _stub_loader(monkeypatch, "stooq", fetch=fetch)
+ result = health.probe("stooq", TODAY)
+ assert result["status"] == "healthy" and result["attempts"] == 1
+ assert "evidence" not in result
+
+
+def test_another_loggers_warning_is_not_evidence(monkeypatch):
+ """Guards the attach point: only this package's loaders may become evidence.
+
+ A logger outside the `backtest.loaders` hierarchy bypasses the handler
+ entirely, so this also fails if the handler is ever moved to the root
+ logger without a working name filter.
+ """
+
+ def fetch(self, codes, start, end, *, interval):
+ logging.getLogger("urllib3.connectionpool").warning("Retrying after connection break")
+ return {}
+
+ _stub_loader(monkeypatch, "stooq", fetch=fetch)
+ assert "evidence" not in health.probe("stooq", TODAY)
+
+
+def test_evidence_survives_the_parent_report(monkeypatch):
+ """The parent copies the child's fields through, `evidence` included."""
+ from pathlib import Path
+
+ payload = (
+ '{"status":"invalid","reason":"empty_frame","attempts":2,'
+ '"evidence":["stooq is serving an anti-bot challenge page instead of CSV data"]}'
+ )
+
+ def child(command, **kwargs):
+ Path(command[command.index("--output") + 1]).write_text(payload)
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(health.subprocess, "run", child)
+ assert health.run_source("stooq", TODAY, 1) == {
+ "source": "stooq",
+ "symbol": "AAPL.US",
+ "status": "invalid",
+ "reason": "empty_frame",
+ "attempts": 2,
+ "evidence": ["stooq is serving an anti-bot challenge page instead of CSV data"],
+ }