"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(shadow-account): stop the result cache hiding rules and currencies (#2075)
cgycorey8084f29db3a4
diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.pyindex 3cc4af237..d191b0478 100644--- a/agent/src/shadow_account/backtester.py+++ b/agent/src/shadow_account/backtester.py@@ -305,11 +305,42 @@ def run_shadow_backtest(+_CACHE_EPOCH = 1+"""Bumped when the extractor or the generated engine changes meaning.++A cached run is derived from (profile inputs, engine semantics, journal,+window); when one of those changes, results produced before the change must+miss instead of being served as current.+"""+++def _run_inputs_digest(profile: ShadowProfile) -> str:+ """Stable digest of the profile inputs a cached result was produced from."""+ payload = json.dumps(+ {+ "source_market": profile.source_market,+ "preferred_markets": list(profile.preferred_markets),+ "rules": [rule.__dict__ for rule in profile.rules],+ },+ sort_keys=True,+ default=str,+ )+ return hashlib.sha1(payload.encode()).hexdigest()[:12]++def _cache_key(profile: ShadowProfile, window_start: str, window_end: str) -> str:- """Digest for the result cache: window plus the journal hash the profile- was extracted from, so a re-render with a different window or an edited- journal cannot silently reuse a stale run."""- raw = f"{window_start}|{window_end}|{profile.journal_hash}"+ """Digest for the result cache.++ Covers the window, the journal the profile was extracted from, the profile+ inputs (rules, markets) and the engine epoch, so neither a re-render with+ another window nor an edited journal, an edited rule or market selection,+ or a change in how rules are turned into an engine can silently reuse a+ stale run.+ """+ raw = (+ f"{_CACHE_EPOCH}|{window_start}|{window_end}|"+ f"{profile.journal_hash}|{_run_inputs_digest(profile)}"+ )return hashlib.sha1(raw.encode()).hexdigest()[:12]@@ -348,6 +379,7 @@ def load_cached_result(late_exit_pnl=float(attr.get("late_exit_pnl", 0.0)),overtrading_pnl=float(attr.get("overtrading_pnl", 0.0)),counterfactual_trades=tuple(attr.get("counterfactual_trades") or ()),+ excluded_currencies=dict(attr.get("excluded_currencies") or {}),),shadow_total_pnl=(None if data.get("shadow_total_pnl") is None else float(data["shadow_total_pnl"])),real_total_pnl=float(data.get("real_total_pnl", 0.0)),diff --git a/agent/tests/test_shadow_result_cache.py b/agent/tests/test_shadow_result_cache.pyindex c2dd694ec..fb60e556a 100644--- a/agent/tests/test_shadow_result_cache.py+++ b/agent/tests/test_shadow_result_cache.py@@ -8,6 +8,8 @@ hash; a different window deliberately misses.from __future__ import annotations+from dataclasses import replace+from src.shadow_account.backtester import _cache_key, _cache_result, load_cached_resultfrom src.shadow_account.models import (AttributionBreakdown,@@ -85,6 +87,65 @@ def test_cache_hits_only_on_exact_window_and_journal(tmp_path, monkeypatch) -> Nassert load_cached_result(other, window_start="2025-01-01", window_end="2026-01-01") is None+def test_cached_run_keeps_the_currency_disclosure(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ profile = _profile()+ from src.shadow_account.storage import runs_dir++ cached = _result()+ result = replace(+ cached,+ attribution=replace(cached.attribution, excluded_currencies={"HKD": 7}),+ )+ _cache_result(+ runs_dir(profile.shadow_id), result,+ profile=profile, window_start="2025-01-01", window_end="2026-01-01",+ )++ hit = load_cached_result(profile, window_start="2025-01-01", window_end="2026-01-01")+ assert hit is not None+ # The disclosure that HKD was left out must survive the cache, otherwise a+ # cached report silently reads as if every currency had been summed.+ assert hit.attribution.excluded_currencies == {"HKD": 7}+++def test_cache_key_changes_with_the_rules_not_only_the_journal() -> None:+ profile = _profile()+ base = _cache_key(profile, "2025-01-01", "2026-01-01")++ original = profile.rules[0]+ edited = ShadowRule(**{+ **original.__dict__,+ "entry_condition": {"market": "us", "prior_5d_return": {"min": -0.8, "max": -0.1}},+ })+ assert edited.entry_condition != original.entry_condition++ edited_profile = ShadowProfile(**{**profile.__dict__, "rules": (edited,)})+ # Same journal, same window, different rule: the cached run is stale.+ assert base != _cache_key(edited_profile, "2025-01-01", "2026-01-01")+++def test_cache_key_tracks_the_market_selection() -> None:+ profile = _profile()+ base = _cache_key(profile, "2025-01-01", "2026-01-01")+ # The selected markets decide which symbols are pooled into the run.+ wider = ShadowProfile(+ **{**profile.__dict__, "preferred_markets": ("us", "hk")}+ )+ assert base != _cache_key(wider, "2025-01-01", "2026-01-01")+++def test_cache_key_tracks_the_engine_epoch(monkeypatch) -> None:+ from src.shadow_account import backtester++ profile = _profile()+ base = _cache_key(profile, "2025-01-01", "2026-01-01")+ monkeypatch.setattr(backtester, "_CACHE_EPOCH", backtester._CACHE_EPOCH + 1)+ # A semantics change in the extractor or the generated engine cannot reuse+ # results produced by the previous one.+ assert base != _cache_key(profile, "2025-01-01", "2026-01-01")++def test_cache_key_changes_with_window_and_hash() -> None:profile = _profile()base = _cache_key(profile, "2025-01-01", "2026-01-01")