Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loaders): make the stooq latch see every refusal, and probe once

cgycoreyf1b3f7e13db1
diff --git a/agent/backtest/loaders/stooq_loader.py b/agent/backtest/loaders/stooq_loader.py
index 801f80570..00ddfc25c 100644
--- a/agent/backtest/loaders/stooq_loader.py
+++ b/agent/backtest/loaders/stooq_loader.py
@@ -16,13 +16,19 @@ Symbol convention (Vibe-Trading -> Stooq):
Response body is CSV ``Date,Open,High,Low,Close,Volume``. An unknown symbol or
empty window yields the literal ``"N/D"`` or an empty body, both treated as
"no data" for that symbol (skipped, never fatal to the batch).
+
+A refusal is not CSV: the endpoint answers a blocked client with a proof-of-work
+challenge page, a plain-text quota message, or a bare 403/429. Those latch the
+source off for a cooldown instead of parsing as "no data" (see ``_denial_reason``).
"""
from __future__ import annotations
import io
import logging
-from typing import Dict, List, Optional
+import time
+from threading import Lock
+from typing import Any, Dict, List, Optional
import pandas as pd
@@ -38,20 +44,76 @@ HOST_KEY = "stooq"
_MIN_INTERVAL_ENV = "VIBE_TRADING_STOOQ_MIN_INTERVAL"
_DEFAULT_MIN_INTERVAL_S = 0.6
-# Stooq currently answers non-browser clients with a JavaScript proof-of-work
-# challenge page (HTTP 200, HTML body) instead of CSV. Without detection the
-# loader parses it as "no data" and the fallback chain slides past a source
-# that never serves, with nothing in the run log to show for it. The flag is
-# the process-wide latch behind that warning: once the challenge is seen, no
-# further symbol is probed, because a second request can only be answered the
-# same way.
-_challenge_warned = False
+# Stooq refuses non-browser clients in more than one way: a JavaScript
+# proof-of-work challenge page (HTTP 200, HTML body), the plain-text quota
+# refusal its free CSV endpoint serves once the per-IP limit trips, or a bare
+# 403/429. Without detection the loader parses the body as "no data" and the
+# fallback chain slides past a source that never serves, with nothing in the run
+# log to show for it. This deadline is the process-wide latch behind that
+# warning: while it lies in the future no further symbol is probed, because a
+# second request can only be answered the same way. It expires rather than
+# latching for the process lifetime, so one transient block does not downgrade
+# stooq for as long as ``vibe-trading serve`` happens to run.
+_challenge_until = 0.0
+# How long a latched process waits before it probes Stooq again.
+_LATCH_COOLDOWN_S = 300.0
+# Serialize each process-local probe with the latch check. Otherwise callers
+# already waiting in the shared HTTP throttle can send after another caller
+# discovers that Stooq is refusing requests.
+_probe_lock = Lock()
+
+# Refusals that arrive without an error status. Matched against the head of the
+# body only, so a CSV row can never trip them.
+_DENIAL_STATUS_CODES = frozenset({403, 429})
+_DENIAL_TEXT_MARKERS = (
+ "exceeded the daily hits limit",
+ "daily hits limit",
+ "too many requests",
+)
def _looks_like_challenge_page(body: str) -> bool:
text = (body or "").lstrip().lower()
return text.startswith("<") or "challenge" in text[:2000] or "proof of work" in text[:2000]
+
+def _denial_reason(response: Any) -> Optional[str]:
+ """Return a short reason when the response is a refusal, else ``None``.
+
+ Args:
+ response: The HTTP response from Stooq's CSV endpoint.
+
+ Returns:
+ A human-readable cause when the source is refusing this client -- a
+ 403/429 status, the proof-of-work challenge page, or the plain-text
+ quota message -- otherwise ``None`` for a response worth parsing. An
+ ordinary "no data" body (``N/D``, empty) is not a refusal.
+ """
+ if response.status_code in _DENIAL_STATUS_CODES:
+ return f"HTTP {response.status_code}"
+ body = response.text or ""
+ if _looks_like_challenge_page(body):
+ return "anti-bot challenge page"
+ head = body.lstrip().lower()[:2000]
+ for marker in _DENIAL_TEXT_MARKERS:
+ if marker in head:
+ return f"refusal text {marker!r}"
+ return None
+
+
+def _latch(reason: str) -> None:
+ """Stop probing for the cooldown and tell the operator why."""
+ global _challenge_until
+ _challenge_until = time.monotonic() + _LATCH_COOLDOWN_S
+ logger.warning(
+ "stooq is unavailable to this process (%s); skipping it for %g seconds. "
+ "Move stooq to the end of the chain via MARKET_DATA_ORDER_* (e.g. "
+ "MARKET_DATA_ORDER_US_EQUITY); the override must be a permutation of the "
+ "default chain, so a source can be reordered but not removed.",
+ reason,
+ _LATCH_COOLDOWN_S,
+ )
+
# Stooq's CSV header columns mapped to our output field names.
_COLUMN_MAP = {
"Open": "open",
@@ -163,39 +225,35 @@ class DataLoader:
self, code: str, start_date: str, end_date: str,
) -> Optional[pd.DataFrame]:
"""Fetch and parse one symbol's CSV; ``None`` when Stooq has no data."""
- global _challenge_warned
- if _challenge_warned:
- # Latched earlier in this process: the warning already told the
- # operator the source is unavailable, so spending a throttled
- # request per remaining symbol (0.6s apart) only delays the chain's
- # move to the next source. A new process re-probes.
- return None
- params = {
- "s": map_symbol(code),
- "d1": _compact_date(start_date),
- "d2": _compact_date(end_date),
- "i": "d",
- }
- response = throttled_get(
- _BASE_URL,
- host_key=HOST_KEY,
- min_interval=_min_interval(),
- params=params,
- )
- response.raise_for_status()
- if _looks_like_challenge_page(response.text):
- if not _challenge_warned:
- logger.warning(
- "stooq is serving an anti-bot challenge page instead of CSV "
- "data; treating it as unavailable for the rest of this "
- "process. Move stooq to the end of the chain via "
- "MARKET_DATA_ORDER_* (e.g. MARKET_DATA_ORDER_US_EQUITY); the "
- "override must be a permutation of the default chain, so a "
- "source can be reordered but not removed."
- )
- _challenge_warned = True
- return None
- return _parse_csv(response.text)
+ with _probe_lock:
+ if _challenge_until > time.monotonic():
+ # Latched by an earlier probe: the warning already told the
+ # operator the source is unavailable, and a second request can
+ # only be answered the same way. Probing resumes once the
+ # cooldown expires.
+ return None
+ params = {
+ "s": map_symbol(code),
+ "d1": _compact_date(start_date),
+ "d2": _compact_date(end_date),
+ "i": "d",
+ }
+ response = throttled_get(
+ _BASE_URL,
+ host_key=HOST_KEY,
+ min_interval=_min_interval(),
+ params=params,
+ )
+ # Check for a refusal before ``raise_for_status()``: a 403/429 is the
+ # source blocking this client, not one symbol failing, and letting it
+ # raise would spend one throttled request on every remaining symbol.
+ reason = _denial_reason(response)
+ if reason is not None:
+ _latch(reason)
+ return None
+ response.raise_for_status()
+ body = response.text
+ return _parse_csv(body)
def _parse_csv(body: str) -> Optional[pd.DataFrame]:
diff --git a/agent/tests/test_stooq_loader.py b/agent/tests/test_stooq_loader.py
index 497aa5db0..292235938 100644
--- a/agent/tests/test_stooq_loader.py
+++ b/agent/tests/test_stooq_loader.py
@@ -8,6 +8,9 @@ we monkeypatch that name on the ``stooq_loader`` module.
from __future__ import annotations
import logging
+import time
+from concurrent.futures import ThreadPoolExecutor
+from threading import Event, Lock
from typing import Any, Dict, List
import pandas as pd
@@ -191,7 +194,7 @@ class TestChallengePageDetection:
)
def test_challenge_page_yields_no_data_and_warns_once(self, monkeypatch, caplog):
- monkeypatch.setattr(stooq_loader, "_challenge_warned", False)
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
monkeypatch.setattr(
stooq_loader,
"throttled_get",
@@ -215,7 +218,7 @@ class TestChallengePageDetection:
probe still spent one throttled request per missing symbol on an
endpoint that can only answer with the challenge page.
"""
- monkeypatch.setattr(stooq_loader, "_challenge_warned", False)
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
probed: List[str] = []
def fake_get(url, **kwargs):
@@ -239,8 +242,62 @@ class TestChallengePageDetection:
assert loader.fetch(["AMZN.US"], "2024-01-01", "2024-01-31") == {}
assert probed == ["aapl.us"]
+ def test_challenge_latch_stops_concurrent_loader_instances(self, monkeypatch):
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
+ first_probe_started = Event()
+ second_probe_attempted = Event()
+ release_first_probe = Event()
+ probed: List[str] = []
+ probe_lock = getattr(stooq_loader, "_probe_lock", Lock())
+
+ class ObservedLock:
+ def __enter__(self):
+ # Observe the contender before it blocks on the real lock.
+ # This lets the first response wait for both callers without
+ # sleeps or requiring the second caller to send a request.
+ if first_probe_started.is_set():
+ second_probe_attempted.set()
+ probe_lock.acquire()
+
+ def __exit__(self, *args):
+ probe_lock.release()
+
+ monkeypatch.setattr(stooq_loader, "_probe_lock", ObservedLock(), raising=False)
+
+ def fake_get(url, **kwargs):
+ symbol = kwargs["params"]["s"]
+ probed.append(symbol)
+ if symbol == "aapl.us":
+ first_probe_started.set()
+ if not release_first_probe.wait(5):
+ raise RuntimeError("first probe was not released")
+ else:
+ # The unsynchronized implementation reaches HTTP instead of
+ # waiting at the gate, reproducing the extra request.
+ second_probe_attempted.set()
+ return _FakeResponse(text=self._CHALLENGE_HTML)
+
+ monkeypatch.setattr(stooq_loader, "throttled_get", fake_get)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ first = pool.submit(
+ stooq_loader.DataLoader().fetch, ["AAPL.US"], "2024-01-01", "2024-01-31",
+ )
+ try:
+ assert first_probe_started.wait(5)
+ second = pool.submit(
+ stooq_loader.DataLoader().fetch, ["MSFT.US"], "2024-01-01", "2024-01-31",
+ )
+ assert second_probe_attempted.wait(5)
+ finally:
+ release_first_probe.set()
+ assert first.result(timeout=5) == {}
+ assert second.result(timeout=5) == {}
+
+ assert stooq_loader._challenge_until > time.monotonic()
+ assert probed == ["aapl.us"]
+
def test_challenge_page_does_not_reach_csv_parser(self, monkeypatch):
- monkeypatch.setattr(stooq_loader, "_challenge_warned", True) # latch already set
+ monkeypatch.setattr(stooq_loader, "_challenge_until", time.monotonic() + 60) # latched
monkeypatch.setattr(
stooq_loader,
"throttled_get",
@@ -269,7 +326,7 @@ class TestChallengeWarningNamesRealOverride:
)
def _warning(self, monkeypatch, caplog) -> str:
- monkeypatch.setattr(stooq_loader, "_challenge_warned", False)
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
monkeypatch.setattr(
stooq_loader,
"throttled_get",
@@ -311,3 +368,101 @@ class TestChallengeWarningNamesRealOverride:
assert "drop stooq" not in message.lower(), (
f"advice is rejected by is_valid_source_order: {message!r}"
)
+
+
+# ---------------------------------------------------------------------------
+# Every refusal shape latches (#1648)
+# ---------------------------------------------------------------------------
+
+
+class TestEveryRefusalShapeLatches:
+ """One probe must be enough, whatever shape the refusal arrives in.
+
+ The latch used to see only the proof-of-work page: a 403/429 was raised out
+ of ``raise_for_status()`` before the body was inspected, and the plain-text
+ quota message parsed as "no data". Both then cost one throttled request per
+ remaining symbol, and the plain-text shape cost them with no log line at
+ all -- the exact behaviour the latch exists to prevent.
+ """
+
+ _QUOTA_TEXT = "Exceeded the daily hits limit"
+
+ @pytest.mark.parametrize(
+ ("label", "status_code", "text"),
+ [
+ ("429 status", 429, ""),
+ ("403 status", 403, ""),
+ ("200 with quota text", 200, _QUOTA_TEXT),
+ ],
+ )
+ def test_refusal_latches_so_one_request_covers_the_batch(
+ self, monkeypatch, caplog, label, status_code, text,
+ ):
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
+ probed: List[str] = []
+
+ def fake_get(url, **kwargs):
+ probed.append(kwargs["params"]["s"])
+ return _FakeResponse(status_code=status_code, text=text)
+
+ monkeypatch.setattr(stooq_loader, "throttled_get", fake_get)
+ loader = stooq_loader.DataLoader()
+
+ with caplog.at_level(logging.WARNING, logger="backtest.loaders.stooq_loader"):
+ assert loader.fetch(["AAPL.US", "MSFT.US", "NVDA.US"], "2024-01-01", "2024-01-31") == {}
+ # A later batch in the same process costs nothing either.
+ assert loader.fetch(["AMZN.US"], "2024-01-01", "2024-01-31") == {}
+
+ assert probed == ["aapl.us"], f"{label}: spent {len(probed)} requests"
+ # The latch must be a finite future deadline, not a permanent one: an
+ # infinite cooldown would never re-probe (the old behaviour).
+ now = time.monotonic()
+ assert now < stooq_loader._challenge_until <= now + stooq_loader._LATCH_COOLDOWN_S
+ assert any("stooq is unavailable to this process" in r.message for r in caplog.records)
+
+ def test_refusal_warning_names_the_cause(self, monkeypatch, caplog):
+ """A 429 must not report itself as an anti-bot challenge page."""
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
+ monkeypatch.setattr(
+ stooq_loader,
+ "throttled_get",
+ lambda url, **kw: _FakeResponse(status_code=429, text=""),
+ )
+
+ with caplog.at_level(logging.WARNING, logger="backtest.loaders.stooq_loader"):
+ stooq_loader.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")
+
+ warnings = [r.message for r in caplog.records if "stooq is unavailable" in r.message]
+ assert len(warnings) == 1
+ assert "429" in warnings[0]
+
+ def test_expired_cooldown_probes_again(self, monkeypatch):
+ """A deadline in the past must re-probe, or the latch is permanent."""
+ monkeypatch.setattr(stooq_loader, "_challenge_until", time.monotonic() - 1)
+ probed: List[str] = []
+
+ def fake_get(url, **kwargs):
+ probed.append(kwargs["params"]["s"])
+ return _FakeResponse(text=_CSV)
+
+ monkeypatch.setattr(stooq_loader, "throttled_get", fake_get)
+ out = stooq_loader.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")
+
+ assert probed == ["aapl.us"]
+ assert list(out) == ["AAPL.US"]
+
+ def test_no_data_response_does_not_latch(self, monkeypatch):
+ """``N/D`` means "unknown symbol", not "this client is blocked"."""
+ monkeypatch.setattr(stooq_loader, "_challenge_until", 0.0)
+ probed: List[str] = []
+
+ def fake_get(url, **kwargs):
+ probed.append(kwargs["params"]["s"])
+ return _FakeResponse(text="N/D\n")
+
+ monkeypatch.setattr(stooq_loader, "throttled_get", fake_get)
+ out = stooq_loader.DataLoader().fetch(["AAPL.US", "MSFT.US"], "2024-01-01", "2024-01-31")
+
+ assert out == {}
+ assert probed == ["aapl.us", "msft.us"]
+ assert stooq_loader._challenge_until == 0.0