"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(sdm/ocr): cloud OCR strictly opt-in + duplicate-name guard + all-None metrics guard
Haozhe Wu75bcd0cf3e5d
diff --git a/agent/src/strategy_store/metrics.py b/agent/src/strategy_store/metrics.pyindex 59be0416c..462811f54 100644--- a/agent/src/strategy_store/metrics.py+++ b/agent/src/strategy_store/metrics.py@@ -9,6 +9,17 @@ from __future__ import annotationsfrom typing import Any+_DECAY_INPUT_KEYS = ("ic_ratio", "rolling_ir", "ic_positive_ratio", "rolling_sharpe")+++def has_decay_inputs(metrics: dict[str, float | None]) -> bool:+ """Return True if at least one evaluate_decay input metric is available.++ With all inputs ``None``, ``DecayEvaluator.evaluate_decay`` defaults to+ HEALTHY — callers should report ``insufficient_data`` instead.+ """+ return any(metrics.get(key) is not None for key in _DECAY_INPUT_KEYS)+def compute_decay_metrics(bench_history: list[Any],diff --git a/agent/src/strategy_store/sqlite_store.py b/agent/src/strategy_store/sqlite_store.pyindex 20c4615b0..8f17ead35 100644--- a/agent/src/strategy_store/sqlite_store.py+++ b/agent/src/strategy_store/sqlite_store.py@@ -307,42 +307,50 @@ class SqliteStrategyStore:artifact_id = artifact.id or _new_artifact_id()created_at = artifact.created_at or now- with self._write_transaction():- self._conn.execute(- """- INSERT INTO artifacts (- id, type, name, source_paper, source_url, formula_latex,- theme, columns_required, decay_horizon, signal_definition,- entry_rules, exit_rules, position_sizing, universe,- signal_engine_path, run_dir, hypothesis_id, status,- created_at, updated_at, disabled_at, disabled_reason- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- """,- (- artifact_id,- artifact.type.value,- artifact.name,- artifact.source_paper,- artifact.source_url,- artifact.formula_latex,- _json_dumps(list(artifact.theme)),- _json_dumps(list(artifact.columns_required)),- artifact.decay_horizon,- artifact.signal_definition,- artifact.entry_rules,- artifact.exit_rules,- artifact.position_sizing,- artifact.universe,- artifact.signal_engine_path,- artifact.run_dir,- artifact.hypothesis_id,- artifact.status.value,- created_at,- now,- artifact.disabled_at,- artifact.disabled_reason,- ),- )+ try:+ with self._write_transaction():+ self._conn.execute(+ """+ INSERT INTO artifacts (+ id, type, name, source_paper, source_url, formula_latex,+ theme, columns_required, decay_horizon, signal_definition,+ entry_rules, exit_rules, position_sizing, universe,+ signal_engine_path, run_dir, hypothesis_id, status,+ created_at, updated_at, disabled_at, disabled_reason+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ artifact_id,+ artifact.type.value,+ artifact.name,+ artifact.source_paper,+ artifact.source_url,+ artifact.formula_latex,+ _json_dumps(list(artifact.theme)),+ _json_dumps(list(artifact.columns_required)),+ artifact.decay_horizon,+ artifact.signal_definition,+ artifact.entry_rules,+ artifact.exit_rules,+ artifact.position_sizing,+ artifact.universe,+ artifact.signal_engine_path,+ artifact.run_dir,+ artifact.hypothesis_id,+ artifact.status.value,+ created_at,+ now,+ artifact.disabled_at,+ artifact.disabled_reason,+ ),+ )+ except sqlite3.IntegrityError as exc:+ if "artifacts.name" in str(exc):+ raise ValueError(+ f"artifact '{artifact.name}' already exists in "+ f"universe '{artifact.universe}'"+ ) from exc+ raisereturn artifact_id@_synchronizeddiff --git a/agent/src/strategy_store/store.py b/agent/src/strategy_store/store.pyindex fa72437f5..3dcce3d17 100644--- a/agent/src/strategy_store/store.py+++ b/agent/src/strategy_store/store.py@@ -162,6 +162,12 @@ class InMemoryStrategyStore:Returns:The assigned ``artifact_id``."""+ for existing in self._artifacts.values():+ if existing.name == artifact.name and existing.universe == artifact.universe:+ raise ValueError(+ f"artifact '{artifact.name}' already exists in "+ f"universe '{artifact.universe}'"+ )now = _now_iso()artifact_id = artifact.id or _new_artifact_id()stored = replace(diff --git a/agent/src/tools/ocr/engine.py b/agent/src/tools/ocr/engine.pyindex 373c347d6..ede9a9431 100644--- a/agent/src/tools/ocr/engine.py+++ b/agent/src/tools/ocr/engine.py@@ -46,10 +46,13 @@ def get_ocr_engine() -> OcrEngine | None:"""Return the configured OCR engine, or None if unavailable.Engine selection via VIBE_TRADING_OCR_ENGINE:- - "auto" (default): try rapid first, then qwen-vl+ - "auto" (default): local RapidOCR if installed, else no OCR- "rapid": RapidOCR only (local, ONNX)- "qwen-vl": Qwen-VL vision model (cloud, DashScope API)- "none": disable OCR entirely++ Cloud OCR is never auto-selected: document pages leave the machine, so+ "qwen-vl" must be an explicit user choice."""choice = _get_ocr_choice()if choice not in _VALID_ENGINES:@@ -59,23 +62,10 @@ def get_ocr_engine() -> OcrEngine | None:if choice == "none":return None- if choice == "rapid":- return _try_rapid()-if choice == "qwen-vl":return _try_qwen_vl()- engines_to_try = [(_try_rapid, "rapid"), (_try_qwen_vl, "qwen-vl")]- for factory, name in engines_to_try:- try:- engine = factory()- if engine is not None and engine.is_available():- logger.info("OCR engine selected: %s", name)- return engine- except Exception:- logger.debug("OCR engine '%s' not available", name, exc_info=True)-- return None+ return _try_rapid()def _try_rapid() -> OcrEngine | None:@@ -123,6 +113,7 @@ def get_ocr_install_hint(engine: OcrEngine | None) -> str:return ("No OCR engine available. Install one of:\n"" 1. Local OCR: pip install rapidocr_onnxruntime\n"- " 2. Cloud vision: export DASHSCOPE_API_KEY=your_key (uses Qwen-VL)\n"+ " 2. Cloud vision (pages are sent to DashScope): set "+ "VIBE_TRADING_OCR_ENGINE=qwen-vl and DASHSCOPE_API_KEY=your_key\n""Or set VIBE_TRADING_OCR_ENGINE=none to disable OCR.")diff --git a/agent/src/tools/sdm_decay_scan_tool.py b/agent/src/tools/sdm_decay_scan_tool.pyindex cf3409af6..abfd71500 100644--- a/agent/src/tools/sdm_decay_scan_tool.py+++ b/agent/src/tools/sdm_decay_scan_tool.py@@ -7,7 +7,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.strategy_store.decay import DecayEvaluator-from src.strategy_store.metrics import compute_decay_metrics+from src.strategy_store.metrics import compute_decay_metrics, has_decay_inputsfrom src.strategy_store.models import (ArtifactStatus,ArtifactType,@@ -111,6 +111,16 @@ class SdmDecayScanTool(BaseTool):metrics = compute_decay_metrics(bench_history)+ if not has_decay_inputs(metrics):+ counts["insufficient_data"] += 1+ per_artifact.append({+ "artifact_id": artifact.id,+ "name": artifact.name,+ "signal": "insufficient_data",+ "bench_count": len(bench_history),+ })+ continue+signal = evaluator.evaluate_decay(ic_ratio=metrics["ic_ratio"],ir=metrics["rolling_ir"],diff --git a/agent/src/tools/sdm_status_tool.py b/agent/src/tools/sdm_status_tool.pyindex 2ef1ed535..df64534bb 100644--- a/agent/src/tools/sdm_status_tool.py+++ b/agent/src/tools/sdm_status_tool.py@@ -8,7 +8,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.strategy_store.decay import DecayEvaluator-from src.strategy_store.metrics import compute_decay_metrics+from src.strategy_store.metrics import compute_decay_metrics, has_decay_inputsfrom src.strategy_store.models import (ArtifactStatus,ArtifactType,@@ -203,6 +203,15 @@ class SdmStatusTool(BaseTool):})metrics = compute_decay_metrics(bench_history)+ if not has_decay_inputs(metrics):+ return _ok({+ "artifact_id": artifact_id,+ "signal": "insufficient_data",+ "message": (+ f"{len(bench_history)} bench results but no evaluable "+ "metric (need ic_mean or sharpe values)"+ ),+ })evaluator = DecayEvaluator()signal = evaluator.evaluate_decay(diff --git a/agent/tests/test_ocr_engine.py b/agent/tests/test_ocr_engine.pynew file mode 100644index 000000000..38ddf0fb2--- /dev/null+++ b/agent/tests/test_ocr_engine.py@@ -0,0 +1,65 @@+"""Tests for the pluggable OCR engine factory.++Cloud OCR uploads document pages to a third party, so the qwen-vl engine+must only ever be reachable through an explicit VIBE_TRADING_OCR_ENGINE+choice — never via "auto" fallback.+"""++from __future__ import annotations++import pytest++from src.config.accessor import reset_env_config+from src.tools.ocr import engine as ocr_engine++[email protected](autouse=True)+def _reset_config():+ """Reset the cached EnvConfig around each test."""+ reset_env_config()+ yield+ reset_env_config()+++def test_auto_never_selects_cloud_engine(monkeypatch):+ """auto must not fall through to Qwen-VL even with DASHSCOPE_API_KEY set."""+ monkeypatch.setenv("DASHSCOPE_API_KEY", "sk-test-not-real")+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")+ reset_env_config()++ monkeypatch.setattr(+ ocr_engine, "_try_qwen_vl",+ lambda: pytest.fail("auto mode must never try the cloud engine"),+ )+ engine = ocr_engine.get_ocr_engine()+ assert engine is None or engine.name == "rapid"+++def test_explicit_qwen_vl_reaches_cloud_factory(monkeypatch):+ """qwen-vl is reachable, but only as an explicit choice."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "qwen-vl")+ reset_env_config()++ sentinel = object()+ monkeypatch.setattr(ocr_engine, "_try_qwen_vl", lambda: sentinel)+ assert ocr_engine.get_ocr_engine() is sentinel+++def test_none_disables_ocr(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "none")+ reset_env_config()+ assert ocr_engine.get_ocr_engine() is None+++def test_unknown_choice_falls_back_to_local_only(monkeypatch):+ """An unknown engine name degrades to auto, which stays local."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "bogus-engine")+ monkeypatch.setenv("DASHSCOPE_API_KEY", "sk-test-not-real")+ reset_env_config()++ monkeypatch.setattr(+ ocr_engine, "_try_qwen_vl",+ lambda: pytest.fail("fallback from unknown choice must stay local"),+ )+ engine = ocr_engine.get_ocr_engine()+ assert engine is None or engine.name == "rapid"diff --git a/agent/tests/test_strategy_store.py b/agent/tests/test_strategy_store.pyindex cf6c6b1b3..95c747a74 100644--- a/agent/tests/test_strategy_store.py+++ b/agent/tests/test_strategy_store.py@@ -172,6 +172,14 @@ class TestInMemoryStore:assert art.created_at != ""assert art.updated_at != ""+ def test_register_duplicate_name_universe_rejected(self):+ store = InMemoryStrategyStore()+ store.register_artifact(_make_artifact())+ with pytest.raises(ValueError, match="already exists"):+ store.register_artifact(_make_artifact())+ # Same name in a different universe is allowed+ store.register_artifact(_make_artifact(universe="SP500"))+def test_list_artifacts_empty(self):store = InMemoryStrategyStore()assert store.list_artifacts() == []@@ -501,6 +509,74 @@ class TestSdmTools:assert result["transitions_applied"] == 0assert result["summary"]["total_scanned"] == 1+ def test_register_tool_duplicate_rejected(self):+ """Registering the same (name, universe) twice returns an error."""+ from src.tools.sdm_register_tool import SdmRegisterTool++ first = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="dup_tool", universe="CSI300"+ )+ )+ assert first["status"] == "ok"+ second = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="dup_tool", universe="CSI300"+ )+ )+ assert second["status"] == "error"+ assert "already exists" in second["error"]++ def test_decay_scan_no_evaluable_metrics_insufficient(self):+ """3+ bench rows with all-None metrics report insufficient_data, not HEALTHY."""+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_decay_scan_tool import SdmDecayScanTool++ reg = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="metricless", universe="CSI300"+ )+ )+ aid = reg["artifact"]["id"]++ import src.strategy_store._shared as shared++ store = shared._store+ assert store is not None+ store.update_status(aid, ArtifactStatus.ACTIVE)+ for _ in range(5):+ store.record_bench(BenchResult(artifact_id=aid))++ result = json.loads(SdmDecayScanTool().execute(dry_run=True))+ assert result["status"] == "ok"+ assert result["summary"]["insufficient_data"] == 1+ assert result["summary"].get("healthy", 0) == 0++ def test_status_tool_decay_check_no_evaluable_metrics(self):+ """decay_check with all-None metrics reports insufficient_data."""+ from src.tools.sdm_register_tool import SdmRegisterTool+ from src.tools.sdm_status_tool import SdmStatusTool++ reg = json.loads(+ SdmRegisterTool().execute(+ artifact_type="factor", name="metricless2", universe="CSI300"+ )+ )+ aid = reg["artifact"]["id"]++ import src.strategy_store._shared as shared++ store = shared._store+ assert store is not None+ for _ in range(4):+ store.record_bench(BenchResult(artifact_id=aid))++ result = json.loads(+ SdmStatusTool().execute(action="decay_check", artifact_id=aid)+ )+ assert result["status"] == "ok"+ assert result["signal"] == "insufficient_data"+def test_decay_scan_tool_active_to_monitoring_transition(self):"""Non-dry-run scan transitions active → monitoring after 3+ warnings."""from src.tools.sdm_register_tool import SdmRegisterTool@@ -595,6 +671,16 @@ class TestSqliteStore:assert fetched.created_at != ""assert fetched.updated_at != ""+ def test_register_duplicate_name_universe_rejected(self):+ """UNIQUE(name, universe) surfaces as a friendly ValueError."""+ self.store.register_artifact(_make_artifact(name="dup_factor"))+ with pytest.raises(ValueError, match="already exists"):+ self.store.register_artifact(_make_artifact(name="dup_factor"))+ # Same name in a different universe is allowed+ self.store.register_artifact(+ _make_artifact(name="dup_factor", universe="SP500")+ )+def test_list_with_filters(self):"""List with type/status/universe filters."""self.store.register_artifact(