From dec920f358c65b8764fb5d492f69ad3e8e0f6891 Mon Sep 17 00:00:00 2001 From: ZhuLinsen Date: Sun, 22 Nov 2026 15:49:38 +0800 Subject: [PATCH] fix(rsi): harden factor sandbox, governance split, RSI engine, council/crossover, and arena OOS (Rounds 7-11) --- src/alphaevo/alpha_factory/factor_store.py | 257 +- src/alphaevo/alpha_factory/factory.py | 170 +- src/alphaevo/alpha_factory/governance.py | 217 +- src/alphaevo/alpha_factory/sandbox.py | 819 +++++- src/alphaevo/arena/runner.py | 427 +-- src/alphaevo/reflection/experience.py | 55 +- src/alphaevo/reflection/mutator.py | 138 +- src/alphaevo/rsi/co_steer.py | 195 +- src/alphaevo/rsi/council.py | 78 +- src/alphaevo/rsi/crossover.py | 98 +- src/alphaevo/rsi/engine.py | 428 ++- src/alphaevo/rsi/mechanism.py | 237 +- src/alphaevo/strategy/store.py | 62 +- ..._sandbox_governance_rsi_arena_integrity.py | 2412 +++++++++++++++++ tests/unit/test_sandbox.py | 23 +- 15 files changed, 4919 insertions(+), 697 deletions(-) create mode 100644 tests/unit/test_round7_to_11_sandbox_governance_rsi_arena_integrity.py diff --git a/src/alphaevo/alpha_factory/factor_store.py b/src/alphaevo/alpha_factory/factor_store.py index 98683f4..4b165e4 100644 --- a/src/alphaevo/alpha_factory/factor_store.py +++ b/src/alphaevo/alpha_factory/factor_store.py @@ -8,6 +8,7 @@ import logging import sqlite3 +import threading from datetime import datetime, timezone from pathlib import Path from typing import Literal, cast @@ -71,72 +72,122 @@ class FactorStore: def __init__(self, db_path: str | Path = ":memory:") -> None: self._db_path = _normalize_db_path(db_path) + self._lock = threading.RLock() self._conn: sqlite3.Connection | None = None self._ensure_table() def _get_conn(self) -> sqlite3.Connection: - if self._conn is None: - self._conn = sqlite3.connect(self._db_path) - self._conn.row_factory = sqlite3.Row - return self._conn + with self._lock: + if self._conn is None: + self._conn = sqlite3.connect(self._db_path, timeout=30.0, check_same_thread=False) + self._conn.row_factory = sqlite3.Row + self._conn.execute("PRAGMA busy_timeout=5000") + if self._db_path != ":memory:": + self._conn.execute("PRAGMA journal_mode=WAL") + return self._conn def _ensure_table(self) -> None: - conn = self._get_conn() - conn.executescript(_FACTOR_SCHEMA) - conn.commit() + with self._lock: + conn = self._get_conn() + conn.executescript(_FACTOR_SCHEMA) + conn.commit() def save(self, record: FactorRecord) -> None: """Insert or update a factor record.""" - conn = self._get_conn() - now = datetime.now(timezone.utc).isoformat() - conn.execute( - """ - INSERT INTO factors ( - name, description, rationale, code, expected_direction, - ic_mean, ic_std, ir, monthly_win_rate, turnover, - status, usage_count, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(name) DO UPDATE SET - description = excluded.description, - rationale = excluded.rationale, - code = excluded.code, - expected_direction = excluded.expected_direction, - ic_mean = excluded.ic_mean, - ic_std = excluded.ic_std, - ir = excluded.ir, - monthly_win_rate = excluded.monthly_win_rate, - turnover = excluded.turnover, - status = excluded.status, - usage_count = excluded.usage_count, - updated_at = ? - """, - ( - record.name, - record.description, - record.rationale, - record.code, - record.expected_direction, - record.ic_mean, - record.ic_std, - record.ir, - record.monthly_win_rate, - record.turnover, - record.status, - record.usage_count, - record.created_at.isoformat(), - now, - now, # updated_at in ON CONFLICT - ), - ) - conn.commit() + with self._lock: + conn = self._get_conn() + now = datetime.now(timezone.utc).isoformat() + conn.execute( + """ + INSERT INTO factors ( + name, description, rationale, code, expected_direction, + ic_mean, ic_std, ir, monthly_win_rate, turnover, + status, usage_count, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(name) DO UPDATE SET + description = excluded.description, + rationale = excluded.rationale, + code = excluded.code, + expected_direction = excluded.expected_direction, + ic_mean = excluded.ic_mean, + ic_std = excluded.ic_std, + ir = excluded.ir, + monthly_win_rate = excluded.monthly_win_rate, + turnover = excluded.turnover, + status = excluded.status, + usage_count = excluded.usage_count, + updated_at = ? + """, + ( + record.name, + record.description, + record.rationale, + record.code, + record.expected_direction, + record.ic_mean, + record.ic_std, + record.ir, + record.monthly_win_rate, + record.turnover, + record.status, + record.usage_count, + record.created_at.isoformat(), + now, + now, # updated_at in ON CONFLICT + ), + ) + conn.commit() + + def save_if_absent(self, record: FactorRecord) -> tuple[FactorRecord, bool]: + """Atomically insert ``record`` only if ``name`` does not already exist. + + Returns ``(stored_record, inserted)`` so concurrent writers cannot + silently overwrite or reactivate an existing/retired factor. + """ + with self._lock: + conn = self._get_conn() + now = datetime.now(timezone.utc).isoformat() + cursor = conn.execute( + """ + INSERT INTO factors ( + name, description, rationale, code, expected_direction, + ic_mean, ic_std, ir, monthly_win_rate, turnover, + status, usage_count, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(name) DO NOTHING + """, + ( + record.name, + record.description, + record.rationale, + record.code, + record.expected_direction, + record.ic_mean, + record.ic_std, + record.ir, + record.monthly_win_rate, + record.turnover, + record.status, + record.usage_count, + record.created_at.isoformat(), + now, + ), + ) + conn.commit() + inserted = cursor.rowcount == 1 + row = conn.execute("SELECT * FROM factors WHERE name = ?", (record.name,)).fetchone() + if row is None: + return record, inserted + return self._row_to_record(row), inserted def get(self, name: str) -> FactorRecord | None: """Retrieve a factor by name.""" - conn = self._get_conn() - row = conn.execute("SELECT * FROM factors WHERE name = ?", (name,)).fetchone() - if row is None: - return None - return self._row_to_record(row) + with self._lock: + conn = self._get_conn() + row = conn.execute("SELECT * FROM factors WHERE name = ?", (name,)).fetchone() + if row is None: + return None + return self._row_to_record(row) def list_all( self, @@ -144,15 +195,16 @@ def list_all( status: str | None = None, ) -> list[FactorRecord]: """List all factors, optionally filtered by status.""" - conn = self._get_conn() - if status: - rows = conn.execute( - "SELECT * FROM factors WHERE status = ? ORDER BY ir DESC", - (status,), - ).fetchall() - else: - rows = conn.execute("SELECT * FROM factors ORDER BY ir DESC").fetchall() - return [self._row_to_record(r) for r in rows] + with self._lock: + conn = self._get_conn() + if status: + rows = conn.execute( + "SELECT * FROM factors WHERE status = ? ORDER BY ir DESC", + (status,), + ).fetchall() + else: + rows = conn.execute("SELECT * FROM factors ORDER BY ir DESC").fetchall() + return [self._row_to_record(r) for r in rows] def top_factors( self, @@ -161,53 +213,66 @@ def top_factors( status: str = "active", ) -> list[FactorRecord]: """Get top factors ranked by IR.""" - conn = self._get_conn() - rows = conn.execute( - "SELECT * FROM factors WHERE status = ? ORDER BY ir DESC LIMIT ?", - (status, limit), - ).fetchall() - return [self._row_to_record(r) for r in rows] + with self._lock: + conn = self._get_conn() + rows = conn.execute( + "SELECT * FROM factors WHERE status = ? ORDER BY ir DESC LIMIT ?", + (status, limit), + ).fetchall() + return [self._row_to_record(r) for r in rows] def increment_usage(self, name: str) -> None: """Increment usage count for a factor.""" - conn = self._get_conn() - conn.execute( - "UPDATE factors SET usage_count = usage_count + 1, updated_at = ? WHERE name = ?", - (datetime.now(timezone.utc).isoformat(), name), - ) - conn.commit() + with self._lock: + conn = self._get_conn() + conn.execute( + "UPDATE factors SET usage_count = usage_count + 1, updated_at = ? WHERE name = ?", + (datetime.now(timezone.utc).isoformat(), name), + ) + conn.commit() def retire(self, name: str) -> None: """Mark a factor as retired.""" - conn = self._get_conn() - conn.execute( - "UPDATE factors SET status = 'retired', updated_at = ? WHERE name = ?", - (datetime.now(timezone.utc).isoformat(), name), - ) - conn.commit() + with self._lock: + conn = self._get_conn() + conn.execute( + "UPDATE factors SET status = 'retired', updated_at = ? WHERE name = ?", + (datetime.now(timezone.utc).isoformat(), name), + ) + conn.commit() def delete(self, name: str) -> bool: """Delete a factor. Returns True if it existed.""" - conn = self._get_conn() - cursor = conn.execute("DELETE FROM factors WHERE name = ?", (name,)) - conn.commit() - return cursor.rowcount > 0 + with self._lock: + conn = self._get_conn() + cursor = conn.execute("DELETE FROM factors WHERE name = ?", (name,)) + conn.commit() + return cursor.rowcount > 0 def count(self, *, status: str | None = None) -> int: """Count factors, optionally by status.""" - conn = self._get_conn() - if status: - row = conn.execute( - "SELECT COUNT(*) FROM factors WHERE status = ?", (status,) - ).fetchone() - else: - row = conn.execute("SELECT COUNT(*) FROM factors").fetchone() - return cast("int", row[0]) + with self._lock: + conn = self._get_conn() + if status: + row = conn.execute( + "SELECT COUNT(*) FROM factors WHERE status = ?", (status,) + ).fetchone() + else: + row = conn.execute("SELECT COUNT(*) FROM factors").fetchone() + return cast("int", row[0]) def close(self) -> None: - if self._conn: - self._conn.close() - self._conn = None + """Close the backing SQLite connection if open.""" + with self._lock: + if self._conn: + self._conn.close() + self._conn = None + + def __enter__(self) -> FactorStore: + return self + + def __exit__(self, *args: object) -> None: + self.close() @staticmethod def _row_to_record(row: sqlite3.Row) -> FactorRecord: diff --git a/src/alphaevo/alpha_factory/factory.py b/src/alphaevo/alpha_factory/factory.py index d624fb3..09b101a 100644 --- a/src/alphaevo/alpha_factory/factory.py +++ b/src/alphaevo/alpha_factory/factory.py @@ -14,13 +14,17 @@ from __future__ import annotations +import hashlib import logging +import threading +from collections import OrderedDict from typing import TYPE_CHECKING, Any, cast +import numpy as np import pandas as pd from alphaevo.alpha_factory.factor_store import FactorRecord, FactorStore -from alphaevo.alpha_factory.sandbox import FactorSandbox, build_restricted_namespace +from alphaevo.alpha_factory.sandbox import FactorSandbox from alphaevo.alpha_factory.synthesizer import FactorHypothesis, FactorSynthesizer from alphaevo.alpha_factory.validator import FactorValidator, ValidationThresholds from alphaevo.backtest.indicators import IndicatorFn, IndicatorRegistry @@ -34,12 +38,99 @@ logger = logging.getLogger(__name__) +_INDICATOR_CACHE_MAX_ENTRIES = 8 + + +def _object_type_digest(values: list[Any]) -> bytes: + """Hash per-element Python type identity for object-dtype columns/indexes.""" + hasher = hashlib.blake2b(digest_size=16) + for val in values: + cls = type(val) + hasher.update(f"{cls.__module__}.{cls.__qualname__}\x00".encode()) + return hasher.digest() + + +def _df_cache_key(df: pd.DataFrame) -> tuple[Any, ...] | None: + """Build a dtype-, category-, object-type-, column-, index-, and order-sensitive cache key.""" + try: + col_dtypes = tuple(str(dt) for dt in df.dtypes) + idx_dtype = str(df.index.dtype) + col_cats = tuple( + ( + col, + str(df[col].cat.categories.dtype), + tuple(df[col].cat.categories.tolist()), + bool(df[col].cat.ordered), + ) + for col in df.columns + if isinstance(df[col].dtype, pd.CategoricalDtype) + ) + idx_cats = ( + ( + str(cast("Any", df.index).categories.dtype), + tuple(cast("Any", df.index).categories.tolist()), + bool(cast("Any", df.index).ordered), + ) + if isinstance(df.index.dtype, pd.CategoricalDtype) + else () + ) + obj_col_sigs = tuple( + (col, _object_type_digest(df[col].tolist())) + for col in df.columns + if df[col].dtype == object + ) + if isinstance(df.index, pd.MultiIndex): + obj_idx_sig: tuple[Any, ...] = tuple( + ( + str(df.index.get_level_values(i).dtype), + ( + _object_type_digest(df.index.get_level_values(i).tolist()) + if df.index.get_level_values(i).dtype == object + else b"" + ), + ) + for i in range(df.index.nlevels) + ) + elif df.index.dtype == object: + obj_idx_sig = (_object_type_digest(df.index.tolist()),) + else: + obj_idx_sig = () + if df.empty: + return ( + tuple(df.columns), + col_dtypes, + idx_dtype, + col_cats, + idx_cats, + obj_col_sigs, + obj_idx_sig, + (0, 0), + b"", + ) + hashed = pd.util.hash_pandas_object(df, index=True) + digest = hashlib.blake2b( + hashed.to_numpy(dtype=np.uint64).tobytes(), digest_size=16 + ).digest() + return ( + tuple(df.columns), + col_dtypes, + idx_dtype, + col_cats, + idx_cats, + obj_col_sigs, + obj_idx_sig, + df.shape, + digest, + ) + except Exception: + return None + def _build_indicator_fn( factor_code: str, sandbox: FactorSandbox, ) -> Callable[[pd.DataFrame, int, IndicatorContext | None], float | bool]: - """Create an indicator function from validated factor code.""" + """Create an isolated worker-backed indicator function from validated factor code.""" def _zero_indicator( df: pd.DataFrame, @@ -49,20 +140,12 @@ def _zero_indicator( del df, idx, ctx return 0.0 - is_safe, _ = sandbox.validate_code(factor_code) + is_safe, _ = sandbox.preflight_code(factor_code) if not is_safe: return _zero_indicator - namespace = build_restricted_namespace() - try: - exec(factor_code, namespace) # noqa: S102 - except Exception: - return _zero_indicator - - compute_fn = namespace.get("compute") - if compute_fn is None: - return _zero_indicator - compute = cast("Callable[[pd.DataFrame, int], Any]", compute_fn) + series_cache: OrderedDict[tuple[Any, ...], list[float]] = OrderedDict() + cache_lock = threading.Lock() def indicator_fn( df: pd.DataFrame, @@ -70,15 +153,41 @@ def indicator_fn( ctx: IndicatorContext | None = None, ) -> float | bool: del ctx - try: - pit_df = df.iloc[: idx + 1] - val = float(compute(pit_df, idx)) - import numpy as np + if idx < 0 or idx >= len(df): + return 0.0 - return val if np.isfinite(val) else 0.0 - except Exception: + cache_key = _df_cache_key(df) + if cache_key is not None: + with cache_lock: + cached_values = series_cache.get(cache_key) + if cached_values is not None: + series_cache.move_to_end(cache_key) + if 0 <= idx < len(cached_values): + val = float(cached_values[idx]) + return val if np.isfinite(val) else 0.0 + + result = sandbox.execute( + factor_code, + df, + verify_pit=False, + enforce_pit_slice=True, + ) + if not result.success or result.values is None or len(result.values) != len(df): return 0.0 + computed = [float(v) if np.isfinite(float(v)) else 0.0 for v in result.values] + if cache_key is not None: + with cache_lock: + series_cache[cache_key] = computed + series_cache.move_to_end(cache_key) + while len(series_cache) > _INDICATOR_CACHE_MAX_ENTRIES: + series_cache.popitem(last=False) + + return computed[idx] + + cast("Any", indicator_fn)._alphaevo_factor_code_hash = hashlib.sha256( + factor_code.encode("utf-8") + ).hexdigest() return indicator_fn @@ -88,17 +197,28 @@ def _execute_factor_series( sandbox: FactorSandbox, *, verify_pit: bool = True, + enforce_pit_slice: bool = False, ) -> tuple[pd.Series | None, str | None]: """Execute factor code while respecting symbol boundaries.""" if "_symbol" not in ohlcv_data.columns: - sandbox_result = sandbox.execute(code, ohlcv_data, verify_pit=verify_pit) + sandbox_result = sandbox.execute( + code, + ohlcv_data, + verify_pit=verify_pit, + enforce_pit_slice=enforce_pit_slice, + ) if not sandbox_result.success or sandbox_result.values is None: return None, sandbox_result.error or "Sandbox execution failed" return pd.Series(sandbox_result.values, index=ohlcv_data.index, dtype=float), None factor_values = pd.Series(index=ohlcv_data.index, dtype=float) for symbol, group in ohlcv_data.groupby("_symbol", sort=False): - sandbox_result = sandbox.execute(code, group, verify_pit=verify_pit) + sandbox_result = sandbox.execute( + code, + group, + verify_pit=verify_pit, + enforce_pit_slice=enforce_pit_slice, + ) if not sandbox_result.success or sandbox_result.values is None: err = sandbox_result.error or "Sandbox execution failed" return None, f"{symbol}: {err}" @@ -333,4 +453,12 @@ def store(self) -> FactorStore: return self._store def close(self) -> None: + """Close backing store and sandbox worker process.""" self._store.close() + self._sandbox.close() + + def __enter__(self) -> AlphaFactory: + return self + + def __exit__(self, *args: object) -> None: + self.close() diff --git a/src/alphaevo/alpha_factory/governance.py b/src/alphaevo/alpha_factory/governance.py index 7c6d918..df825de 100644 --- a/src/alphaevo/alpha_factory/governance.py +++ b/src/alphaevo/alpha_factory/governance.py @@ -5,6 +5,7 @@ import logging from collections import defaultdict from collections.abc import Sequence +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Literal, cast @@ -20,10 +21,11 @@ from alphaevo.models.strategy import Strategy from alphaevo.strategy.dsl.parser import StrategyParser from alphaevo.strategy.store import StrategyStore -from alphaevo.truth.pit_probe import probe_point_in_time_invariance logger = logging.getLogger(__name__) +_OOS_WARMUP_BARS = 60 + FactorHealthStatus = Literal[ "healthy", "decayed", @@ -82,15 +84,26 @@ class FactorGovernanceReport(BaseModel): entries: list[FactorAuditEntry] = Field(default_factory=list) +@dataclass(frozen=True) +class _SplitPanelData: + """Purged train/OOS factor evaluation slices with causal OOS warmup bars.""" + + train_ohlcv: pd.DataFrame + train_fwd_ret: pd.Series + oos_eval_ohlcv: pd.DataFrame + oos_mask: pd.Series + oos_fwd_ret: pd.Series + sample_df: pd.DataFrame | None + + def _split_panel( market_data: dict[str, pd.DataFrame], *, train_ratio: float, forward_horizon: int, -) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame | None]: - """Chronologically split symbol OHLCVs into stacked train and OOS evaluation panels.""" - train_frames: list[pd.DataFrame] = [] - oos_frames: list[pd.DataFrame] = [] +) -> _SplitPanelData: + """Chronologically split symbol OHLCVs into purged train and warmup-backed OOS panels.""" + ordered_by_sym: dict[str, pd.DataFrame] = {} sample_df: pd.DataFrame | None = None for sym in sorted(market_data): @@ -103,25 +116,91 @@ def _split_panel( else df.reset_index(drop=True) ) if sample_df is None or len(ordered) > len(sample_df): - sample_df = ordered - close = pd.to_numeric(ordered["close"], errors="coerce").astype(float) + sample_df = ordered.copy() ordered = ordered.copy() ordered["_symbol"] = sym - ordered["_fwd_ret"] = close.shift(-forward_horizon) / close - 1.0 + ordered_by_sym[sym] = ordered + + split_date = None + if ordered_by_sym and all("date" in df.columns for df in ordered_by_sym.values()): + all_dates = sorted( + { + d + for df in ordered_by_sym.values() + for d in pd.to_datetime(df["date"], errors="coerce").dt.date.dropna().tolist() + } + ) + if len(all_dates) >= 25: + cut_pos = max(12, min(len(all_dates) - 10, int(len(all_dates) * train_ratio))) + split_date = all_dates[cut_pos] - split_idx = max(12, int(len(ordered) * train_ratio)) - split_idx = min(split_idx, len(ordered) - 10) - if split_idx < 10 or len(ordered) - split_idx < 10: + train_frames: list[pd.DataFrame] = [] + train_fwd_parts: list[pd.Series] = [] + oos_frames: list[pd.DataFrame] = [] + oos_mask_parts: list[pd.Series] = [] + oos_fwd_parts: list[pd.Series] = [] + + for sym in sorted(ordered_by_sym): + ordered = ordered_by_sym[sym] + n_bars = len(ordered) + if split_date is not None: + sym_dates = pd.to_datetime(ordered["date"], errors="coerce").dt.date + split_idx = int((sym_dates < split_date).sum()) + else: + split_idx = max(12, int(n_bars * train_ratio)) + split_idx = min(split_idx, n_bars - 10) + if ( + split_idx - forward_horizon < 5 + or n_bars - split_idx <= forward_horizon + or n_bars - split_idx < 10 + ): continue - train_frames.append(ordered.iloc[:split_idx].copy()) - oos_frames.append(ordered.iloc[split_idx:].copy()) - train_panel = pd.concat(train_frames, ignore_index=True) if train_frames else pd.DataFrame() - oos_panel = pd.concat(oos_frames, ignore_index=True) if oos_frames else pd.DataFrame() - return ( - cast("pd.DataFrame", train_panel), - cast("pd.DataFrame", oos_panel), - sample_df, + train_df = ordered.iloc[:split_idx].copy() + train_close = pd.to_numeric(train_df["close"], errors="coerce").astype(float) + # Purge the final forward_horizon bars of train so targets never cross split_idx. + train_fwd = train_close.shift(-forward_horizon) / train_close - 1.0 + + warmup_start = max(0, split_idx - _OOS_WARMUP_BARS) + oos_eval_df = ordered.iloc[warmup_start:].copy() + oos_only_len = n_bars - split_idx + warmup_len = split_idx - warmup_start + sym_mask = pd.Series([False] * warmup_len + [True] * oos_only_len, dtype=bool) + oos_close = pd.to_numeric(oos_eval_df["close"], errors="coerce").astype(float) + oos_fwd = (oos_close.shift(-forward_horizon) / oos_close - 1.0).iloc[warmup_len:] + + train_frames.append(train_df) + train_fwd_parts.append(train_fwd) + oos_frames.append(oos_eval_df) + oos_mask_parts.append(sym_mask) + oos_fwd_parts.append(oos_fwd) + + empty_df = cast("pd.DataFrame", pd.DataFrame()) + empty_series = pd.Series(dtype=float) + empty_mask = pd.Series(dtype=bool) + return _SplitPanelData( + train_ohlcv=( + cast("pd.DataFrame", pd.concat(train_frames, ignore_index=True)) + if train_frames + else empty_df + ), + train_fwd_ret=( + pd.concat(train_fwd_parts, ignore_index=True) if train_fwd_parts else empty_series + ), + oos_eval_ohlcv=( + cast("pd.DataFrame", pd.concat(oos_frames, ignore_index=True)) + if oos_frames + else empty_df + ), + oos_mask=( + pd.concat(oos_mask_parts, ignore_index=True).astype(bool) + if oos_mask_parts + else empty_mask + ), + oos_fwd_ret=( + pd.concat(oos_fwd_parts, ignore_index=True) if oos_fwd_parts else empty_series + ), + sample_df=sample_df, ) @@ -172,6 +251,16 @@ def __init__( ) ) + def close(self) -> None: + """Terminate and reap the backing sandbox worker process.""" + self._sandbox.close() + + def __enter__(self) -> FactorGovernanceEngine: + return self + + def __exit__(self, *args: object) -> None: + self.close() + def audit_factors( self, market_data: dict[str, pd.DataFrame], @@ -191,11 +280,31 @@ def audit_factors( loaded_strategies = self._resolve_strategies(strategies) strat_lineage, fam_lineage = _collect_factor_lineage(loaded_strategies) - train_panel, oos_panel, sample_df = _split_panel( + split_data = _split_panel( market_data, train_ratio=self.config.train_ratio, forward_horizon=self.config.forward_horizon, ) + sample_df = split_data.sample_df + train_panel = split_data.train_ohlcv + train_fwd_ret = split_data.train_fwd_ret.reset_index(drop=True) + oos_eval_panel = split_data.oos_eval_ohlcv + oos_mask = split_data.oos_mask.reset_index(drop=True) + oos_fwd_ret = split_data.oos_fwd_ret.reset_index(drop=True) + oos_only_df = ( + oos_eval_panel.loc[oos_mask].reset_index(drop=True) + if not oos_eval_panel.empty and len(oos_mask) == len(oos_eval_panel) + else pd.DataFrame() + ) + has_valid_labels = (not train_fwd_ret.dropna().empty) and ( + not oos_fwd_ret.dropna().empty + ) + insufficient_panel = ( + train_panel.empty + or oos_eval_panel.empty + or oos_only_df.empty + or not has_valid_labels + ) oos_series_by_name: dict[str, pd.Series] = {} prelim: list[dict[str, object]] = [] @@ -204,7 +313,7 @@ def audit_factors( reasons: list[str] = [] pit_ok = True if self.config.require_pit_invariance and sample_df is not None: - pit_res = probe_point_in_time_invariance(rec.code, sample_df) + pit_res = self._sandbox.probe_pit(rec.code, sample_df) pit_ok = pit_res.passed if not pit_ok: if pit_res.error: @@ -222,36 +331,60 @@ def audit_factors( oos_ic, oos_ir, turnover = 0.0, 0.0, 0.0 exec_ok = True - if train_panel.empty or oos_panel.empty: + if insufficient_panel: exec_ok = False - reasons.append("Market panel too short to split train/OOS slices") + reasons.append("Market panel too short to compute train/OOS forward labels") else: tr_vals, tr_err = _execute_factor_series( - rec.code, train_panel, self._sandbox, verify_pit=False + rec.code, + train_panel, + self._sandbox, + verify_pit=False, + enforce_pit_slice=True, ) - te_vals, te_err = _execute_factor_series( - rec.code, oos_panel, self._sandbox, verify_pit=False + te_raw_vals, te_err = _execute_factor_series( + rec.code, + oos_eval_panel, + self._sandbox, + verify_pit=False, + enforce_pit_slice=True, ) - if tr_vals is None or te_vals is None: + if tr_vals is None or te_raw_vals is None: exec_ok = False reasons.append(f"Sandbox execution failed: {te_err or tr_err}") else: - train_ic, train_ir = self._validator._compute_ic( - tr_vals, - train_panel["_fwd_ret"], - dates=train_panel["date"] if "date" in train_panel.columns else None, - symbols=train_panel["_symbol"], + tr_aligned = tr_vals.reset_index(drop=True) + te_vals = ( + te_raw_vals.reset_index(drop=True).loc[oos_mask].reset_index(drop=True) + ) + train_dates = ( + train_panel["date"].reset_index(drop=True) + if "date" in train_panel.columns + else None + ) + oos_dates = ( + oos_only_df["date"].reset_index(drop=True) + if "date" in oos_only_df.columns + else None ) - oos_ic, oos_ir = self._validator._compute_ic( + train_ic, train_ic_std = self._validator._compute_ic( + tr_aligned, + train_fwd_ret, + dates=train_dates, + symbols=train_panel["_symbol"].reset_index(drop=True), + ) + train_ir = train_ic / train_ic_std if train_ic_std > 1e-10 else 0.0 + oos_ic, oos_ic_std = self._validator._compute_ic( te_vals, - oos_panel["_fwd_ret"], - dates=oos_panel["date"] if "date" in oos_panel.columns else None, - symbols=oos_panel["_symbol"], + oos_fwd_ret, + dates=oos_dates, + symbols=oos_only_df["_symbol"].reset_index(drop=True), ) + oos_ir = oos_ic / oos_ic_std if oos_ic_std > 1e-10 else 0.0 turnover = self._validator._compute_turnover( te_vals, - dates=oos_panel["date"] if "date" in oos_panel.columns else None, - symbols=oos_panel["_symbol"], + dates=oos_dates, + symbols=oos_only_df["_symbol"].reset_index(drop=True), ) oos_series_by_name[rec.name] = te_vals @@ -346,7 +479,9 @@ def audit_factors( action: Literal["kept", "retired", "would_retire"] = "kept" if health != "healthy": - if auto_retire: + if insufficient_panel and pit_ok: + action = "kept" + elif auto_retire: if store.get(rec.name) is not None: store.retire(rec.name) action = "retired" @@ -393,12 +528,16 @@ def _resolve_strategies(self, strategies: Sequence[Strategy] | None) -> list[Str if strategies is not None: return list(strategies) resolved: dict[str, Strategy] = {} + strat_store: StrategyStore | None = None try: strat_store = StrategyStore(self.db_path) for s in strat_store.list_all(): resolved[s.meta.id] = s except Exception: pass + finally: + if strat_store is not None: + strat_store.close() try: from alphaevo.cli.demo import _find_builtin_strategy_dir diff --git a/src/alphaevo/alpha_factory/sandbox.py b/src/alphaevo/alpha_factory/sandbox.py index 57e346d..8681cd5 100644 --- a/src/alphaevo/alpha_factory/sandbox.py +++ b/src/alphaevo/alpha_factory/sandbox.py @@ -9,24 +9,66 @@ from __future__ import annotations import ast +import atexit +import contextlib import logging import multiprocessing -from typing import Any +import threading +import weakref +from typing import TYPE_CHECKING, Any, Literal, cast import numpy as np import pandas as pd # type: ignore[import-untyped] from pydantic import BaseModel -if TYPE_CHECKING_IMPORT := False: - pass - -from typing import TYPE_CHECKING - if TYPE_CHECKING: + from multiprocessing.connection import Connection + from alphaevo.truth.pit_probe import PITProbeResult logger = logging.getLogger(__name__) +_SPAWN_CTX = multiprocessing.get_context("spawn") +_ACTIVE_WORKER_STATES: dict[int, dict[str, Any]] = {} +_ACTIVE_WORKERS_LOCK = threading.Lock() + + +def _shutdown_worker_state(state: dict[str, Any]) -> None: + """Terminate and reap a reusable sandbox worker process and its pipe.""" + with _ACTIVE_WORKERS_LOCK: + _ACTIVE_WORKER_STATES.pop(id(state), None) + conn = state.get("conn") + proc = state.get("proc") + state["conn"] = None + state["proc"] = None + if conn is not None: + with contextlib.suppress(Exception): + if not conn.closed: + conn.send(None) + with contextlib.suppress(Exception): + conn.close() + if proc is not None: + with contextlib.suppress(Exception): + if proc.is_alive(): + proc.join(timeout=1.0) + if proc.is_alive(): + proc.terminate() + proc.join(timeout=2.0) + if proc.is_alive(): + proc.kill() + proc.join(timeout=1.0) + + +def _shutdown_all_workers() -> None: + with _ACTIVE_WORKERS_LOCK: + states = list(_ACTIVE_WORKER_STATES.values()) + _ACTIVE_WORKER_STATES.clear() + for st in states: + _shutdown_worker_state(st) + + +atexit.register(_shutdown_all_workers) + # Modules allowed inside factor code _ALLOWED_IMPORTS = frozenset({"numpy", "pandas", "math", "np", "pd"}) @@ -47,6 +89,21 @@ "open", "input", "print", + "breakpoint", + "help", + "memoryview", + "object", + "super", + "type", + "hasattr", + "id", + "builtins", + "__builtins__", + "__loader__", + "__spec__", + "__file__", + "__cached__", + "__package__", "os", "sys", "subprocess", @@ -87,6 +144,103 @@ } ) +# Frame, coroutine, generator, traceback, and serialization/IO attributes +_FORBIDDEN_ATTRS = frozenset( + { + "f_back", + "f_builtins", + "f_code", + "f_globals", + "f_locals", + "gi_frame", + "gi_code", + "cr_frame", + "cr_code", + "ag_frame", + "ag_code", + "tb_frame", + "tb_next", + "func_globals", + "func_code", + "im_func", + "im_self", + "im_class", + "mro", + "subclasses", + "system", + "popen", + "spawn", + "fork", + "to_pickle", + "read_pickle", + "to_csv", + "read_csv", + "to_parquet", + "read_parquet", + "to_json", + "read_json", + "to_hdf", + "read_hdf", + "to_sql", + "read_sql", + "read_fwf", + "read_table", + "read_excel", + "to_excel", + "read_feather", + "to_feather", + "read_orc", + "read_clipboard", + "to_clipboard", + "load", + "loads", + "dump", + "dumps", + "save", + "savez", + "fromfile", + "tofile", + "memmap", + "ctypes", + "query", + "gi_yieldfrom", + "cr_await", + "ag_await", + "tb_lasti", + "base", + "_mgr", + "_values", + "_data", + "blocks", + "loadtxt", + "savetxt", + "genfromtxt", + "fromregex", + "savez_compressed", + "DataSource", + "io", + "ctypeslib", + "testing", + "distutils", + "f2py", + "lib", + } +) + +_SAFE_TO_ATTRS = frozenset( + { + "to_numpy", + "tolist", + "to_list", + "to_dict", + "to_frame", + "to_series", + "to_numeric", + "to_datetime", + "to_period", + } +) + class SandboxResult(BaseModel): """Result of a sandboxed factor execution.""" @@ -102,7 +256,7 @@ class SandboxSecurityError(Exception): class FactorSandbox: - """Execute factor code safely. + """Execute factor code safely inside an isolated ``spawn`` worker process. Example:: @@ -120,6 +274,46 @@ def __init__( ) -> None: self.timeout = timeout_seconds self.max_memory = max_memory_mb + self._worker_lock = threading.RLock() + self._worker_state: dict[str, Any] = {"proc": None, "conn": None} + with _ACTIVE_WORKERS_LOCK: + _ACTIVE_WORKER_STATES[id(self._worker_state)] = self._worker_state + self._finalizer = weakref.finalize(self, _shutdown_worker_state, self._worker_state) + + def close(self) -> None: + """Terminate and reap the backing sandbox worker process.""" + with self._worker_lock: + _shutdown_worker_state(self._worker_state) + + def __enter__(self) -> FactorSandbox: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def _reset_worker_locked(self) -> None: + _shutdown_worker_state(self._worker_state) + + def _ensure_worker_locked(self) -> Connection: + proc = self._worker_state.get("proc") + conn = self._worker_state.get("conn") + if proc is not None and proc.is_alive() and conn is not None and not conn.closed: + return cast("Connection", conn) + self._reset_worker_locked() + with _ACTIVE_WORKERS_LOCK: + _ACTIVE_WORKER_STATES[id(self._worker_state)] = self._worker_state + parent_conn, child_conn = _SPAWN_CTX.Pipe(duplex=True) + proc = _SPAWN_CTX.Process( + target=_sandbox_worker_main, + args=(child_conn, self.max_memory), + daemon=True, + ) + proc.start() + with contextlib.suppress(Exception): + child_conn.close() + self._worker_state["proc"] = proc + self._worker_state["conn"] = parent_conn + return parent_conn def validate_code(self, code: str) -> tuple[bool, str]: """Validate factor code via AST analysis. @@ -137,26 +331,49 @@ def validate_code(self, code: str) -> tuple[bool, str]: for alias in node.names: if alias.name not in _ALLOWED_IMPORTS: return False, f"Forbidden import: {alias.name}" + if alias.asname and ( + alias.asname.startswith("_") or alias.asname in _FORBIDDEN_NAMES + ): + return False, f"Forbidden import alias: {alias.asname}" elif isinstance(node, ast.ImportFrom): - if node.module and node.module.split(".")[0] not in _ALLOWED_IMPORTS: + if node.level and node.level > 0: + return False, "Forbidden relative import" + if not node.module or node.module not in _ALLOWED_IMPORTS: return False, f"Forbidden import from: {node.module}" - - # Check function calls to forbidden names + for alias in node.names: + if ( + alias.name == "*" + or alias.name.startswith("_") + or alias.name in _FORBIDDEN_NAMES + or alias.name in _FORBIDDEN_ATTRS + ): + return False, f"Forbidden import symbol: {alias.name}" + if alias.asname and ( + alias.asname.startswith("_") or alias.asname in _FORBIDDEN_NAMES + ): + return False, f"Forbidden import alias: {alias.asname}" + + # Check function calls and name references elif isinstance(node, ast.Name): - if node.id in _FORBIDDEN_NAMES: + if node.id in _FORBIDDEN_NAMES or node.id in _FORBIDDEN_DUNDERS: return False, f"Forbidden name: {node.id}" # Check attribute access for forbidden patterns elif isinstance(node, ast.Attribute): + if node.attr.startswith("__") and node.attr.endswith("__"): + return False, f"Forbidden dunder access: {node.attr}" if node.attr in _FORBIDDEN_NAMES: return False, f"Forbidden attribute: {node.attr}" # Block dunder reflection chains (e.g. __class__.__subclasses__) if node.attr in _FORBIDDEN_DUNDERS: return False, f"Forbidden dunder access: {node.attr}" - # Block system() and similar - if node.attr in ("system", "popen", "spawn", "fork"): - return False, f"Forbidden system call: {node.attr}" + if node.attr in _FORBIDDEN_ATTRS: + return False, f"Forbidden system/IO call: {node.attr}" + if node.attr.startswith("read_") or ( + node.attr.startswith("to_") and node.attr not in _SAFE_TO_ATTRS + ): + return False, f"Forbidden IO attribute: {node.attr}" # Check string-based eval/exec patterns elif ( @@ -180,15 +397,128 @@ def validate_code(self, code: str) -> tuple[bool, str]: return True, "" - def probe_pit(self, code: str, df: pd.DataFrame) -> PITProbeResult: - """Run runtime future-noise and truncation probes to catch hidden lookahead.""" - from alphaevo.truth.pit_probe import probe_point_in_time_invariance + def preflight_code(self, code: str) -> tuple[bool, str]: + """Static AST + bytecode compilation check without executing untrusted code.""" + is_safe, err = self.validate_code(code) + if not is_safe: + return False, err + try: + tree = ast.parse(code) + compute_defs = [ + n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "compute" + ] + if not any( + len(fn.args.posonlyargs) + len(fn.args.args) >= 2 or fn.args.vararg is not None + for fn in compute_defs + ): + return False, "Function 'compute' must accept '(df, idx)' parameters" + compile(code, "", "exec") + except SyntaxError as exc: + return False, f"Syntax error: {exc}" + return True, "" + + def probe_pit( + self, + code: str, + df: pd.DataFrame, + *, + probe_indices: list[int] | None = None, + atol: float = 1e-9, + ) -> PITProbeResult: + """Run runtime future-noise and truncation probes inside the hardened spawn worker.""" + import math as std_math + + from alphaevo.truth.pit_probe import PITProbeResult, PITProbeViolation + + is_safe, err_msg = self.preflight_code(code) + if not is_safe: + return PITProbeResult(passed=False, error=f"Security: {err_msg}") + + if len(df) < 10: + return PITProbeResult( + passed=False, error="DataFrame needs at least 10 rows for PIT probe" + ) - return probe_point_in_time_invariance( - code, - df, - timeout_seconds=self.timeout, + raw_indices = ( + list(probe_indices) + if probe_indices is not None + else [ + max(5, int(len(df) * 0.35)), + max(6, int(len(df) * 0.60)), + max(7, min(len(df) - 3, int(len(df) * 0.80))), + ] ) + indices = sorted({i for i in raw_indices if 1 <= i <= len(df) - 2}) + if not indices: + return PITProbeResult(passed=False, error="No valid interior probe indices") + + clean_df = df.reset_index(drop=True) + with self._worker_lock: + try: + conn = self._ensure_worker_locked() + req = ("probe_pit", code, clean_df, indices, float(atol)) + try: + conn.send(req) + except (EOFError, BrokenPipeError, OSError): + self._reset_worker_locked() + conn = self._ensure_worker_locked() + conn.send(req) + + if not conn.poll(self.timeout): + self._reset_worker_locked() + return PITProbeResult( + passed=False, + checked_indices=indices, + error=f"PIT probe timed out after {self.timeout}s", + ) + + status, payload = conn.recv() + if status != "ok": + return PITProbeResult( + passed=False, + checked_indices=indices, + error=str(payload), + ) + + violations: list[PITProbeViolation] = [] + for v in payload: + raw_clean = float(v["clean_value"]) + raw_pert = float(v["perturbed_value"]) + p_type: Literal["future_noise", "truncation"] = ( + "future_noise" if v.get("probe_type") == "future_noise" else "truncation" + ) + violations.append( + PITProbeViolation( + probe_type=p_type, + probe_index=int(v["probe_index"]), + clean_value=round(raw_clean, 8) + if std_math.isfinite(raw_clean) + else 0.0, + perturbed_value=( + round(raw_pert, 8) if std_math.isfinite(raw_pert) else 0.0 + ), + abs_diff=float(v["abs_diff"]), + ) + ) + return PITProbeResult( + passed=len(violations) == 0, + checked_indices=indices, + violations=violations, + ) + except (EOFError, BrokenPipeError): + self._reset_worker_locked() + return PITProbeResult( + passed=False, + checked_indices=indices, + error="PIT probe subprocess produced no output (may have crashed)", + ) + except Exception as exc: + self._reset_worker_locked() + return PITProbeResult( + passed=False, + checked_indices=indices, + error=f"PIT probe error: {exc}", + ) def execute( self, @@ -196,16 +526,18 @@ def execute( df: pd.DataFrame, *, verify_pit: bool = False, + enforce_pit_slice: bool = False, ) -> SandboxResult: - """Execute factor code and compute values for all valid indices. + """Execute factor code inside an isolated worker process. - The code is run in a child process for isolation. When ``verify_pit`` is True, - also verifies runtime point-in-time invariance against future noise/truncation. + When ``verify_pit`` is True, also verifies runtime point-in-time invariance + against future noise/truncation. When ``enforce_pit_slice`` is True, each bar + ``idx`` only receives ``df.iloc[: idx + 1]``. """ import time - # Step 1: AST validation - is_safe, err_msg = self.validate_code(code) + # Step 1: AST + preflight validation + is_safe, err_msg = self.preflight_code(code) if not is_safe: return SandboxResult(success=False, error=f"Security: {err_msg}") @@ -220,59 +552,54 @@ def execute( ) return SandboxResult(success=False, error=f"PIT violation: {detail}") - # Step 2: Execute in subprocess + # Step 2: Execute in persistent spawn worker start = time.monotonic() - try: - result_queue: multiprocessing.Queue = multiprocessing.Queue() - proc = multiprocessing.Process( - target=_run_in_subprocess, - args=(code, df, result_queue, self.max_memory), - ) - proc.start() - proc.join(timeout=self.timeout) - - if proc.is_alive(): - proc.terminate() - proc.join(timeout=5) - if proc.is_alive(): - proc.kill() + with self._worker_lock: + try: + conn = self._ensure_worker_locked() + try: + conn.send(("exec", code, df, enforce_pit_slice)) + except (EOFError, BrokenPipeError, OSError): + self._reset_worker_locked() + conn = self._ensure_worker_locked() + conn.send(("exec", code, df, enforce_pit_slice)) + + if not conn.poll(self.timeout): + self._reset_worker_locked() + return SandboxResult( + success=False, + error=f"Execution timed out after {self.timeout}s", + execution_time_ms=(time.monotonic() - start) * 1000, + ) + + status, payload = conn.recv() + elapsed = (time.monotonic() - start) * 1000 + if status != "ok": + return SandboxResult( + success=False, + error=str(payload), + execution_time_ms=elapsed, + ) return SandboxResult( - success=False, - error=f"Execution timed out after {self.timeout}s", - execution_time_ms=(time.monotonic() - start) * 1000, + success=True, + values=payload, + execution_time_ms=elapsed, ) - - elapsed = (time.monotonic() - start) * 1000 - - if result_queue.empty(): + except (EOFError, BrokenPipeError): + self._reset_worker_locked() return SandboxResult( success=False, error="Subprocess produced no output (may have crashed)", - execution_time_ms=elapsed, + execution_time_ms=(time.monotonic() - start) * 1000, ) - - result = result_queue.get_nowait() - if isinstance(result, Exception): + except Exception as e: + self._reset_worker_locked() return SandboxResult( success=False, - error=str(result), - execution_time_ms=elapsed, + error=f"Sandbox error: {e}", + execution_time_ms=(time.monotonic() - start) * 1000, ) - return SandboxResult( - success=True, - values=result, - execution_time_ms=elapsed, - ) - - except Exception as e: - elapsed = (time.monotonic() - start) * 1000 - return SandboxResult( - success=False, - error=f"Sandbox error: {e}", - execution_time_ms=elapsed, - ) - def _check_future_data_access(tree: ast.AST) -> str | None: """Detect code patterns that access future data relative to ``idx``. @@ -332,8 +659,105 @@ def _check_future_data_access(tree: ast.AST) -> str | None: return None +class _SafeModuleProxy: + """Attribute-filtering proxy exposing computational symbols without file/IO helpers.""" + + __slots__ = ("_module", "_module_name") + + def __init__(self, module: Any, module_name: str) -> None: + object.__setattr__(self, "_module", module) + object.__setattr__(self, "_module_name", module_name) + + def __getattr__(self, name: str) -> Any: + if ( + name.startswith("_") + or name.startswith("read_") + or (name.startswith("to_") and name not in _SAFE_TO_ATTRS) + or name in _FORBIDDEN_ATTRS + or name in _FORBIDDEN_NAMES + or name in _FORBIDDEN_DUNDERS + ): + mod_name = object.__getattribute__(self, "_module_name") + raise AttributeError(f"Access to '{mod_name}.{name}' is blocked in factor sandbox") + return getattr(object.__getattribute__(self, "_module"), name) + + def __setattr__(self, name: str, value: Any) -> None: + raise AttributeError("Mutating sandboxed modules is forbidden") + + def __dir__(self) -> list[str]: + return [] + + +_IN_FACTOR_EXEC = False +_AUDIT_HOOK_INSTALLED = False + +_BLOCKED_AUDIT_EXACT = frozenset({"open"}) +_BLOCKED_AUDIT_PREFIXES = ( + "os.", + "subprocess.", + "socket.", + "urllib.", + "http.client.", + "shutil.", + "ctypes.", + "ftplib.", + "smtplib.", + "webbrowser.", + "tempfile.", +) +_BLOCKED_IMPORT_ROOTS = frozenset( + { + "os", + "sys", + "subprocess", + "shutil", + "pathlib", + "socket", + "http", + "urllib", + "requests", + "pickle", + "shelve", + "marshal", + "importlib", + "ctypes", + "ftplib", + "smtplib", + "webbrowser", + "tempfile", + "sqlite3", + "ssl", + "pty", + "posix", + "nt", + } +) + + +def _install_worker_audit_hook() -> None: + """Register a process-wide PEP 578 audit hook blocking I/O during factor execution.""" + global _AUDIT_HOOK_INSTALLED + if _AUDIT_HOOK_INSTALLED: + return + import sys + + def _audit_hook(event: str, args: tuple[Any, ...]) -> None: + if not _IN_FACTOR_EXEC: + return + if event in _BLOCKED_AUDIT_EXACT or event.startswith(_BLOCKED_AUDIT_PREFIXES): + raise PermissionError(f"Sandbox audit hook blocked operation: {event}") + if event == "import" and args: + mod = str(args[0] or "") + root = mod.split(".", 1)[0] + if root in _BLOCKED_IMPORT_ROOTS: + raise PermissionError(f"Sandbox audit hook blocked import: {mod}") + + sys.addaudithook(_audit_hook) + _AUDIT_HOOK_INSTALLED = True + + def build_restricted_namespace() -> dict[str, Any]: - """Build an isolated execution namespace with safe non-I/O builtins.""" + """Build an isolated execution namespace with safe non-I/O builtins and proxied modules.""" safe_builtins: dict[str, Any] = { k: v for k, v in ( @@ -376,9 +800,6 @@ def build_restricted_namespace() -> dict[str, Any]: "all", "isinstance", "issubclass", - "type", - "hasattr", - "id", "hash", "repr", "ValueError", @@ -397,12 +818,15 @@ def build_restricted_namespace() -> dict[str, Any]: } import math as _math - allowed_modules = { - "numpy": np, - "pandas": pd, - "math": _math, - "np": np, - "pd": pd, + safe_np = _SafeModuleProxy(np, "numpy") + safe_pd = _SafeModuleProxy(pd, "pandas") + safe_math = _SafeModuleProxy(_math, "math") + allowed_modules: dict[str, Any] = { + "numpy": safe_np, + "pandas": safe_pd, + "math": safe_math, + "np": safe_np, + "pd": safe_pd, } def _safe_import(name: str, *args: Any, **kwargs: Any) -> Any: @@ -414,69 +838,210 @@ def _safe_import(name: str, *args: Any, **kwargs: Any) -> Any: safe_builtins["__import__"] = _safe_import return { "__builtins__": safe_builtins, - "np": np, - "pd": pd, - "math": _math, - "numpy": np, - "pandas": pd, + "np": safe_np, + "pd": safe_pd, + "math": safe_math, + "numpy": safe_np, + "pandas": safe_pd, } -def _run_in_subprocess( +def _execute_in_worker_namespace( code: str, df: pd.DataFrame, - result_queue: multiprocessing.Queue, - max_memory_mb: int, -) -> None: - """Worker function that runs in a child process.""" - try: - # Set resource limits (Linux only) + *, + enforce_pit_slice: bool = False, +) -> list[float]: + """Compile and evaluate factor code inside a clean restricted namespace.""" + namespace = build_restricted_namespace() + exec(code, namespace) # noqa: S102 — code has passed AST + preflight validation + compute_fn = namespace.get("compute") + if compute_fn is None or not callable(compute_fn): + raise ValueError("No callable 'compute' function defined") + + values: list[float] = [] + for idx in range(len(df)): try: - import os - import resource + target_df = df.iloc[: idx + 1].copy(deep=True) if enforce_pit_slice else df + val = float(compute_fn(target_df, idx)) + if not np.isfinite(val): + val = 0.0 + values.append(val) + except (PermissionError, SandboxSecurityError): + raise + except Exception: + values.append(0.0) + return values + + +def _probe_pit_in_worker( + code: str, + prepared: list[tuple[int, pd.DataFrame, pd.DataFrame, pd.DataFrame]], + atol: float, +) -> list[dict[str, Any]]: + """Run clean vs future-corrupted vs truncated PIT comparisons in restricted namespace.""" + namespace = build_restricted_namespace() + exec(code, namespace) # noqa: S102 — code has passed AST + preflight validation + compute_fn = namespace.get("compute") + if compute_fn is None or not callable(compute_fn): + raise ValueError("No callable 'compute' function defined") + + violations: list[dict[str, Any]] = [] + for idx, clean_copy, noisy_df, trunc_df in prepared: + raw_clean = float(compute_fn(clean_copy, idx)) + clean_val = raw_clean if np.isfinite(raw_clean) else 0.0 + + raw_noisy = float(compute_fn(noisy_df, idx)) + noisy_val = raw_noisy if np.isfinite(raw_noisy) else 0.0 + diff_noise = abs(clean_val - noisy_val) + if diff_noise > atol: + violations.append( + { + "probe_type": "future_noise", + "probe_index": idx, + "clean_value": clean_val, + "perturbed_value": noisy_val, + "abs_diff": diff_noise, + } + ) - # Memory limit (add inherited VmSize on fork so parent OpenBLAS/thread - # arenas do not immediately exhaust RLIMIT_AS in the child) - mem_bytes = max_memory_mb * 1024 * 1024 - try: - with open("/proc/self/statm", encoding="utf-8") as statm_f: - vm_pages = int(statm_f.read().split()[0]) - current_vm = vm_pages * os.sysconf("SC_PAGE_SIZE") - mem_bytes = max(mem_bytes, current_vm + mem_bytes) - except (OSError, ValueError): - pass - resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes)) - except (ImportError, ValueError) as e: - import sys - - print( - f"[sandbox] Memory limits not available ({e}); " - "factor code runs without memory protection", - file=sys.stderr, + raw_trunc = float(compute_fn(trunc_df, idx)) + trunc_val = raw_trunc if np.isfinite(raw_trunc) else 0.0 + diff_trunc = abs(clean_val - trunc_val) + if diff_trunc > atol: + violations.append( + { + "probe_type": "truncation", + "probe_index": idx, + "clean_value": clean_val, + "perturbed_value": trunc_val, + "abs_diff": diff_trunc, + } ) + return violations - namespace = build_restricted_namespace() - # Execute the code to define the compute function - exec(code, namespace) # noqa: S102 — code has passed AST validation +def _sandbox_worker_main(conn: Connection, max_memory_mb: int) -> None: + """Persistent spawn worker main loop with BLAS thread caps, RLIMIT_AS, and audit hooks.""" + global _IN_FACTOR_EXEC + import os - compute_fn = namespace.get("compute") - if compute_fn is None or not callable(compute_fn): - result_queue.put(ValueError("No callable 'compute' function defined")) - return + for env_key in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + ): + os.environ.setdefault(env_key, "1") + + try: + import resource + + mem_bytes = max_memory_mb * 1024 * 1024 + try: + with open("/proc/self/statm", encoding="utf-8") as statm_f: + vm_pages = int(statm_f.read().split()[0]) + current_vm = vm_pages * os.sysconf("SC_PAGE_SIZE") + mem_bytes = max(mem_bytes, current_vm + mem_bytes) + except (OSError, ValueError): + pass + _soft, hard = resource.getrlimit(resource.RLIMIT_AS) + if hard != resource.RLIM_INFINITY: + mem_bytes = min(mem_bytes, hard) + resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, hard)) + except (ImportError, ValueError) as e: + import sys + + print( + f"[sandbox] Memory limits not available ({e}); " + "factor code runs without memory protection", + file=sys.stderr, + ) + + from alphaevo.truth.pit_probe import _corrupt_future_rows - # Compute values for each index - values = [] - for idx in range(len(df)): + _install_worker_audit_hook() + + while True: + try: + request = conn.recv() + except EOFError: + break + if request is None: + break + if isinstance(request, tuple) and len(request) == 5 and request[0] == "probe_pit": + _tag, code, clean_df, indices, atol = request + prepared = [ + ( + idx, + cast("pd.DataFrame", clean_df.copy(deep=True)), + _corrupt_future_rows(clean_df, idx), + cast( + "pd.DataFrame", + clean_df.iloc[: idx + 1].copy(deep=True).reset_index(drop=True), + ), + ) + for idx in indices + ] try: - val = float(compute_fn(df, idx)) - if not np.isfinite(val): - val = 0.0 - values.append(val) - except Exception: - values.append(0.0) + _IN_FACTOR_EXEC = True + violations = _probe_pit_in_worker(code, prepared, float(atol)) + conn.send(("ok", violations)) + except BaseException as exc: + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + raise + conn.send(("err", f"{type(exc).__name__}: {exc}")) + finally: + _IN_FACTOR_EXEC = False + continue + + if isinstance(request, tuple) and len(request) == 4 and request[0] == "exec": + _tag, code, df, enforce_pit_slice = request + else: + code, df, enforce_pit_slice = request + try: + _IN_FACTOR_EXEC = True + values = _execute_in_worker_namespace( + code, + df, + enforce_pit_slice=bool(enforce_pit_slice), + ) + conn.send(("ok", values)) + except BaseException as exc: + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + raise + conn.send(("err", f"{type(exc).__name__}: {exc}")) + finally: + _IN_FACTOR_EXEC = False + + +def _run_in_subprocess( + code: str, + df: pd.DataFrame, + result_queue: multiprocessing.Queue, + max_memory_mb: int, +) -> None: + """Compatibility helper executing factor code with resource limits.""" + try: + import os + import resource - result_queue.put(values) + mem_bytes = max_memory_mb * 1024 * 1024 + try: + with open("/proc/self/statm", encoding="utf-8") as statm_f: + vm_pages = int(statm_f.read().split()[0]) + current_vm = vm_pages * os.sysconf("SC_PAGE_SIZE") + mem_bytes = max(mem_bytes, current_vm + mem_bytes) + except (OSError, ValueError): + pass + _soft, hard = resource.getrlimit(resource.RLIMIT_AS) + if hard != resource.RLIM_INFINITY: + mem_bytes = min(mem_bytes, hard) + resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, hard)) + except (ImportError, ValueError): + pass + try: + result_queue.put(_execute_in_worker_namespace(code, df, enforce_pit_slice=False)) except Exception as e: result_queue.put(e) diff --git a/src/alphaevo/arena/runner.py b/src/alphaevo/arena/runner.py index c5caa11..353835e 100644 --- a/src/alphaevo/arena/runner.py +++ b/src/alphaevo/arena/runner.py @@ -289,6 +289,31 @@ def run( ) symbols = sorted(market_data.keys()) + min_evo_rows = min(15, self._bt_config.min_data_days) + min_shadow_pre_rows = max(15, min_evo_rows) + evolution_market = market_data + shadow_start_date: date | None = None + if len(all_dates) >= min_shadow_pre_rows + 10: + evo_cut_pos = max(min_shadow_pre_rows, int(len(all_dates) * 0.70)) + evo_cut_pos = min(evo_cut_pos, len(all_dates) - 10) + evo_cutoff: date = all_dates[evo_cut_pos] + sliced_evo: dict[str, pd.DataFrame] = {} + for sym, df in market_data.items(): + if df is None or df.empty or "date" not in df.columns: + continue + sym_dates = pd.to_datetime(df["date"], errors="coerce").dt.date + sub = df.loc[sym_dates < evo_cutoff].copy() + if len(sub) >= min_evo_rows: + sliced_evo[sym] = sub.reset_index(drop=True) + if ( + sliced_evo + and any(len(sub) >= 15 for sub in sliced_evo.values()) + and len(all_dates) - evo_cut_pos >= 10 + ): + evolution_market = sliced_evo + shadow_start_date = evo_cutoff + evo_symbols = sorted(evolution_market.keys()) + kernel = EvaluationKernel( backtest_config=self._bt_config, db_path=self._db_path, @@ -312,147 +337,135 @@ def run( snapshot_veto_breakdown: dict[str, int] = {} all_chains_verified = True - for idx, base_strat in enumerate(strategies): - base_outcome = kernel.evaluate( - base_strat, - market_data, - mode="fast", - record_trial=False, - run_null_control=False, - seed=seed + idx, - ) - baseline_score = float(base_outcome.evaluation.confidence_score) - - allowed_lvls = ( - [RSILevel.L1_STRATEGY, RSILevel.L2_FACTOR] - if enable_l2_factors - else [RSILevel.L1_STRATEGY] - ) - charter = RSICharter( - name=f"arena_{base_strat.meta.id}", - seed_strategy_id=base_strat.meta.id, - allowed_levels=allowed_lvls, - max_rounds=max(1, rounds), - max_candidates_per_round=2, - max_trials_budget=max(10, rounds * 8 + 4), - min_signals=min(15, self._bt_config.min_data_days), - require_null_control=True, - null_permutations=30, - ) - rsi_res = rsi_engine.run( - base_strat, - market_data, - charter=charter, - persist_champion=False, - seed=seed + idx, - ) - - champion = rsi_res.champion_strategy - champions.append(champion) - champ_outcome = kernel.evaluate( - champion, - market_data, - mode="full", - record_trial=False, - run_null_control=True, - null_permutations=30, - seed=seed + idx, - ) - champ_eval = champ_outcome.evaluation - ov = champ_eval.overall - - base_yaml = self._serializer.to_yaml(base_strat) - champ_yaml = self._serializer.to_yaml(champion) - diff_lines = list( - difflib.unified_diff( - base_yaml.splitlines(), - champ_yaml.splitlines(), - fromfile=f"{base_strat.meta.id}.yaml", - tofile=f"{champion.meta.id}.yaml", - lineterm="", + try: + for idx, base_strat in enumerate(strategies): + base_outcome = kernel.evaluate( + base_strat, + evolution_market, + mode="fast", + record_trial=False, + run_null_control=False, + seed=seed + idx, ) - ) + baseline_score = float(base_outcome.evaluation.confidence_score) - veto_count = ( - sum( - 1 - for d in rsi_res.deliberations - if d.l0_outcome in {"prosecutor_vetoed", "revert"} + allowed_lvls = ( + [RSILevel.L1_STRATEGY, RSILevel.L2_FACTOR] + if enable_l2_factors + else [RSILevel.L1_STRATEGY] + ) + charter = RSICharter( + name=f"arena_{base_strat.meta.id}", + seed_strategy_id=base_strat.meta.id, + allowed_levels=allowed_lvls, + max_rounds=max(1, rounds), + max_candidates_per_round=2, + max_trials_budget=max(10, rounds * 8 + 4), + min_signals=min(15, self._bt_config.min_data_days), + require_null_control=True, + null_permutations=30, + ) + rsi_res = rsi_engine.run( + base_strat, + evolution_market, + charter=charter, + persist_champion=False, + seed=seed + idx, ) - if rsi_res.deliberations - else sum(1 for row in rsi_res.rows if row.status in {"vetoed", "revert"}) - ) - total_promotions += rsi_res.promotions - total_vetoes += veto_count - total_deliberations += len(rsi_res.deliberations) - total_prosecutor_vetoes += sum( - 1 for d in rsi_res.deliberations if d.l0_outcome == "prosecutor_vetoed" - ) - for v_key, v_cnt in rsi_res.veto_breakdown.items(): - snapshot_veto_breakdown[v_key] = snapshot_veto_breakdown.get(v_key, 0) + v_cnt - nodes: list[EvolutionNodeView] = [] - for row in rsi_res.rows: - row_diff = ( - diff_lines if row.strategy_id == champion.meta.id and row.round_num > 0 else [] + champion = rsi_res.champion_strategy + champions.append(champion) + champ_outcome = kernel.evaluate( + champion, + evolution_market, + mode="full", + record_trial=False, + run_null_control=True, + null_permutations=30, + seed=seed + idx, ) - nodes.append( - EvolutionNodeView( - round_num=row.round_num, - strategy_id=row.strategy_id, - parent_id=row.parent_id - or (base_strat.meta.id if row.round_num > 0 else None), - secondary_parent_id=row.secondary_parent_id, - status=row.status, - level=row.level.value, - score=round(float(row.fitness_score), 4), - win_rate=round(float(row.win_rate), 4), - avg_return=round(float(row.avg_return), 6), - signals=int(row.signals), - dsr_prob=round(float(row.dsr_probability), 4), - null_passed=bool(row.null_passed), - description=row.description, - veto_reasons=list(row.veto_reasons), - yaml_diff=row_diff[:40], + champ_eval = champ_outcome.evaluation + ov = champ_eval.overall + + base_yaml = self._serializer.to_yaml(base_strat) + champ_yaml = self._serializer.to_yaml(champion) + diff_lines = list( + difflib.unified_diff( + base_yaml.splitlines(), + champ_yaml.splitlines(), + fromfile=f"{base_strat.meta.id}.yaml", + tofile=f"{champion.meta.id}.yaml", + lineterm="", ) ) - committee_verdict = self._committee.review( - champion, - champ_eval, - data_source=data_source, - symbols=symbols, - ) - verdicts_json = [v.model_dump(mode="json") for v in committee_verdict.verdicts] - - shadow_stage = "shadow" - shadow_mature = 0 - shadow_avg = 0.0 - shadow_verified = True - if len(all_dates) >= 25: - try: - if shadow_dir is not None: - s_dir = Path(shadow_dir) / champion.meta.id - ledger = ShadowLedger(s_dir) - sim_rep = ledger.simulate_rolling( - champion, - market_data, - start_date=all_dates[max(15, int(len(all_dates) * 0.65))], - end_date=all_dates[-1], - step_days=2, - horizon_days=5, - min_trading_days=5, - min_mature_signals=5, - min_effective_signals=3.0, - is_replay=True, + veto_count = ( + sum( + 1 + for d in rsi_res.deliberations + if d.l0_outcome in {"prosecutor_vetoed", "revert"} + ) + if rsi_res.deliberations + else sum(1 for row in rsi_res.rows if row.status in {"vetoed", "revert"}) + ) + total_promotions += rsi_res.promotions + total_vetoes += veto_count + total_deliberations += len(rsi_res.deliberations) + total_prosecutor_vetoes += sum( + 1 for d in rsi_res.deliberations if d.l0_outcome == "prosecutor_vetoed" + ) + for v_key, v_cnt in rsi_res.veto_breakdown.items(): + snapshot_veto_breakdown[v_key] = snapshot_veto_breakdown.get(v_key, 0) + v_cnt + + nodes: list[EvolutionNodeView] = [] + for row in rsi_res.rows: + row_diff = ( + diff_lines + if row.strategy_id == champion.meta.id and row.round_num > 0 + else [] + ) + nodes.append( + EvolutionNodeView( + round_num=row.round_num, + strategy_id=row.strategy_id, + parent_id=row.parent_id + or (base_strat.meta.id if row.round_num > 0 else None), + secondary_parent_id=row.secondary_parent_id, + status=row.status, + level=row.level.value, + score=round(float(row.fitness_score), 4), + win_rate=round(float(row.win_rate), 4), + avg_return=round(float(row.avg_return), 6), + signals=int(row.signals), + dsr_prob=round(float(row.dsr_probability), 4), + null_passed=bool(row.null_passed), + description=row.description, + veto_reasons=list(row.veto_reasons), + yaml_diff=row_diff[:40], ) - else: - with tempfile.TemporaryDirectory() as tmpdir: - ledger = ShadowLedger(tmpdir) + ) + + committee_verdict = self._committee.review( + champion, + champ_eval, + data_source=data_source, + symbols=evo_symbols, + ) + verdicts_json = [v.model_dump(mode="json") for v in committee_verdict.verdicts] + + shadow_stage = "shadow" + shadow_mature = 0 + shadow_avg = 0.0 + shadow_verified = False + if shadow_start_date is not None: + try: + if shadow_dir is not None: + s_dir = Path(shadow_dir) / champion.meta.id + ledger = ShadowLedger(s_dir) sim_rep = ledger.simulate_rolling( champion, market_data, - start_date=all_dates[max(15, int(len(all_dates) * 0.65))], + start_date=shadow_start_date, end_date=all_dates[-1], step_days=2, horizon_days=5, @@ -461,70 +474,87 @@ def run( min_effective_signals=3.0, is_replay=True, ) - shadow_stage = sim_rep.final_stage.value - shadow_mature = sim_rep.final_decay_report.mature_signals - shadow_avg = sim_rep.final_decay_report.forward_avg_post_cost_return - shadow_verified = sim_rep.chain_verified - except Exception: - shadow_verified = True - all_chains_verified = all_chains_verified and shadow_verified - - equity_curve = self.compute_equity_curve( - champ_outcome.backtest_result.signals, market_data - ) - trade_replays = self.build_trade_replays( - champ_outcome.backtest_result.signals, market_data - ) - champ_score = float(champ_eval.confidence_score) - - entries.append( - ArenaStrategyEntry( - strategy_id=base_strat.meta.id, - champion_id=champion.meta.id, - name=champion.meta.name, - category=champion.meta.category.value, - market=champion.meta.market.value, - baseline_score=round(baseline_score, 4), - champion_score=round(champ_score, 4), - score_delta=round(champ_score - baseline_score, 4), - win_rate=round(float(ov.win_rate), 4), - avg_return=round(float(ov.avg_return), 6), - total_return=round(float(ov.total_return), 6), - sharpe_ratio=round(float(ov.sharpe_ratio), 4), - max_drawdown=round(float(ov.max_drawdown), 4), - signal_count=int(ov.signal_count), - dsr_prob=round(float(champ_eval.deflated_sharpe_prob or 0.0), 4), - null_passed=bool(champ_eval.null_control_passed), - promotions=rsi_res.promotions, - vetoes=veto_count, - trials_recorded=rsi_res.total_trials_recorded, - shadow_stage=shadow_stage, - shadow_mature_signals=shadow_mature, - shadow_avg_return=round(float(shadow_avg), 6), - shadow_chain_verified=shadow_verified, - equity_curve=equity_curve, - evolution_nodes=nodes, - deliberations=[d.model_dump(mode="json") for d in rsi_res.deliberations], - veto_breakdown=dict(rsi_res.veto_breakdown), - map_elites_cells=[ - { - "regime_bucket": cell.niche.regime_bucket, - "style_bucket": cell.niche.style_bucket, - "horizon_bucket": cell.niche.horizon_bucket, - "strategy_id": cell.strategy_id, - "fitness_score": round(float(cell.fitness_score), 4), - } - for cell in rsi_res.archive_summary.cells - ], - synthesized_factors=list(rsi_res.persisted_factors), - crossovers_kept=int(rsi_res.crossovers_kept), - trade_replays=trade_replays, - committee_verdicts=verdicts_json, - champion_yaml=champ_yaml, - baseline_yaml=base_yaml, - yaml_diff=diff_lines[:80], + else: + with tempfile.TemporaryDirectory() as tmpdir: + ledger = ShadowLedger(tmpdir) + sim_rep = ledger.simulate_rolling( + champion, + market_data, + start_date=shadow_start_date, + end_date=all_dates[-1], + step_days=2, + horizon_days=5, + min_trading_days=5, + min_mature_signals=5, + min_effective_signals=3.0, + is_replay=True, + ) + shadow_stage = sim_rep.final_stage.value + shadow_mature = sim_rep.final_decay_report.mature_signals + shadow_avg = sim_rep.final_decay_report.forward_avg_post_cost_return + shadow_verified = bool(sim_rep.chain_verified) + except Exception: + shadow_verified = False + all_chains_verified = all_chains_verified and shadow_verified + + equity_curve = self.compute_equity_curve( + champ_outcome.backtest_result.signals, evolution_market ) - ) + trade_replays = self.build_trade_replays( + champ_outcome.backtest_result.signals, evolution_market + ) + champ_score = float(champ_eval.confidence_score) + + entries.append( + ArenaStrategyEntry( + strategy_id=base_strat.meta.id, + champion_id=champion.meta.id, + name=champion.meta.name, + category=champion.meta.category.value, + market=champion.meta.market.value, + baseline_score=round(baseline_score, 4), + champion_score=round(champ_score, 4), + score_delta=round(champ_score - baseline_score, 4), + win_rate=round(float(ov.win_rate), 4), + avg_return=round(float(ov.avg_return), 6), + total_return=round(float(ov.total_return), 6), + sharpe_ratio=round(float(ov.sharpe_ratio), 4), + max_drawdown=round(float(ov.max_drawdown), 4), + signal_count=int(ov.signal_count), + dsr_prob=round(float(champ_eval.deflated_sharpe_prob or 0.0), 4), + null_passed=bool(champ_eval.null_control_passed), + promotions=rsi_res.promotions, + vetoes=veto_count, + trials_recorded=rsi_res.total_trials_recorded, + shadow_stage=shadow_stage, + shadow_mature_signals=shadow_mature, + shadow_avg_return=round(float(shadow_avg), 6), + shadow_chain_verified=shadow_verified, + equity_curve=equity_curve, + evolution_nodes=nodes, + deliberations=[d.model_dump(mode="json") for d in rsi_res.deliberations], + veto_breakdown=dict(rsi_res.veto_breakdown), + map_elites_cells=[ + { + "regime_bucket": cell.niche.regime_bucket, + "style_bucket": cell.niche.style_bucket, + "horizon_bucket": cell.niche.horizon_bucket, + "strategy_id": cell.strategy_id, + "fitness_score": round(float(cell.fitness_score), 4), + } + for cell in rsi_res.archive_summary.cells + ], + synthesized_factors=list(rsi_res.persisted_factors), + crossovers_kept=int(rsi_res.crossovers_kept), + trade_replays=trade_replays, + committee_verdicts=verdicts_json, + champion_yaml=champ_yaml, + baseline_yaml=base_yaml, + yaml_diff=diff_lines[:80], + ) + ) + finally: + rsi_engine.close() entries.sort(key=lambda e: (e.champion_score, e.sharpe_ratio), reverse=True) @@ -534,7 +564,7 @@ def run( try: alloc_report = RegimeAdaptiveAllocator().allocate( champions, - market_data, + evolution_market, backtest_config=self._bt_config, ) latest_weights = ( @@ -564,11 +594,12 @@ def run( "pit_unsafe": 0, } try: - gov_rep = FactorGovernanceEngine(db_path=self._db_path).audit_factors( - market_data, - strategies=champions, - auto_retire=False, - ) + with FactorGovernanceEngine(db_path=self._db_path) as gov_engine: + gov_rep = gov_engine.audit_factors( + market_data, + strategies=champions, + auto_retire=False, + ) gov_summary = { "total_audited": gov_rep.total_audited, "healthy": gov_rep.healthy_count, diff --git a/src/alphaevo/reflection/experience.py b/src/alphaevo/reflection/experience.py index 2db4705..50ff72f 100644 --- a/src/alphaevo/reflection/experience.py +++ b/src/alphaevo/reflection/experience.py @@ -11,6 +11,8 @@ import json import logging import sqlite3 +import threading +from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -108,9 +110,12 @@ class ExperienceStore: def __init__(self, db_path: str | Path = "~/.alphaevo/alphaevo.db") -> None: normalized_path, use_memory = _normalize_db_path(db_path) self._is_memory = use_memory + self._lock = threading.RLock() if self._is_memory: self._db_path = ":memory:" - self._shared_conn: sqlite3.Connection | None = sqlite3.connect(":memory:") + self._shared_conn: sqlite3.Connection | None = sqlite3.connect( + ":memory:", check_same_thread=False + ) self._shared_conn.execute("PRAGMA foreign_keys=ON") else: self._db_path = normalized_path @@ -494,13 +499,47 @@ def _row_to_record(self, row: tuple) -> ExperienceRecord: score_metric=str(row[21]) if len(row) > 21 and row[21] else "confidence_score", ) - def _connect(self) -> sqlite3.Connection: - if self._shared_conn is not None: - return self._shared_conn - conn = sqlite3.connect(self._db_path) - conn.execute("PRAGMA journal_mode=WAL") - conn.execute("PRAGMA foreign_keys=ON") - return conn + def close(self) -> None: + """Close persistent in-memory SQLite connection if open.""" + lock = getattr(self, "_lock", None) + if lock is None: + lock = threading.RLock() + self._lock = lock + with lock: + conn = getattr(self, "_shared_conn", None) + if conn is not None: + conn.close() + self._shared_conn = None + + def __enter__(self) -> ExperienceStore: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + @contextlib.contextmanager + def _connect(self) -> Iterator[sqlite3.Connection]: + shared_conn = getattr(self, "_shared_conn", None) + if shared_conn is not None: + lock = getattr(self, "_lock", None) + if lock is None: + lock = threading.RLock() + self._lock = lock + with lock: + if getattr(self, "_shared_conn", None) is None: + raise RuntimeError("ExperienceStore connection is closed") + with shared_conn: + yield shared_conn + return + conn = sqlite3.connect(self._db_path, timeout=30.0) + try: + conn.execute("PRAGMA busy_timeout=5000") + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA foreign_keys=ON") + with conn: + yield conn + finally: + conn.close() def _fuzzy_signature( diff --git a/src/alphaevo/reflection/mutator.py b/src/alphaevo/reflection/mutator.py index 83b677f..3ae1f07 100644 --- a/src/alphaevo/reflection/mutator.py +++ b/src/alphaevo/reflection/mutator.py @@ -82,6 +82,9 @@ def mutate( if not applied: raise MutationError("No changes could be applied") + if any(c.change_type == ChangeType.ADJUST_EXIT for c in applied): + prune_dangling_exit_tunables(new) + # Enforce complexity limit on total entry trigger/filter rules. n_conditions = _entry_rule_count(new) if n_conditions > self.complexity_limit: @@ -131,6 +134,46 @@ def _loosen_filter(strategy: Strategy, change: StrategyChange) -> None: _update_condition_value(strategy, change) +def promote_legacy_conditions_to_triggers( + strategy: Strategy, + new_trigger: StrategyCondition, +) -> None: + """Promote legacy entry.conditions into entry.triggers (+ guards for multi-AND) and retarget tunables.""" + if strategy.entry.logic == "and" and len(strategy.entry.conditions) >= 2: + orig_conds = list(strategy.entry.conditions) + guard_offset = len(strategy.entry.guards) + promoted_first = orig_conds[0] + moved_guards = orig_conds[1:] + strategy.entry.triggers = [promoted_first, new_trigger] + strategy.entry.guards.extend(moved_guards) + strategy.entry.conditions = [] + first_ind = promoted_first.indicator + for param in strategy.params.tunable: + if not param.target.startswith("entry.conditions["): + continue + m = re.match(r"^entry\.conditions\[(\d+)\](.*)$", param.target) + if m is not None: + idx = int(m.group(1)) + suffix = m.group(2) + if idx == 0: + param.target = f"entry.triggers[0]{suffix}" + elif 1 <= idx < len(orig_conds): + param.target = f"entry.guards[{guard_offset + idx - 1}]{suffix}" + else: + replacement_bucket = ( + "entry.triggers[" + if f"[indicator={first_ind}]" in param.target + else "entry.guards[" + ) + param.target = param.target.replace("entry.conditions[", replacement_bucket, 1) + else: + strategy.entry.triggers = [*strategy.entry.conditions, new_trigger] + strategy.entry.conditions = [] + for param in strategy.params.tunable: + if param.target.startswith("entry.conditions["): + param.target = param.target.replace("entry.conditions[", "entry.triggers[", 1) + + def _add_condition(strategy: Strategy, change: StrategyChange) -> None: """Add a new entry condition.""" if not isinstance(change.to_value, dict): @@ -147,9 +190,40 @@ def _add_condition(strategy: Strategy, change: StrategyChange) -> None: f"Available: {IndicatorRegistry.available()}" ) + if ( + change.target.startswith("entry.triggers") + and not strategy.entry.triggers + and strategy.entry.conditions + ): + promote_legacy_conditions_to_triggers(strategy, new_cond) + return + _entry_bucket(strategy, change.target).append(new_cond) +def prune_dangling_exit_tunables(strategy: Strategy) -> None: + """Drop tunable targets referencing exit fields no longer active after exit changes.""" + sl = strategy.exit.stop_loss + tp = strategy.exit.take_profit + kept = [] + for param in strategy.params.tunable: + tgt = param.target.strip() + if tgt == "exit.stop_loss.value" and sl.value is None: + continue + if tgt in {"exit.stop_loss.multiplier", "exit.stop_loss.atr_period"} and (sl.type != "atr"): + continue + if tgt == "exit.take_profit.value" and tp.value is None: + continue + if tgt == "exit.take_profit.target" and tp.type != "target_ma": + continue + if tgt in {"exit.take_profit.trigger_pct", "exit.take_profit.trail_pct"} and ( + tp.type != "trailing" + ): + continue + kept.append(param) + strategy.params.tunable = kept + + def _remove_condition(strategy: Strategy, change: StrategyChange) -> None: """Remove an entry condition by indicator name.""" indicator = change.target.split("indicator=")[-1].split("]")[0].strip() @@ -173,9 +247,30 @@ def _remove_condition(strategy: Strategy, change: StrategyChange) -> None: def _adjust_exit(strategy: Strategy, change: StrategyChange) -> None: """Modify exit parameters (stop loss, take profit, max holding days).""" target = change.target - val = _sanitize_condition_value(change.to_value) - if "stop_loss.value" in target and val is not None: - strategy.exit.stop_loss.value = float(val) + raw_val = change.to_value + if "stop_loss.conditions" in target: + if raw_val is None: + strategy.exit.stop_loss.conditions = None + elif isinstance(raw_val, list): + strategy.exit.stop_loss.conditions = [ + c if isinstance(c, StrategyCondition) else StrategyCondition(**c) for c in raw_val + ] + else: + raise MutationError(f"Invalid stop_loss.conditions value: {raw_val}") + return + if "exit.triggers" in target or target == "triggers": + if raw_val is None: + strategy.exit.triggers = [] + elif isinstance(raw_val, list): + strategy.exit.triggers = [ + c if isinstance(c, StrategyCondition) else StrategyCondition(**c) for c in raw_val + ] + else: + raise MutationError(f"Invalid exit.triggers value: {raw_val}") + return + val = _sanitize_condition_value(raw_val) + if "stop_loss.value" in target: + strategy.exit.stop_loss.value = None if val is None else float(val) elif "stop_loss.type" in target and val is not None: new_type = str(val) strategy.exit.stop_loss.type = new_type @@ -198,18 +293,25 @@ def _adjust_exit(strategy: Strategy, change: StrategyChange) -> None: strategy.exit.stop_loss.atr_period = None strategy.exit.stop_loss.reference = None strategy.exit.stop_loss.conditions = None - elif "stop_loss.reference" in target and val is not None: - strategy.exit.stop_loss.reference = str(val) - elif "stop_loss.multiplier" in target and val is not None: - strategy.exit.stop_loss.multiplier = float(val) - elif "stop_loss.atr_period" in target and val is not None: - if not set_tunable_target(strategy, target, val): + elif "stop_loss.reference" in target: + strategy.exit.stop_loss.reference = None if val is None else str(val) + elif "stop_loss.multiplier" in target: + strategy.exit.stop_loss.multiplier = None if val is None else float(val) + elif "stop_loss.atr_period" in target: + if val is None: + strategy.exit.stop_loss.atr_period = None + elif not set_tunable_target(strategy, target, val): raise MutationError(f"Invalid stop_loss.atr_period update: {change.target}") - elif "take_profit.value" in target and val is not None: - strategy.exit.take_profit.value = float(val) - elif "take_profit.target" in target and val is not None: - if not set_tunable_target(strategy, target, val): - raise MutationError(f"Invalid take_profit.target update: {change.target}") + elif "take_profit.value" in target: + strategy.exit.take_profit.value = None if val is None else float(val) + elif "take_profit.target" in target: + if val is None: + strategy.exit.take_profit.target = None + elif not set_tunable_target(strategy, target, val): + if isinstance(val, str) and val.strip(): + strategy.exit.take_profit.target = val.strip() + else: + raise MutationError(f"Invalid take_profit.target update: {change.target}") elif "take_profit.type" in target and val is not None: new_type = str(val) strategy.exit.take_profit.type = new_type @@ -224,10 +326,10 @@ def _adjust_exit(strategy: Strategy, change: StrategyChange) -> None: strategy.exit.take_profit.target = None strategy.exit.take_profit.trigger_pct = None strategy.exit.take_profit.trail_pct = None - elif "take_profit.trigger_pct" in target and val is not None: - strategy.exit.take_profit.trigger_pct = float(val) - elif "take_profit.trail_pct" in target and val is not None: - strategy.exit.take_profit.trail_pct = float(val) + elif "take_profit.trigger_pct" in target: + strategy.exit.take_profit.trigger_pct = None if val is None else float(val) + elif "take_profit.trail_pct" in target: + strategy.exit.take_profit.trail_pct = None if val is None else float(val) elif "max_holding_days" in target and val is not None: strategy.exit.max_holding_days = int(val) else: diff --git a/src/alphaevo/rsi/co_steer.py b/src/alphaevo/rsi/co_steer.py index 48d24c4..0dba1a0 100644 --- a/src/alphaevo/rsi/co_steer.py +++ b/src/alphaevo/rsi/co_steer.py @@ -7,6 +7,7 @@ import inspect import json import math +import threading import uuid from datetime import datetime, timezone from pathlib import Path @@ -19,13 +20,78 @@ import pandas as pd # type: ignore[import-untyped] from alphaevo.alpha_factory.factor_store import FactorRecord, FactorStore -from alphaevo.alpha_factory.factory import _build_indicator_fn +from alphaevo.alpha_factory.factory import _build_indicator_fn, register_factor_record from alphaevo.alpha_factory.sandbox import FactorSandbox from alphaevo.backtest.indicators import IndicatorFn, IndicatorRegistry from alphaevo.models.enums import ChangeType, EvidenceLevel, ExitReason, RSILevel from alphaevo.models.execution import EvaluationReport, StrategyChange from alphaevo.models.strategy import Strategy +_DYNAMIC_LEASE_LOCK = threading.RLock() +_DYNAMIC_LEASES: dict[str, int] = {} +_TRANSIENT_FACTORS: set[str] = set() + + +def _uses_indicator(strategy: Strategy, indicator_name: str) -> bool: + conds = ( + strategy.entry.triggers + + strategy.entry.conditions + + strategy.entry.guards + + strategy.entry.filters + + strategy.exit.triggers + ) + stop_conds = getattr(strategy.exit.stop_loss, "conditions", None) or [] + return any(getattr(cond, "indicator", None) == indicator_name for cond in [*conds, *stop_conds]) + + +def acquire_dynamic_lease( + factor_name: str | None, + *, + in_pre_registered: bool, + factor_record: Any | None, + factor_store: FactorStore, +) -> str | None: + """Acquire a refcounted lease for a transient L2 dynamic factor across concurrent runs.""" + if not factor_name: + return None + with _DYNAMIC_LEASE_LOCK: + is_transient = factor_name in _TRANSIENT_FACTORS + if not in_pre_registered and not is_transient and factor_store.get(factor_name) is None: + _TRANSIENT_FACTORS.add(factor_name) + is_transient = True + if not is_transient: + return None + if not IndicatorRegistry.is_registered(factor_name) and factor_record is not None: + register_factor_record(factor_record) + _DYNAMIC_LEASES[factor_name] = _DYNAMIC_LEASES.get(factor_name, 0) + 1 + return factor_name + + +def release_dynamic_lease( + factor_name: str | None, + *, + persisted: bool, + protected_strategies: tuple[Strategy, ...], +) -> None: + """Release one dynamic factor lease and unregister only when zero transient leases remain.""" + if not factor_name: + return + with _DYNAMIC_LEASE_LOCK: + if persisted: + _TRANSIENT_FACTORS.discard(factor_name) + rem = _DYNAMIC_LEASES.get(factor_name, 1) - 1 + if rem > 0: + _DYNAMIC_LEASES[factor_name] = rem + return + _DYNAMIC_LEASES.pop(factor_name, None) + if persisted or factor_name not in _TRANSIENT_FACTORS: + return + _TRANSIENT_FACTORS.discard(factor_name) + if any(_uses_indicator(s, factor_name) for s in protected_strategies): + return + IndicatorRegistry.unregister_dynamic(factor_name) + + FailureClusterId = Literal[ "zero_signal_lockout", "whipsaw_stopout_in_chop", @@ -54,6 +120,8 @@ class CoSteerDecision(BaseModel): synthesized_via: Literal["llm", "offline_template"] | None = None pit_verified: bool = False persisted_to_store: bool = False + lease_acquired: bool = False + synthesized_factor_record: FactorRecord | None = None proposed_changes: list[StrategyChange] = Field(default_factory=list) @@ -64,6 +132,7 @@ class OfflineFactorTemplate(BaseModel): description: str op: Literal["<", "<=", ">", ">="] threshold: float + expected_direction: Literal["positive", "negative"] = "positive" code: str @@ -73,6 +142,7 @@ class OfflineFactorTemplate(BaseModel): description="10-day relative range compression ratio (smaller = calmer base before rebound)", op="<=", threshold=1.15, + expected_direction="negative", code=""" import numpy as np @@ -150,6 +220,7 @@ def compute(df, idx): description="10-day downside vs total return volatility ratio filtering asymmetric panic bars", op="<=", threshold=0.78, + expected_direction="negative", code=""" import numpy as np @@ -190,6 +261,7 @@ def compute(df, idx): description="5-day vs 14-day true-range expansion ratio filtering parabolic exhaustion spikes", op="<=", threshold=1.35, + expected_direction="negative", code=""" import numpy as np @@ -386,6 +458,7 @@ def __init__( synthesizer: Any | None = None, ) -> None: self._sandbox = sandbox or FactorSandbox(timeout_seconds=10) + self._owns_sandbox = sandbox is None self._factor_store = factor_store # Transient LLM synthesizer settings only; never persisted or logged. self._llm_model = (llm_model or "").strip() or None @@ -394,6 +467,17 @@ def __init__( self._pit_cache: dict[str, bool] = {} self._failed_llm_factors: set[str] = set() + def close(self) -> None: + """Close owned sandbox worker resources if created by this miner.""" + if self._owns_sandbox: + self._sandbox.close() + + def __enter__(self) -> BlindSpotMiner: + return self + + def __exit__(self, *args: object) -> None: + self.close() + def _calibrate_causal_threshold( self, code: str, @@ -438,7 +522,10 @@ def _try_llm_synthesize( cluster: BlindSpotCluster, used_indicators: set[str], sample_df: pd.DataFrame, - ) -> tuple[str, str, str, Literal[">=", "<="], float, str] | None: + ) -> ( + tuple[str, str, str, Literal[">=", "<="], float, Literal["positive", "negative"], str] + | None + ): """Attempt PIT-verified LLM factor synthesis, returning None on any failure.""" synth = self._synthesizer if synth is None: @@ -492,6 +579,8 @@ def _try_llm_synthesize( or not fname.isidentifier() or fname in used_indicators or fname in self._failed_llm_factors + or IndicatorRegistry.is_registered(fname) + or (self._factor_store is not None and self._factor_store.get(fname) is not None) or not code ): if fname: @@ -516,7 +605,7 @@ def _try_llm_synthesize( continue op_val, thresh_val = calibrated - return fname, desc, code, op_val, thresh_val, "llm" + return fname, desc, code, op_val, thresh_val, direction, "llm" return None @@ -581,6 +670,8 @@ def steer( *, allowed_levels: list[RSILevel], stagnant_l1_rounds: int = 0, + persist: bool = True, + acquire_lease: bool = False, ) -> CoSteerDecision: """Decide L1 vs L2 step and synthesize/PIT-verify an L2 factor when escalating.""" cluster = self.diagnose_blind_spot( @@ -612,6 +703,8 @@ def steer( ) if should_try_l2 and sample_df is not None: + existing_dynamic_map = IndicatorRegistry._dynamic_registry + existing_dynamic = set(existing_dynamic_map.keys()) chosen: ( tuple[ str, @@ -619,10 +712,12 @@ def steer( str, Literal["<", "<=", ">", ">="], float, + Literal["positive", "negative"], Literal["llm", "offline_template"], ] | None ) = None + reused_stored_record: FactorRecord | None = None llm_candidate = self._try_llm_synthesize(cluster, used_indicators, sample_df) if llm_candidate is not None: chosen = ( @@ -631,46 +726,108 @@ def steer( llm_candidate[2], llm_candidate[3], llm_candidate[4], + llm_candidate[5], "llm", ) else: for template in _select_ordered_templates(cluster.cluster_id): + code_hash = hashlib.sha256(template.code.encode("utf-8")).hexdigest() if template.name in used_indicators: continue - code_hash = hashlib.sha256(template.code.encode("utf-8")).hexdigest() + if template.name in existing_dynamic: + existing_fn = existing_dynamic_map.get(template.name) + if getattr(existing_fn, "_alphaevo_factor_code_hash", None) != code_hash: + continue + elif IndicatorRegistry.is_registered(template.name): + continue + stored: FactorRecord | None = None + if self._factor_store is not None: + stored = self._factor_store.get(template.name) + if stored is not None and ( + stored.status != "active" or stored.code != template.code + ): + continue if code_hash not in self._pit_cache: self._pit_cache[code_hash] = self._sandbox.probe_pit( template.code, sample_df ).passed if not self._pit_cache[code_hash]: continue + reused_stored_record = stored chosen = ( template.name, template.description, template.code, template.op, template.threshold, + template.expected_direction, "offline_template", ) break if chosen is not None: - f_name, f_desc, f_code, f_op, f_thresh, via = chosen - IndicatorRegistry.register_dynamic( - f_name, - cast("IndicatorFn", _build_indicator_fn(f_code, self._sandbox)), - ) - persisted = False - if self._factor_store is not None: - self._factor_store.save( - FactorRecord( - name=f_name, - description=f_desc, - rationale=f"Co-STEER L2 ({cluster.cluster_id}, via={via}): {cluster.evidence}", - code=f_code, - status="active", + f_name, f_desc, f_code, f_op, f_thresh, f_dir, via = chosen + f_code_hash = hashlib.sha256(f_code.encode("utf-8")).hexdigest() + lease_acquired = False + with _DYNAMIC_LEASE_LOCK: + live_dynamic = IndicatorRegistry._dynamic_registry + if f_name in live_dynamic: + if ( + getattr(live_dynamic.get(f_name), "_alphaevo_factor_code_hash", None) + != f_code_hash + ): + return CoSteerDecision( + chosen_level=RSILevel.L1_STRATEGY, + cluster=cluster, + proposed_changes=[], + ) + else: + if ( + not persist + and reused_stored_record is None + and ( + self._factor_store is None or self._factor_store.get(f_name) is None + ) + ): + _TRANSIENT_FACTORS.add(f_name) + IndicatorRegistry.register_dynamic( + f_name, + cast("IndicatorFn", _build_indicator_fn(f_code, self._sandbox)), ) + if acquire_lease and not persist and f_name in _TRANSIENT_FACTORS: + _DYNAMIC_LEASES[f_name] = _DYNAMIC_LEASES.get(f_name, 0) + 1 + lease_acquired = True + factor_record = ( + reused_stored_record + if reused_stored_record is not None + else FactorRecord( + name=f_name, + description=f_desc, + rationale=f"Co-STEER L2 ({cluster.cluster_id}, via={via}): {cluster.evidence}", + code=f_code, + expected_direction=f_dir, + status="active", ) + ) + persisted = reused_stored_record is not None + if persist and self._factor_store is not None and reused_stored_record is None: + stored_rec, inserted = self._factor_store.save_if_absent(factor_record) + if not inserted and ( + stored_rec.status != "active" or stored_rec.code != factor_record.code + ): + with _DYNAMIC_LEASE_LOCK: + if ( + f_name not in existing_dynamic + and _DYNAMIC_LEASES.get(f_name, 0) == 0 + ): + _TRANSIENT_FACTORS.discard(f_name) + IndicatorRegistry.unregister_dynamic(f_name) + return CoSteerDecision( + chosen_level=RSILevel.L1_STRATEGY, + cluster=cluster, + proposed_changes=[], + ) + factor_record = stored_rec persisted = True if strategy.entry.triggers: target_field = "entry.guards" @@ -697,6 +854,8 @@ def steer( synthesized_via=via, pit_verified=True, persisted_to_store=persisted, + lease_acquired=lease_acquired, + synthesized_factor_record=factor_record, proposed_changes=[change], ) diff --git a/src/alphaevo/rsi/council.py b/src/alphaevo/rsi/council.py index 7cb2e6c..8f948c2 100644 --- a/src/alphaevo/rsi/council.py +++ b/src/alphaevo/rsi/council.py @@ -4,6 +4,7 @@ import json import logging +import os import subprocess from typing import Any, Literal @@ -320,6 +321,19 @@ def _run_prosecutor( objections: list[str] = [f"{c.target}: {reason}" for c, reason in verdict.rejected] approved = len(verdict.approved) == len(changes) + if ( + committee.overall_status == "fail" + and evaluation.anti_overfit.is_overfit + and any(c.change_type == ChangeType.ADD_CONDITION for c in changes) + and not any( + c.change_type in {ChangeType.REMOVE_CONDITION, ChangeType.LOOSEN_FILTER} + for c in changes + ) + ): + objections.append( + "committee: overall_status=fail blocks adding conditions to an overfit strategy" + ) + approved = False diag_ctx = _format_diagnostic_context( strategy, @@ -523,8 +537,13 @@ def _tunable_values( and not isinstance(cond_obj.value, bool) ): v_curr = float(cond_obj.value) - if cond_obj.op in {"<", "<="} and v_curr > 0: - v_nxt = round(v_curr * 1.45, 4) + if cond_obj.op in {"<", "<="}: + v_nxt = round( + v_curr * 1.45 + if v_curr > 0 + else (v_curr * 0.55 if v_curr < 0 else 0.1), + 4, + ) elif cond_obj.op in {">", ">="}: v_nxt = round(v_curr * 0.65 if v_curr > 0 else v_curr - 0.1, 4) else: @@ -949,10 +968,12 @@ def _try_cli_prosecutor( *, diag_ctx: str = "", ) -> list[str]: - """Optionally invoke adversarial CLI prosecutor; falls back cleanly on unavailability.""" + """Invoke configured adversarial CLI prosecutor and fail closed on unavailability or parse error.""" tool = q_spec.cli_tool if tool not in {"agy", "codex"}: - return [] + return [ + f"CLI prosecutor misconfigured (unsupported cli_tool={tool!r}); fail-closed veto" + ] change_desc = "; ".join(f"{c.change_type.value}:{c.target}->{c.to_value}" for c in changes) ctx_line = f"{diag_ctx}\n" if diag_ctx else "" prompt = ( @@ -975,18 +996,24 @@ def _try_cli_prosecutor( check=False, ) if proc.returncode != 0 or not proc.stdout.strip(): - return [] + return [ + f"CLI prosecutor ({tool}) returned exit={proc.returncode} with no output; fail-closed veto" + ] raw = proc.stdout.strip() start, end = raw.find("{"), raw.rfind("}") - if start != -1 and end > start: - parsed: dict[str, Any] = json.loads(raw[start : end + 1]) - if parsed.get("veto") is True: - return [str(parsed.get("reason", "Vetoed by CLI Prosecutor"))] + if start == -1 or end <= start: + return [f"CLI prosecutor ({tool}) returned non-JSON output; fail-closed veto"] + parsed = json.loads(raw[start : end + 1]) + if not isinstance(parsed, dict) or not isinstance(parsed.get("veto"), bool): + return [ + f"CLI prosecutor ({tool}) response missing boolean 'veto'; fail-closed veto" + ] + if parsed["veto"] is True: + return [str(parsed.get("reason", "Vetoed by CLI Prosecutor"))] + return [] except Exception as exc: - logger.debug( - "CLI prosecutor %s unavailable (%s); using deterministic critic", tool, exc - ) - return [] + logger.debug("CLI prosecutor %s failed (%s); failing closed", tool, exc) + return [f"CLI prosecutor ({tool}) unavailable ({exc}); fail-closed veto"] def _try_litellm_prosecutor( self, @@ -997,16 +1024,21 @@ def _try_litellm_prosecutor( *, diag_ctx: str = "", ) -> list[str]: - """Optionally invoke LiteLLM prosecutor; falls back cleanly when unconfigured.""" + """Invoke LiteLLM prosecutor when configured and fail closed on API/parse failure.""" + api_key_resolved = bool( + (self._api_key or "").strip() or os.environ.get("ALPHAEVO_API_KEY", "").strip() + ) try: from alphaevo.core.config import ConfigManager from alphaevo.core.llm import LLMClient - cfg = ConfigManager().load() - cfg.llm.model = q_spec.model - api_key = self._api_key or ConfigManager().get_llm_api_key() + cfg_mgr = ConfigManager() + api_key = (self._api_key or "").strip() or (cfg_mgr.get_llm_api_key() or "").strip() if not api_key: return [] + api_key_resolved = True + cfg = cfg_mgr.load() + cfg.llm.model = q_spec.model llm = LLMClient(cfg.llm, api_key=api_key) change_desc = "; ".join( f"{c.change_type.value}:{c.target}->{c.to_value}" for c in changes @@ -1024,11 +1056,19 @@ def _try_litellm_prosecutor( model=q_spec.model, timeout=q_spec.timeout_seconds, ) - if parsed.get("veto") is True: + if not isinstance(parsed, dict) or not isinstance(parsed.get("veto"), bool): + return [ + f"LiteLLM prosecutor ({q_spec.model}) returned malformed verdict; fail-closed veto" + ] + if parsed["veto"] is True: return [str(parsed.get("reason", "Vetoed by LiteLLM Prosecutor"))] + return [] except Exception as exc: + if api_key_resolved: + logger.debug("LiteLLM prosecutor failed (%s); failing closed", exc) + return [f"LiteLLM prosecutor ({q_spec.model}) failed ({exc}); fail-closed veto"] logger.debug("LiteLLM prosecutor fallback to deterministic critic: %s", exc) - return [] + return [] __all__ = [ diff --git a/src/alphaevo/rsi/crossover.py b/src/alphaevo/rsi/crossover.py index d58dd8c..eafc82a 100644 --- a/src/alphaevo/rsi/crossover.py +++ b/src/alphaevo/rsi/crossover.py @@ -11,6 +11,10 @@ from alphaevo.models.enums import ChangeType from alphaevo.models.execution import StrategyChange from alphaevo.models.strategy import Strategy, StrategyCondition +from alphaevo.reflection.mutator import ( + promote_legacy_conditions_to_triggers, + prune_dangling_exit_tunables, +) CrossoverOperator = Literal["exit_graft", "filter_graft", "trigger_blend"] @@ -59,13 +63,20 @@ def _canonical_hash(strategy: Strategy) -> str: payload = strategy.model_dump(mode="json", exclude={"meta", "complexity_score"}) return json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + @staticmethod + def _prune_dangling_exit_tunables(strategy: Strategy) -> None: + """Drop tunable targets referencing exit fields no longer active after exit grafting.""" + prune_dangling_exit_tunables(strategy) + @staticmethod def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[StrategyChange]: """Build StrategyMutator-compatible exit change descriptors for Prosecutor/Critic.""" changes: list[StrategyChange] = [] p_sl, s_sl = primary.exit.stop_loss, secondary.exit.stop_loss p_tp, s_tp = primary.exit.take_profit, secondary.exit.take_profit - if s_sl.type != p_sl.type: + sl_type_changed = s_sl.type != p_sl.type + tp_type_changed = s_tp.type != p_tp.type + if sl_type_changed: changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -75,7 +86,7 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover stop_loss.type from {secondary.meta.id}", ) ) - if s_sl.value is not None and s_sl.value != p_sl.value: + if s_sl.value != p_sl.value or (sl_type_changed and s_sl.value is not None): changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -85,7 +96,7 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover stop_loss.value from {secondary.meta.id}", ) ) - if s_sl.multiplier is not None and s_sl.multiplier != p_sl.multiplier: + if s_sl.multiplier != p_sl.multiplier or (sl_type_changed and s_sl.multiplier is not None): changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -95,7 +106,45 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover stop_loss.multiplier from {secondary.meta.id}", ) ) - if s_tp.type != p_tp.type: + if s_sl.atr_period != p_sl.atr_period or (sl_type_changed and s_sl.atr_period is not None): + changes.append( + StrategyChange( + change_type=ChangeType.ADJUST_EXIT, + target="exit.stop_loss.atr_period", + from_value=p_sl.atr_period, + to_value=s_sl.atr_period, + reason=f"Crossover stop_loss.atr_period from {secondary.meta.id}", + ) + ) + if s_sl.reference != p_sl.reference or (sl_type_changed and s_sl.reference is not None): + changes.append( + StrategyChange( + change_type=ChangeType.ADJUST_EXIT, + target="exit.stop_loss.reference", + from_value=p_sl.reference, + to_value=s_sl.reference, + reason=f"Crossover stop_loss.reference from {secondary.meta.id}", + ) + ) + if s_sl.conditions != p_sl.conditions or (sl_type_changed and s_sl.conditions is not None): + changes.append( + StrategyChange( + change_type=ChangeType.ADJUST_EXIT, + target="exit.stop_loss.conditions", + from_value=( + None + if p_sl.conditions is None + else [c.model_dump(mode="json") for c in p_sl.conditions] + ), + to_value=( + None + if s_sl.conditions is None + else [c.model_dump(mode="json") for c in s_sl.conditions] + ), + reason=f"Crossover stop_loss.conditions from {secondary.meta.id}", + ) + ) + if tp_type_changed: changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -105,7 +154,7 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover take_profit.type from {secondary.meta.id}", ) ) - if s_tp.value is not None and s_tp.value != p_tp.value: + if s_tp.value != p_tp.value or (tp_type_changed and s_tp.value is not None): changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -115,7 +164,19 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover take_profit.value from {secondary.meta.id}", ) ) - if s_tp.trigger_pct is not None and s_tp.trigger_pct != p_tp.trigger_pct: + if s_tp.target != p_tp.target or (tp_type_changed and s_tp.target is not None): + changes.append( + StrategyChange( + change_type=ChangeType.ADJUST_EXIT, + target="exit.take_profit.target", + from_value=p_tp.target, + to_value=s_tp.target, + reason=f"Crossover take_profit.target from {secondary.meta.id}", + ) + ) + if s_tp.trigger_pct != p_tp.trigger_pct or ( + tp_type_changed and s_tp.trigger_pct is not None + ): changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -125,7 +186,7 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover take_profit.trigger_pct from {secondary.meta.id}", ) ) - if s_tp.trail_pct is not None and s_tp.trail_pct != p_tp.trail_pct: + if s_tp.trail_pct != p_tp.trail_pct or (tp_type_changed and s_tp.trail_pct is not None): changes.append( StrategyChange( change_type=ChangeType.ADJUST_EXIT, @@ -135,6 +196,16 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover take_profit.trail_pct from {secondary.meta.id}", ) ) + if secondary.exit.triggers != primary.exit.triggers: + changes.append( + StrategyChange( + change_type=ChangeType.ADJUST_EXIT, + target="exit.triggers", + from_value=[c.model_dump(mode="json") for c in primary.exit.triggers], + to_value=[c.model_dump(mode="json") for c in secondary.exit.triggers], + reason=f"Crossover exit.triggers from {secondary.meta.id}", + ) + ) if secondary.exit.max_holding_days != primary.exit.max_holding_days: changes.append( StrategyChange( @@ -155,7 +226,7 @@ def _summarize_exit_changes(primary: Strategy, secondary: Strategy) -> list[Stra reason=f"Crossover exit structure from {secondary.meta.id}", ) ) - return changes[:3] + return changes @staticmethod def _filter_target_bucket(primary: Strategy) -> tuple[str, list[StrategyCondition]]: @@ -211,6 +282,7 @@ def _try_accept( if secondary.exit.model_dump(mode="json") != primary.exit.model_dump(mode="json"): child_exit = primary.model_copy(deep=True) child_exit.exit = secondary.exit.model_copy(deep=True) + self._prune_dangling_exit_tunables(child_exit) _try_accept( child_exit, "exit_graft", @@ -263,13 +335,21 @@ def _try_accept( if donor_trigs: blend_cond = donor_trigs[0].model_copy(deep=True) child_blend = primary.model_copy(deep=True) + prev_logic = child_blend.entry.logic if child_blend.entry.triggers: trig_target = "entry.triggers" child_blend.entry.triggers.append(blend_cond) + elif ( + not child_blend.entry.triggers + and prev_logic == "and" + and len(child_blend.entry.conditions) >= 2 + ): + # Preserve conjunctive legacy AND filters by migrating extras into entry.guards. + trig_target = "entry.triggers" + promote_legacy_conditions_to_triggers(child_blend, blend_cond) else: trig_target = "entry.conditions" child_blend.entry.conditions.append(blend_cond) - prev_logic = child_blend.entry.logic child_blend.entry.logic = "or" changes_blend = [ StrategyChange( diff --git a/src/alphaevo/rsi/engine.py b/src/alphaevo/rsi/engine.py index 34ff2f9..757e870 100644 --- a/src/alphaevo/rsi/engine.py +++ b/src/alphaevo/rsi/engine.py @@ -17,6 +17,7 @@ load_registered_factors, register_factor_record, ) +from alphaevo.backtest.indicators import IndicatorRegistry from alphaevo.core.config import BacktestConfig from alphaevo.evaluator.metrics import Evaluator from alphaevo.models.enums import EvidenceLevel, RSILevel @@ -25,7 +26,16 @@ from alphaevo.reflection.critic import SelfCritic from alphaevo.reflection.experience import ExperienceRecord, ExperienceStore from alphaevo.reflection.mutator import StrategyMutator -from alphaevo.rsi.co_steer import BlindSpotMiner, ScarRegistry +from alphaevo.rsi.co_steer import ( + BlindSpotMiner, + ScarRegistry, +) +from alphaevo.rsi.co_steer import ( + acquire_dynamic_lease as _acquire_dynamic_lease, +) +from alphaevo.rsi.co_steer import ( + release_dynamic_lease as _release_dynamic_lease_entry, +) from alphaevo.rsi.council import HeterogeneousCouncil from alphaevo.rsi.crossover import SemanticCrossoverBreeder from alphaevo.rsi.diagnostics import analyze_entry_bottlenecks @@ -225,6 +235,45 @@ def _structural_strategy_hash(strategy: Strategy) -> str: return hashlib.sha256(canonical.encode("utf-8")).hexdigest() +def _strategy_uses_indicator(strategy: Strategy, indicator_name: str) -> bool: + """Return True if *indicator_name* appears in any entry or exit condition.""" + conds = ( + strategy.entry.triggers + + strategy.entry.conditions + + strategy.entry.guards + + strategy.entry.filters + + strategy.exit.triggers + ) + stop_conds = getattr(strategy.exit.stop_loss, "conditions", None) or [] + return any(getattr(cond, "indicator", None) == indicator_name for cond in [*conds, *stop_conds]) + + +def _passes_base_l0_gates( + cand_fit: float, + verified_champion_fitness: float, + cand_eval: EvaluationReport, + cand_outcome: KernelEvaluationOutcome, + cfg: RSICharter, + dsr_prob: float, +) -> bool: + """Evaluate all deterministic L0 promotion gates except optional rerun-null worlds.""" + return ( + cand_fit > verified_champion_fitness + 1e-4 + and cand_eval.overall.avg_return > 0.0 + and cand_eval.overall.max_drawdown <= cfg.max_drawdown + and not cand_eval.anti_overfit.is_overfit + and cand_eval.overall.signal_count >= cfg.min_signals + and dsr_prob >= cfg.min_dsr_prob + and (not cfg.require_null_control or cand_eval.null_control_passed is True) + and ( + not cfg.require_portfolio_gate + or ( + cand_outcome.portfolio_verdict is not None and cand_outcome.portfolio_verdict.passed + ) + ) + ) + + class StockRSIEngine: """Self-improving stock strategy/factor loop guarded by L0 Truth & MAP-Elites.""" @@ -280,6 +329,21 @@ def __init__( min_data_days=15, ) + def close(self) -> None: + """Close backing stores and L2 sandbox worker resources.""" + self._experience_store.close() + self._factor_store.close() + self._miner.close() + close_fn = getattr(self._trial_ledger, "close", None) + if callable(close_fn): + close_fn() + + def __enter__(self) -> StockRSIEngine: + return self + + def __exit__(self, *args: object) -> None: + self.close() + def run( self, seed_strategy: Strategy, @@ -295,6 +359,40 @@ def run( on_event: Callable[[dict[str, Any]], None] | None = None, ) -> RSIRunResult: """Execute a bounded L1/L2 RSI evolution session and persist traceable outputs.""" + active_leases: list[Callable[[], None]] = [] + try: + return self._run_impl( + seed_strategy, + market_data, + charter=charter, + output_dir=output_dir, + seed=seed, + persist_champion=persist_champion, + shadow_ledger=shadow_ledger, + auto_enroll_shadow=auto_enroll_shadow, + artifact_store=artifact_store, + on_event=on_event, + _active_leases=active_leases, + ) + finally: + while active_leases: + active_leases.pop()() + + def _run_impl( + self, + seed_strategy: Strategy, + market_data: dict[str, pd.DataFrame], + *, + charter: RSICharter | None = None, + output_dir: Path | None = None, + seed: int = 42, + persist_champion: bool = True, + shadow_ledger: ShadowLedger | None = None, + auto_enroll_shadow: bool = False, + artifact_store: RunArtifactStore | None = None, + on_event: Callable[[dict[str, Any]], None] | None = None, + _active_leases: list[Callable[[], None]] | None = None, + ) -> RSIRunResult: def _emit(payload: dict[str, Any]) -> None: if on_event is None: @@ -308,15 +406,11 @@ def _emit(payload: dict[str, Any]) -> None: vault: LockedHoldoutVault | None = None search_market = market_data if cfg.locked_holdout_pct > 0.0: - try: - vault, _split = split_market_data_with_holdout( - market_data, - holdout_pct=cfg.locked_holdout_pct, - ) - search_market = vault.search_data - except ValueError: - vault = None - search_market = market_data + vault, _split = split_market_data_with_holdout( + market_data, + holdout_pct=cfg.locked_holdout_pct, + ) + search_market = vault.search_data family_id = self._trial_ledger.resolve_trial_family_id(seed_strategy) sample_df = next( @@ -418,22 +512,56 @@ def _bump_veto(reasons: list[str]) -> None: parent_strategy = elite.strategy parent_eval = elite.evaluation + pre_registered = set(IndicatorRegistry.available()) | set( + IndicatorRegistry.dynamic_names() + ) steer = self._miner.steer( parent_strategy, parent_eval, sample_df, allowed_levels=cfg.allowed_levels, stagnant_l1_rounds=stagnant_l1, + persist=False, + acquire_lease=True, ) + if getattr(steer, "lease_acquired", False): + new_dynamic_factor = steer.synthesized_factor_name + else: + new_dynamic_factor = _acquire_dynamic_lease( + steer.synthesized_factor_name, + in_pre_registered=( + steer.synthesized_factor_name in pre_registered + if steer.synthesized_factor_name is not None + else False + ), + factor_record=steer.synthesized_factor_record, + factor_store=self._factor_store, + ) + lease_released = False + + def _cleanup_unused_dynamic( + *, + persisted: bool = False, + cand_name: str | None = new_dynamic_factor, + cur_work: Strategy = working_strategy, + cur_champ: Strategy = verified_champion_strategy, + ) -> None: + nonlocal lease_released + if lease_released: + return + lease_released = True + _release_dynamic_lease_entry( + cand_name, + persisted=persisted, + protected_strategies=(cur_work, cur_champ), + ) + + if _active_leases is not None: + _active_leases.append(_cleanup_unused_dynamic) + bottleneck = analyze_entry_bottlenecks(parent_strategy, search_market) if bottleneck.diagnosis_summary: steer.cluster.bottleneck_hint = bottleneck.diagnosis_summary - if ( - steer.persisted_to_store - and steer.synthesized_factor_name - and steer.synthesized_factor_name not in persisted_factors - ): - persisted_factors.append(steer.synthesized_factor_name) parent_tried = tried_by_parent.setdefault(parent_strategy.meta.id, set()) raw_deliberations = self._council.generate_candidates( @@ -565,6 +693,7 @@ def _bump_veto(reasons: list[str]) -> None: ) if not approved: + _cleanup_unused_dynamic() veto_row = RSIRoundRow( round_num=rnd, strategy_id=parent_strategy.meta.id, @@ -593,7 +722,7 @@ def _bump_veto(reasons: list[str]) -> None: stagnant_l1 += 1 continue - best_cand_bundle: ( + evaluated_bundles: list[ tuple[ Strategy, KernelEvaluationOutcome, @@ -601,9 +730,10 @@ def _bump_veto(reasons: list[str]) -> None: list[StrategyChange], RSILevel, DeliberationRecord, + float, + bool, ] - | None - ) = None + ] = [] round_approved_records: list[DeliberationRecord] = [] for p_model, p_fam, p_rat, changes, aud, prebuilt_strat, sec_parent in approved: @@ -708,8 +838,6 @@ def _bump_veto(reasons: list[str]) -> None: deliberations.append(cand_rec) round_approved_records.append(cand_rec) - archive.insert(cand_strategy, cand_eval, cand_fit) - if self._enable_pinned_scars and ( (working_eval.overall.signal_count > 0 and cand_eval.overall.signal_count == 0) or (cand_fit - working_fitness) < -0.08 @@ -749,18 +877,30 @@ def _bump_veto(reasons: list[str]) -> None: ) ) - if best_cand_bundle is None or cand_fit > best_cand_bundle[2]: - best_cand_bundle = ( + passes_base = _passes_base_l0_gates( + cand_fit, + verified_champion_fitness, + cand_eval, + cand_outcome, + cfg, + cand_dsr, + ) + evaluated_bundles.append( + ( cand_strategy, cand_outcome, cand_fit, changes, level_used, cand_rec, + cand_dsr, + passes_base, ) + ) next_version += 1 - if best_cand_bundle is None: + if not evaluated_bundles: + _cleanup_unused_dynamic() for rec in round_approved_records: if rec.veto_reasons: _bump_veto(rec.veto_reasons) @@ -774,52 +914,166 @@ def _bump_veto(reasons: list[str]) -> None: stagnant_l1 += 1 continue - cand_strat, cand_outcome, cand_fit, chs, lvl, best_rec = best_cand_bundle - cand_eval = cand_outcome.evaluation - cand_null = cand_outcome.null_control - best_trial = cand_outcome.trial_record - dsr_prob = ( - float(cand_eval.deflated_sharpe_prob) - if cand_eval.deflated_sharpe_prob is not None - else 0.0 - ) - passes_base_gates = ( - cand_fit > verified_champion_fitness + 1e-4 - and cand_eval.overall.avg_return > 0.0 - and cand_eval.overall.max_drawdown <= cfg.max_drawdown - and not cand_eval.anti_overfit.is_overfit - and cand_eval.overall.signal_count >= cfg.min_signals - and dsr_prob >= cfg.min_dsr_prob - and (not cfg.require_null_control or cand_eval.null_control_passed is True) - and ( - not cfg.require_portfolio_gate - or ( - cand_outcome.portfolio_verdict is not None - and cand_outcome.portfolio_verdict.passed + # TrialLedger (frozen L0) persists sequential insertion-time DSR rows; here we + # recompute order-invariant round-end DSR for gates, deliberations, and MAP-Elites + # without mutating historical L0 rows. + round_end_trials = max(1, self._trial_ledger.count_family_trials(family_id)) + refreshed_bundles: list[ + tuple[ + Strategy, + KernelEvaluationOutcome, + float, + list[StrategyChange], + RSILevel, + DeliberationRecord, + float, + bool, + ] + ] = [] + for bundle in evaluated_bundles: + b_strat, b_outcome, b_fit, b_chs, b_lvl, b_rec, b_dsr, b_ok = bundle + b_eval = b_outcome.evaluation + bt_res = getattr(b_outcome, "backtest_result", None) + if bt_res is not None: + executed = [s for s in bt_res.signals if s.exit_price is not None] + dsr_returns = ( + self._evaluator.compute_daily_mtm_returns(executed, search_market)[0] + if b_eval.overall.metrics_basis == "daily_mtm" and search_market + else [] + ) + dsr_input = dsr_returns if dsr_returns else [s.return_pct for s in executed] + dsr_obs = len(dsr_input) if dsr_returns else b_eval.overall.signal_count + dsr_res = self._trial_ledger.compute_dsr_for_trials( + family_id=family_id, + n_trials=round_end_trials, + returns=dsr_input, + observed_sharpe=b_eval.overall.sharpe_ratio, + signal_count=dsr_obs, + ) + b_eval.family_trial_count = round_end_trials + b_eval.deflated_sharpe_prob = dsr_res.dsr_probability + b_dsr = float(dsr_res.dsr_probability) + b_fit = _compute_rsi_fitness( + b_eval, + objective=cfg.objective, + min_signals=cfg.min_signals, + max_drawdown=cfg.max_drawdown, + ) + b_rec.fitness_after = b_fit + b_rec.dsr_probability = b_dsr + b_rec.veto_reasons = _diagnose_gate_failures( + b_fit, + verified_champion_fitness, + b_eval, + b_outcome, + cfg, + b_dsr, ) + b_ok = _passes_base_l0_gates( + b_fit, + verified_champion_fitness, + b_eval, + b_outcome, + cfg, + b_dsr, + ) + refreshed_bundles.append( + (b_strat, b_outcome, b_fit, b_chs, b_lvl, b_rec, b_dsr, b_ok) ) - ) - rerun_null_failed = False - if passes_base_gates and cfg.require_strategy_rerun_null: - rerun_null = self._null_ctrl.evaluate_strategy_against_null_worlds( - cand_strat, - search_market, - cand_eval, - n_worlds=cfg.strategy_rerun_null_worlds, - seed=seed + rnd, - backtest_engine=self._kernel._build_engine(), + evaluated_bundles = refreshed_bundles + for b_strat, b_outcome, b_fit, *_ in evaluated_bundles: + uses_transient = bool( + new_dynamic_factor is not None + and _strategy_uses_indicator(b_strat, new_dynamic_factor) ) - cand_outcome.strategy_rerun_null = rerun_null - if not rerun_null.passed: - rerun_null_failed = True - cand_eval.null_control_passed = False - cand_eval.null_p_value = round( - max(float(cand_eval.null_p_value or 0.0), rerun_null.worst_p_value), + if not uses_transient: + archive.insert(b_strat, b_outcome.evaluation, b_fit) + + selected_bundle: ( + tuple[ + Strategy, + KernelEvaluationOutcome, + float, + list[StrategyChange], + RSILevel, + DeliberationRecord, + float, + bool, + ] + | None + ) = None + passes_gate = False + + base_passing = sorted( + [b for b in evaluated_bundles if b[7]], + key=lambda b: b[2], + reverse=True, + ) + for bundle in base_passing: + b_strat, b_outcome, b_fit, _b_chs, _b_lvl, b_rec, b_dsr, _b_ok = bundle + b_eval = b_outcome.evaluation + if cfg.require_strategy_rerun_null: + rerun_null = self._null_ctrl.evaluate_strategy_against_null_worlds( + b_strat, + search_market, + b_eval, + n_worlds=cfg.strategy_rerun_null_worlds, + seed=seed + rnd, + backtest_engine=self._kernel._build_engine(), + ) + b_outcome.strategy_rerun_null = rerun_null + if rerun_null.passed: + selected_bundle = bundle + passes_gate = True + break + b_eval.null_control_passed = False + b_eval.null_p_value = round( + max(float(b_eval.null_p_value or 0.0), rerun_null.worst_p_value), 4, ) - passes_gate = rerun_null.passed - else: - passes_gate = passes_base_gates + b_rec.null_passed = False + b_rec.veto_reasons = _diagnose_gate_failures( + b_fit, + verified_champion_fitness, + b_eval, + b_outcome, + cfg, + b_dsr, + rerun_null_failed=True, + ) + else: + selected_bundle = bundle + passes_gate = True + break + + if selected_bundle is None: + ordered_all = sorted(evaluated_bundles, key=lambda b: b[2], reverse=True) + stepping_candidates = [ + b + for b in ordered_all + if promotions == 0 + and b[1].evaluation.overall.signal_count >= min(5, cfg.min_signals) + and b[2] > working_fitness + 1e-4 + and ( + working_eval.overall.signal_count < 5 + or ( + b[1].evaluation.overall.max_drawdown + <= max(cfg.max_drawdown, working_eval.overall.max_drawdown) + and b[1].evaluation.overall.avg_return + >= working_eval.overall.avg_return + ) + ) + ] + selected_bundle = stepping_candidates[0] if stepping_candidates else ordered_all[0] + + cand_strat, cand_outcome, cand_fit, chs, lvl, best_rec, dsr_prob, _ = selected_bundle + cand_eval = cand_outcome.evaluation + cand_null = cand_outcome.null_control + best_trial = cand_outcome.trial_record + best_rerun_failed = bool( + cand_outcome.strategy_rerun_null is not None + and not cand_outcome.strategy_rerun_null.passed + ) best_reasons = _diagnose_gate_failures( cand_fit, @@ -828,7 +1082,7 @@ def _bump_veto(reasons: list[str]) -> None: cand_outcome, cfg, dsr_prob, - rerun_null_failed=rerun_null_failed, + rerun_null_failed=best_rerun_failed, ) is_stepping_stone = ( @@ -847,6 +1101,33 @@ def _bump_veto(reasons: list[str]) -> None: ) desc = "; ".join(f"{c.target}->{c.to_value}" for c in chs) + synthesized_rec = steer.synthesized_factor_record + needs_factor_persist = ( + (passes_gate or is_stepping_stone) + and synthesized_rec is not None + and _strategy_uses_indicator(cand_strat, synthesized_rec.name) + ) + factor_save_failed = False + if needs_factor_persist and synthesized_rec is not None: + try: + stored_rec, inserted = self._factor_store.save_if_absent(synthesized_rec) + if inserted or ( + stored_rec.status == "active" and stored_rec.code == synthesized_rec.code + ): + steer.persisted_to_store = True + if synthesized_rec.name not in persisted_factors: + persisted_factors.append(synthesized_rec.name) + else: + factor_save_failed = True + passes_gate = False + is_stepping_stone = False + best_reasons = [*best_reasons, "factor_store_conflict"] + except Exception: + factor_save_failed = True + passes_gate = False + is_stepping_stone = False + best_reasons = [*best_reasons, "factor_store_save_failed"] + if passes_gate: if best_trial is not None: self._trial_ledger.mark_trial_accepted(best_trial.trial_id, True) @@ -877,6 +1158,17 @@ def _bump_veto(reasons: list[str]) -> None: status = "revert" best_rec.veto_reasons = best_reasons + if ( + not factor_save_failed + and status in {"keep", "stepping_stone"} + and new_dynamic_factor is not None + and _strategy_uses_indicator(cand_strat, new_dynamic_factor) + ): + _cleanup_unused_dynamic(persisted=True) + archive.insert(cand_strat, cand_eval, cand_fit) + else: + _cleanup_unused_dynamic() + best_rec.l0_outcome = status if best_rec.secondary_parent_id and status in {"keep", "stepping_stone"}: crossovers_kept += 1 @@ -933,12 +1225,16 @@ def _bump_veto(reasons: list[str]) -> None: holdout_eval = holdout_outcome.evaluation if persist_champion and has_verified_promotion and str(self._db_path) != ":memory:": + strat_store: StrategyStore | None = None try: strat_store = StrategyStore(self._db_path) strat_store.save(verified_champion_strategy) strat_store.save_evaluation(verified_champion_eval) except Exception: pass + finally: + if strat_store is not None: + strat_store.close() enrolled_in_shadow = False if auto_enroll_shadow and has_verified_promotion and shadow_ledger is not None: diff --git a/src/alphaevo/rsi/mechanism.py b/src/alphaevo/rsi/mechanism.py index 18890db..7050988 100644 --- a/src/alphaevo/rsi/mechanism.py +++ b/src/alphaevo/rsi/mechanism.py @@ -11,7 +11,7 @@ from alphaevo.evaluator.metrics import Evaluator from alphaevo.models.enums import RSILevel -from alphaevo.models.execution import BacktestResult +from alphaevo.models.execution import BacktestResult, TradeSignal from alphaevo.models.strategy import Strategy from alphaevo.rsi.program import RSICharter from alphaevo.truth.kernel import EvaluationKernel, PortfolioGateConfig @@ -107,10 +107,11 @@ def _temporal_split_with_warmup( train_ratio: float = 0.65, warmup_bars: int = 60, ) -> tuple[dict[str, pd.DataFrame], dict[str, pd.DataFrame], dict[str, date]]: - """Split each symbol into train and warmup-padded forward slices + OOS cutoff dates.""" + """Split each symbol into train and warmup-padded forward slices with a unified calendar cutoff.""" train_data: dict[str, pd.DataFrame] = {} fwd_data: dict[str, pd.DataFrame] = {} fwd_cutoffs: dict[str, date] = {} + ordered_by_sym: dict[str, pd.DataFrame] = {} for sym, df in market_data.items(): if df.empty or len(df) < 35: continue @@ -119,14 +120,60 @@ def _temporal_split_with_warmup( if "date" in df else df.reset_index(drop=True) ) - split_idx = max(20, int(len(ordered) * train_ratio)) - if len(ordered) - split_idx < 20: - split_idx = max(20, len(ordered) - 20) - train_data[sym] = ordered.iloc[:split_idx].copy().reset_index(drop=True) - fwd_start = max(0, split_idx - warmup_bars) - fwd_data[sym] = ordered.iloc[fwd_start:].copy().reset_index(drop=True) - if "date" in ordered.columns: - fwd_cutoffs[sym] = pd.to_datetime(ordered["date"].iloc[split_idx]).date() + ordered_by_sym[sym] = ordered + + dated_syms = {s for s, df in ordered_by_sym.items() if "date" in df.columns} + cutoff_date: date | None = None + min_side = 20 + if dated_syms: + panel_dates = sorted( + { + d + for sym in dated_syms + for d in pd.to_datetime(ordered_by_sym[sym]["date"], errors="coerce") + .dt.date.dropna() + .tolist() + } + ) + if len(panel_dates) >= 25: + min_side = 20 if len(panel_dates) >= 40 else 10 + cut_pos = max( + min_side, + min(len(panel_dates) - min_side, int(len(panel_dates) * train_ratio)), + ) + cutoff_date = panel_dates[cut_pos] + + for sym, ordered in ordered_by_sym.items(): + if cutoff_date is not None and sym in dated_syms: + sym_dates = pd.to_datetime(ordered["date"], errors="coerce").dt.date + split_idx = int((sym_dates < cutoff_date).sum()) + if split_idx < min_side or len(ordered) - split_idx < min_side: + continue + train_data[sym] = ordered.iloc[:split_idx].copy().reset_index(drop=True) + fwd_start = max(0, split_idx - warmup_bars) + fwd_data[sym] = ordered.iloc[fwd_start:].copy().reset_index(drop=True) + fwd_cutoffs[sym] = cutoff_date + else: + split_idx = max(20, int(len(ordered) * train_ratio)) + if len(ordered) - split_idx < 20: + split_idx = max(20, len(ordered) - 20) + work = ordered.copy() + has_valid_dates = False + parsed_split_date: date | None = None + if "date" in work.columns: + parsed_dates = pd.to_datetime(work["date"], errors="coerce").dt.date + if not parsed_dates.isna().any() and isinstance(parsed_dates.iloc[split_idx], date): + has_valid_dates = True + parsed_split_date = parsed_dates.iloc[split_idx] + if has_valid_dates and parsed_split_date is not None: + fwd_cutoffs[sym] = parsed_split_date + else: + synth_dates = [d.date() for d in pd.bdate_range("2020-01-02", periods=len(work))] + work["date"] = synth_dates + fwd_cutoffs[sym] = synth_dates[split_idx] + train_data[sym] = work.iloc[:split_idx].copy().reset_index(drop=True) + fwd_start = max(0, split_idx - warmup_bars) + fwd_data[sym] = work.iloc[fwd_start:].copy().reset_index(drop=True) return train_data, fwd_data, fwd_cutoffs @@ -288,43 +335,114 @@ def _run_single_variant( complexity_limit=variant.complexity_limit, enable_pinned_scars=variant.enable_pinned_scars, ) - res = rsi_engine.run( - seed_strategy, - train_data, - charter=charter, - seed=seed, - ) + try: + res = rsi_engine.run( + seed_strategy, + train_data, + charter=charter, + seed=seed, + ) + finally: + rsi_engine.close() champ = res.champion_strategy kernel = EvaluationKernel(min_data_days=15) portfolio_cfg = ( PortfolioGateConfig(enabled=True) if variant.require_portfolio_gate else None ) - min_fwd_date = min(fwd_cutoffs.values()) if fwd_cutoffs else None - outcome = kernel.evaluate( - champ, - fwd_data, - mode="fast", - record_trial=False, - run_null_control=False, - portfolio_gate=portfolio_cfg, - min_entry_date=min_fwd_date, - ) - raw_bt = outcome.backtest_result - oos_signals = [ - sig - for sig in raw_bt.signals - if sig.symbol not in fwd_cutoffs or sig.signal_date >= fwd_cutoffs[sig.symbol] - ] - if len(oos_signals) != len(raw_bt.signals): + groups_by_cutoff: dict[date, dict[str, pd.DataFrame]] = {} + for sym, df in fwd_data.items(): + cut = fwd_cutoffs.get(sym) + if cut is not None: + groups_by_cutoff.setdefault(cut, {})[sym] = df + + if not groups_by_cutoff: + today = date.today() fwd_bt = BacktestResult( - strategy_id=raw_bt.strategy_id, - batch_id=raw_bt.batch_id, - signals=oos_signals, - total_signals=len(oos_signals), - executed_signals=len([s for s in oos_signals if s.exit_price is not None]), - skipped_signals=len([s for s in oos_signals if s.exit_price is None]), - date_range=raw_bt.date_range, + strategy_id=champ.meta.id, + batch_id="mech_fwd_empty", + signals=[], + total_signals=0, + executed_signals=0, + skipped_signals=0, + date_range=(today, today), + ) + fwd_eval = Evaluator().evaluate_fast(fwd_bt, champ, market_data=fwd_data) + portfolio_ok = True + elif len(groups_by_cutoff) == 1: + sole_cutoff, sole_data = next(iter(groups_by_cutoff.items())) + outcome = kernel.evaluate( + champ, + sole_data, + mode="fast", + record_trial=False, + run_null_control=False, + portfolio_gate=portfolio_cfg, + min_entry_date=sole_cutoff, + ) + raw_bt = outcome.backtest_result + oos_signals = [ + sig + for sig in raw_bt.signals + if sig.symbol in fwd_cutoffs and sig.signal_date >= fwd_cutoffs[sig.symbol] + ] + if len(oos_signals) != len(raw_bt.signals) or len(sole_data) != len(fwd_data): + fwd_bt = BacktestResult( + strategy_id=raw_bt.strategy_id, + batch_id=raw_bt.batch_id, + signals=oos_signals, + total_signals=len(oos_signals), + executed_signals=len([s for s in oos_signals if s.exit_price is not None]), + skipped_signals=len([s for s in oos_signals if s.exit_price is None]), + date_range=raw_bt.date_range, + ) + fwd_eval = Evaluator().evaluate_fast(fwd_bt, champ, market_data=fwd_data) + portfolio_ok = ( + EvaluationKernel._evaluate_portfolio_gate( + fwd_bt, fwd_data, portfolio_cfg + ).passed + if portfolio_cfg is not None + else True + ) + else: + fwd_bt = raw_bt + fwd_eval = outcome.evaluation + portfolio_ok = ( + outcome.portfolio_verdict.passed + if outcome.portfolio_verdict is not None + else True + ) + else: + oos_signals_multi: list[TradeSignal] = [] + group_ranges: list[tuple[date, date]] = [] + for cutoff, group_data in sorted(groups_by_cutoff.items()): + group_outcome = kernel.evaluate( + champ, + group_data, + mode="fast", + record_trial=False, + run_null_control=False, + portfolio_gate=None, + min_entry_date=cutoff, + ) + group_bt = group_outcome.backtest_result + group_ranges.append(group_bt.date_range) + for sig in group_bt.signals: + if sig.symbol in fwd_cutoffs and sig.signal_date >= fwd_cutoffs[sig.symbol]: + oos_signals_multi.append(sig) + oos_signals_multi.sort(key=lambda s: (s.signal_date, s.symbol)) + combined_range = ( + min(r[0] for r in group_ranges), + max(r[1] for r in group_ranges), + ) + fwd_bt = BacktestResult( + strategy_id=champ.meta.id, + batch_id="mech_fwd_multi_cutoff", + signals=oos_signals_multi, + total_signals=len(oos_signals_multi), + executed_signals=len([s for s in oos_signals_multi if s.exit_price is not None]), + skipped_signals=len([s for s in oos_signals_multi if s.exit_price is None]), + date_range=combined_range, ) fwd_eval = Evaluator().evaluate_fast(fwd_bt, champ, market_data=fwd_data) portfolio_ok = ( @@ -332,12 +450,6 @@ def _run_single_variant( if portfolio_cfg is not None else True ) - else: - fwd_bt = raw_bt - fwd_eval = outcome.evaluation - portfolio_ok = ( - outcome.portfolio_verdict.passed if outcome.portfolio_verdict is not None else True - ) train_avg = res.champion_evaluation.overall.avg_return fwd_avg = fwd_eval.overall.avg_return @@ -349,14 +461,33 @@ def _run_single_variant( promoted_beyond_seed = res.promotions > 0 fwd_null_ok = False - if fwd_sigs >= 5: - null_rep = NullSignalController().evaluate_candidate_against_nulls( - fwd_bt.signals, - fwd_data, - n_permutations=25, - seed=seed, + executed_fwd = [s for s in fwd_bt.signals if s.exit_price is not None] + if len(executed_fwd) >= 5: + avg_hold_fwd = max( + 1, + round(sum(max(1, s.holding_days) for s in executed_fwd) / len(executed_fwd)), + ) + fwd_oos_only_market: dict[str, pd.DataFrame] = {} + for sym, df in fwd_data.items(): + cut = fwd_cutoffs.get(sym) + if cut is None or df.empty or "date" not in df.columns: + continue + sym_dates = pd.to_datetime(df["date"], errors="coerce").dt.date + oos_slice = df.loc[sym_dates >= cut].copy().reset_index(drop=True) + if not oos_slice.empty: + fwd_oos_only_market[sym] = oos_slice + has_market_null_pool = any( + "close" in df.columns and len(df) >= avg_hold_fwd + 3 + for df in fwd_oos_only_market.values() ) - fwd_null_ok = null_rep.passed + if has_market_null_pool: + null_rep = NullSignalController().evaluate_candidate_against_nulls( + fwd_bt.signals, + fwd_oos_only_market, + n_permutations=25, + seed=seed, + ) + fwd_null_ok = null_rep.passed false_promo = promoted_beyond_seed and (fwd_avg <= 0.0 or not fwd_null_ok) decay_bonus = 0.02 * min(1.5, max(0.0, decay)) if decay is not None else 0.0 diff --git a/src/alphaevo/strategy/store.py b/src/alphaevo/strategy/store.py index c489f19..54e0982 100644 --- a/src/alphaevo/strategy/store.py +++ b/src/alphaevo/strategy/store.py @@ -6,8 +6,11 @@ from __future__ import annotations +import contextlib import logging import sqlite3 +import threading +from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path @@ -66,11 +69,14 @@ def __init__(self, db_path: str | Path = "~/.alphaevo/alphaevo.db") -> None: """ normalized_path, use_memory = _normalize_db_path(db_path) self._is_memory = use_memory + self._lock = threading.RLock() if self._is_memory: self._db_path = ":memory:" # Keep a persistent connection for in-memory databases, # since each sqlite3.connect(":memory:") creates a *new* DB. - self._shared_conn: sqlite3.Connection | None = sqlite3.connect(":memory:") + self._shared_conn: sqlite3.Connection | None = sqlite3.connect( + ":memory:", check_same_thread=False + ) self._shared_conn.execute("PRAGMA foreign_keys=ON") else: self._db_path = normalized_path @@ -287,18 +293,48 @@ def import_builtin_strategies(self, strategies_dir: Path) -> int: # ── Internal helpers ────────────────────────────────────────────── - def _connect(self) -> sqlite3.Connection: - """Return a database connection. - - For file-based DBs: creates a new connection per call (thread-safe). - For in-memory DBs: reuses the shared connection. - """ - if self._shared_conn is not None: - return self._shared_conn - conn = sqlite3.connect(self._db_path) - conn.execute("PRAGMA journal_mode=WAL") - conn.execute("PRAGMA foreign_keys=ON") - return conn + def close(self) -> None: + """Close persistent in-memory SQLite connection if open.""" + lock = getattr(self, "_lock", None) + if lock is None: + lock = threading.RLock() + self._lock = lock + with lock: + conn = getattr(self, "_shared_conn", None) + if conn is not None: + conn.close() + self._shared_conn = None + + def __enter__(self) -> StrategyStore: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + @contextlib.contextmanager + def _connect(self) -> Iterator[sqlite3.Connection]: + """Yield a thread-safe SQLite connection and close file-backed handles.""" + shared_conn = getattr(self, "_shared_conn", None) + if shared_conn is not None: + lock = getattr(self, "_lock", None) + if lock is None: + lock = threading.RLock() + self._lock = lock + with lock: + if getattr(self, "_shared_conn", None) is None: + raise RuntimeError("StrategyStore connection is closed") + with shared_conn: + yield shared_conn + return + conn = sqlite3.connect(self._db_path, timeout=30.0) + try: + conn.execute("PRAGMA busy_timeout=5000") + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA foreign_keys=ON") + with conn: + yield conn + finally: + conn.close() def _normalize_db_path(db_path: str | Path) -> tuple[str, bool]: diff --git a/tests/unit/test_round7_to_11_sandbox_governance_rsi_arena_integrity.py b/tests/unit/test_round7_to_11_sandbox_governance_rsi_arena_integrity.py new file mode 100644 index 0000000..4e99458 --- /dev/null +++ b/tests/unit/test_round7_to_11_sandbox_governance_rsi_arena_integrity.py @@ -0,0 +1,2412 @@ +"""Regression tests for Rounds 7-11 hardening across sandbox, governance, RSI, council, and arena.""" + +from __future__ import annotations + +import math +import subprocess +import threading +from datetime import date, timedelta +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +import numpy as np +import pandas as pd +import pytest + +from alphaevo.alpha_factory.factor_store import FactorRecord, FactorStore +from alphaevo.alpha_factory.factory import _build_indicator_fn +from alphaevo.alpha_factory.governance import ( + FactorGovernanceConfig, + FactorGovernanceEngine, + _split_panel, +) +from alphaevo.alpha_factory.sandbox import ( + FactorSandbox, + _execute_in_worker_namespace, + build_restricted_namespace, +) +from alphaevo.arena import ArenaRunner +from alphaevo.backtest.indicators import IndicatorRegistry +from alphaevo.models.enums import ChangeType, MarketType, RSILevel, StrategyCategory +from alphaevo.models.execution import ( + AntiFitMetrics, + EvaluationReport, + OverallMetrics, + StrategyChange, +) +from alphaevo.models.strategy import ( + ExecutionConfig, + StopLossConfig, + Strategy, + StrategyCondition, + StrategyEntry, + StrategyExit, + StrategyMeta, + StrategyParams, + TakeProfitConfig, + TunableParam, +) +from alphaevo.reflection.experience import ExperienceRecord, ExperienceStore +from alphaevo.rsi.co_steer import _OFFLINE_FACTOR_TEMPLATES, BlindSpotMiner +from alphaevo.rsi.council import ( + CouncilProposal, + HeterogeneousCouncil, + HeterogeneousCouncilConfig, + ModelSpec, + ProsecutorAudit, +) +from alphaevo.rsi.crossover import SemanticCrossoverBreeder +from alphaevo.rsi.diagnostics import ConditionPassRate, StrategyBottleneckReport +from alphaevo.rsi.engine import StockRSIEngine +from alphaevo.rsi.mechanism import _temporal_split_with_warmup +from alphaevo.rsi.program import RSICharter +from alphaevo.strategy.store import StrategyStore + + +def _make_ohlcv( + n_bars: int = 80, + *, + start: date = date(2025, 1, 2), + seed: int = 42, + drift: float = 0.001, + osc_amp: float = 0.03, +) -> pd.DataFrame: + rng = np.random.default_rng(seed) + dates = [start + timedelta(days=i) for i in range(n_bars)] + closes: list[float] = [] + px = 100.0 + for i in range(n_bars): + px = px * ( + 1.0 + drift + osc_amp * math.sin(i * math.pi / 4.0) + float(rng.normal(0.0, 0.004)) + ) + closes.append(max(5.0, px)) + arr = np.asarray(closes, dtype=float) + return pd.DataFrame( + { + "date": dates, + "open": arr * 0.998, + "high": arr * 1.01, + "low": arr * 0.99, + "close": arr, + "volume": np.full(n_bars, 1_500_000.0), + } + ) + + +def _make_strategy( + strat_id: str = "r7_11_base_v1", + *, + logic: str = "and", + triggers: list[StrategyCondition] | None = None, + conditions: list[StrategyCondition] | None = None, + guards: list[StrategyCondition] | None = None, + filters: list[StrategyCondition] | None = None, + sl: StopLossConfig | None = None, + tp: TakeProfitConfig | None = None, + exit_triggers: list[StrategyCondition] | None = None, + tunable: list[TunableParam] | None = None, +) -> Strategy: + return Strategy( + meta=StrategyMeta( + id=strat_id, + name=f"Strat {strat_id}", + market=MarketType.US, + category=StrategyCategory.TREND, + ), + description="Synthetic strategy for Rounds 7-11 hardening tests.", + entry=StrategyEntry( + logic="or" if logic == "or" else "and", + triggers=triggers or [], + conditions=conditions + if conditions is not None + else [StrategyCondition(indicator="rsi_14", op="<=", value=60.0)], + guards=guards or [], + filters=filters or [], + execution=ExecutionConfig(timing="next_open", slippage=0.001), + ), + exit=StrategyExit( + triggers=exit_triggers or [], + stop_loss=sl or StopLossConfig(type="pct", value=0.05), + take_profit=tp or TakeProfitConfig(type="rr", value=2.0), + max_holding_days=8, + ), + params=StrategyParams(tunable=tunable or []), + ) + + +# --------------------------------------------------------------------------- +# Round 7: FactorSandbox AST, Restricted Builtins, & Spawn Worker Isolation +# --------------------------------------------------------------------------- + + +def test_round7_sandbox_ast_hardening_and_worker_cache() -> None: + ns_builtins = build_restricted_namespace()["__builtins__"] + for blocked_builtin in ("type", "hasattr", "id"): + assert blocked_builtin not in ns_builtins + + with FactorSandbox(timeout_seconds=10) as sb: + dangerous_snippets = [ + "from pandas.io.pickle import read_pickle\ndef compute(df, idx): return 0.0", + "from . import helper\ndef compute(df, idx): return 0.0", + "from math import *\ndef compute(df, idx): return 0.0", + "def compute(df, idx):\n df.to_csv('/tmp/leak.csv')\n return 0.0", + "def compute(df, idx):\n return float(len(df.query('close > 0')))", + "def compute(df, idx):\n g = (x for x in [1])\n return float(bool(g.gi_frame))", + "def compute(df, idx):\n return float(bool(type(df)))", + "def compute(df, idx):\n return float(bool(hasattr(df, 'close')))", + "def compute(df, idx):\n return float(id(df))", + "def compute(df, idx):\n return float(bool(''.__eq__('a')))", + ] + for snippet in dangerous_snippets: + ok, msg = sb.preflight_code(snippet) + assert not ok, f"Expected rejection for snippet:\n{snippet}" + assert msg + + bad_sig = "def compute(df):\n return 1.0" + ok_sig, _ = sb.preflight_code(bad_sig) + assert not ok_sig + + # Verify _build_indicator_fn executes strictly inside isolated worker with PIT slicing + LRU cache + lookfuture_code = ( + "def compute(df, idx):\n" + " return float(len(df) - 1 - idx + float(df['close'].iloc[idx]))\n" + ) + df = _make_ohlcv(30, seed=11) + fn = _build_indicator_fn(lookfuture_code, sb) + with patch.object(sb, "execute", wraps=sb.execute) as spy_exec: + v1 = fn(df, 10) + v2 = fn(df, 12) + assert spy_exec.call_count == 1 # second call hits series LRU cache + assert spy_exec.call_args.kwargs.get("enforce_pit_slice") is True + assert v1 == pytest.approx(float(df["close"].iloc[10])) + assert v2 == pytest.approx(float(df["close"].iloc[12])) + + # Mutating df in-place invalidates blake2b cache key cleanly + df.iloc[12, df.columns.get_loc("close")] = 777.5 + v2_mut = fn(df, 12) + assert spy_exec.call_count == 2 + assert v2_mut == pytest.approx(777.5) + + +# --------------------------------------------------------------------------- +# Round 8: FactorGovernanceEngine Purged/Warmup Split & Negative L2 Direction +# --------------------------------------------------------------------------- + + +def test_round8_governance_split_warmup_no_leak_and_negative_direction(tmp_path: Path) -> None: + # Build staggered dates panel (A starts earlier, B starts later) so calendar alignment is exercised + base_start = date(2025, 1, 2) + market_data: dict[str, pd.DataFrame] = {} + for sym_idx, sym in enumerate(("GOV_A", "GOV_B", "GOV_C")): + n_bars = 120 + dates = [base_start + timedelta(days=i + sym_idx * 3) for i in range(n_bars)] + # Synthetic cyclic compression -> larger compression precedes lower forward returns (inverse relation) + closes = [ + 100.0 * (1.0 + 0.04 * math.sin((i + sym_idx) * math.pi / 4.0)) for i in range(n_bars) + ] + arr = np.asarray(closes, dtype=float) + spread = np.array([0.04 if (i % 4 == 0) else 0.005 for i in range(n_bars)], dtype=float) + market_data[sym] = pd.DataFrame( + { + "date": dates, + "open": arr, + "high": arr * (1.0 + spread), + "low": arr * (1.0 - spread), + "close": arr, + "volume": np.full(n_bars, 1_000_000.0 + sym_idx * 5_000.0), + } + ) + + split = _split_panel(market_data, train_ratio=0.60, forward_horizon=5) + assert "_fwd_ret" not in split.train_ohlcv.columns + assert "_fwd_ret" not in split.oos_eval_ohlcv.columns + train_dates = set(pd.to_datetime(split.train_ohlcv["date"]).dt.date) + oos_only_dates = set(pd.to_datetime(split.oos_eval_ohlcv.loc[split.oos_mask, "date"]).dt.date) + assert train_dates.isdisjoint(oos_only_dates) + # OOS warmup prefix exists before masked OOS window + assert (~split.oos_mask).sum() > 0 + + # Verify offline negative-direction L2 templates & LLM direction preservation + tpl_dirs = {t.name: t.expected_direction for t in _OFFLINE_FACTOR_TEMPLATES} + assert tpl_dirs["intraday_range_compression_10d"] == "negative" + assert tpl_dirs["downside_vol_ratio_10d"] == "negative" + assert tpl_dirs["atr_expansion_ratio_14d"] == "negative" + + fake_synth = SimpleNamespace( + generate=lambda **kwargs: [ + SimpleNamespace( + name="inverse_range_compression_test", + code=( + "def compute(df, idx):\n" + " if idx < 1:\n" + " return 0.0\n" + " return float((df['high'].iloc[idx] - df['low'].iloc[idx]) / max(1e-6, df['close'].iloc[idx]))\n" + ), + description="High spread precedes reversion", + expected_direction="negative", + ) + ] + ) + strat = _make_strategy("co_dir_strat_v1") + weak_eval = EvaluationReport( + strategy_id=strat.meta.id, + overall=OverallMetrics(win_rate=0.42, avg_return=-0.01, signal_count=20), + ) + fname = "inverse_range_compression_test" + try: + with BlindSpotMiner(synthesizer=fake_synth) as miner: + decision = miner.steer( + strat, + weak_eval, + market_data["GOV_A"], + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + persist=False, + ) + assert decision.synthesized_factor_name == fname + assert decision.persisted_to_store is False + assert decision.synthesized_factor_record is not None + assert decision.synthesized_factor_record.expected_direction == "negative" + finally: + IndicatorRegistry.unregister_dynamic(fname) + + # Confirm governance reads no _fwd_ret leak column from df + db_path = tmp_path / "gov_r8.db" + with FactorStore(db_path) as fs: + fs.save( + FactorRecord( + name="fwd_ret_sniffer", + description="Must observe zero _fwd_ret column", + rationale="Leak test", + code=( + "def compute(df, idx):\n return 1.0 if '_fwd_ret' in df.columns else 0.0\n" + ), + expected_direction="positive", + ) + ) + with FactorGovernanceEngine( + db_path=db_path, + config=FactorGovernanceConfig( + train_ratio=0.60, + forward_horizon=5, + min_oos_ic=0.02, + min_oos_ir=0.10, + require_pit_invariance=False, + ), + ) as gov: + rep = gov.audit_factors(market_data, strategies=[strat], auto_retire=False) + by_name = {e.name: e for e in rep.entries} + assert by_name["fwd_ret_sniffer"].health == "decayed" + assert by_name["fwd_ret_sniffer"].oos_ic == pytest.approx(0.0) + + +# --------------------------------------------------------------------------- +# Round 9: StockRSIEngine Fail-Closed Holdout, Non-Starvation, Deferred L2 & SQLite +# --------------------------------------------------------------------------- + + +def test_round9_rsi_holdout_fail_closed_and_non_starving_promotion(tmp_path: Path) -> None: + short_market = {"SHORT": _make_ohlcv(20, seed=1)} + strat = _make_strategy("holdout_fail_v1") + with StockRSIEngine(db_path=":memory:", enable_crossover=False) as engine: + charter = RSICharter( + name="strict_holdout", + seed_strategy_id=strat.meta.id, + locked_holdout_pct=0.25, + max_rounds=1, + null_permutations=10, + ) + with pytest.raises(ValueError): + engine.run(strat, short_market, charter=charter) + + # Non-starvation: higher-fitness Candidate A violates overfit gate; lower-fitness B passes all gates + market_data = {"M1": _make_ohlcv(90, seed=7), "M2": _make_ohlcv(90, seed=13)} + base = _make_strategy( + "starve_seed_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=55.0)], + ) + high_fail_change = [ + StrategyChange( + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[indicator=rsi_14].value", + from_value=55.0, + to_value=70.0, + reason="Candidate A high raw fitness but overfit", + ) + ] + pass_change = [ + StrategyChange( + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[indicator=rsi_14].value", + from_value=55.0, + to_value=62.0, + reason="Candidate B passes all L0 gates", + ) + ] + + with StockRSIEngine(db_path=":memory:", enable_crossover=False) as engine: + charter = RSICharter( + name="non_starvation", + seed_strategy_id=base.meta.id, + allowed_levels=[RSILevel.L1_STRATEGY], + max_rounds=1, + max_candidates_per_round=2, + min_signals=5, + max_drawdown=0.45, + min_dsr_prob=0.0, + require_null_control=False, + ) + + def _fake_generate(parent, ev, **kwargs): + del parent, ev, kwargs + return [ + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", + proposer_family="f1", + rationale="High overfit cand A", + changes=high_fail_change, + ), + audit=ProsecutorAudit( + prosecutor_model="p1", + prosecutor_family="f2", + approved=True, + ), + ), + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", + proposer_family="f1", + rationale="Clean passing cand B", + changes=pass_change, + ), + audit=ProsecutorAudit( + prosecutor_model="p1", + prosecutor_family="f2", + approved=True, + ), + ), + ] + + def _fake_eval(self_arg, *, strategy, **kwargs): + del self_arg, kwargs + thresh = float(strategy.entry.conditions[0].value) + if strategy.meta.id == base.meta.id: + ov = OverallMetrics( + win_rate=0.45, avg_return=0.002, max_drawdown=0.08, signal_count=20 + ) + ao = AntiFitMetrics() + elif thresh >= 69.0: + # Higher raw fitness (win_rate=0.65, avg_return=0.04) but fails overfit gate! + ov = OverallMetrics( + win_rate=0.65, avg_return=0.04, max_drawdown=0.05, signal_count=25 + ) + ao = AntiFitMetrics(train_val_gap=0.25) + else: + # Slightly lower fitness than A, higher than baseline, cleanly passes all gates! + ov = OverallMetrics( + win_rate=0.58, avg_return=0.02, max_drawdown=0.06, signal_count=22 + ) + ao = AntiFitMetrics() + ev = EvaluationReport( + strategy_id=strategy.meta.id, + overall=ov, + anti_overfit=ao, + confidence_score=ov.win_rate, + deflated_sharpe_prob=0.80, + null_control_passed=True, + ) + return SimpleNamespace( + evaluation=ev, + null_control=None, + portfolio_verdict=None, + trial_record=None, + strategy_rerun_null=None, + ) + + with ( + patch.object(engine._council, "generate_candidates", side_effect=_fake_generate), + patch.object( + StockRSIEngine, "_eval_with_kernel", autospec=True, side_effect=_fake_eval + ), + ): + res = engine.run(base, market_data, charter=charter, persist_champion=False) + + assert res.promotions == 1 + assert res.champion_strategy.entry.conditions[0].value == pytest.approx(62.0) + + +def test_round9_deferred_l2_unregister_on_revert_and_sqlite_concurrency(tmp_path: Path) -> None: + db_path = tmp_path / "l2_defer.db" + market_data = {"M1": _make_ohlcv(70, seed=3)} + strat = _make_strategy("l2_defer_v1") + transient_factor = "transient_reverted_l2_test" + + def _fake_steer(parent, ev, sample_df, **kwargs): + del parent, ev, sample_df, kwargs + code = "def compute(df, idx):\n return 1.0\n" + IndicatorRegistry.register_dynamic(transient_factor, lambda df, idx, ctx=None: 1.0) + return SimpleNamespace( + chosen_level=RSILevel.L2_FACTOR, + cluster=SimpleNamespace(bottleneck_hint=""), + synthesized_factor_name=transient_factor, + synthesized_via="offline_template", + pit_verified=True, + persisted_to_store=False, + synthesized_factor_record=FactorRecord( + name=transient_factor, + description="Transient factor", + rationale="Should unregister and skip store on revert", + code=code, + expected_direction="positive", + ), + proposed_changes=[ + StrategyChange( + change_type=ChangeType.ADD_CONDITION, + target="entry.filters", + from_value=None, + to_value={"indicator": transient_factor, "op": ">=", "value": 0.5}, + reason="Add transient L2 filter", + ) + ], + ) + + try: + with StockRSIEngine(db_path=db_path, enable_crossover=False) as engine: + charter = RSICharter( + name="l2_revert", + seed_strategy_id=strat.meta.id, + allowed_levels=[RSILevel.L1_STRATEGY, RSILevel.L2_FACTOR], + max_rounds=1, + max_candidates_per_round=1, + min_signals=500, # force revert + require_null_control=False, + ) + with ( + patch.object(engine._miner, "steer", side_effect=_fake_steer), + patch.object( + engine._council, + "generate_candidates", + return_value=[ + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", + proposer_family="f1", + rationale="Use transient L2", + changes=[ + StrategyChange( + change_type=ChangeType.ADD_CONDITION, + target="entry.filters", + from_value=None, + to_value={ + "indicator": transient_factor, + "op": ">=", + "value": 0.5, + }, + reason="Test transient revert", + ) + ], + ), + audit=ProsecutorAudit( + prosecutor_model="p1", + prosecutor_family="f2", + approved=True, + ), + ) + ], + ), + ): + res = engine.run(strat, market_data, charter=charter, persist_champion=False) + + assert res.promotions == 0 + assert res.persisted_factors == [] + assert not IndicatorRegistry.is_registered(transient_factor) + with FactorStore(db_path) as check_fs: + assert check_fs.get(transient_factor) is None + finally: + IndicatorRegistry.unregister_dynamic(transient_factor) + + # SQLite thread safety across :memory: stores & context manager cleanup on file stores + with ( + StrategyStore(":memory:") as ms, + ExperienceStore(":memory:") as me, + FactorStore(":memory:") as mf, + ): + errors: list[Exception] = [] + + def _worker(tid: int) -> None: + try: + s = _make_strategy(f"thread_strat_{tid}") + ms.save(s) + assert ms.get(s.meta.id) is not None + me.record( + ExperienceRecord( + strategy_family="f", + strategy_id=s.meta.id, + round_num=tid, + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[0].value", + to_value=60.0, + ) + ) + mf.save( + FactorRecord( + name=f"tf_{tid}", + description="t", + rationale="t", + code="def compute(df, idx): return 0.0", + ) + ) + assert mf.get(f"tf_{tid}") is not None + except Exception as exc: + errors.append(exc) + + threads = [threading.Thread(target=_worker, args=(i,)) for i in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + assert errors == [] + + +# --------------------------------------------------------------------------- +# Round 10: Council Committee & Fail-Closed Prosecutors, Crossover, Mechanism +# --------------------------------------------------------------------------- + + +def test_round10_council_crossover_and_mechanism_cutoff() -> None: + strat = _make_strategy("council_r10_v1") + overfit_eval = EvaluationReport( + strategy_id=strat.meta.id, + overall=OverallMetrics(win_rate=0.45, avg_return=0.001, signal_count=20), + anti_overfit=AntiFitMetrics(train_val_gap=0.25), + ) + council = HeterogeneousCouncil() + add_change = [ + StrategyChange( + change_type=ChangeType.ADD_CONDITION, + target="entry.filters", + from_value=None, + to_value={"indicator": "close_above_ma20", "op": "==", "value": True}, + reason="Add condition while overfit", + ) + ] + with patch.object( + council._committee, + "review", + return_value=SimpleNamespace(overall_status="fail"), + ): + aud = council._run_prosecutor(strat, overfit_eval, add_change) + assert aud.approved is False + assert any("committee: overall_status=fail" in o for o in aud.objections) + + # Heuristic relaxation for <= with negative and zero thresholds + strat_neg = _make_strategy( + "neg_thresh_v1", + guards=[ + StrategyCondition(indicator="neg_ind", op="<=", value=-0.05), + StrategyCondition(indicator="zero_ind", op="<", value=0.0), + ], + ) + bn = StrategyBottleneckReport( + strategy_id=strat_neg.meta.id, + entry_logic=strat_neg.entry.logic, + total_evaluated_bars=100, + conditions=[ + ConditionPassRate( + group="guards", + indicator="neg_ind", + op="<=", + value=-0.05, + pass_rate=0.04, + ), + ConditionPassRate( + group="guards", + indicator="zero_ind", + op="<", + value=0.0, + pass_rate=0.03, + ), + ], + ) + props = council._build_heuristic_proposals( + strat_neg, + EvaluationReport( + strategy_id=strat_neg.meta.id, + overall=OverallMetrics(win_rate=0.4, signal_count=2), + ), + ModelSpec(model="heuristic"), + bottleneck=bn, + ) + relaxed_targets = {c.target: c.to_value for p in props for c in p.changes} + assert relaxed_targets["entry.guards[indicator=neg_ind].value"] == pytest.approx(-0.0275) + assert relaxed_targets["entry.guards[indicator=zero_ind].value"] == pytest.approx(0.1) + + # Fail-closed CLI prosecutor on error & malformed output + cli_council = HeterogeneousCouncil( + config=HeterogeneousCouncilConfig( + proposer=ModelSpec(model="openai/gpt-6-astra"), + prosecutor=ModelSpec( + model="anthropic/claude-opus-5.5", backend="cli", cli_tool="codex" + ), + ) + ) + with patch("alphaevo.rsi.council.subprocess.run") as mock_sub: + mock_sub.return_value = subprocess.CompletedProcess( + args=["codex"], returncode=1, stdout="", stderr="boom" + ) + veto_err = cli_council._try_cli_prosecutor( + strat, overfit_eval, add_change, cli_council.config.prosecutor + ) + assert veto_err and "fail-closed" in veto_err[0] + mock_sub.return_value = subprocess.CompletedProcess( + args=["codex"], returncode=0, stdout="not json", stderr="" + ) + veto_bad = cli_council._try_cli_prosecutor( + strat, overfit_eval, add_change, cli_council.config.prosecutor + ) + assert veto_bad and "fail-closed" in veto_bad[0] + + # Fail-closed LiteLLM prosecutor when api_key is configured, offline fallback when None + llm_council = HeterogeneousCouncil( + config=HeterogeneousCouncilConfig( + proposer=ModelSpec(model="openai/gpt-6-astra"), + prosecutor=ModelSpec(model="anthropic/claude-opus-5.5", backend="litellm"), + ), + api_key="sk-configured-test", + ) + from alphaevo.core.llm import LLMClient + + with patch.object(LLMClient, "chat_json", side_effect=RuntimeError("timeout")): + llm_veto = llm_council._try_litellm_prosecutor( + strat, overfit_eval, add_change, llm_council.config.prosecutor + ) + assert llm_veto and "fail-closed" in llm_veto[0] + + offline_council = HeterogeneousCouncil( + config=HeterogeneousCouncilConfig( + proposer=ModelSpec(model="openai/gpt-6-astra"), + prosecutor=ModelSpec(model="anthropic/claude-opus-5.5", backend="litellm"), + ), + api_key=None, + ) + with patch("alphaevo.core.config.ConfigManager.get_llm_api_key", return_value=None): + assert ( + offline_council._try_litellm_prosecutor( + strat, overfit_eval, add_change, offline_council.config.prosecutor + ) + == [] + ) + + # Fail-closed CLI prosecutor when cli_tool is unconfigured/unsupported + bad_cli_council = HeterogeneousCouncil( + config=HeterogeneousCouncilConfig( + proposer=ModelSpec(model="openai/gpt-6-astra"), + prosecutor=ModelSpec(model="anthropic/claude-opus-5.5", backend="cli", cli_tool=None), + ) + ) + bad_cli_veto = bad_cli_council._try_cli_prosecutor( + strat, overfit_eval, add_change, bad_cli_council.config.prosecutor + ) + assert bad_cli_veto and "misconfigured" in bad_cli_veto[0] + + # Crossover exit_graft: summarizes ALL exit fields, passes SelfCritic, prunes dangling tunables; + # trigger_blend preserves multi-AND conditions in entry.guards instead of loosening them under OR. + p_strat = _make_strategy( + "p_xover", + logic="and", + conditions=[ + StrategyCondition(indicator="rsi_14", op="<=", value=40.0), + StrategyCondition(indicator="close_above_ma20", op="==", value=True), + ], + tp=TakeProfitConfig(type="target_ma", target="ma60"), + tunable=[ + TunableParam(target="exit.take_profit.target", range=(20, 80), step=5), + TunableParam(target="exit.stop_loss.value", range=(0.02, 0.08), step=0.01), + TunableParam(target="exit.max_holding_days", range=(5, 20), step=5), + ], + ) + s_strat = _make_strategy( + "s_xover", + conditions=[StrategyCondition(indicator="momentum_10d", op=">", value=0.02)], + sl=StopLossConfig(type="atr", multiplier=2.0, atr_period=21), + tp=TakeProfitConfig(type="pct", value=0.12), + exit_triggers=[StrategyCondition(indicator="close_below_ma10", op="==", value=True)], + ) + children = SemanticCrossoverBreeder().breed(p_strat, s_strat, max_children=3) + by_op = {c.operator: c for c in children} + assert "trigger_blend" in by_op + blend_child = by_op["trigger_blend"].child_strategy + assert blend_child.entry.logic == "or" + assert blend_child.entry.conditions == [] + assert [c.indicator for c in blend_child.entry.triggers] == ["rsi_14", "momentum_10d"] + assert [c.indicator for c in blend_child.entry.guards] == ["close_above_ma20"] + + exit_child = by_op["exit_graft"].child_strategy + assert all(p.target != "exit.take_profit.target" for p in exit_child.params.tunable) + assert all(p.target != "exit.stop_loss.value" for p in exit_child.params.tunable) + assert any(p.target == "exit.max_holding_days" for p in exit_child.params.tunable) + summary_targets = {c.target for c in by_op["exit_graft"].summary_changes} + assert { + "exit.stop_loss.atr_period", + "exit.take_profit.target", + "exit.triggers", + } <= summary_targets + exit_aud = council.audit_changes( + p_strat, + EvaluationReport( + strategy_id=p_strat.meta.id, + overall=OverallMetrics(win_rate=0.52, avg_return=0.015, signal_count=25), + ), + by_op["exit_graft"].summary_changes, + ) + assert exit_aud.approved is True, exit_aud.objections + + # Mechanism unified calendar cutoff across staggered symbols even when an undated symbol is present + mech_data = { + "EARLY": _make_ohlcv(80, start=date(2025, 1, 1), seed=1), + "LATE": _make_ohlcv(80, start=date(2025, 1, 10), seed=2), + "UNDATED": _make_ohlcv(80, start=date(2025, 1, 1), seed=3).drop(columns=["date"]), + } + _tr, _fwd, cutoffs = _temporal_split_with_warmup(mech_data, train_ratio=0.65, warmup_bars=10) + assert cutoffs["EARLY"] == cutoffs["LATE"] + assert "UNDATED" in cutoffs + + +# --------------------------------------------------------------------------- +# Round 11: ArenaRunner Strict Out-of-Sample Evolution vs Unseen Shadow Replay +# --------------------------------------------------------------------------- + + +def test_round11_arena_evolves_strictly_before_shadow_cutoff() -> None: + strat = _make_strategy("arena_oos_v1") + clean_market = { + "US_1": _make_ohlcv(80, start=date(2025, 1, 2), seed=10, drift=0.002), + "US_2": _make_ohlcv(80, start=date(2025, 1, 2), seed=20, drift=0.002), + } + perturbed_market = {k: v.copy() for k, v in clean_market.items()} + # Severely corrupt trailing 30% (>= bar 56): future bars after shadow cutoff must NOT alter champion or metrics + for _sym, df in perturbed_market.items(): + df.loc[58:, ["open", "high", "low", "close"]] = 1.0 + + snap_clean = ArenaRunner().run( + [strat], clean_market, rounds=1, enable_l2_factors=False, enable_crossover=False, seed=42 + ) + snap_perturbed = ArenaRunner().run( + [strat], + perturbed_market, + rounds=1, + enable_l2_factors=False, + enable_crossover=False, + seed=42, + ) + + e_clean = snap_clean.entries[0] + e_pert = snap_perturbed.entries[0] + assert e_clean.champion_yaml == e_pert.champion_yaml + assert e_clean.baseline_score == pytest.approx(e_pert.baseline_score) + assert e_clean.champion_score == pytest.approx(e_pert.champion_score) + assert e_clean.equity_curve == e_pert.equity_curve + assert e_clean.shadow_mature_signals >= 1 + assert e_clean.shadow_chain_verified is True + + # Short (<25 bar) panel cannot separate unseen shadow replay from evolution: + # shadow replay must be skipped and reported truthfully as unverified. + tiny_market = {"US_SHORT": _make_ohlcv(20, start=date(2025, 1, 2), seed=9)} + snap_tiny = ArenaRunner().run( + [strat], tiny_market, rounds=1, enable_l2_factors=False, enable_crossover=False, seed=42 + ) + assert snap_tiny.entries[0].shadow_chain_verified is False + assert snap_tiny.chain_verified is False + + +def test_round7_to_11_codex_hardening_invariants(tmp_path: Path) -> None: + import multiprocessing + + from alphaevo.alpha_factory.sandbox import _sandbox_worker_main + from alphaevo.backtest.engine import BacktestResult + from alphaevo.models.enums import SignalDirection + from alphaevo.models.execution import TradeSignal + from alphaevo.truth.ledger import compute_deflated_sharpe + + # 1. Worker proxied modules + AST IO attributes + worker sys.addaudithook runtime guard + ns = build_restricted_namespace() + with pytest.raises(AttributeError): + _ = ns["np"].loadtxt + with pytest.raises(AttributeError): + _ = ns["pd"].read_csv + + with FactorSandbox(timeout_seconds=10) as sb: + for snippet in ( + "import numpy as np\ndef compute(df, idx): return float(len(np.loadtxt('x')))", + "def compute(df, idx): return float(df['close'].to_numpy().base is not None)", + "def compute(df, idx): return float(bool(df._mgr))", + "import pandas as pd\ndef compute(df, idx): return float(bool(pd.read_json('{}')))", + ): + ok, _ = sb.preflight_code(snippet) + assert not ok, f"Expected AST rejection for {snippet}" + + # Verify spawned worker audit hook raises PermissionError even if code bypasses AST check + spawn_ctx = multiprocessing.get_context("spawn") + p_conn, c_conn = spawn_ctx.Pipe(duplex=True) + proc = spawn_ctx.Process(target=_sandbox_worker_main, args=(c_conn, 256), daemon=True) + proc.start() + c_conn.close() + try: + df_small = _make_ohlcv(12, seed=5) + blocked_out = tmp_path / "blocked.csv" + p_conn.send( + ( + f"def compute(df, idx):\n df.to_csv({str(blocked_out)!r})\n return 1.0", + df_small, + False, + ) + ) + assert p_conn.poll(5.0) + status, payload = p_conn.recv() + assert status == "err" + assert "PermissionError" in str(payload) + assert not blocked_out.exists() + + # Deep PIT copy isolates underlying array buffer to [: idx + 1] + values = _execute_in_worker_namespace( + "def compute(df, idx):\n return float(len(df['close'].to_numpy().tolist()))\n", + df_small, + enforce_pit_slice=True, + ) + assert values == [float(i + 1) for i in range(len(df_small))] + assert df_small.iloc[:4].copy(deep=True)["close"].to_numpy().shape == (4,) + finally: + import contextlib + + with contextlib.suppress(Exception): + p_conn.send(None) + p_conn.close() + proc.join(timeout=3.0) + if proc.is_alive(): + proc.terminate() + proc.join(timeout=2.0) + + # 2. Governance keeps healthy negative-direction factor using true signed IR (not negated std) + base_start = date(2025, 1, 2) + gov_market: dict[str, pd.DataFrame] = {} + for sym_idx, sym in enumerate(("NEG1", "NEG2", "NEG3")): + n_bars = 140 + dates = [base_start + timedelta(days=i) for i in range(n_bars)] + arr = np.array( + [ + 100.0 * (1.0 + 0.04 * math.sin((i + sym_idx * 1.7) * math.pi / 5.0)) + for i in range(n_bars) + ], + dtype=float, + ) + gov_market[sym] = pd.DataFrame( + { + "date": dates, + "open": arr * 0.999, + "high": arr * 1.005, + "low": arr * 0.995, + "close": arr, + "volume": np.full(n_bars, 1_000_000.0), + } + ) + neg_db = tmp_path / "neg_gov.db" + with FactorStore(neg_db) as fs: + fs.save( + FactorRecord( + name="inverse_mean_reversion_healthy", + description="High above 5d mean predicts negative 5d forward return", + rationale="Negative expected_direction IC & IR test", + code=( + "def compute(df, idx):\n" + " if idx < 4:\n" + " return 0.0\n" + " w = df['close'].iloc[idx - 4 : idx + 1]\n" + " return float(df['close'].iloc[idx] / w.mean() - 1.0)\n" + ), + expected_direction="negative", + ) + ) + with FactorGovernanceEngine( + db_path=neg_db, + config=FactorGovernanceConfig( + train_ratio=0.55, + forward_horizon=5, + min_oos_ic=0.05, + min_oos_ir=0.20, + require_pit_invariance=True, + ), + ) as gov_eng: + neg_rep = gov_eng.audit_factors( + gov_market, strategies=[_make_strategy("ref_neg")], auto_retire=True + ) + neg_entry = neg_rep.entries[0] + assert neg_entry.health == "healthy", neg_entry.reasons + assert neg_entry.oos_ic < -0.05 + assert neg_entry.oos_ir < -0.20 + assert neg_entry.action_taken == "kept" + + # 3. Co-STEER rejects LLM factor names colliding with built-in indicators + colliding_synth = SimpleNamespace( + generate=lambda **kwargs: [ + SimpleNamespace( + name="rsi_14", + code="def compute(df, idx):\n return 50.0\n", + description="Built-in collision attempt", + expected_direction="positive", + ) + ] + ) + df_sample = gov_market["NEG1"] + strat_no_rsi = _make_strategy( + "collision_guard_v1", + conditions=[StrategyCondition(indicator="close_above_ma20", op="==", value=True)], + ) + with BlindSpotMiner(synthesizer=colliding_synth) as miner: + col_dec = miner.steer( + strat_no_rsi, + EvaluationReport( + strategy_id=strat_no_rsi.meta.id, + overall=OverallMetrics(win_rate=0.40, avg_return=-0.01, signal_count=20), + ), + df_sample, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + ) + assert col_dec.synthesized_via != "llm" + assert "rsi_14" not in IndicatorRegistry.dynamic_names() + + # 4. Round-end DSR refresh prevents early candidate promotion under stale trial count + dsr_market = {"D1": _make_ohlcv(90, seed=19), "D2": _make_ohlcv(90, seed=29)} + base_dsr = _make_strategy( + "dsr_round_end_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=55.0)], + ) + with StockRSIEngine(db_path=":memory:", enable_crossover=False) as dsr_engine: + charter_dsr = RSICharter( + name="dsr_refresh", + seed_strategy_id=base_dsr.meta.id, + allowed_levels=[RSILevel.L1_STRATEGY], + max_rounds=1, + max_candidates_per_round=2, + min_signals=5, + max_drawdown=0.5, + min_dsr_prob=0.70, + require_null_control=False, + ) + ch1 = [ + StrategyChange( + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[indicator=rsi_14].value", + from_value=55.0, + to_value=60.0, + reason="Candidate 1 early DSR", + ) + ] + ch2 = [ + StrategyChange( + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[indicator=rsi_14].value", + from_value=55.0, + to_value=65.0, + reason="Candidate 2 bumps family trials", + ) + ] + + def _fake_gen_dsr(parent, ev, **kwargs): + del parent, ev, kwargs + return [ + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", proposer_family="f1", rationale="C1", changes=ch1 + ), + audit=ProsecutorAudit( + prosecutor_model="p1", prosecutor_family="f2", approved=True + ), + ), + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", proposer_family="f1", rationale="C2", changes=ch2 + ), + audit=ProsecutorAudit( + prosecutor_model="p1", prosecutor_family="f2", approved=True + ), + ), + ] + + trials_seen = {"n": 0} + + def _fake_eval_dsr(self_arg, *, strategy, **kwargs): + del self_arg, kwargs + if strategy.meta.id == base_dsr.meta.id: + trials_seen["n"] = 1 + ov = OverallMetrics( + win_rate=0.45, avg_return=0.001, max_drawdown=0.05, signal_count=20 + ) + dsr_p = 0.40 + f_trials = 1 + elif abs(float(strategy.entry.conditions[0].value) - 60.0) < 1e-6: + trials_seen["n"] = 2 + ov = OverallMetrics( + win_rate=0.60, avg_return=0.02, max_drawdown=0.05, signal_count=20 + ) + dsr_p = 0.85 # passes at n_trials=2, fails when round-end trials becomes 3! + f_trials = 2 + else: + trials_seen["n"] = 3 + ov = OverallMetrics( + win_rate=0.50, avg_return=0.005, max_drawdown=0.05, signal_count=20 + ) + dsr_p = 0.30 + f_trials = 3 + sigs = [ + TradeSignal( + symbol="D1", + signal_date=date(2025, 1, 2) + timedelta(days=i), + direction=SignalDirection.LONG, + entry_price=100.0, + exit_price=101.0, + return_pct=0.01, + holding_days=1, + ) + for i in range(20) + ] + return SimpleNamespace( + evaluation=EvaluationReport( + strategy_id=strategy.meta.id, + overall=ov, + anti_overfit=AntiFitMetrics(), + confidence_score=ov.win_rate, + family_trial_count=f_trials, + deflated_sharpe_prob=dsr_p, + null_control_passed=True, + ), + backtest_result=BacktestResult( + strategy_id=strategy.meta.id, + batch_id="b_dsr", + signals=sigs, + ), + null_control=None, + portfolio_verdict=None, + trial_record=SimpleNamespace(trial_id=f"tr_{f_trials}"), + strategy_rerun_null=None, + ) + + with ( + patch.object(dsr_engine._council, "generate_candidates", side_effect=_fake_gen_dsr), + patch.object( + StockRSIEngine, "_eval_with_kernel", autospec=True, side_effect=_fake_eval_dsr + ), + patch.object( + dsr_engine._trial_ledger, + "count_family_trials", + side_effect=lambda _fid: trials_seen["n"], + ), + patch.object( + dsr_engine._trial_ledger, + "compute_dsr_for_trials", + side_effect=lambda **kw: ( + compute_deflated_sharpe( + 1.0, + max(1, int(kw["n_trials"])), + 20, + min_dsr_prob=0.70, + ) + if int(kw["n_trials"]) < 3 + else SimpleNamespace(dsr_probability=0.45) + ), + ), + ): + dsr_res = dsr_engine.run( + base_dsr, dsr_market, charter=charter_dsr, persist_champion=False + ) + assert dsr_res.promotions == 0 + c1_delibs = [d for d in dsr_res.deliberations if d.dsr_probability == pytest.approx(0.45)] + assert c1_delibs and "dsr_gate" in c1_delibs[0].veto_reasons + + # 5. FactorStore save failure aborts BEFORE marking trial accepted + fail_save_db = tmp_path / "fail_save.db" + fail_factor = "l2_save_fail_test_factor" + try: + with StockRSIEngine(db_path=fail_save_db, enable_crossover=False) as fs_engine: + rec = FactorRecord( + name=fail_factor, + description="fails persistence", + rationale="atomic order test", + code="def compute(df, idx):\n return 1.0\n", + expected_direction="positive", + ) + IndicatorRegistry.register_dynamic(fail_factor, lambda df, idx, ctx=None: 1.0) + l2_ch = [ + StrategyChange( + change_type=ChangeType.ADD_CONDITION, + target="entry.filters", + from_value=None, + to_value={"indicator": fail_factor, "op": ">=", "value": 0.5}, + reason="L2 keep candidate", + ) + ] + with ( + patch.object( + fs_engine._miner, + "steer", + return_value=SimpleNamespace( + chosen_level=RSILevel.L2_FACTOR, + cluster=SimpleNamespace(bottleneck_hint=""), + synthesized_factor_name=fail_factor, + synthesized_via="offline_template", + pit_verified=True, + persisted_to_store=False, + synthesized_factor_record=rec, + proposed_changes=l2_ch, + ), + ), + patch.object( + fs_engine._council, + "generate_candidates", + return_value=[ + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", + proposer_family="f1", + rationale="Use L2", + changes=l2_ch, + ), + audit=ProsecutorAudit( + prosecutor_model="p1", + prosecutor_family="f2", + approved=True, + ), + ) + ], + ), + patch.object( + fs_engine._factor_store, + "save_if_absent", + side_effect=RuntimeError("simulated sqlite failure"), + ), + patch.object(fs_engine._trial_ledger, "mark_trial_accepted") as spy_accept, + ): + charter_fail = RSICharter( + name="fail_save", + seed_strategy_id=base_dsr.meta.id, + allowed_levels=[RSILevel.L1_STRATEGY, RSILevel.L2_FACTOR], + max_rounds=1, + max_candidates_per_round=1, + min_signals=1, + max_drawdown=0.50, + min_dsr_prob=0.0, + require_null_control=False, + ) + + def _fake_eval_save_fail(self_arg, *, strategy, **kwargs): + del self_arg, kwargs + is_seed = strategy.meta.id == base_dsr.meta.id + wr = 0.45 if is_seed else 0.70 + ret = 0.002 if is_seed else 0.04 + return SimpleNamespace( + evaluation=EvaluationReport( + strategy_id=strategy.meta.id, + overall=OverallMetrics( + win_rate=wr, avg_return=ret, max_drawdown=0.05, signal_count=20 + ), + anti_overfit=AntiFitMetrics(), + confidence_score=wr, + deflated_sharpe_prob=0.90, + null_control_passed=True, + ), + null_control=None, + portfolio_verdict=None, + trial_record=SimpleNamespace(trial_id="t_fail_save"), + strategy_rerun_null=None, + ) + + with patch.object( + StockRSIEngine, + "_eval_with_kernel", + autospec=True, + side_effect=_fake_eval_save_fail, + ): + fs_res = fs_engine.run( + base_dsr, dsr_market, charter=charter_fail, persist_champion=False + ) + assert fs_res.promotions == 0 + assert spy_accept.call_count == 0 + assert any("factor_store_save_failed" in r.veto_reasons for r in fs_res.rows) + finally: + IndicatorRegistry.unregister_dynamic(fail_factor) + + +def test_round7_to_11_codex_second_pass_hardening_invariants(tmp_path: Path) -> None: + import os + + from alphaevo.alpha_factory.factory import _df_cache_key + from alphaevo.backtest.engine import BacktestResult + from alphaevo.core.config import BacktestConfig + from alphaevo.models.enums import SignalDirection + from alphaevo.models.execution import TradeSignal + from alphaevo.rsi.mechanism import HarnessVariant, MechanismEvaluator + + # 1. FactorSandbox.probe_pit runs in hardened spawn worker & FactorGovernanceEngine delegates to it + df_pit = _make_ohlcv(25, seed=31) + with FactorSandbox(timeout_seconds=10) as sb: + causal_code = ( + "def compute(df, idx):\n" + " if idx < 2:\n" + " return 0.0\n" + " return float(df['close'].iloc[idx] - df['close'].iloc[idx - 1])\n" + ) + assert sb.probe_pit(causal_code, df_pit).passed is True + leak_code = ( + "def compute(df, idx):\n" + " return float(df['close'].iloc[-1] - df['close'].iloc[idx])\n" + ) + assert sb.probe_pit(leak_code, df_pit).passed is False + + # Bypass preflight only to prove worker audit hook & _SafeModuleProxy enforce runtime limits in probe_pit + blocked_csv = tmp_path / "pit_blocked.csv" + with patch.object(sb, "preflight_code", return_value=(True, "")): + io_pit = sb.probe_pit( + f"def compute(df, idx):\n df.to_csv({str(blocked_csv)!r})\n return 1.0\n", + df_pit, + ) + np_pit = sb.probe_pit( + "import numpy as np\ndef compute(df, idx):\n return float(len(np.loadtxt('x')))\n", + df_pit, + ) + assert io_pit.passed is False + assert "PermissionError" in (io_pit.error or "") + assert not blocked_csv.exists() + assert np_pit.passed is False + assert "AttributeError" in (np_pit.error or "") + + gov_db = tmp_path / "gov_sandbox_pit.db" + with FactorStore(gov_db) as gfs: + gfs.save( + FactorRecord( + name="gov_sandbox_delegate_factor", + description="Causal momentum check", + rationale="Delegates PIT probe to self._sandbox.probe_pit", + code=( + "def compute(df, idx):\n" + " if idx < 3:\n" + " return 0.0\n" + " return float(df['close'].iloc[idx] / df['close'].iloc[idx - 2] - 1.0)\n" + ), + expected_direction="positive", + ) + ) + gov_market = { + "GA": _make_ohlcv(90, seed=1), + "GB": _make_ohlcv(90, seed=2), + } + with ( + FactorGovernanceEngine( + db_path=gov_db, + config=FactorGovernanceConfig( + train_ratio=0.55, + forward_horizon=5, + require_pit_invariance=True, + ), + ) as gov_eng, + patch.object( + gov_eng._sandbox, "probe_pit", wraps=gov_eng._sandbox.probe_pit + ) as spy_sandbox_pit, + patch( + "alphaevo.truth.pit_probe.probe_point_in_time_invariance", + side_effect=AssertionError("unhardened pit_probe worker must not be called"), + ), + ): + gov_rep = gov_eng.audit_factors( + gov_market, strategies=[_make_strategy("gov_ref_s1")], auto_retire=False + ) + assert spy_sandbox_pit.call_count == 1 + assert gov_rep.entries and gov_rep.entries[0].health != "pit_unsafe" + + # 2. _df_cache_key distinguishes identical-value int64 vs uint64 frames + df_i64 = pd.DataFrame({"close": pd.Series([5] * 6, dtype=np.int64)}) + df_u64 = pd.DataFrame({"close": pd.Series([5] * 6, dtype=np.uint64)}) + assert _df_cache_key(df_i64) != _df_cache_key(df_u64) + with FactorSandbox(timeout_seconds=10) as sb_dtype: + fn_dtype = _build_indicator_fn( + "def compute(df, idx):\n return float((df['close'] - 10).iloc[idx])\n", + sb_dtype, + ) + assert getattr(fn_dtype, "_alphaevo_factor_code_hash", None) is not None + with patch.object(sb_dtype, "execute", wraps=sb_dtype.execute) as spy_dtype_exec: + val_i = fn_dtype(df_i64, 2) + val_u = fn_dtype(df_u64, 2) + assert spy_dtype_exec.call_count == 2 + assert val_i == pytest.approx(-5.0) + assert val_u != val_i + + # 3. Co-STEER skips offline template whose name collides with an existing different dynamic callable + collide_name = "intraday_range_compression_10d" + collision_db = tmp_path / "offline_collide.db" + IndicatorRegistry.register_dynamic(collide_name, lambda df, idx, ctx=None: 999.0) + try: + with ( + FactorStore(collision_db) as fs_col, + BlindSpotMiner(factor_store=fs_col) as miner_col, + ): + dec_col = miner_col.steer( + _make_strategy( + "offline_col_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=60.0)], + ), + EvaluationReport( + strategy_id="offline_col_v1", + overall=OverallMetrics(win_rate=0.40, avg_return=-0.01, signal_count=20), + ), + df_pit, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + ) + assert dec_col.synthesized_factor_name != collide_name + assert fs_col.get(collide_name) is None + if dec_col.synthesized_factor_name: + IndicatorRegistry.unregister_dynamic(dec_col.synthesized_factor_name) + finally: + IndicatorRegistry.unregister_dynamic(collide_name) + + # 4. Unconditional round-end DSR refresh updates the LAST candidate AND MAP-Elites stores refreshed fitness + last_base = _make_strategy( + "last_cand_dsr_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=55.0)], + ) + dsr_mkt = {"D1": _make_ohlcv(90, seed=51), "D2": _make_ohlcv(90, seed=52)} + with StockRSIEngine(db_path=":memory:", enable_crossover=False) as dsr_eng2: + dsr_charter = RSICharter( + name="last_dsr_and_map_elites", + seed_strategy_id=last_base.meta.id, + objective="deflated_sharpe", + allowed_levels=[RSILevel.L1_STRATEGY], + max_rounds=1, + max_candidates_per_round=2, + min_signals=5, + max_drawdown=0.50, + min_dsr_prob=0.70, + require_null_control=False, + ) + ch_a = [ + StrategyChange( + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[indicator=rsi_14].value", + from_value=55.0, + to_value=60.0, + reason="Candidate A", + ) + ] + ch_b = [ + StrategyChange( + change_type=ChangeType.LOOSEN_FILTER, + target="entry.conditions[indicator=rsi_14].value", + from_value=55.0, + to_value=65.0, + reason="Last Candidate B", + ) + ] + + def _fake_gen2(parent, ev, **kwargs): + del parent, ev, kwargs + return [ + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", proposer_family="f1", rationale="A", changes=ch_a + ), + audit=ProsecutorAudit( + prosecutor_model="p1", prosecutor_family="f2", approved=True + ), + ), + SimpleNamespace( + proposal=CouncilProposal( + proposer_model="m1", proposer_family="f1", rationale="B", changes=ch_b + ), + audit=ProsecutorAudit( + prosecutor_model="p1", prosecutor_family="f2", approved=True + ), + ), + ] + + def _fake_eval2(self_arg, *, strategy, **kwargs): + del self_arg, kwargs + if strategy.meta.id == last_base.meta.id: + dsr_p, f_tr = 0.50, 1 + elif abs(float(strategy.entry.conditions[0].value) - 60.0) < 1e-6: + dsr_p, f_tr = 0.65, 2 + else: + dsr_p, f_tr = 0.90, 3 # Last candidate already has final count, pre-refresh high! + ov = OverallMetrics( + win_rate=0.55, + avg_return=0.01, + sharpe_ratio=1.2, + max_drawdown=0.05, + signal_count=20, + ) + sigs = [ + TradeSignal( + symbol="D1", + signal_date=date(2025, 1, 2) + timedelta(days=i), + direction=SignalDirection.LONG, + entry_price=100.0, + exit_price=101.0, + return_pct=0.01, + holding_days=1, + ) + for i in range(20) + ] + return SimpleNamespace( + evaluation=EvaluationReport( + strategy_id=strategy.meta.id, + overall=ov, + anti_overfit=AntiFitMetrics(), + confidence_score=0.55, + family_trial_count=f_tr, + deflated_sharpe_prob=dsr_p, + null_control_passed=True, + ), + backtest_result=BacktestResult( + strategy_id=strategy.meta.id, + batch_id="b_last", + signals=sigs, + ), + null_control=None, + portfolio_verdict=None, + trial_record=SimpleNamespace(trial_id=f"tr2_{f_tr}"), + strategy_rerun_null=None, + ) + + with ( + patch.object(dsr_eng2._council, "generate_candidates", side_effect=_fake_gen2), + patch.object( + StockRSIEngine, "_eval_with_kernel", autospec=True, side_effect=_fake_eval2 + ), + patch.object(dsr_eng2._trial_ledger, "count_family_trials", return_value=3), + patch.object( + dsr_eng2._trial_ledger, + "compute_dsr_for_trials", + return_value=SimpleNamespace(dsr_probability=0.20), + ) as spy_dsr, + ): + res2 = dsr_eng2.run(last_base, dsr_mkt, charter=dsr_charter, persist_champion=False) + assert spy_dsr.call_count == 2 + assert res2.promotions == 0 + # Seed enters archive with fitness 0.504; refreshed candidates fall to 0.354 and must NOT beat seed + assert res2.archive_summary is not None + assert res2.archive_summary.best_strategy_id == last_base.meta.id + assert res2.archive_summary.best_fitness == pytest.approx(0.504, abs=1e-4) + + # 5. MechanismEvaluator assigns synthetic dates & strict fwd_cutoffs to undated frames (zero warmup leak) + undated = pd.DataFrame( + { + "open": [100.0] * 60, + "high": [101.0] * 60, + "low": [99.0] * 60, + "close": [100.0] * 20 + [70.0] * 5 + [100.0] * 35, + "volume": [1_000_000.0] * 60, + } + ) + tr_u, fwd_u, cut_u = _temporal_split_with_warmup( + {"SYNTH": undated}, train_ratio=0.65, warmup_bars=30 + ) + assert "SYNTH" in cut_u + assert "date" in tr_u["SYNTH"].columns and "date" in fwd_u["SYNTH"].columns + oversold_strat = _make_strategy( + "undated_mech_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=40.0)], + ) + mech = MechanismEvaluator() + with patch.object( + StockRSIEngine, + "run", + return_value=SimpleNamespace( + champion_strategy=oversold_strat, + champion_evaluation=EvaluationReport( + strategy_id=oversold_strat.meta.id, + overall=OverallMetrics(win_rate=0.6, avg_return=0.02, signal_count=5), + ), + promotions=0, + total_trials_recorded=1, + ), + ): + paired = mech._run_single_variant( + seed_strategy=oversold_strat, + train_data=tr_u, + fwd_data=fwd_u, + fwd_cutoffs=cut_u, + variant=HarnessVariant(variant_id="v1", name="Base", require_null_control=False), + max_rounds=1, + seed=42, + ) + assert paired.forward_signals == 0 + + # 6. ArenaRunner with min_data_days=10 and short panel skips shadow replay instead of OOS baseline fallback + short_arena_market = { + "SHORT_A": _make_ohlcv(22, start=date(2025, 1, 2), seed=61), + "SHORT_B": _make_ohlcv(22, start=date(2025, 1, 2), seed=62), + } + snap_short = ArenaRunner(backtest_config=BacktestConfig(min_data_days=10)).run( + [_make_strategy("arena_short_v1")], + short_arena_market, + rounds=1, + enable_l2_factors=False, + enable_crossover=False, + seed=42, + ) + assert snap_short.entries[0].shadow_chain_verified is False + assert snap_short.chain_verified is False + + # 7. Crossover _summarize_exit_changes preserves None resets on TP trailing & ATR multiplier + p_trail = _make_strategy( + "p_trail", + sl=StopLossConfig(type="atr", multiplier=2.5, atr_period=14), + tp=TakeProfitConfig(type="trailing", trigger_pct=0.08, trail_pct=0.03), + ) + s_trail = _make_strategy( + "s_trail", + sl=StopLossConfig(type="pct", value=0.04), + tp=TakeProfitConfig(type="trailing"), + ) + reset_changes = SemanticCrossoverBreeder._summarize_exit_changes(p_trail, s_trail) + by_target = {c.target: c for c in reset_changes} + assert by_target["exit.stop_loss.multiplier"].to_value is None + assert by_target["exit.take_profit.trigger_pct"].to_value is None + assert by_target["exit.take_profit.trail_pct"].to_value is None + + # 8. Council _try_litellm_prosecutor fails closed when ALPHAEVO_API_KEY env var is set and ConfigManager.load fails + env_council = HeterogeneousCouncil( + config=HeterogeneousCouncilConfig( + proposer=ModelSpec(model="openai/gpt-6-astra"), + prosecutor=ModelSpec(model="anthropic/claude-opus-5.5", backend="litellm"), + ), + api_key=None, + ) + old_key = os.environ.get("ALPHAEVO_API_KEY") + os.environ["ALPHAEVO_API_KEY"] = "sk-env-fail-closed-test" + try: + with patch("alphaevo.core.config.ConfigManager.load", side_effect=RuntimeError("boom")): + env_veto = env_council._try_litellm_prosecutor( + p_trail, + EvaluationReport( + strategy_id=p_trail.meta.id, + overall=OverallMetrics(win_rate=0.5, signal_count=10), + ), + [], + env_council.config.prosecutor, + ) + finally: + if old_key is None: + os.environ.pop("ALPHAEVO_API_KEY", None) + else: + os.environ["ALPHAEVO_API_KEY"] = old_key + assert env_veto and "fail-closed" in env_veto[0] + + +def test_round7_to_11_codex_third_pass_edge_cases(tmp_path: Path) -> None: + from alphaevo.alpha_factory.factory import _df_cache_key + from alphaevo.reflection.critic import SelfCritic + from alphaevo.reflection.mutator import StrategyMutator + from alphaevo.rsi.co_steer import _OFFLINE_FACTOR_TEMPLATES + from alphaevo.rsi.mechanism import HarnessVariant, MechanismEvaluator + + # 1. Mechanism per-cutoff execution: warmup entries before dated cutoff never block post-cutoff entries + # Dated symbol dips during warmup (2025-03-26..28, while its cutoff is 2025-04-01) so position is closed or skipped, + # and dips AGAIN on 2025-04-01..02; mixed with an earlier undated symbol whose synthetic cutoff is 2020. + n_dated = 45 + dated_start = date(2025, 2, 18) + dated_dates = [dated_start + timedelta(days=i) for i in range(n_dated)] + # Make dip on indices 36..41 (Mar 26 .. Mar 31) and again on indices 42..44 (Apr 1 .. Apr 3) + dated_closes = [100.0] * n_dated + for i in range(36, 42): + dated_closes[i] = 75.0 + dated_df = pd.DataFrame( + { + "date": dated_dates, + "open": dated_closes, + "high": [c * 1.01 for c in dated_closes], + "low": [c * 0.99 for c in dated_closes], + "close": dated_closes, + "volume": [1_500_000.0] * n_dated, + } + ) + undated_df = pd.DataFrame( + { + "open": [100.0] * 45, + "high": [101.0] * 45, + "low": [99.0] * 45, + "close": [100.0] * 45, + "volume": [1_500_000.0] * 45, + } + ) + tr_mix, fwd_mix, cut_mix = _temporal_split_with_warmup( + {"DATED": dated_df, "UNDATED": undated_df}, train_ratio=0.70, warmup_bars=25 + ) + assert "DATED" in cut_mix and "UNDATED" in cut_mix + # Override DATED cutoff to index 41 (2025-03-31) after warmup dip (36..40) that would otherwise stay open + # under min(cutoffs) (2020) and block entry on 2025-04-01 with max_holding_days=10! + cut_override = {"DATED": dated_dates[41], "UNDATED": cut_mix["UNDATED"]} + trig_strat = _make_strategy( + "mech_multi_cut_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=45.0)], + tp=TakeProfitConfig(type="pct", value=0.50), + sl=StopLossConfig(type="pct", value=0.50), + ) + trig_strat.exit.max_holding_days = 15 + mech_ev = MechanismEvaluator() + with patch.object( + StockRSIEngine, + "run", + return_value=SimpleNamespace( + champion_strategy=trig_strat, + champion_evaluation=EvaluationReport( + strategy_id=trig_strat.meta.id, + overall=OverallMetrics(win_rate=0.5, avg_return=0.01, signal_count=5), + ), + promotions=0, + total_trials_recorded=1, + ), + ): + paired_mix = mech_ev._run_single_variant( + seed_strategy=trig_strat, + train_data=tr_mix, + fwd_data={"DATED": dated_df, "UNDATED": fwd_mix["UNDATED"]}, + fwd_cutoffs=cut_override, + variant=HarnessVariant(variant_id="mix", name="Mix", require_null_control=False), + max_rounds=1, + seed=42, + ) + assert paired_mix.forward_signals >= 1 + + # 2. Co-STEER blocks reactivation of retired offline templates, unloaded LLM name reuse, and active metric wipes + tpl = next(t for t in _OFFLINE_FACTOR_TEMPLATES if t.name == "trend_alignment_slope_20d") + retired_db = tmp_path / "retired_co_steer.db" + sample_df = _make_ohlcv(25, seed=77) + try: + with FactorStore(retired_db) as rfs: + rfs.save( + FactorRecord( + name=tpl.name, + description="Previously retired offline template", + rationale="Must stay retired", + code=tpl.code, + expected_direction=tpl.expected_direction, + status="retired", + ) + ) + rfs.save( + FactorRecord( + name="custom_retired_llm_factor", + description="Retired unloaded LLM factor", + rationale="Must not be overwritten", + code="def compute(df, idx):\n return 0.0\n", + expected_direction="positive", + status="retired", + ) + ) + ret_synth = SimpleNamespace( + generate=lambda **kwargs: [ + SimpleNamespace( + name="custom_retired_llm_factor", + code="def compute(df, idx):\n return 1.0\n", + description="Overwrite retired factor", + expected_direction="positive", + ) + ] + ) + with BlindSpotMiner(factor_store=rfs, synthesizer=ret_synth) as r_miner: + dec_ret = r_miner.steer( + _make_strategy( + "ret_strat_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=60.0)], + ), + EvaluationReport( + strategy_id="ret_strat_v1", + overall=OverallMetrics(win_rate=0.40, avg_return=-0.01, signal_count=20), + ), + sample_df, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + persist=True, + ) + assert dec_ret.synthesized_factor_name != tpl.name + assert dec_ret.synthesized_factor_name != "custom_retired_llm_factor" + assert rfs.get(tpl.name).status == "retired" # type: ignore[union-attr] + assert ( + rfs.get("custom_retired_llm_factor").code # type: ignore[union-attr] + == "def compute(df, idx):\n return 0.0\n" + ) + if dec_ret.synthesized_factor_name: + IndicatorRegistry.unregister_dynamic(dec_ret.synthesized_factor_name) + finally: + IndicatorRegistry.unregister_dynamic(tpl.name) + + # Active offline factor keeps existing governance metrics/usage_count on reuse + active_db = tmp_path / "active_preserve.db" + try: + with FactorStore(active_db) as afs: + afs.save( + FactorRecord( + name=tpl.name, + description=tpl.description, + rationale="Tracked active factor", + code=tpl.code, + expected_direction=tpl.expected_direction, + ic_mean=0.14, + ic_std=0.05, + ir=2.8, + usage_count=9, + status="active", + ) + ) + with BlindSpotMiner(factor_store=afs) as a_miner: + dec_act = a_miner.steer( + _make_strategy( + "act_strat_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=60.0)], + ), + EvaluationReport( + strategy_id="act_strat_v1", + overall=OverallMetrics(win_rate=0.40, avg_return=-0.01, signal_count=20), + ), + sample_df, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + persist=True, + ) + assert dec_act.synthesized_factor_name == tpl.name + stored_after = afs.get(tpl.name) + assert stored_after is not None + assert stored_after.ic_mean == pytest.approx(0.14) + assert stored_after.usage_count == 9 + finally: + IndicatorRegistry.unregister_dynamic(tpl.name) + + # 3. _df_cache_key distinguishes identical-value CategoricalDtype frames with reversed categories + df_cat1 = pd.DataFrame( + {"tag": pd.Categorical(["a", "b", "a", "b"], categories=["a", "b"], ordered=True)} + ) + df_cat2 = pd.DataFrame( + {"tag": pd.Categorical(["a", "b", "a", "b"], categories=["b", "a"], ordered=True)} + ) + assert _df_cache_key(df_cat1) != _df_cache_key(df_cat2) + with FactorSandbox(timeout_seconds=10) as sb_cat: + fn_cat = _build_indicator_fn( + "def compute(df, idx):\n return float(df['tag'].cat.codes.iloc[idx])\n", + sb_cat, + ) + assert fn_cat(df_cat1, 0) == pytest.approx(0.0) + assert fn_cat(df_cat2, 0) == pytest.approx(1.0) + + # 4. Exit-graft preserves overlapping fields on type transitions so SelfCritic/Mutator replay identically + p_pl = _make_strategy("p_pl_eq", sl=StopLossConfig(type="pct", value=0.04)) + s_pl = _make_strategy("s_pl_eq", sl=StopLossConfig(type="price_level", value=0.04)) + summary = SemanticCrossoverBreeder._summarize_exit_changes(p_pl, s_pl) + targets = [c.target for c in summary] + assert targets == ["exit.stop_loss.type", "exit.stop_loss.value"] + replayed = StrategyMutator(max_changes=10).mutate(p_pl, summary, atomic=True) + assert replayed.exit.stop_loss.type == "price_level" + assert replayed.exit.stop_loss.value == pytest.approx(0.04) + verdict = SelfCritic().critique( + p_pl, + EvaluationReport( + strategy_id=p_pl.meta.id, + overall=OverallMetrics(win_rate=0.52, avg_return=0.015, signal_count=25), + ), + SimpleNamespace(proposed_changes=summary), # type: ignore[arg-type] + ) + assert len(verdict.rejected) == 0 + + +def test_round7_to_11_codex_fourth_pass_invariants(tmp_path: Path) -> None: + from alphaevo.alpha_factory.factory import _df_cache_key + from alphaevo.reflection.critic import SelfCritic + from alphaevo.reflection.mutator import StrategyMutator + from alphaevo.rsi.co_steer import _OFFLINE_FACTOR_TEMPLATES + from alphaevo.rsi.engine import _acquire_dynamic_lease, _release_dynamic_lease_entry + from alphaevo.rsi.mechanism import HarnessVariant, MechanismEvaluator + from alphaevo.truth.kernel import EvaluationKernel + from alphaevo.truth.null_control import NullSignalController + + sample_df = _make_ohlcv(25, seed=91) + tpl = next(t for t in _OFFLINE_FACTOR_TEMPLATES if t.name == "trend_alignment_slope_20d") + + # 1. Atomic FactorStore.save_if_absent blocks competing overwrites/reactivations + atomic_db = tmp_path / "atomic_fs.db" + with FactorStore(atomic_db) as afs: + retired_rec = FactorRecord( + name="atomic_race_factor", + description="Originally retired", + rationale="Do not reactivate", + code="def compute(df, idx):\n return 0.0\n", + expected_direction="positive", + status="retired", + ) + stored1, ins1 = afs.save_if_absent(retired_rec) + assert ins1 is True + assert stored1.status == "retired" + + competing_rec = FactorRecord( + name="atomic_race_factor", + description="Competing overwrite", + rationale="Should lose race cleanly", + code="def compute(df, idx):\n return 1.0\n", + expected_direction="positive", + status="active", + ) + stored2, ins2 = afs.save_if_absent(competing_rec) + assert ins2 is False + assert stored2.status == "retired" + assert stored2.code == "def compute(df, idx):\n return 0.0\n" + + # Simulate BlindSpotMiner.steer racing with another writer on save_if_absent -> rollback to L1 + with ( + patch.object(afs, "get", return_value=None), + patch.object(afs, "save_if_absent", return_value=(retired_rec, False)), + BlindSpotMiner(factor_store=afs) as race_miner, + ): + try: + dec_race = race_miner.steer( + _make_strategy( + "race_l1_fallback_v1", + conditions=[StrategyCondition(indicator="rsi_14", op="<=", value=60.0)], + ), + EvaluationReport( + strategy_id="race_l1_fallback_v1", + overall=OverallMetrics(win_rate=0.40, avg_return=-0.01, signal_count=20), + ), + sample_df, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + persist=True, + ) + finally: + IndicatorRegistry.unregister_dynamic(tpl.name) + assert dec_race.chosen_level == RSILevel.L1_STRATEGY + assert dec_race.proposed_changes == [] + assert not IndicatorRegistry.is_registered(tpl.name) + + # 2. Lease refcounting protects shared transient dynamic factors across concurrent RSI runs + lease_db = tmp_path / "lease_fs.db" + shared_factor = "concurrent_lease_test_factor" + dummy_strat = _make_strategy("lease_dummy_v1") + with FactorStore(lease_db) as lfs: + IndicatorRegistry.register_dynamic(shared_factor, lambda df, idx, ctx=None: 1.0) + try: + rec_lease = FactorRecord( + name=shared_factor, + description="Concurrent transient", + rationale="Lease test", + code="def compute(df, idx):\n return 1.0\n", + expected_direction="positive", + ) + l1 = _acquire_dynamic_lease( + shared_factor, + in_pre_registered=False, + factor_record=rec_lease, + factor_store=lfs, + ) + l2 = _acquire_dynamic_lease( + shared_factor, + in_pre_registered=True, + factor_record=rec_lease, + factor_store=lfs, + ) + assert l1 == shared_factor and l2 == shared_factor + _release_dynamic_lease_entry(l1, persisted=False, protected_strategies=(dummy_strat,)) + # Run 2 is still active -> factor MUST remain registered! + assert IndicatorRegistry.is_registered(shared_factor) is True + _release_dynamic_lease_entry(l2, persisted=False, protected_strategies=(dummy_strat,)) + # Last lease released -> transient factor cleanly unregistered! + assert IndicatorRegistry.is_registered(shared_factor) is False + finally: + IndicatorRegistry.unregister_dynamic(shared_factor) + + # 3. Mechanism forward null test receives strictly OOS-only bars (no pre-cutoff warmup rows) + mech_df = _make_ohlcv(70, start=date(2025, 1, 2), seed=88) + tr_n, fwd_n, cut_n = _temporal_split_with_warmup( + {"NULL_CHK": mech_df}, train_ratio=0.65, warmup_bars=25 + ) + strat_n = _make_strategy("mech_null_oos_v1") + captured_null_dfs: list[dict[str, pd.DataFrame]] = [] + orig_null = NullSignalController.evaluate_candidate_against_nulls + + def _spy_null(self_arg, signals, market_data, **kwargs): + captured_null_dfs.append({k: v.copy() for k, v in market_data.items()}) + return orig_null(self_arg, signals, market_data, **kwargs) + + with ( + patch.object( + StockRSIEngine, + "run", + return_value=SimpleNamespace( + champion_strategy=strat_n, + champion_evaluation=EvaluationReport( + strategy_id=strat_n.meta.id, + overall=OverallMetrics(win_rate=0.6, avg_return=0.02, signal_count=10), + ), + promotions=1, + total_trials_recorded=1, + ), + ), + patch.object(EvaluationKernel, "evaluate") as mock_ke, + patch.object( + NullSignalController, + "evaluate_candidate_against_nulls", + autospec=True, + side_effect=_spy_null, + ), + ): + from alphaevo.models.enums import SignalDirection + from alphaevo.models.execution import BacktestResult, TradeSignal + + fut_sigs = [ + TradeSignal( + symbol="NULL_CHK", + signal_date=cut_n["NULL_CHK"] + timedelta(days=i), + direction=SignalDirection.LONG, + entry_price=100.0, + exit_price=102.0, + return_pct=0.02, + holding_days=1, + ) + for i in range(6) + ] + mock_ke.return_value = SimpleNamespace( + backtest_result=BacktestResult( + strategy_id=strat_n.meta.id, + batch_id="b_null", + signals=fut_sigs, + total_signals=6, + executed_signals=6, + skipped_signals=0, + date_range=(cut_n["NULL_CHK"], cut_n["NULL_CHK"] + timedelta(days=5)), + ), + evaluation=EvaluationReport( + strategy_id=strat_n.meta.id, + overall=OverallMetrics(win_rate=1.0, avg_return=0.02, signal_count=6), + ), + portfolio_verdict=None, + ) + MechanismEvaluator()._run_single_variant( + seed_strategy=strat_n, + train_data=tr_n, + fwd_data=fwd_n, + fwd_cutoffs=cut_n, + variant=HarnessVariant(variant_id="n", name="Null", require_null_control=False), + max_rounds=1, + seed=42, + ) + assert len(captured_null_dfs) == 1 + null_dates = pd.to_datetime(captured_null_dfs[0]["NULL_CHK"]["date"]).dt.date + assert (null_dates >= cut_n["NULL_CHK"]).all() + + # 4. Governance never retires active factors when disjoint calendars yield empty train/OOS split + disjoint_data = { + str(y): pd.DataFrame( + { + "date": pd.date_range(f"{y}-01-01", periods=40), + "open": range(1, 41), + "high": [x + 1 for x in range(1, 41)], + "low": list(range(1, 41)), + "close": range(1, 41), + "volume": [100_000.0] * 40, + } + ) + for y in (2023, 2025) + } + disjoint_db = tmp_path / "disjoint_gov.db" + with FactorStore(disjoint_db) as dfs: + dfs.save( + FactorRecord( + name="disjoint_kept_factor", + description="Must not auto-retire on empty panel split", + rationale="Disjoint calendar safety", + code="def compute(df, idx):\n return 1.0\n", + expected_direction="positive", + status="active", + ) + ) + with FactorGovernanceEngine( + db_path=disjoint_db, + config=FactorGovernanceConfig(train_ratio=0.5, require_pit_invariance=False), + ) as d_gov: + d_rep = d_gov.audit_factors(disjoint_data, strategies=[], auto_retire=True) + assert d_rep.retired_count == 0 + assert d_rep.entries[0].action_taken == "kept" + with FactorStore(disjoint_db) as chk_fs: + assert chk_fs.get("disjoint_kept_factor").status == "active" # type: ignore[union-attr] + + # 5. CategoricalDtype int64 vs uint64 categories distinguish column & CategoricalIndex cache keys + df_ci64 = pd.DataFrame( + {"c": pd.Categorical([1, 2, 1, 2], categories=pd.Index([1, 2], dtype=np.int64))}, + index=pd.CategoricalIndex([1, 2, 1, 2], categories=pd.Index([1, 2], dtype=np.int64)), + ) + df_cu64 = pd.DataFrame( + {"c": pd.Categorical([1, 2, 1, 2], categories=pd.Index([1, 2], dtype=np.uint64))}, + index=pd.CategoricalIndex([1, 2, 1, 2], categories=pd.Index([1, 2], dtype=np.uint64)), + ) + assert _df_cache_key(df_ci64) != _df_cache_key(df_cu64) + with FactorSandbox(timeout_seconds=10) as sb_cdtype: + fn_cdtype = _build_indicator_fn( + "def compute(df, idx):\n return 1.0 if df['c'].cat.categories.dtype.kind == 'u' else 0.0\n", + sb_cdtype, + ) + assert fn_cdtype(df_ci64, 0) == pytest.approx(0.0) + assert fn_cdtype(df_cu64, 0) == pytest.approx(1.0) + + # 6. Composite->pct exit_graft preserves None conditions & prunes dangling exit tunables identically on replay + p_comp = _make_strategy( + "p_comp_r", + sl=StopLossConfig( + type="composite", + conditions=[StrategyCondition(indicator="close_below_ma10", op="==", value=True)], + ), + tunable=[ + TunableParam(target="exit.stop_loss.value", range=(0.02, 0.08), step=0.01), + TunableParam(target="exit.max_holding_days", range=(5, 20), step=5), + ], + ) + s_pct = _make_strategy("s_pct_r", sl=StopLossConfig(type="pct", value=0.04)) + comp_cands = SemanticCrossoverBreeder().breed(p_comp, s_pct, max_children=3) + comp_graft = next(c for c in comp_cands if c.operator == "exit_graft") + replayed_comp = StrategyMutator(max_changes=20).mutate( + p_comp, comp_graft.summary_changes, atomic=True + ) + assert replayed_comp.exit == comp_graft.child_strategy.exit + assert replayed_comp.params.tunable == comp_graft.child_strategy.params.tunable + + # Also ATR exit_graft drops exit.stop_loss.value tunable identically on replay + p_atr = _make_strategy( + "p_atr_r", + sl=StopLossConfig(type="pct", value=0.04), + tunable=[TunableParam(target="exit.stop_loss.value", range=(0.02, 0.08), step=0.01)], + ) + s_atr = _make_strategy( + "s_atr_r", + conditions=[StrategyCondition(indicator="momentum_10d", op=">", value=0.02)], + sl=StopLossConfig(type="atr", multiplier=2.0, atr_period=14), + ) + atr_graft = next( + c + for c in SemanticCrossoverBreeder().breed(p_atr, s_atr, max_children=3) + if c.operator == "exit_graft" + ) + replayed_atr = StrategyMutator(max_changes=20).mutate( + p_atr, atr_graft.summary_changes, atomic=True + ) + assert replayed_atr.exit == atr_graft.child_strategy.exit + assert replayed_atr.params.tunable == atr_graft.child_strategy.params.tunable + + # 7. Legacy multi-AND trigger_blend replay reproduces triggers + guards + entry.logic + tunables identically + p_leg = _make_strategy( + "p_leg_r", + logic="and", + conditions=[ + StrategyCondition(indicator="rsi_14", op="<=", value=40.0), + StrategyCondition(indicator="close_above_ma20", op="==", value=True), + ], + tunable=[ + TunableParam(target="entry.conditions[indicator=rsi_14].value", range=(25, 50), step=5), + TunableParam( + target="entry.conditions[indicator=close_above_ma20].value", + range=(0, 1), + step=1, + ), + ], + ) + s_leg = _make_strategy( + "s_leg_r", + conditions=[StrategyCondition(indicator="momentum_10d", op=">", value=0.02)], + ) + leg_blend = next( + c + for c in SemanticCrossoverBreeder().breed(p_leg, s_leg, max_children=3) + if c.operator == "trigger_blend" + ) + replayed_blend = StrategyMutator(max_changes=10).mutate( + p_leg, leg_blend.summary_changes, atomic=True + ) + assert replayed_blend.entry == leg_blend.child_strategy.entry + assert replayed_blend.params.tunable == leg_blend.child_strategy.params.tunable + verdict_blend = SelfCritic().critique( + p_leg, + EvaluationReport( + strategy_id=p_leg.meta.id, + overall=OverallMetrics(win_rate=0.30, avg_return=0.01, signal_count=25), + ), + SimpleNamespace(proposed_changes=leg_blend.summary_changes), # type: ignore[arg-type] + ) + assert len(verdict_blend.rejected) == 0 + + +def test_round7_to_11_codex_fifth_pass_invariants(tmp_path: Path) -> None: + from alphaevo.alpha_factory.factory import _df_cache_key + from alphaevo.models.enums import SignalDirection + from alphaevo.models.execution import BacktestResult, TradeSignal + from alphaevo.reflection.mutator import StrategyMutator + from alphaevo.rsi.mechanism import HarnessVariant, MechanismEvaluator + from alphaevo.strategy.tunable import resolve_tunable_target + from alphaevo.truth.kernel import EvaluationKernel + + sample_df = _make_ohlcv(25, seed=97) + + # 1. Atomic co_steer registration + exception-safe lease cleanup in StockRSIEngine.run + from alphaevo.rsi.co_steer import _DYNAMIC_LEASES, _TRANSIENT_FACTORS + + synth_code = "def compute(df, idx):\n return float(df['close'].iloc[idx] * 0.01)\n" + atomic_factor = "trend_alignment_slope_20d" + + lease_db = tmp_path / "atomic_lease.db" + strat_l = _make_strategy("atomic_l_v1") + weak_ev = EvaluationReport( + strategy_id=strat_l.meta.id, + overall=OverallMetrics(win_rate=0.40, avg_return=-0.01, signal_count=20), + ) + try: + with FactorStore(lease_db) as lfs: + m1 = BlindSpotMiner(factor_store=lfs) + m2 = BlindSpotMiner(factor_store=lfs) + with m1, m2: + # Run 1 publishes and atomically acquires lease #1 + d1 = m1.steer( + strat_l, + weak_ev, + sample_df, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + persist=False, + acquire_lease=True, + ) + assert d1.synthesized_factor_name == atomic_factor + assert d1.lease_acquired is True + assert atomic_factor in _TRANSIENT_FACTORS + assert _DYNAMIC_LEASES.get(atomic_factor) == 1 + + # Run 2 enters AFTER IndicatorRegistry sees atomic_factor -> MUST still acquire lease #2 + assert IndicatorRegistry.is_registered(atomic_factor) + d2 = m2.steer( + strat_l, + weak_ev, + sample_df, + allowed_levels=[RSILevel.L2_FACTOR], + stagnant_l1_rounds=3, + persist=False, + acquire_lease=True, + ) + assert d2.synthesized_factor_name == atomic_factor + assert d2.lease_acquired is True + assert _DYNAMIC_LEASES.get(atomic_factor) == 2 + + # Releasing Run 1 keeps atomic_factor alive for Run 2 + from alphaevo.rsi.co_steer import release_dynamic_lease + + release_dynamic_lease( + atomic_factor, persisted=False, protected_strategies=(strat_l,) + ) + assert IndicatorRegistry.is_registered(atomic_factor) is True + release_dynamic_lease( + atomic_factor, persisted=False, protected_strategies=(strat_l,) + ) + assert IndicatorRegistry.is_registered(atomic_factor) is False + + # Exception inside StockRSIEngine.run after steer releases transient lease cleanly + exc_factor = "exception_cleanup_lease_factor" + with StockRSIEngine(db_path=":memory:", enable_crossover=False) as exc_eng: + + def _boom_steer(*args, **kwargs): + del args, kwargs + IndicatorRegistry.register_dynamic(exc_factor, lambda df, idx, ctx=None: 1.0) + return SimpleNamespace( + chosen_level=RSILevel.L2_FACTOR, + cluster=SimpleNamespace(bottleneck_hint=""), + synthesized_factor_name=exc_factor, + synthesized_via="offline_template", + pit_verified=True, + persisted_to_store=False, + lease_acquired=False, + synthesized_factor_record=FactorRecord( + name=exc_factor, + description="exc", + rationale="exc", + code=synth_code, + expected_direction="positive", + ), + proposed_changes=[], + ) + + with ( + patch.object(exc_eng._miner, "steer", side_effect=_boom_steer), + patch.object( + exc_eng._council, "generate_candidates", side_effect=RuntimeError("boom") + ), + pytest.raises(RuntimeError, match="boom"), + ): + exc_eng.run( + strat_l, + {"M1": _make_ohlcv(50, seed=5)}, + charter=RSICharter( + name="exc_lease", + seed_strategy_id=strat_l.meta.id, + max_rounds=1, + null_permutations=10, + ), + persist_champion=False, + ) + assert not IndicatorRegistry.is_registered(exc_factor) + assert exc_factor not in _DYNAMIC_LEASES + finally: + IndicatorRegistry.unregister_dynamic(atomic_factor) + + # 2. Governance never retires active factor when OOS length <= forward_horizon (0 valid labels) + staggered_short = { + "SHORT_A": _make_ohlcv(30, start=date(2025, 1, 1), seed=1), + "SHORT_B": _make_ohlcv(30, start=date(2025, 1, 5), seed=2), + } + hz_db = tmp_path / "gov_horizon_nan.db" + with FactorStore(hz_db) as hfs: + hfs.save( + FactorRecord( + name="zero_oos_label_kept_factor", + description="Must survive when OOS window <= forward_horizon", + rationale="No bogus 0-label retirement", + code="def compute(df, idx):\n return 1.0\n", + expected_direction="positive", + status="active", + ) + ) + with FactorGovernanceEngine( + db_path=hz_db, + config=FactorGovernanceConfig( + train_ratio=0.5, forward_horizon=20, require_pit_invariance=False + ), + ) as hgov: + hrep = hgov.audit_factors(staggered_short, strategies=[], auto_retire=True) + assert hrep.retired_count == 0 + assert hrep.entries[0].action_taken == "kept" + + # 3. _df_cache_key distinguishes object-dtype [1, 2] vs ["1", "2"] + df_obj_int = pd.DataFrame({"v": pd.Series([1, 2, 1, 2], dtype=object)}) + df_obj_str = pd.DataFrame({"v": pd.Series(["1", "2", "1", "2"], dtype=object)}) + assert _df_cache_key(df_obj_int) != _df_cache_key(df_obj_str) + with FactorSandbox(timeout_seconds=10) as sb_obj: + fn_obj = _build_indicator_fn( + "def compute(df, idx):\n return 1.0 if isinstance(df['v'].iloc[idx], str) else 0.0\n", + sb_obj, + ) + assert fn_obj(df_obj_int, 0) == pytest.approx(0.0) + assert fn_obj(df_obj_str, 0) == pytest.approx(1.0) + + # 4. Mechanism forward null test refuses centered fallback when OOS length < avg_hold + 3 + short_oos_df = _make_ohlcv(40, start=date(2025, 1, 1), seed=19) + tr_s = {"S1": short_oos_df.iloc[:28].copy().reset_index(drop=True)} + fwd_s = {"S1": short_oos_df.iloc[28:].copy().reset_index(drop=True)} # 12 bars + cut_s = {"S1": short_oos_df["date"].iloc[28]} + ident_sigs = [ + TradeSignal( + symbol="S1", + signal_date=short_oos_df["date"].iloc[28 + i], + direction=SignalDirection.LONG, + entry_price=100.0, + exit_price=104.0, + return_pct=0.04, + holding_days=10, + ) + for i in range(5) + ] + strat_s = _make_strategy("mech_deg_null_v1") + with ( + patch.object( + StockRSIEngine, + "run", + return_value=SimpleNamespace( + champion_strategy=strat_s, + champion_evaluation=EvaluationReport( + strategy_id=strat_s.meta.id, + overall=OverallMetrics(win_rate=0.6, avg_return=0.02, signal_count=10), + ), + promotions=1, + total_trials_recorded=1, + ), + ), + patch.object( + EvaluationKernel, + "evaluate", + return_value=SimpleNamespace( + backtest_result=BacktestResult( + strategy_id=strat_s.meta.id, + batch_id="b_deg", + signals=ident_sigs, + total_signals=5, + executed_signals=5, + skipped_signals=0, + date_range=(short_oos_df["date"].iloc[28], short_oos_df["date"].iloc[39]), + ), + evaluation=EvaluationReport( + strategy_id=strat_s.meta.id, + overall=OverallMetrics(win_rate=1.0, avg_return=0.04, signal_count=5), + ), + portfolio_verdict=None, + ), + ), + ): + paired_deg = MechanismEvaluator()._run_single_variant( + seed_strategy=strat_s, + train_data=tr_s, + fwd_data=fwd_s, + fwd_cutoffs=cut_s, + variant=HarnessVariant(variant_id="deg", name="Deg", require_null_control=False), + max_rounds=1, + seed=42, + ) + assert paired_deg.false_promotion is True + + # 5. Legacy multi-AND trigger_blend remaps positional entry.conditions[0/1] accurately with guard offset + p_pos = _make_strategy( + "p_pos_blend", + logic="and", + conditions=[ + StrategyCondition(indicator="rsi_14", op="<=", value=35.0), + StrategyCondition(indicator="close_above_ma20", op="==", value=True), + ], + guards=[StrategyCondition(indicator="ma5_above_ma10", op="==", value=True)], + tunable=[ + TunableParam(target="entry.conditions[0].value", range=(20, 45), step=5), + TunableParam(target="entry.conditions[1].value", range=(0, 1), step=1), + ], + ) + s_pos = _make_strategy( + "s_pos_blend", + conditions=[StrategyCondition(indicator="momentum_10d", op=">", value=0.02)], + ) + pos_blend = next( + c + for c in SemanticCrossoverBreeder().breed(p_pos, s_pos, max_children=3) + if c.operator == "trigger_blend" + ) + rep_pos = StrategyMutator(max_changes=10).mutate(p_pos, pos_blend.summary_changes, atomic=True) + expected_tgts = ["entry.triggers[0].value", "entry.guards[1].value"] + assert [p.target for p in pos_blend.child_strategy.params.tunable] == expected_tgts + assert [p.target for p in rep_pos.params.tunable] == expected_tgts + assert resolve_tunable_target(rep_pos, "entry.triggers[0].value") == 35.0 + assert resolve_tunable_target(rep_pos, "entry.guards[1].value") is True + + # 6. Exit-graft None vs [] conditions replay faithfully + p_none_c = _make_strategy( + "p_none_c", sl=StopLossConfig(type="pct", value=0.04, conditions=None) + ) + s_empty_c = _make_strategy( + "s_empty_c", + conditions=[StrategyCondition(indicator="momentum_10d", op=">", value=0.02)], + sl=StopLossConfig(type="pct", value=0.04, conditions=[]), + ) + empty_graft = next( + c + for c in SemanticCrossoverBreeder().breed(p_none_c, s_empty_c, max_children=3) + if c.operator == "exit_graft" + ) + assert any(c.target == "exit.stop_loss.conditions" for c in empty_graft.summary_changes) + rep_empty_c = StrategyMutator(max_changes=10).mutate( + p_none_c, empty_graft.summary_changes, atomic=True + ) + assert rep_empty_c.exit.stop_loss.conditions == [] diff --git a/tests/unit/test_sandbox.py b/tests/unit/test_sandbox.py index adcd2ea..5674ade 100644 --- a/tests/unit/test_sandbox.py +++ b/tests/unit/test_sandbox.py @@ -188,15 +188,17 @@ def test_execution_time_tracked(self): def test_execute_passes_configured_memory_limit_to_subprocess(self): sandbox = FactorSandbox(timeout_seconds=1, max_memory_mb=128) + try: + with patch("alphaevo.alpha_factory.sandbox._SPAWN_CTX.Process") as MockProcess: + proc = MockProcess.return_value + proc.is_alive.return_value = False - with patch("alphaevo.alpha_factory.sandbox.multiprocessing.Process") as MockProcess: - proc = MockProcess.return_value - proc.is_alive.return_value = False + sandbox.execute(_GOOD_CODE, self.df) - sandbox.execute(_GOOD_CODE, self.df) - - process_args = MockProcess.call_args.kwargs["args"] - assert process_args[3] == 128 + process_args = MockProcess.call_args.kwargs["args"] + assert process_args[1] == 128 + finally: + sandbox.close() # --------------------------------------------------------------------------- @@ -319,10 +321,7 @@ class TestRestrictedBuiltins: def test_safe_code_still_works(self): """Normal factor code using allowed builtins should still work.""" - code = ( - "def compute(df, idx):\n" - " return float(max(0, min(df[\'close\'].iloc[idx], 999)))" - ) + code = "def compute(df, idx):\n return float(max(0, min(df['close'].iloc[idx], 999)))" result = self.sandbox.execute(code, _make_df(10)) assert result.success @@ -346,7 +345,7 @@ def test_import_not_in_builtins(self): code = ( "def compute(df, idx):\n" " try:\n" - " __import__(\'os\')\n" + " __import__('os')\n" " return 1.0\n" " except NameError:\n" " return 0.0\n"