diff --git a/docs/sh2-entry-gates.md b/docs/sh2-entry-gates.md new file mode 100644 index 0000000..f453625 --- /dev/null +++ b/docs/sh2-entry-gates.md @@ -0,0 +1,25 @@ +# SH-2 Entry-Gate Record & Digest-Pinned Engine Provenance + +## 1. Upstream Entry Gates (`FuseControl` -> `ShadowResearch`) + +- **Upstream Repository:** `QuantStrategyLab/FuseControl` (`main` merge commit `46a86eedb0d33f6133a066edeb8c3660cda9097d`) +- **Vendored Package Path:** `vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/` (`0444` read-only permissions, 8 `.py` files only, zero committed `__pycache__/`) +- **`spec_version`:** `fuse-eval-spec/v1` +- **`engine_hash`:** `12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45` +- **`bundle_hash`:** `78fed9dfc9b0b0a618fce6bb5a956063135f34845545e6a5154a32e119354cc9` +- **`freeze_hash`:** `1da74ca508161ba6d9a424101321381a9f5156d8cb2c84c03be2fd2fe3f22a74` + +| Gate | Requirement | Result | Source Artifact | +| --- | --- | --- | --- | +| `F1-A01` | Exact 24-ID set equality (`spec.json` == `ROW_IDS` == `ALL_BREAKER_IDS`) | `PASS` (`24/24`) | `metadata/spec.json` | +| `F1-A03` | Base matrix trip verification | `PASS` (`264/264`, 0 failed) | `metadata/result-bundle.json` | +| `F1-A04` | Tier repetitions verification | `PASS` (`132/132`, 0 failed) | `metadata/result-bundle.json` | +| `F1-A10` | Successor continuity cases | `PASS` (`13/13`, 0 failed) | `metadata/result-bundle.json` | +| `F1-A11` | Disposition register unresolved items fail closed | `PASS` (`O5`, `V5`, `V7` `UNRESOLVED-FAIL-CLOSED`, 0 unknown) | `metadata/disposition-register.json` | + +## 2. SH-1 & C-SA-22 Entry Gate Continuity + +- **SH-1 Baseline Commit:** `20be23f1ce4f4f23bd2f863aef43213894947bf3` (`96/96` unit tests preserved unbroken) +- **SH-1 Policy Config Hash:** `1f4fd701ee63f78b4445e3ece177b854e75618f307491a638c4e3d4546d17ad8` +- **C-SA-22 v2 Merge Commit:** `204120875403519d10d75d35a5abc17ade71a71a` (`csa22-v2` `spec_digest = 2ba8cd7684c361209df68bfa2e10004c1f9922a645c7ec55d421fda520561798`) +- **Runtime Verification:** [`VendoredFuseEvaluator`](../src/shadow/fuse_adapter.py) verifies all 8 `.py` SHA-256 digests against `metadata/provenance.json`, checks framed SHA-256 (`engine_hash`), checks `spec_version == "fuse-eval-spec/v1"`, and validates any existing `__pycache__/*.pyc` against source bytecode prior to every `evaluate()` call. diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py new file mode 100644 index 0000000..f79d26f --- /dev/null +++ b/src/shadow/fuse_adapter.py @@ -0,0 +1,1918 @@ +"""Digest-pinned vendored FUSE-1 consumer adapter and entry-gate verifier.""" + +from __future__ import annotations + +import copy +import hashlib +import importlib.abc +import importlib.util +import json +import marshal +import math +import re +import sys +import types +from collections.abc import Mapping, Sequence +from decimal import Decimal +from pathlib import Path +from typing import Any + +from shadow.evaluator import ALL_BREAKER_IDS, REQUIRED_MARKET_SERIES, StubEvaluator +from shadow.sizing import ( + INSTRUMENT_ORDER, + TIER_CONFIGS, + SizingInputError, + canonical_decimal_str, + compute_raw_vs_adjusted_separation, + compute_tier_max_loss_fraction, +) + +PINNED_FUSE_SPEC_VERSION = "fuse-eval-spec/v1" +PINNED_FUSE_ENGINE_HASH = ( + "12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45" +) +PINNED_FUSE_BUNDLE_HASH = ( + "78fed9dfc9b0b0a618fce6bb5a956063135f34845545e6a5154a32e119354cc9" +) +PINNED_FUSE_FREEZE_HASH = ( + "1da74ca508161ba6d9a424101321381a9f5156d8cb2c84c03be2fd2fe3f22a74" +) +PINNED_CSA22_V2_DIGEST = ( + "2ba8cd7684c361209df68bfa2e10004c1f9922a645c7ec55d421fda520561798" +) +PINNED_SH1_COMMIT = "20be23f1ce4f4f23bd2f863aef43213894947bf3" +# Complete required metadata set, pinned in code: provenance.json itself is not trusted +# to attest its own siblings (P1: unpinned self-referential metadata manifest). +PINNED_FUSE_METADATA_SHA256: dict[str, str] = { + "FREEZE.json": "2262eabd746d2c6ff9e0e5f49853244d638b550330db049d2af9c41c659dd89d", + "SH1-ACCEPTANCE.json": "830ec9519edfa8b996039f53b98cc33659c7c5f53c2934fe009a0e6f925e39fc", + "disposition-register.json": "4f2c497f727f9fa4be43d4aa287ff740f2affe1f602ab8518f10916cbfbe105c", + "provenance.json": "a6ab4981e77b64a750f243f2ac79c073ef2e522eb2548b9c078bd59036d34e14", + "result-bundle.json": "ca3af33909c2fd5c26364458406de710197dd87dc8c9f1234adef0c1f60cbd42", + "spec.json": "94b99e5da90ce559c916aba10aca91cf9c370847266da59cd9e441a4c3bb2e1f", +} + +EXPECTED_ENGINE_FILES: tuple[str, ...] = ( + "__init__.py", + "canonical.py", + "canonical_state.py", + "evaluator.py", + "rows_loss.py", + "rows_ops.py", + "rows_vehicle.py", + "state.py", +) +_EXPECTED_ENGINE_STEMS = frozenset(Path(name).stem for name in EXPECTED_ENGINE_FILES) +_PYCACHE_RE = re.compile( + r"^([A-Za-z0-9_]+)\.(cpython-\d+(?:t)?)(?:\.opt-([12]))?\.pyc$" +) + +DEFAULT_VENDOR_ENGINE_ROOT = ( + Path(__file__).resolve().parents[2] + / "vendor" + / "fuse_engine" + / "fuse-eval-spec-v1" + / PINNED_FUSE_ENGINE_HASH +) + +_STATE_PRECEDENCE = { + "NORMAL": 0, + "NO-NEW-RISK": 1, + "DE-RISK": 2, + "ORDER-UNKNOWN": 3, + "HALT": 4, +} + +_TIER_D_MAP = { + "conservative": 0.15, + "balanced": 0.30, + "aggressive": 0.50, +} + +_LOADED_PACKAGE_CACHE: dict[tuple[str, str], types.ModuleType] = {} + + +class EngineIdentityError(RuntimeError): + """Raised on any mismatch in vendored FUSE-1 identity, hash, files, or bytecode.""" + + +class ProductionChainLockedError(RuntimeError): + """Raised when production forward-clock writes are attempted while locked (OA-SH2-2).""" + + +class CorporateActionConflictError(ValueError): + """Two distinct corporate actions for one fund/bar that V2 cannot both represent.""" + + +class V2PayloadSchemaError(ValueError): + """Raised when V2 reconciliation payload omits or mis-types boolean hwm_adjusted.""" + + +def is_stub_evaluator(evaluator: object) -> bool: + """Return True if evaluator is a synthetic stub or lacks production capability.""" + if evaluator is None or isinstance(evaluator, StubEvaluator): + return True + if getattr(evaluator, "production_clock_capable", False) is not True: + return True + ehash = getattr(evaluator, "engine_hash", "") + return not isinstance(ehash, str) or not ehash or ehash.startswith("stub-") + + +def resolve_aggregate_control_state(effective_state_by_scope: Mapping[str, str]) -> str: + """Resolve most restrictive state across scopes (supports native or aggregated maps).""" + if not isinstance(effective_state_by_scope, Mapping) or not effective_state_by_scope: + return "NORMAL" + if "aggregate" in effective_state_by_scope: + val = str(effective_state_by_scope["aggregate"]) + if val in _STATE_PRECEDENCE: + return val + best_state = "NORMAL" + best_rank = 0 + for state in effective_state_by_scope.values(): + rank = _STATE_PRECEDENCE.get(str(state)) + if rank is None: + raise EngineIdentityError(f"Unrecognized control state in scope map: {state!r}") + if rank > best_rank: + best_rank = rank + best_state = str(state) + return best_state + + +def resolve_account_and_fund_control_states( + effective_state_by_scope: Mapping[str, str], + fund_symbols: tuple[str, ...] | list[str] = ("SOXL", "TQQQ"), +) -> tuple[str, dict[str, str] | None, str]: + """Return (account_state, per_fund_states_or_None, overall_aggregate_state).""" + overall = resolve_aggregate_control_state(effective_state_by_scope) + if not isinstance(effective_state_by_scope, Mapping) or "aggregate" in effective_state_by_scope: + return overall, None, overall + account_scopes = { + k: v for k, v in effective_state_by_scope.items() if k in ("account", "joint") + } + account_state = ( + resolve_aggregate_control_state(account_scopes) if account_scopes else overall + ) + fund_states: dict[str, str] = {} + for sym in fund_symbols: + sym_scopes = { + k: v + for k, v in effective_state_by_scope.items() + if k in (f"fund:{sym}", f"symbol:{sym}") + } + fund_states[sym] = ( + resolve_aggregate_control_state(sym_scopes) if sym_scopes else "NORMAL" + ) + return account_state, fund_states, overall + + +def _sanitize_for_canonical_ledger(val: object) -> object: + """Recursively convert finite floats in FUSE-1 breaker diagnostics into canonical decimal strings.""" + if val is None or isinstance(val, (bool, str, int)): + return val + if isinstance(val, Decimal): + return canonical_decimal_str(val) + if isinstance(val, float): + return canonical_decimal_str(Decimal(str(val))) + if isinstance(val, dict): + return {str(k): _sanitize_for_canonical_ledger(v) for k, v in val.items()} + if isinstance(val, (list, tuple)): + return [_sanitize_for_canonical_ledger(item) for item in val] + return val + + +def serialize_breakers_for_ledger(rows_by_id: Mapping[str, Mapping[str, Any]]) -> list[dict[str, Any]]: + """Serialize FUSE-1 rows_by_ID into sorted C-SH-LEDGER 24-breaker list without floats.""" + actual_ids = set(rows_by_id.keys()) + expected_ids = set(ALL_BREAKER_IDS) + if actual_ids != expected_ids: + raise EngineIdentityError( + f"F1-A01 breaker ID-set mismatch: expected={sorted(expected_ids)}, got={sorted(actual_ids)}" + ) + out: list[dict[str, Any]] = [] + for bid in ALL_BREAKER_IDS: + row = dict(rows_by_id[bid]) + if "id" in row and row["id"] != bid: + raise EngineIdentityError(f"Breaker row id mismatch for {bid}: {row['id']!r}") + sanitized = _sanitize_for_canonical_ledger(row) + assert isinstance(sanitized, dict) + sanitized["id"] = bid + out.append(sanitized) + return out + + +def _verify_pyc_matches_source( + pyc_path: Path, + src_path: Path, + src_bytes: bytes, + rel: str, + cache_tag: str, + optimize: int, +) -> None: + pyc_bytes = pyc_path.read_bytes() + if len(pyc_bytes) < 16 or pyc_bytes[:4] != importlib.util.MAGIC_NUMBER: + raise EngineIdentityError(f"Invalid .pyc magic header in vendored engine: {rel!r}") + if sys.implementation.cache_tag and cache_tag != sys.implementation.cache_tag: + raise EngineIdentityError(f"Unexpected .pyc cache tag in vendored engine: {rel!r}") + + bitfield = int.from_bytes(pyc_bytes[4:8], "little") + if bitfield & ~0b11: + raise EngineIdentityError(f"Invalid .pyc bitfield in vendored engine: {rel!r}") + if bitfield & 0b01: + if pyc_bytes[8:16] != importlib.util.source_hash(src_bytes): + raise EngineIdentityError(f"Tampered hash-based .pyc in vendored engine: {rel!r}") + else: + pyc_size = int.from_bytes(pyc_bytes[12:16], "little") + if pyc_size != (len(src_bytes) & 0xFFFFFFFF): + raise EngineIdentityError(f"Mismatched .pyc source size in vendored engine: {rel!r}") + + try: + pyc_code = marshal.loads(pyc_bytes[16:]) + except Exception as exc: + raise EngineIdentityError(f"Corrupt .pyc code payload in vendored engine: {rel!r}") from exc + + if not isinstance(pyc_code, types.CodeType) or not isinstance(pyc_code.co_filename, str): + raise EngineIdentityError(f"Invalid .pyc code object in vendored engine: {rel!r}") + norm_fn = pyc_code.co_filename.replace("\\", "/") + if norm_fn != src_path.name and not norm_fn.endswith("/" + src_path.name): + raise EngineIdentityError(f"Unexpected .pyc co_filename in vendored engine: {rel!r}") + + expected_code = compile(src_bytes, pyc_code.co_filename, "exec", dont_inherit=True, optimize=optimize) + # Compare code objects structurally (bytecode, constants incl. nested code, names, flags, + # line/exception tables); marshal byte encoding of shared references differs across + # py_compile and in-process compile() on some CPython versions. + if pyc_code != expected_code: + raise EngineIdentityError(f"Tampered .pyc bytecode mismatch in vendored engine: {rel!r}") + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def verify_vendored_engine_bundle( + vendor_root: str | Path | None = None, + *, + expected_engine_hash: str = PINNED_FUSE_ENGINE_HASH, + expected_spec_version: str = PINNED_FUSE_SPEC_VERSION, + require_read_only: bool = False, + expected_metadata_sha256: Mapping[str, str] = PINNED_FUSE_METADATA_SHA256, +) -> dict[str, Any]: + """Verify vendored FUSE-1 source files, provenance SHA-256s, framed digest, and __pycache__.""" + root = Path(vendor_root) if vendor_root is not None else DEFAULT_VENDOR_ENGINE_ROOT + if root.is_symlink() or not root.is_dir(): + raise EngineIdentityError(f"Vendored engine root missing or invalid: {root}") + + engine_dir = root / "fuse_engine" + metadata_dir = root / "metadata" + if engine_dir.is_symlink() or not engine_dir.is_dir(): + raise EngineIdentityError(f"Vendored engine directory missing or symlinked: {engine_dir}") + if metadata_dir.is_symlink() or not metadata_dir.is_dir(): + raise EngineIdentityError(f"Vendored metadata directory missing or symlinked: {metadata_dir}") + + for fname, pinned_digest in sorted(expected_metadata_sha256.items()): + mpath = metadata_dir / fname + if mpath.is_symlink() or not mpath.is_file(): + raise EngineIdentityError(f"Missing pinned vendored metadata file: {fname}") + if _sha256_bytes(mpath.read_bytes()) != pinned_digest: + raise EngineIdentityError(f"Vendored metadata does not match pinned digest: {fname}") + + prov_path = metadata_dir / "provenance.json" + if prov_path.is_symlink() or not prov_path.is_file(): + raise EngineIdentityError(f"Missing vendored provenance.json: {prov_path}") + provenance = json.loads(prov_path.read_text(encoding="utf-8")) + if provenance.get("spec_version") != expected_spec_version: + raise EngineIdentityError( + f"provenance spec_version mismatch: expected {expected_spec_version!r}, got {provenance.get('spec_version')!r}" + ) + if provenance.get("engine_hash") != expected_engine_hash: + raise EngineIdentityError( + f"provenance engine_hash mismatch: expected {expected_engine_hash!r}, got {provenance.get('engine_hash')!r}" + ) + + py_files: list[Path] = [] + rel_py_paths: list[str] = [] + pyc_entries: list[tuple[Path, str, str, str, int]] = [] + pycache_present = False + + for entry in sorted(engine_dir.rglob("*"), key=lambda p: p.relative_to(engine_dir).as_posix()): + rel = entry.relative_to(engine_dir).as_posix() + if entry.is_symlink(): + raise EngineIdentityError(f"Unexpected symlink in vendored engine dir: {rel!r}") + if entry.is_dir(): + if rel != "__pycache__": + raise EngineIdentityError(f"Unexpected subdirectory in vendored engine dir: {rel!r}") + pycache_present = True + continue + if not entry.is_file(): + raise EngineIdentityError(f"Unexpected non-regular entry in vendored engine dir: {rel!r}") + if entry.parent == engine_dir: + if rel not in EXPECTED_ENGINE_FILES: + raise EngineIdentityError(f"Unexpected artifact in vendored engine dir: {rel!r}") + py_files.append(entry) + rel_py_paths.append(rel) + elif entry.parent == engine_dir / "__pycache__": + pycache_present = True + match = _PYCACHE_RE.match(entry.name) + if not match or match.group(1) not in _EXPECTED_ENGINE_STEMS: + raise EngineIdentityError(f"Unexpected __pycache__ artifact: {rel!r}") + opt = int(match.group(3)) if match.group(3) else 0 + pyc_entries.append((entry, rel, match.group(1), match.group(2), opt)) + else: + raise EngineIdentityError(f"Unexpected nested artifact in vendored engine dir: {rel!r}") + + if rel_py_paths != list(EXPECTED_ENGINE_FILES): + raise EngineIdentityError( + f"Vendored engine file set mismatch: expected {list(EXPECTED_ENGINE_FILES)}, got {rel_py_paths}" + ) + + prov_engine_files = provenance.get("engine_files") + if not isinstance(prov_engine_files, dict) or set(prov_engine_files.keys()) != set(EXPECTED_ENGINE_FILES): + raise EngineIdentityError("provenance engine_files map missing expected entries") + + src_by_stem: dict[str, tuple[Path, bytes]] = {} + actual_file_hashes: dict[str, dict[str, Any]] = {} + hasher = hashlib.sha256() + read_only_ok = True + + for py_file, rel_path in zip(py_files, rel_py_paths): + data = py_file.read_bytes() + digest = _sha256_bytes(data) + recorded = prov_engine_files.get(rel_path) + if ( + not isinstance(recorded, dict) + or recorded.get("sha256") != digest + or recorded.get("bytes") != len(data) + ): + raise EngineIdentityError( + f"Vendored engine file hash mismatch for {rel_path}: actual={digest}" + ) + if py_file.stat().st_mode & 0o222: + read_only_ok = False + if require_read_only: + raise EngineIdentityError(f"Vendored engine file is writable (expected read-only): {rel_path}") + src_by_stem[py_file.stem] = (py_file, data) + actual_file_hashes[rel_path] = {"sha256": digest, "bytes": len(data)} + rel_bytes = rel_path.encode("utf-8") + hasher.update(len(rel_bytes).to_bytes(4, "big")) + hasher.update(rel_bytes) + hasher.update(len(data).to_bytes(8, "big")) + hasher.update(data) + + for pyc_file, rel, stem, cache_tag, opt in pyc_entries: + py_file, src_bytes = src_by_stem[stem] + _verify_pyc_matches_source(pyc_file, py_file, src_bytes, rel, cache_tag, opt) + + computed_engine_hash = hasher.hexdigest() + if computed_engine_hash != expected_engine_hash: + raise EngineIdentityError( + f"Vendored engine framed SHA-256 mismatch: expected={expected_engine_hash}, got={computed_engine_hash}" + ) + + prov_meta_files = provenance.get("metadata_files") + if not isinstance(prov_meta_files, dict) or not prov_meta_files: + raise EngineIdentityError("provenance metadata_files map missing") + for fname, recorded in prov_meta_files.items(): + mpath = metadata_dir / fname + if mpath.is_symlink() or not mpath.is_file(): + raise EngineIdentityError(f"Missing vendored metadata file: {fname}") + mbytes = mpath.read_bytes() + mdigest = _sha256_bytes(mbytes) + if ( + not isinstance(recorded, dict) + or recorded.get("sha256") != mdigest + or recorded.get("bytes") != len(mbytes) + ): + raise EngineIdentityError(f"Vendored metadata digest mismatch for {fname}") + if mpath.stat().st_mode & 0o222: + read_only_ok = False + if require_read_only: + raise EngineIdentityError(f"Vendored metadata file is writable: {fname}") + + return { + "vendor_root": str(root), + "engine_dir": str(engine_dir), + "metadata_dir": str(metadata_dir), + "spec_version": expected_spec_version, + "engine_hash": computed_engine_hash, + "bundle_hash": provenance.get("bundle_hash"), + "freeze_hash": provenance.get("freeze_hash"), + "file_hashes": actual_file_hashes, + "pycache_present": pycache_present, + "pycache_verified": True, + "read_only_verified": read_only_ok, + } + + +class _VerifiedSourceLoader(importlib.abc.Loader): + """Execute pre-verified source bytes; never consults bytecode caches or PYTHONPYCACHEPREFIX.""" + + def __init__(self, path: Path, src_bytes: bytes) -> None: + self._path = path + self._src_bytes = src_bytes + + def create_module(self, spec: Any) -> None: + return None + + def exec_module(self, module: types.ModuleType) -> None: + code = compile(self._src_bytes, str(self._path), "exec", dont_inherit=True) + exec(code, module.__dict__) + + +class _VerifiedPackageFinder(importlib.abc.MetaPathFinder): + """Resolve the isolated vendored package and its submodules to verified source bytes only.""" + + def __init__(self, pkg_name: str, engine_dir: Path, sources: Mapping[str, bytes]) -> None: + self.pkg_name = pkg_name + self.engine_dir = engine_dir + self.sources = dict(sources) + + def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any: + if fullname == self.pkg_name: + stem, is_pkg = "__init__", True + elif fullname.startswith(self.pkg_name + "."): + stem, is_pkg = fullname[len(self.pkg_name) + 1 :], False + if "." in stem or stem == "__init__": + return None + else: + return None + if stem not in self.sources: + return None + file_path = self.engine_dir / f"{stem}.py" + spec = importlib.util.spec_from_loader( + fullname, + _VerifiedSourceLoader(file_path, self.sources[stem]), + origin=str(file_path), + is_package=is_pkg, + ) + if spec is None: + return None + spec.has_location = True + if is_pkg: + spec.submodule_search_locations = [str(self.engine_dir)] + return spec + + +def _read_verified_engine_sources(engine_dir: Path, info: Mapping[str, Any]) -> dict[str, bytes]: + """Re-read engine sources and bind them to the digests just verified (closes read TOCTOU).""" + sources: dict[str, bytes] = {} + file_hashes = info["file_hashes"] + for rel in EXPECTED_ENGINE_FILES: + data = (engine_dir / rel).read_bytes() + recorded = file_hashes.get(rel) + if not isinstance(recorded, Mapping) or recorded.get("sha256") != _sha256_bytes(data): + raise EngineIdentityError(f"Vendored engine source changed after verification: {rel}") + sources[Path(rel).stem] = data + return sources + + +def _load_verified_fuse_package( + vendor_root: str | Path | None = None, + *, + expected_engine_hash: str = PINNED_FUSE_ENGINE_HASH, + expected_spec_version: str = PINNED_FUSE_SPEC_VERSION, + require_read_only: bool = False, +) -> types.ModuleType: + """Verify vendored engine dir on disk and return isolated imported package.""" + info = verify_vendored_engine_bundle( + vendor_root, + expected_engine_hash=expected_engine_hash, + expected_spec_version=expected_spec_version, + require_read_only=require_read_only, + ) + engine_dir = Path(info["engine_dir"]).resolve() + cache_key = (str(engine_dir), info["engine_hash"]) + cached = _LOADED_PACKAGE_CACHE.get(cache_key) + if cached is not None: + if getattr(cached, "__version__", None) != expected_spec_version: + raise EngineIdentityError("Cached vendored module spec_version mismatch") + if cached.evaluator.compute_engine_hash() != expected_engine_hash: + raise EngineIdentityError("Cached vendored module engine_hash mismatch") + return cached + + pkg_suffix = hashlib.sha256(f"{engine_dir}:{info['engine_hash']}".encode("utf-8")).hexdigest()[:16] + pkg_name = f"_shadow_vendored_fuse_{pkg_suffix}" + init_path = engine_dir / "__init__.py" + finder = _VerifiedPackageFinder(pkg_name, engine_dir, _read_verified_engine_sources(engine_dir, info)) + sys.meta_path[:] = [ + f for f in sys.meta_path + if not (isinstance(f, _VerifiedPackageFinder) and f.pkg_name == pkg_name) + ] + sys.meta_path.insert(0, finder) + spec = finder.find_spec(pkg_name) + if spec is None or spec.loader is None: + raise EngineIdentityError(f"Unable to build import spec for vendored engine: {init_path}") + + module = importlib.util.module_from_spec(spec) + prev_dont_write = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + sys.modules[pkg_name] = module + spec.loader.exec_module(module) + except Exception: + for key in list(sys.modules.keys()): + if key == pkg_name or key.startswith(pkg_name + "."): + sys.modules.pop(key, None) + raise + finally: + sys.dont_write_bytecode = prev_dont_write + + if getattr(module, "__version__", None) != expected_spec_version: + raise EngineIdentityError( + f"Loaded FUSE-1 spec_version mismatch: expected {expected_spec_version!r}, got {getattr(module, '__version__', None)!r}" + ) + actual_hash = module.evaluator.compute_engine_hash() + if actual_hash != expected_engine_hash: + raise EngineIdentityError( + f"Loaded FUSE-1 compute_engine_hash mismatch: expected {expected_engine_hash!r}, got {actual_hash!r}" + ) + if set(module.evaluator.ROW_IDS) != set(ALL_BREAKER_IDS) or len(module.evaluator.ROW_IDS) != 24: + raise EngineIdentityError("Loaded FUSE-1 ROW_IDS fails F1-A01 24-ID set equality") + + _LOADED_PACKAGE_CACHE[cache_key] = module + return module + + +def verify_f1_entry_gates( + vendor_root: str | Path | None = None, + *, + require_read_only: bool = False, +) -> dict[str, Any]: + """Verify F1-A01/A03/A04/A10/A11 entry gates and archived SH-1 acceptance record.""" + bundle_info = verify_vendored_engine_bundle( + vendor_root, + require_read_only=require_read_only, + ) + pkg = _load_verified_fuse_package( + vendor_root, + require_read_only=require_read_only, + ) + metadata_dir = Path(bundle_info["metadata_dir"]) + + spec_obj = json.loads((metadata_dir / "spec.json").read_text(encoding="utf-8")) + result_bundle = json.loads((metadata_dir / "result-bundle.json").read_text(encoding="utf-8")) + disp_register = json.loads((metadata_dir / "disposition-register.json").read_text(encoding="utf-8")) + freeze_obj = json.loads((metadata_dir / "FREEZE.json").read_text(encoding="utf-8")) + sh1_obj = json.loads((metadata_dir / "SH1-ACCEPTANCE.json").read_text(encoding="utf-8")) + + # F1-A01 exact 24-ID set equality + spec_ids = [r.get("id") for r in spec_obj.get("rows", [])] + if len(spec_ids) != 24 or len(set(spec_ids)) != 24 or set(spec_ids) != set(ALL_BREAKER_IDS): + raise EngineIdentityError("F1-A01 spec.json ID-set mismatch") + if set(pkg.evaluator.ROW_IDS) != set(ALL_BREAKER_IDS): + raise EngineIdentityError("F1-A01 engine ROW_IDS ID-set mismatch") + + # F1-A03 / F1-A04 / F1-A10 result bundle checks + if ( + result_bundle.get("spec_version") != PINNED_FUSE_SPEC_VERSION + or result_bundle.get("engine_hash") != PINNED_FUSE_ENGINE_HASH + or result_bundle.get("bundle_hash") != PINNED_FUSE_BUNDLE_HASH + or result_bundle.get("freeze_hash") != PINNED_FUSE_FREEZE_HASH + or result_bundle.get("enforcement_mode") != "shadow_would_have_tripped" + or result_bundle.get("loss_breakers_armed") is not False + ): + raise EngineIdentityError("Pinned result-bundle.json identity or safety invariant mismatch") + if freeze_obj.get("combined_freeze_hash") != PINNED_FUSE_FREEZE_HASH: + raise EngineIdentityError("FREEZE.json combined_freeze_hash mismatch") + + base_cells = result_bundle.get("base_cells", {}) + tier_reps = result_bundle.get("tier_repetitions", {}) + succ_cases = result_bundle.get("successor_cases", {}) + if base_cells.get("total") != 264 or base_cells.get("passed") != 264 or base_cells.get("failed") != 0: + raise EngineIdentityError(f"F1-A03 base_cells gate failed: {base_cells}") + if tier_reps.get("total") != 132 or tier_reps.get("passed") != 132 or tier_reps.get("failed") != 0: + raise EngineIdentityError(f"F1-A04 tier_repetitions gate failed: {tier_reps}") + if succ_cases.get("total") != 13 or succ_cases.get("passed") != 13 or succ_cases.get("failed") != 0: + raise EngineIdentityError(f"F1-A10 successor_cases gate failed: {succ_cases}") + + # F1-A11 disposition register verification + entries = disp_register.get("entries", []) + unresolved_rows = { + e.get("row_id"): e.get("disposition") + for e in entries + if e.get("disposition") == "UNRESOLVED-FAIL-CLOSED" + } + if set(unresolved_rows.keys()) != {"V5", "V7", "O5"}: + raise EngineIdentityError( + f"F1-A11 unexpected unresolved disposition rows: {sorted(unresolved_rows.keys())}" + ) + allowed_disps = {"CONFIRMED-AS-SPEC", "UNRESOLVED-FAIL-CLOSED"} + unknown_disps = [ + (e.get("row_id"), e.get("disposition")) + for e in entries + if e.get("disposition") not in allowed_disps + ] + if unknown_disps: + raise EngineIdentityError(f"F1-A11 unresolved/unrecognized disposition rows: {unknown_disps}") + + # SH1-ACCEPTANCE record check + if ( + sh1_obj.get("sh1_commit") != PINNED_SH1_COMMIT + or sh1_obj.get("csa22_v2_spec_digest") != PINNED_CSA22_V2_DIGEST + or sh1_obj.get("offline_verification", {}).get("acceptance_offline_status") != "PASS_OFFLINE" + ): + raise EngineIdentityError("SH1-ACCEPTANCE.json failed pinned entry-gate checks") + + return { + "ok": True, + "spec_version": PINNED_FUSE_SPEC_VERSION, + "engine_hash": bundle_info["engine_hash"], + "bundle_hash": PINNED_FUSE_BUNDLE_HASH, + "freeze_hash": PINNED_FUSE_FREEZE_HASH, + "f1_a01_id_set_equal": True, + "f1_a03_base_cells": f"{base_cells['passed']}/{base_cells['total']}", + "f1_a04_tier_repetitions": f"{tier_reps['passed']}/{tier_reps['total']}", + "f1_a10_successor_cases": f"{succ_cases['passed']}/{succ_cases['total']}", + "f1_a11_unresolved_fail_closed": sorted(unresolved_rows.keys()), + "sh1_commit": sh1_obj["sh1_commit"], + "csa22_v2_spec_digest": sh1_obj["csa22_v2_spec_digest"], + "read_only_verified": bundle_info["read_only_verified"], + "pycache_verified": bundle_info["pycache_verified"], + } + + +def validate_v2_reconciliation_payload(validated_inputs: Mapping[str, Any]) -> None: + """Enforce caller schema contract requiring explicit boolean hwm_adjusted on V2 reconciliation payloads.""" + if not isinstance(validated_inputs, Mapping): + return + if "hwm_adjusted" in validated_inputs and not isinstance(validated_inputs["hwm_adjusted"], bool): + raise V2PayloadSchemaError( + "Top-level hwm_adjusted must be explicit bool when present" + ) + funds = validated_inputs.get("funds") + if not isinstance(funds, Mapping): + return + for symbol in sorted(funds.keys()): + fdata = funds[symbol] + if not isinstance(fdata, Mapping): + continue + if "hwm_adjusted" in fdata and not isinstance(fdata["hwm_adjusted"], bool): + raise V2PayloadSchemaError( + f"Fund {symbol} hwm_adjusted must be explicit bool when present" + ) + ca = fdata.get("corporate_action") + if not isinstance(ca, Mapping): + continue + if "hwm_adjusted" in ca and not isinstance(ca["hwm_adjusted"], bool): + raise V2PayloadSchemaError( + f"Fund {symbol} corporate_action.hwm_adjusted must be explicit bool when present" + ) + if ca.get("adjustment_complete") is True: + if "hwm_adjusted" not in ca or not isinstance(ca.get("hwm_adjusted"), bool): + raise V2PayloadSchemaError( + f"V2 reconciliation payload for {symbol} with adjustment_complete=True " + "requires explicit boolean hwm_adjusted" + ) + + +def _finite_number(raw: object) -> float | None: + if raw is None or isinstance(raw, bool): + return None + try: + dec = raw if isinstance(raw, Decimal) else Decimal(str(raw)) + except Exception: + return None + if not dec.is_finite(): + return None + val = float(dec) + if not math.isfinite(val): + return None + return val + + +def _preserve_numeric_quantity(val: float | None) -> int | float | None: + if val is None: + return None + fval = float(val) + return int(fval) if fval.is_integer() else fval + + +def _map_calendar_statuses( + calendar_session: Mapping[str, Any] | None, + *, + session_date: str | None = None, +) -> tuple[str | None, str | None]: + if not isinstance(calendar_session, Mapping): + return None, None + if session_date is not None: + raw_td = calendar_session.get("trade_date") + if raw_td is None or str(raw_td) != str(session_date): + return None, None + state = calendar_session.get("session_state") + reason = str(calendar_session.get("reason") or "") + disagreement = bool(calendar_session.get("venue_disagreement")) + observed_venue = calendar_session.get("observed_venue_status") + + # SH-2 makes END-OF-DAY decisions (17:30 ET regular, 14:30 ET half day; orders, if any, + # belong to the next session), so a trading day maps to `open` for the whole day, before + # and after its core window, half days included. FuseControl C-FUSE-GATE + # (`fuse_gate._calendar_status`) emits `half_day_cutoff` when a half day's as_of is at or + # past `order_cutoff_utc`, but that is a PRE-TRADE rule where as_of is an order instant. + # Applying it here would HALT O2 on every half-day EOD decision. Plain `half_day` is + # never emitted (vendored O2 treats it as closed). Late EOD decisions are rejected by the + # scheduler's decision-cutoff check (`late_after_decision_cutoff`), not by O2; time-of-day + # order blocking belongs to V7 `session_time`. + if state in ("regular", "half_day") and calendar_session.get("is_trading_day") and not calendar_session.get("blocks_eligibility"): + cal_status = "open" + exch_status = str(observed_venue) if disagreement and observed_venue is not None else "open" + elif state in ("closed", "unscheduled_closure"): + tok = "holiday" if "holiday" in reason.lower() else "closed" + cal_status = tok + exch_status = str(observed_venue) if disagreement and observed_venue is not None else tok + elif disagreement: + cal_status = "open" if state in ("regular", "half_day") else "closed" + exch_status = str(observed_venue) if observed_venue is not None else "closed" + else: + return None, None + return cal_status, exch_status + + +_FUND_BENCHMARK_INDEX = { + "TQQQ": "XNDX", + "SOXL": "SEMI", +} + +_FUND_EXPOSURE_BETA = { + "TQQQ": Decimal("1"), + "SOXL": Decimal("1.5"), +} + +_LEVERAGE_MULTIPLE = Decimal("3") + +_O5_PASSTHROUGH_KEYS = ( + "o5_symbol", + "symbol", + "o5_symbol_whitelist", + "o5_order_size", + "order_size", + "o5_order_qty", + "order_qty", + "qty", + "o5_side", + "side", + "order_side", + "o5_order_value", + "order_value", + "o5_order_price", + "o5_limit_price", + "limit_price", + "order_price", + "unit_price", + "o5_unit_price", + "price", + "o5_reference_price", + "reference_price", + "account", + "o5_account", + "o5_account_whitelist", + "o5_settled_cash", + "o5_max_order_size", + "max_order_size", + "o5_orders_today", + "orders_today", + "o5_max_orders_per_session", + "max_orders_per_session", + "o5_turnover_today", + "turnover_today", + "o5_max_turnover_per_session", + "max_turnover_per_session", +) + +_INDEX_RETURN_LABELS = ( + ("XNDX", "NDX"), + ("SEMI", "SEMI"), + ("SPX", "SPX"), +) + + +def _is_valid_sizing_signal(raw: object) -> bool: + """Return True when raw decodes to a finite Decimal signal within sizing's [0, 1] contract.""" + dec = _sizing_decimal(raw) + return dec is not None and Decimal("0") <= dec <= Decimal("1") + + +def _compute_return_ratio(cur_raw: object, prev_raw: object) -> float | None: + cur_f = _finite_number(cur_raw) + prev_f = _finite_number(prev_raw) + if cur_f is None or prev_f is None or prev_f <= 0.0: + return None + cur_d = Decimal(str(cur_raw)) + prev_d = Decimal(str(prev_raw)) + return float((cur_d - prev_d) / prev_d) + + +_CA_UNDATED = object() + + +def _finite_decimal(raw: object) -> Decimal | None: + """Value-compare helper: finite Decimal of a numeric/str observation, else None.""" + if raw is None or isinstance(raw, bool): + return None + try: + dec = raw if isinstance(raw, Decimal) else Decimal(str(raw)) + except Exception: + return None + return dec if dec.is_finite() else None + + +def _ca_identity(ca: object) -> tuple[object, ...] | None: + """Identity of a corporate action for comparing two reported events.""" + if not isinstance(ca, Mapping): + return None + + def _num(v: object) -> object: + d = _sizing_decimal(v) + return d.normalize() if d is not None else v + + return ( + ca.get("type"), + _num(ca.get("ratio")), + _num(ca.get("cash_per_share_usd")), + _parse_valid_ymd(ca.get("ex_date")), + ) + + +def _ca_in_return_interval(ca_obj: object, session_date: str | None) -> object: + """Return the corporate action only if its ex-date falls in this one-session return interval. + + For a one-session return (prior trading close -> session close) the only ex-date inside + the interval is the session date itself. An action dated earlier (e.g. a Friday split + reconciled by V2 on Monday) is already reflected in both closes, so the raw return is + used. An action without a valid ex-date cannot be placed and fails closed. + """ + if not isinstance(ca_obj, Mapping) or session_date is None: + return ca_obj + ex_date = _parse_valid_ymd(ca_obj.get("ex_date")) + if ex_date is None: + return _CA_UNDATED + return ca_obj if ex_date == session_date else None + + +def _compute_ca_adjusted_fund_return( + cur_raw: object, + prev_raw: object, + ca_obj: object, +) -> float | None: + """Derive 1-session fund return from closes, adjusting prior close for splits/distributions.""" + if ca_obj is _CA_UNDATED: + return None + if ca_obj is None: + return _compute_return_ratio(cur_raw, prev_raw) + if not isinstance(ca_obj, Mapping): + return None + cur_f = _finite_number(cur_raw) + prev_f = _finite_number(prev_raw) + if cur_f is None or prev_f is None or prev_f <= 0.0: + return None + cur_d = Decimal(str(cur_raw)) + prev_d = Decimal(str(prev_raw)) + ca_type = ca_obj.get("type") + if ca_type in ("split", "reverse_split"): + ratio_f = _finite_number(ca_obj.get("ratio")) + if ratio_f is None or ratio_f <= 0.0: + return None + prev_adj = prev_d / Decimal(str(ca_obj.get("ratio"))) + if prev_adj <= 0: + return None + raw_cash = ca_obj.get("cash_per_share_usd") + if raw_cash is None: + cash_d = Decimal("0") + else: + cash_f = _finite_number(raw_cash) + if cash_f is None or cash_f < 0.0: + return None + cash_d = Decimal(str(raw_cash)) + return float((cur_d + cash_d - prev_adj) / prev_adj) + if ca_type in ("distribution", "cash_distribution", "dividend"): + cash_f = _finite_number(ca_obj.get("cash_per_share_usd")) + if cash_f is None or cash_f < 0.0: + return None + cash_d = Decimal(str(ca_obj.get("cash_per_share_usd"))) + return float((cur_d + cash_d - prev_d) / prev_d) + return None + + +def _derive_one_session_loss(session_inputs: Mapping[str, Any]) -> float | None: + """Derive L4 one_session_loss from prior_E / external_flow when omitted; return None if undeterminable.""" + if "one_session_loss" in session_inputs: + return _finite_number(session_inputs.get("one_session_loss")) + e_f = _finite_number(session_inputs.get("E")) + if e_f is None or e_f <= 0.0: + return None + raw_ext = session_inputs.get("external_flow", "0") + ext_f = _finite_number(raw_ext) + if ext_f is None: + return None + raw_prior_e = session_inputs.get("prior_E") + if raw_prior_e is not None: + pe_f = _finite_number(raw_prior_e) + if pe_f is None or pe_f <= 0.0: + return None + try: + rva = compute_raw_vs_adjusted_separation( + Decimal(str(session_inputs["E"])), + Decimal(str(raw_prior_e)), + Decimal(str(raw_ext)), + ) + adj_str = rva.get("adjusted_return_pct") + if not isinstance(adj_str, str): + return None + return float(max(Decimal("0"), -Decimal(adj_str))) + except (SizingInputError, ArithmeticError, ValueError): + return None + if ( + _finite_number(session_inputs.get("E_star")) is not None + and _finite_number(session_inputs.get("L")) is not None + ): + e_d = Decimal(str(session_inputs["E"])) + es_d = Decimal(str(session_inputs["E_star"])) + l_d = Decimal(str(session_inputs["L"])) + ext_d = Decimal(str(raw_ext)) + if e_d == es_d and l_d == Decimal("0") and ext_d == Decimal("0"): + return 0.0 + return None + + +_RATE_INSTRUMENTS = frozenset({"SOFR", "TBILL_3M"}) + + +_EXPECTED_RATE_DAY_CACHE: dict[tuple[str, str], str | None] = {} + + +def _parse_aware_instant(raw: object) -> Any: + """Parse an ISO-8601 timestamp into an aware UTC datetime; naive or invalid -> None.""" + from datetime import datetime, timezone + + if not isinstance(raw, str) or not raw: + return None + text = raw[:-1] + "+00:00" if raw.endswith("Z") else raw + try: + parsed = datetime.fromisoformat(text) + except ValueError: + return None + if parsed.tzinfo is None or parsed.utcoffset() is None: + return None + return parsed.astimezone(timezone.utc) + + +def _not_after(raw: object, as_of: str) -> bool: + """True only if raw is a valid aware instant at or before as_of (instants, not strings).""" + ts = _parse_aware_instant(raw) + limit = _parse_aware_instant(as_of) + return ts is not None and limit is not None and ts <= limit + + +def _expected_prior_rate_business_day(session_date: str, calendar_session: Mapping[str, Any] | None) -> str | None: + """Expected T-1 publication business day for rate series, from the pinned calendar spec. + + Mirrors the feeder's freshness rule (feeder.expected_prior_sofr_business_day). Returns + None (fail closed) when the calendar spec cannot be loaded and digest-verified. + """ + if not isinstance(calendar_session, Mapping): + return None + version = calendar_session.get("calendar_version") + digest = calendar_session.get("spec_digest") + if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", version): + return None + key = (session_date, f"{version}:{digest}") + if key in _EXPECTED_RATE_DAY_CACHE: + return _EXPECTED_RATE_DAY_CACHE[key] + result: str | None = None + try: + from shadow.calendar_consumer import load_spec + from shadow.feeder import expected_prior_sofr_business_day + + spec = load_spec(Path(__file__).resolve().parents[2] / "specs" / version) + if spec.get("spec_digest") == digest: + result = expected_prior_sofr_business_day(session_date, calendar_spec=spec) + except Exception: + result = None + _EXPECTED_RATE_DAY_CACHE[key] = result + return result + + +def _is_market_record_valid_for_session( + rec: object, + cal_digest: object, + session_date: str | None, + *, + as_of: str | None = None, + calendar_session: Mapping[str, Any] | None = None, +) -> bool: + """A market record is usable only if eligible, populated, digest-bound and for this session. + + Price/index records must be effective for the decision session itself. Rate series follow + the feeder's exact freshness rule: SOFR must be effective on the expected T-1 publication + business day; the 3M T-bill on the session day or that T-1 day. An archived rate from an + older date is never reused. A record retrieved after the decision instant (as_of), or + without a retrieval time, is look-ahead evidence and is rejected. + """ + if not isinstance(rec, Mapping): + return False + elig = rec.get("eligibility") if isinstance(rec.get("eligibility"), Mapping) else {} + if rec.get("normalized_value") is None or not elig.get("eligible"): + return False + if cal_digest is not None and rec.get("calendar_spec_digest") != cal_digest: + return False + if session_date is not None: + eff = rec.get("effective_session") + if not isinstance(eff, str) or _parse_valid_ymd(eff) is None: + return False + inst = str(rec.get("instrument")) + if inst in _RATE_INSTRUMENTS: + expected_prior = _expected_prior_rate_business_day(session_date, calendar_session) + allowed = {expected_prior} if inst == "SOFR" else {session_date, expected_prior} + if expected_prior is None or eff not in allowed: + return False + elif eff != session_date: + return False + if as_of is not None and not _not_after(rec.get("retrieval_time_utc"), as_of): + return False + return True + + +def _parse_valid_ymd(raw: object) -> str | None: + if not isinstance(raw, str) or len(raw) != 10: + return None + try: + from datetime import date as _date + + return _date.fromisoformat(raw).isoformat() + except ValueError: + return None + + +def _map_market_corporate_action(mca: Mapping[str, Any] | None) -> dict[str, Any] | None: + if not isinstance(mca, Mapping): + return None + raw_split = mca.get("split_ratio") + raw_cash = mca.get("cash_per_share_usd") + if isinstance(raw_split, bool) or isinstance(raw_cash, bool): + return None + try: + split_dec = Decimal("1") if raw_split is None else Decimal(str(raw_split)) + cash_dec = Decimal("0") if raw_cash is None else Decimal(str(raw_cash)) + except Exception: + return None + if not split_dec.is_finite() or not cash_dec.is_finite(): + return None + if split_dec != Decimal("1"): + action: dict[str, Any] = { + "type": "split" if split_dec > Decimal("1") else "reverse_split", + "ratio": float(split_dec), + "ex_date": mca.get("ex_date"), + "adjustment_complete": False, + "exact_reconciliation": False, + } + if cash_dec > Decimal("0"): + action["cash_per_share_usd"] = float(cash_dec) + return action + if cash_dec > Decimal("0"): + return { + "type": "distribution", + "cash_per_share_usd": float(cash_dec), + "ex_date": mca.get("ex_date"), + "adjustment_complete": False, + "exact_reconciliation": False, + } + return None + + +def _resolve_tier_quantity(raw_val: object, tier: str) -> float | None: + """Resolve scalar or tier-keyed quantity before numeric coercion.""" + if isinstance(raw_val, Mapping): + if tier not in raw_val: + return None + return _finite_number(raw_val[tier]) + return _finite_number(raw_val) + + +def _resolve_sizing_q_pre(raw_val: object, tier: str) -> int | None: + """Resolve scalar or tier-keyed q_pre enforcing sizing._resolve_q_pre() integer contract.""" + cand = raw_val + if isinstance(cand, Mapping): + if tier not in cand: + return None + cand = cand[tier] + if cand is None or isinstance(cand, (bool, float)): + return None + if isinstance(cand, int): + return cand if cand >= 0 else None + if isinstance(cand, str): + s = cand.strip() + if not s: + return None + try: + val = int(s) + except ValueError: + return None + return val if val >= 0 else None + try: + val = int(cand) # type: ignore[call-overload] + except Exception: + return None + return val if val >= 0 else None + + +def _sizing_decimal(raw: object) -> Decimal | None: + """Parse a finite Decimal matching sizing._to_decimal()'s strict bankroll contract.""" + if raw is None or isinstance(raw, (bool, float)): + return None + try: + dec = raw if isinstance(raw, Decimal) else Decimal(str(raw)) + except Exception: + return None + return dec if dec.is_finite() else None + + +def _has_valid_sizing_bankroll(session_inputs: Mapping[str, Any]) -> bool: + """Return True when SHADOW inputs satisfy compute_session_sizing()'s required bankroll contract.""" + e_dec = _sizing_decimal(session_inputs.get("E")) + e_star_dec = _sizing_decimal(session_inputs.get("E_star")) + h_dec = _sizing_decimal(session_inputs.get("H", "0")) + l_dec = _sizing_decimal(session_inputs.get("L")) + if e_dec is None or e_star_dec is None or h_dec is None or l_dec is None: + return False + if e_dec <= 0 or e_star_dec <= 0 or e_dec > e_star_dec or h_dec < 0 or l_dec < 0: + return False + raw_w_ref = session_inputs.get("W_ref") + if raw_w_ref is not None: + w_ref_dec = _sizing_decimal(raw_w_ref) + if w_ref_dec is None: + return False + w_ref_eff = w_ref_dec + else: + w_ref_eff = e_star_dec + h_dec + if w_ref_eff - l_dec <= 0: + return False + raw_prior_e = session_inputs.get("prior_E") + if raw_prior_e is not None: + prior_e_dec = _sizing_decimal(raw_prior_e) + if prior_e_dec is None or prior_e_dec <= 0: + return False + if _sizing_decimal(session_inputs.get("external_flow", "0")) is None: + return False + monthly_returns = session_inputs.get("monthly_returns") + if monthly_returns is not None: + if not isinstance(monthly_returns, Sequence) or isinstance( + monthly_returns, (str, bytes, bytearray, Mapping) + ): + return False + if any(_sizing_decimal(item) is None for item in monthly_returns): + return False + return True + + +def _derive_default_max_loss_cap( + session_inputs: Mapping[str, Any], + tier: str, + bankroll_val: float | None, + hwm_val: float | None, + *, + require_sizing_bankroll: bool = True, +) -> float | None: + """Derive L0 max_loss_cap from U-01 sizing Step 3 x_ML(c) * E, failing closed on bad inputs.""" + if bankroll_val is None or bankroll_val <= 0 or tier not in TIER_CONFIGS: + return None + if require_sizing_bankroll and not _has_valid_sizing_bankroll(session_inputs): + return None + try: + e_dec = Decimal(str(session_inputs["E"])) + raw_e_star = session_inputs.get("E_star") + if raw_e_star is not None: + if _finite_number(raw_e_star) is None: + return None + e_star_dec = Decimal(str(raw_e_star)) + elif not require_sizing_bankroll and hwm_val is not None: + e_star_dec = Decimal(str(hwm_val)) + else: + return None + + raw_h = session_inputs.get("H", "0") + if raw_h is None or _finite_number(raw_h) is None: + return None + h_dec = Decimal(str(raw_h)) + + raw_w_ref = session_inputs.get("W_ref") + w_ref_dec: Decimal | None = None + if raw_w_ref is not None: + if _finite_number(raw_w_ref) is None: + return None + w_ref_dec = Decimal(str(raw_w_ref)) + + raw_l = session_inputs.get("L") + if raw_l is not None: + if _finite_number(raw_l) is None: + return None + l_dec = Decimal(str(raw_l)) + elif not require_sizing_bankroll: + w_ref_eff = w_ref_dec if w_ref_dec is not None else (e_star_dec + h_dec) + l_dec = max(Decimal("0"), w_ref_eff - (e_dec + h_dec)) + else: + return None + + _, _, x_ml = compute_tier_max_loss_fraction( + tier, + e_val=e_dec, + e_star=e_star_dec, + l_val=l_dec, + h_val=h_dec, + w_ref=w_ref_dec, + ) + return float(x_ml * e_dec) + except (SizingInputError, ArithmeticError, ValueError, KeyError): + return None + + +def _derive_conv_scale( + session_inputs: Mapping[str, Any], + bankroll_val: float | None, + hwm_val: float | None, +) -> Decimal | None: + """Compute U-01 Step 6 convexity denominator (1 + H / E*), failing closed on invalid inputs.""" + del bankroll_val + try: + raw_e_star = session_inputs.get("E_star") + if raw_e_star is not None: + if _finite_number(raw_e_star) is None: + return None + e_star_dec = Decimal(str(raw_e_star)) + elif hwm_val is not None: + e_star_dec = Decimal(str(hwm_val)) + else: + return None + + raw_h = session_inputs.get("H", "0") + if raw_h is None or _finite_number(raw_h) is None: + return None + h_dec = Decimal(str(raw_h)) + if e_star_dec <= 0 or h_dec < 0: + return None + return Decimal("1") + (h_dec / e_star_dec) + except (ArithmeticError, ValueError): + return None + + +def _apply_explicit_payload_tier( + payload: dict[str, Any], + session_inputs: Mapping[str, Any], + *, + policy_hash: str, +) -> dict[str, Any]: + """Align an explicit/direct FUSE payload with the outer tier request and tier-dependent caps.""" + has_outer_tier = "tier" in session_inputs and session_inputs.get("tier") is not None + requested_tier = str(session_inputs["tier"]) if has_outer_tier else str(payload.get("tier", "balanced")) + if has_outer_tier and requested_tier != payload.get("tier"): + payload["tier"] = requested_tier + if requested_tier in TIER_CONFIGS: + payload["tier_loss_budget_D"] = _TIER_D_MAP[requested_tier] + bankroll_val = _finite_number(payload.get("bankroll", session_inputs.get("E"))) + # No fallback to bankroll: a missing high-water mark leaves the loss cap underivable. + hwm_val = _finite_number( + payload.get( + "high_water_mark", + session_inputs.get("high_water_mark", session_inputs.get("E_star")), + ) + ) + if bankroll_val is not None: + payload["tier_joint_cap"] = float( + Decimal(str(TIER_CONFIGS[requested_tier]["x_joint"])) + * Decimal(str(bankroll_val)) + ) + if "E" in session_inputs: + cap_inputs = session_inputs + else: + cap_inputs = { + "E": bankroll_val, + "E_star": hwm_val, + "H": payload.get("H", payload.get("h_value", session_inputs.get("H", "0"))), + } + if "L" in session_inputs: + cap_inputs["L"] = session_inputs["L"] + derived_cap = _derive_default_max_loss_cap( + cap_inputs, + requested_tier, + bankroll_val, + hwm_val, + require_sizing_bankroll=("E" in session_inputs), + ) + if derived_cap is not None: + payload["max_loss_cap"] = derived_cap + else: + payload.pop("max_loss_cap", None) + else: + # Unknown tier: caps computed for the payload's previous tier must not survive. + for stale_key in ("tier_joint_cap", "max_loss_cap", "tier_loss_budget_D"): + payload.pop(stale_key, None) + else: + payload.setdefault("tier", "balanced") + payload.setdefault("loaded_policy_hash", policy_hash) + payload.setdefault("registered_policy_hash", policy_hash) + return payload + + +def apply_fund_long_run_volatility( + target_inputs: dict[str, Any], + long_run_vol_by_inst: object | None, +) -> None: + """Inject explicit per-fund long_run_volatility observations without mutating shared inputs.""" + if not isinstance(long_run_vol_by_inst, Mapping): + return + funds = target_inputs.get("funds") + if not isinstance(funds, Mapping): + return + funds_copy: dict[str, object] = {} + for inst, fdata in funds.items(): + if isinstance(fdata, Mapping): + entry = dict(copy.deepcopy(fdata)) + if inst in long_run_vol_by_inst and long_run_vol_by_inst[inst] is not None: + entry["long_run_volatility"] = long_run_vol_by_inst[inst] + funds_copy[str(inst)] = entry + else: + funds_copy[str(inst)] = copy.deepcopy(fdata) + target_inputs["funds"] = funds_copy + + +def build_fuse_validated_inputs( + session_inputs: Mapping[str, Any], + calendar_session: Mapping[str, Any] | None, + *, + policy_hash: str, + session_date: str, + as_of: str, +) -> dict[str, Any]: + """Translate ShadowResearch session inputs into FUSE-1 validated_inputs without shims.""" + if not isinstance(session_inputs, Mapping): + raise ValueError("session_inputs must be a mapping") + if "kill_switch_tripped" in session_inputs: + # The pinned engine's evaluate_O8 reads only authorized_events and the prior latch, so a + # boolean flag would be a silently ineffective control. Reject it instead. + raise ValueError( + "kill_switch_tripped is not supported by fuse-eval-spec/v1 O8; supply an owner " + "authorized_events entry {'type': 'kill_switch', 'scope': 'account', ...} instead" + ) + + explicit_fuse = session_inputs.get("fuse_inputs") + if explicit_fuse is not None: + if not isinstance(explicit_fuse, Mapping): + raise ValueError("fuse_inputs must be a mapping when provided") + merged = copy.deepcopy(dict(explicit_fuse)) + return _apply_explicit_payload_tier(merged, session_inputs, policy_hash=policy_hash) + + if ( + "bankroll" in session_inputs + and "session_calendar_status" in session_inputs + and "E" not in session_inputs + ): + direct = copy.deepcopy(dict(session_inputs)) + return _apply_explicit_payload_tier(direct, session_inputs, policy_hash=policy_hash) + + # An omitted tier takes the policy default (balanced); an explicit null or unknown tier is + # not silently mapped to balanced: tier-dependent caps stay missing so L0/L1 fail closed. + tier = str(session_inputs["tier"]) if "tier" in session_inputs else "balanced" + tier_cfg = TIER_CONFIGS.get(tier) + bankroll_val = _finite_number(session_inputs.get("E")) + if "high_water_mark" in session_inputs: + hwm_val = _finite_number(session_inputs.get("high_water_mark")) + elif "E_star" in session_inputs: + hwm_val = _finite_number(session_inputs.get("E_star")) + else: + hwm_val = None + + cal_status, exch_status = _map_calendar_statuses(calendar_session, session_date=session_date) + if "tier_joint_cap" in session_inputs: + tier_joint_cap = _finite_number(session_inputs.get("tier_joint_cap")) + elif bankroll_val is not None and tier_cfg is not None: + tier_joint_cap = float(Decimal(str(tier_cfg["x_joint"])) * Decimal(str(bankroll_val))) + else: + tier_joint_cap = None + if not _has_valid_sizing_bankroll(session_inputs): + max_loss_cap = None + elif "max_loss_cap" in session_inputs: + max_loss_cap = _finite_number(session_inputs.get("max_loss_cap")) + else: + max_loss_cap = _derive_default_max_loss_cap(session_inputs, tier, bankroll_val, hwm_val) + + raw_funds = session_inputs.get("funds") if isinstance(session_inputs.get("funds"), Mapping) else {} + mkt_recs = session_inputs.get("market_records") + req_series = tuple(session_inputs.get("required_series", REQUIRED_MARKET_SERIES)) + prior_closes = ( + session_inputs.get("prior_closes") + if isinstance(session_inputs.get("prior_closes"), Mapping) + else {} + ) + by_inst: dict[str, Mapping[str, Any]] = {} + + mkt_ok = True + idx_ok = True + bad_market_insts: set[str] = set() + bad_market_payload = False + cal_ok = cal_status in ("open", "closed", "holiday") and exch_status == cal_status and not bool((calendar_session or {}).get("venue_disagreement")) + vol_ok = True + + if "market_records" in session_inputs: + if not isinstance(mkt_recs, list): + mkt_ok = False + idx_ok = False + bad_market_payload = True + else: + by_inst = { + str(r.get("instrument")): r + for r in mkt_recs + if isinstance(r, Mapping) and r.get("instrument") + } + cal_digest = calendar_session.get("spec_digest") if isinstance(calendar_session, Mapping) else None + # Every record that can feed a return (required or optional, e.g. SPX) is validated: + # eligible, populated, same calendar digest, and effective for this decision session. + for inst, rec in by_inst.items(): + if not _is_market_record_valid_for_session( + rec, cal_digest, session_date, as_of=as_of, calendar_session=calendar_session + ): + bad_market_insts.add(inst) + for inst in req_series: + rec = by_inst.get(inst) + bad_rec = rec is None or not _is_market_record_valid_for_session( + rec, cal_digest, session_date, as_of=as_of, calendar_session=calendar_session + ) + if bad_rec: + bad_market_insts.add(inst) + if inst in ("XNDX", "SEMI", "QQQ"): + idx_ok = False + mkt_ok = False + + # Derive current closes across instruments for return computation + cur_closes: dict[str, object] = {} + for inst_name, mrec in by_inst.items(): + if inst_name not in bad_market_insts and mrec.get("normalized_value") is not None: + cur_closes[inst_name] = mrec["normalized_value"] + cur_idx_override = session_inputs.get("current_index_closes") + if isinstance(cur_idx_override, Mapping): + for k, v in cur_idx_override.items(): + k = str(k) + if v is None: + continue + if k not in by_inst: + # Override is used only when no market record exists for the instrument. + cur_closes[k] = v + elif k not in bad_market_insts and _finite_decimal(v) != _finite_decimal( + by_inst[k].get("normalized_value") + ): + # Disagreement with a validated record fails closed (same as the fund-close path). + bad_market_insts.add(k) + cur_closes.pop(k, None) + idx_ok = False + mkt_ok = False + + conv_scale = _derive_conv_scale(session_inputs, bankroll_val, hwm_val) + fuse_funds: dict[str, dict[str, Any]] = {} + joint_exposure_dec: Decimal | None = Decimal("0") if conv_scale is not None else None + for req_inst in INSTRUMENT_ORDER: + if not isinstance(raw_funds.get(req_inst), Mapping): + mkt_ok = False + for symbol in sorted(raw_funds.keys()): + fdata = raw_funds[symbol] + if not isinstance(fdata, Mapping): + continue + close_dec = _sizing_decimal(fdata.get("close_price")) + close_val = float(close_dec) if close_dec is not None else None + q_pre_val = _resolve_sizing_q_pre(fdata.get("q_pre"), tier) + sigma_dec = _sizing_decimal(fdata.get("sigma_forecast")) + sigma_val = float(sigma_dec) if sigma_dec is not None else None + signal_ok = _is_valid_sizing_signal(fdata.get("s")) + if sigma_val is None or sigma_val <= 0.0: + vol_ok = False + if close_val is None or close_val <= 0.0 or q_pre_val is None or not signal_ok: + mkt_ok = False + # A held position with an unknown close (or an unknown quantity) has an unknown value: + # it propagates as None into ledger/broker values and the joint aggregate, so + # reconciliation cannot clear on invented zeroes. A flat book (q_pre == 0) is known 0. + if close_val is not None and q_pre_val is not None: + pos_val: float | None = close_val * q_pre_val + elif q_pre_val == 0: + pos_val = 0.0 + else: + pos_val = None + if joint_exposure_dec is not None and conv_scale is not None: + if pos_val is None: + joint_exposure_dec = None + else: + beta_dec = _FUND_EXPOSURE_BETA.get(symbol, Decimal("1")) + joint_exposure_dec += ( + _LEVERAGE_MULTIPLE * beta_dec * Decimal(str(pos_val)) + ) / conv_scale + long_run_vol = _finite_number(fdata.get("long_run_volatility")) + + # Wire feeder market_records[].corporate_action into V2 when fund payload does not override it + ca_obj = copy.deepcopy(fdata.get("corporate_action")) + market_ca = ( + _map_market_corporate_action(by_inst[symbol].get("corporate_action")) # type: ignore[arg-type] + if not bad_market_payload and symbol not in bad_market_insts and symbol in by_inst + else None + ) + ca_conflict = False + if ca_obj is None: + ca_obj = market_ca + elif market_ca is not None and _ca_identity(ca_obj) != _ca_identity(market_ca): + # The fund payload carries one action (e.g. a prior CA being reconciled) while the + # feeder reports a distinct new action for this bar. V2 can hold only one, and a + # successor state built from either would drop the other, so the evaluation is + # rejected before any successor state is produced. + raise CorporateActionConflictError( + f"{symbol}: fund payload corporate action {_ca_identity(ca_obj)!r} conflicts with " + f"feeder corporate action {_ca_identity(market_ca)!r} for {session_date}" + ) + + # The return uses the validated market close when a market record exists for the fund; + # a caller close that disagrees with it is rejected (fail closed). + close_for_return: object = fdata.get("close_price") + close_mismatch = False + if symbol in by_inst and symbol not in bad_market_insts and not bad_market_payload: + mkt_close = by_inst[symbol].get("normalized_value") + close_for_return = mkt_close + caller_close_dec = _finite_decimal(fdata.get("close_price")) + mkt_close_dec = _finite_decimal(mkt_close) + if fdata.get("close_price") is not None and ( + caller_close_dec is None or mkt_close_dec is None or caller_close_dec != mkt_close_dec + ): + close_mismatch = True + mkt_ok = False + + # Derive 1-session fund and benchmark index returns from real closes when not explicitly given + if fdata.get("fund_return") is not None: + fund_ret_val = _finite_number(fdata.get("fund_return")) + elif ( + not bad_market_payload + and symbol not in bad_market_insts + and symbol in prior_closes + and close_for_return is not None + and not ca_conflict + and not close_mismatch + ): + fund_ret_val = _compute_ca_adjusted_fund_return( + close_for_return, + prior_closes.get(symbol), + _ca_in_return_interval(ca_obj, session_date), + ) + else: + fund_ret_val = None + + bench_inst = _FUND_BENCHMARK_INDEX.get(symbol, "XNDX") + if fdata.get("index_return") is not None: + idx_ret_val = _finite_number(fdata.get("index_return")) + elif ( + not bad_market_payload + and bench_inst not in bad_market_insts + and bench_inst in prior_closes + and bench_inst in cur_closes + ): + idx_ret_val = _compute_return_ratio(cur_closes.get(bench_inst), prior_closes.get(bench_inst)) + else: + idx_ret_val = None + + # Stage N (SH-2) has no broker connection and no independent broker evidence in any + # mode. When broker_* observations are absent they are substituted with the modelled + # q_pre / position value / bankroll, so O3 here is a documented model + # self-reconciliation, NOT independent reconciliation evidence. Once SUPPLY-B supplies + # broker evidence, missing broker_* observations must fail closed (tracked follow-up). + # Omitted key = Stage N model-only substitution; explicit null = unknown evidence (missing). + broker_pos_val = ( + (_resolve_tier_quantity(fdata["broker_position"], tier) if fdata["broker_position"] is not None else None) + if "broker_position" in fdata + else q_pre_val + ) + fund_entry: dict[str, Any] = { + "symbol": symbol, + "exposure": ((_finite_number(fdata["exposure"]) if fdata["exposure"] is not None else None) if "exposure" in fdata else pos_val), + "fund_return": fund_ret_val, + "index_return": idx_ret_val, + "modelled_fee": _finite_number(fdata.get("modelled_fee")), + "modelled_financing": _finite_number(fdata.get("modelled_financing")), + "forecast_volatility": sigma_val, + "long_run_volatility": long_run_vol, + "shortfall_observed": _finite_number(fdata.get("shortfall_observed")), + "shortfall_predicted": _finite_number(fdata.get("shortfall_predicted")), + "carrying_cost_measured": _finite_number(fdata.get("carrying_cost_measured")), + "excess_return_shrunk": _finite_number(fdata.get("excess_return_shrunk")), + "quote_staleness": _finite_number(fdata.get("quote_staleness")), + "spread_width": _finite_number(fdata.get("spread_width")), + "trading_pause": fdata.get("trading_pause"), + "session_time": str(fdata["session_time"]) if fdata.get("session_time") is not None else None, + # Unknown ledger quantity stays None (O3/V2 must not match or clear on it); an + # explicitly flat position is the known quantity 0. + "share_count": _preserve_numeric_quantity(q_pre_val), + "ledger_value": ((_finite_number(fdata["ledger_value"]) if fdata["ledger_value"] is not None else None) if "ledger_value" in fdata else pos_val), + "broker_position": _preserve_numeric_quantity(broker_pos_val), + "broker_value": ( + (_finite_number(fdata["broker_value"]) if fdata["broker_value"] is not None else None) + if "broker_value" in fdata + else pos_val + ), + "corporate_action": ca_obj, + "fund_event": copy.deepcopy(fdata.get("fund_event")), + } + if "hwm_adjusted" in fdata: + fund_entry["hwm_adjusted"] = fdata["hwm_adjusted"] + if "v5_tolerance" in fdata: + fund_entry["v5_tolerance"] = fdata["v5_tolerance"] + if "v7_spread_width" in fdata: + fund_entry["v7_spread_width"] = fdata["v7_spread_width"] + for v1_key in ("five_session_history", "sessions_window"): + if v1_key in fdata: + fund_entry[v1_key] = copy.deepcopy(fdata[v1_key]) + fuse_funds[symbol] = fund_entry + + idx_returns: dict[str, float] | None + if "index_one_session_returns" in session_inputs: + raw_idx_rets = session_inputs.get("index_one_session_returns") + idx_returns = copy.deepcopy(raw_idx_rets) if isinstance(raw_idx_rets, dict) else raw_idx_rets # type: ignore[assignment] + elif not bad_market_payload and prior_closes: + derived_idx: dict[str, float] = {} + for inst_key, ret_label in _INDEX_RETURN_LABELS: + if ( + inst_key not in bad_market_insts + and inst_key in prior_closes + and inst_key in cur_closes + ): + r_val = _compute_return_ratio(cur_closes.get(inst_key), prior_closes.get(inst_key)) + if r_val is not None: + derived_idx[ret_label] = r_val + idx_returns = derived_idx if derived_idx else None + else: + idx_returns = None + + # Only populate positions / broker_reconciliation when caller supplies explicit records (fail closed otherwise) + caller_sources = ( + session_inputs.get("source_records") + if isinstance(session_inputs.get("source_records"), Mapping) + else {} + ) + pos_rec = ( + session_inputs.get("positions_source_record") + if "positions_source_record" in session_inputs + else caller_sources.get("positions") + ) + brk_rec = ( + session_inputs.get("broker_reconciliation_source_record") + if "broker_reconciliation_source_record" in session_inputs + else caller_sources.get("broker_reconciliation") + ) + has_all_fund_rets = bool(fuse_funds) and all( + fuse_funds[sym].get("fund_return") is not None + and fuse_funds[sym].get("index_return") is not None + for sym in fuse_funds + ) + raw_source_records: dict[str, dict[str, Any] | None] = { + "market_data": ( + copy.deepcopy(caller_sources.get("market_data")) + if "market_data" in caller_sources + else {"as_of": as_of, "age_sessions": 0} + ) + if (mkt_ok and idx_ok and vol_ok and has_all_fund_rets) + else None, + "index_returns": caller_sources.get("index_returns") + if "index_returns" in caller_sources + else ({"as_of": as_of, "age_sessions": 0} if (idx_ok and idx_returns is not None) else None), + "volatility": caller_sources.get("volatility") + if "volatility" in caller_sources + else ({"as_of": as_of, "age_sessions": 0} if vol_ok else None), + "positions": copy.deepcopy(pos_rec) if isinstance(pos_rec, Mapping) else None, + "broker_reconciliation": copy.deepcopy(brk_rec) if isinstance(brk_rec, Mapping) else None, + "session_calendar": ( + copy.deepcopy(caller_sources.get("session_calendar")) + if "session_calendar" in caller_sources + else {"as_of": as_of, "age_sessions": 0} + ) + if cal_ok + else None, + } + # Every source record (caller-supplied or derived) must be dated at or before the decision + # instant; a future-dated record (look-ahead) is dropped so O1 fails closed. + source_records = { + k: v + for k, v in raw_source_records.items() + if isinstance(v, Mapping) and _not_after(v.get("as_of"), as_of) + } + + derived_joint_exposure = float(joint_exposure_dec) if joint_exposure_dec is not None else None + out: dict[str, Any] = { + "tier": tier, + "bankroll": bankroll_val, + "high_water_mark": hwm_val, + "joint_exposure": ((_finite_number(session_inputs["joint_exposure"]) if session_inputs["joint_exposure"] is not None else None) if "joint_exposure" in session_inputs else derived_joint_exposure), + "tier_joint_cap": tier_joint_cap, + "max_loss_cap": max_loss_cap, + # FUSE runs BEFORE sizing (ledger evaluates rows, then sizes), so no proposal exists yet: + # an omitted proposed_exposure is the current (pre-sizing) exposure, and sizing enforces + # the tier max-loss cap (Step 3 x_ML) on the actual targets. An explicit value, including + # an explicit null, passes through. + "proposed_exposure": ((_finite_number(session_inputs["proposed_exposure"]) if session_inputs["proposed_exposure"] is not None else None) if "proposed_exposure" in session_inputs else derived_joint_exposure), + "one_session_loss": _derive_one_session_loss(session_inputs), + "market_halt_level": session_inputs.get("market_halt_level", None), + "index_one_session_returns": idx_returns, + "funds": fuse_funds, + "source_records": source_records, + "session_calendar_status": cal_status, + "exchange_status": exch_status, + # Stage N model self-reconciliation (see broker_position above): absent cash + # observations default to the bankroll; O3 is not independently evaluated in SH-2. + # Omitted key = model-only substitution; an explicit null stays missing (O3 fails closed). + "positions_cash": ( + (_finite_number(session_inputs["positions_cash"]) if session_inputs["positions_cash"] is not None else None) + if "positions_cash" in session_inputs + else bankroll_val + ), + "broker_cash": ( + (_finite_number(session_inputs["broker_cash"]) if session_inputs["broker_cash"] is not None else None) + if "broker_cash" in session_inputs + else bankroll_val + ), + "reconciliation_tolerance": ((_finite_number(session_inputs["reconciliation_tolerance"]) if session_inputs["reconciliation_tolerance"] is not None else None) if "reconciliation_tolerance" in session_inputs else 1.0), + # Omitted = no pending orders (Stage N never places orders); an explicit value passes through. + "pending_orders": copy.deepcopy(session_inputs["pending_orders"]) if "pending_orders" in session_inputs else {}, + "symbol_whitelist": ( + copy.deepcopy(session_inputs["symbol_whitelist"]) + if "symbol_whitelist" in session_inputs + else ["TQQQ", "SOXL", "BIL"] + ), + "account_whitelist": ( + copy.deepcopy(session_inputs["account_whitelist"]) + if "account_whitelist" in session_inputs + else ["stage_n_shadow"] + ), + "settled_cash": ( + _finite_number(session_inputs["settled_cash"]) + if session_inputs.get("settled_cash") is not None + else None + if "settled_cash" in session_inputs + else _finite_number(session_inputs["o5_settled_cash"]) + if session_inputs.get("o5_settled_cash") is not None + else None + ), + # Supplied values pass through uncoerced (an explicit null stays null so O6/O7 fail closed); + # only an omitted key takes the adapter default. + "loaded_policy_hash": copy.deepcopy(session_inputs["loaded_policy_hash"]) if "loaded_policy_hash" in session_inputs else policy_hash, + "registered_policy_hash": copy.deepcopy(session_inputs["registered_policy_hash"]) if "registered_policy_hash" in session_inputs else policy_hash, + # O7 heartbeat provenance is explicit: "caller" when the session inputs carry + # last_heartbeat, else "adapter_self" (as_of is the job's own self-attested heartbeat, + # not independent liveness evidence). The ledger replaces the self-heartbeat with the + # previous committed record's decision timestamp in a follow-up (see issue #13). + "last_heartbeat": copy.deepcopy(session_inputs["last_heartbeat"]) if "last_heartbeat" in session_inputs else as_of, + "heartbeat_source": ( + str(session_inputs.get("heartbeat_source") or "caller") + if "last_heartbeat" in session_inputs + else "adapter_self" + ), + "scheduled_interval": ( + (_finite_number(session_inputs["scheduled_interval"]) if session_inputs["scheduled_interval"] is not None else None) + if "scheduled_interval" in session_inputs + else 60.0 + ), + "tier_loss_budget_D": _TIER_D_MAP.get(tier), + "v5_tolerance": session_inputs.get("v5_tolerance", None), + "v7_spread_width": session_inputs.get("v7_spread_width", None), + "o5_collar": session_inputs.get("o5_collar", None), + } + if "hwm_adjusted" in session_inputs: + out["hwm_adjusted"] = session_inputs["hwm_adjusted"] + for o7_key in ("o7_runtime_silent", "o7_monitor_silent"): + if o7_key in session_inputs: + out[o7_key] = bool(session_inputs[o7_key]) + for o5_key in _O5_PASSTHROUGH_KEYS: + if o5_key in session_inputs: + out[o5_key] = copy.deepcopy(session_inputs[o5_key]) + # Canonical O5 session counters default to zero only when no alias carries evidence; + # the vendored evaluate_O5() treats conflicting aliases as a limit violation. + # An explicitly supplied null counter is unknown evidence and is preserved as None. + if "session_order_count" in session_inputs: + raw_count = session_inputs["session_order_count"] + out["session_order_count"] = int(raw_count) if raw_count is not None else None + elif not any(k in session_inputs for k in ("o5_orders_today", "orders_today")): + out["session_order_count"] = 0 + if "session_turnover" in session_inputs: + raw_turnover = session_inputs["session_turnover"] + out["session_turnover"] = _finite_number(raw_turnover) if raw_turnover is not None else None + elif not any(k in session_inputs for k in ("o5_turnover_today", "turnover_today")): + out["session_turnover"] = 0.0 + # O9 checks H change descriptors against the live H used for exposure and loss caps. + if session_inputs.get("H") is not None: + out["H"] = copy.deepcopy(session_inputs["H"]) + for key in ("tier_change_event", "o9_change_descriptors"): + if key in session_inputs: + out[key] = copy.deepcopy(session_inputs[key]) + return out + + +def _drop_future_source_records(validated_inputs: Any, as_of: str) -> Any: + """Evaluator-boundary look-ahead guard for every payload path (native, direct, nested). + + Any source record whose as_of is not an aware instant at or before the decision as_of is + removed from the effective payload, so O1 sees it as stale/missing. The caller's mapping is + never mutated. + """ + if not isinstance(validated_inputs, Mapping): + return validated_inputs + src = validated_inputs.get("source_records") + if not isinstance(src, Mapping): + return validated_inputs + kept = { + k: v for k, v in src.items() if isinstance(v, Mapping) and _not_after(v.get("as_of"), as_of) + } + if len(kept) == len(src): + return validated_inputs + out = dict(validated_inputs) + out["source_records"] = kept + return out + + +class VendoredFuseEvaluator: + """Real FUSE-1 vendored evaluator with runtime hash, spec, __pycache__, and V2 checks.""" + + production_clock_capable: bool = True + + def __init__( + self, + vendor_root: str | Path | None = None, + *, + expected_engine_hash: str = PINNED_FUSE_ENGINE_HASH, + expected_spec_version: str = PINNED_FUSE_SPEC_VERSION, + require_read_only: bool = False, + ) -> None: + self.vendor_root = ( + Path(vendor_root) if vendor_root is not None else DEFAULT_VENDOR_ENGINE_ROOT + ) + self.expected_engine_hash = expected_engine_hash + self.expected_spec_version = expected_spec_version + self.require_read_only = require_read_only + self._pkg = _load_verified_fuse_package( + self.vendor_root, + expected_engine_hash=self.expected_engine_hash, + expected_spec_version=self.expected_spec_version, + require_read_only=self.require_read_only, + ) + self.spec_version: str = self._pkg.__version__ + self.engine_hash: str = self._pkg.evaluator.compute_engine_hash() + + def verify_runtime_identity(self) -> dict[str, Any]: + """Re-verify vendored disk artifacts, __pycache__, spec_version, and engine_hash.""" + info = verify_vendored_engine_bundle( + self.vendor_root, + expected_engine_hash=self.expected_engine_hash, + expected_spec_version=self.expected_spec_version, + require_read_only=self.require_read_only, + ) + loaded_hash = self._pkg.evaluator.compute_engine_hash() + if loaded_hash != self.expected_engine_hash or self._pkg.__version__ != self.expected_spec_version: + raise EngineIdentityError( + f"Runtime FUSE-1 identity mismatch: loaded=({self._pkg.__version__}, {loaded_hash})" + ) + return info + + def evaluate( + self, + spec_version: str, + engine_hash: str, + policy_hash: str, + session: str, + as_of: str, + mode: str, + validated_inputs: dict, + prior_row_state: dict | None, + authorized_events: dict | list | None = None, + ) -> tuple[dict[str, dict], dict[str, str], dict]: + """Verify runtime bundle + V2 schema contract and invoke FUSE-1 evaluate() verbatim.""" + self.verify_runtime_identity() + + if spec_version != self.expected_spec_version: + raise EngineIdentityError( + f"Caller spec_version mismatch: expected {self.expected_spec_version!r}, got {spec_version!r}" + ) + if engine_hash != self.expected_engine_hash: + raise EngineIdentityError( + f"Caller engine_hash mismatch: expected {self.expected_engine_hash!r}, got {engine_hash!r}" + ) + + if isinstance(validated_inputs, Mapping) and "kill_switch_tripped" in validated_inputs: + # Checked on the effective payload (native, direct or nested fuse_inputs): the pinned + # O8 reads only authorized_events, so the flag would be a silently ineffective control. + raise ValueError( + "kill_switch_tripped is not supported by fuse-eval-spec/v1 O8; supply an owner " + "authorized_events entry {'type': 'kill_switch', 'scope': 'account', ...} instead" + ) + validated_inputs = _drop_future_source_records(validated_inputs, as_of) + validate_v2_reconciliation_payload(validated_inputs) + + auth_events_arg: dict | list | None + if isinstance(authorized_events, (dict, list)) or authorized_events is None: + auth_events_arg = authorized_events + else: + auth_events_arg = list(authorized_events) + + return self._pkg.evaluator.evaluate( + spec_version, + engine_hash, + policy_hash, + session, + as_of, + mode, + validated_inputs, + prior_row_state, + auth_events_arg, + ) diff --git a/src/shadow/manifest.py b/src/shadow/manifest.py index 287b6d1..61f93ca 100644 --- a/src/shadow/manifest.py +++ b/src/shadow/manifest.py @@ -16,6 +16,7 @@ "src/shadow/evaluator.py", "src/shadow/feeder.py", "src/shadow/feeder_live.py", + "src/shadow/fuse_adapter.py", "src/shadow/ledger.py", "src/shadow/manifest.py", "src/shadow/ots.py", @@ -111,7 +112,14 @@ def compute_code_manifest_hash( cal_ver = cal_ver or "csa22-v1" targets: list[tuple[str, Path]] = [(rel, root / rel) for rel in RUNTIME_MODULE_FILES] - targets.append(("config/drill-scheduler.json", cfg_file)) + if config_path is None: + cfg_rel = "config/drill-scheduler.json" + else: + try: + cfg_rel = cfg_file.resolve().relative_to(root.resolve()).as_posix() + except ValueError: + cfg_rel = f"external/{cfg_file.resolve().as_posix().lstrip('/')}" + targets.append((cfg_rel, cfg_file)) targets.append((f"specs/{cal_ver}/manifest.json", root / "specs" / cal_ver / "manifest.json")) h = hashlib.sha256() diff --git a/src/shadow/sizing.py b/src/shadow/sizing.py index 007ac5c..7497bd0 100644 --- a/src/shadow/sizing.py +++ b/src/shadow/sizing.py @@ -4,7 +4,7 @@ import hashlib import json -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from decimal import Decimal, ROUND_FLOOR, ROUND_HALF_EVEN, localcontext from pathlib import Path @@ -106,6 +106,12 @@ def __init__(self, field: str, message: str) -> None: super().__init__(message) +_MAX_CANONICAL_DECIMAL_DIGITS = 64 +_MAX_CANONICAL_ABS_ADJUSTED_EXP = 64 +_MIN_CANONICAL_EXPONENT = -128 +_MAX_CANONICAL_EXPONENT = 64 + + def canonical_decimal_str(value: Decimal | int | str) -> str: """Format a finite Decimal as an ordinary base-ten canonical string.""" d = value if isinstance(value, Decimal) else Decimal(str(value)) @@ -113,6 +119,16 @@ def canonical_decimal_str(value: Decimal | int | str) -> str: raise ValueError(f"Non-finite decimal disallowed: {value!r}") if d == 0: return "0" + tup = d.as_tuple() + exp = tup.exponent + if ( + not isinstance(exp, int) + or len(tup.digits) > _MAX_CANONICAL_DECIMAL_DIGITS + or exp < _MIN_CANONICAL_EXPONENT + or exp > _MAX_CANONICAL_EXPONENT + or abs(d.adjusted()) > _MAX_CANONICAL_ABS_ADJUSTED_EXP + ): + raise ValueError(f"Decimal exponent or precision out of bounds: {value!r}") s = format(d, "f") if "." in s: s = s.rstrip("0").rstrip(".") @@ -369,9 +385,82 @@ def compute_raw_vs_adjusted_separation( } +_CONTROL_STATE_RANK = { + "NORMAL": 0, + "NO-NEW-RISK": 1, + "DE-RISK": 2, + "ORDER-UNKNOWN": 3, + "HALT": 4, + "J1_TRIM": 1, +} + + +def _validate_control_state(state: object, field: str) -> str: + if not isinstance(state, str) or state not in _CONTROL_STATE_RANK: + raise SizingInputError(field, f"Unknown control state for {field}: {state!r}") + return state + + +def _most_restrictive_sizing_state(base_state: str, fund_state: str | None) -> str: + valid_base = _validate_control_state(base_state, "base_control_state") + if fund_state is None: + return valid_base + valid_fund = _validate_control_state(fund_state, "fund_control_state") + if valid_fund == valid_base: + return valid_base + if _CONTROL_STATE_RANK[valid_fund] > _CONTROL_STATE_RANK[valid_base]: + return valid_fund + return valid_base + + +def compute_tier_max_loss_fraction( + tier_id: str, + *, + e_val: Decimal, + e_star: Decimal, + l_val: Decimal, + h_val: Decimal = Decimal("0"), + w_ref: Decimal | None = None, +) -> tuple[Decimal, str, Decimal]: + """Compute Step 3 (cushion, binding_subbound, x_ML) using prec=28 U-01 math.""" + if tier_id not in TIER_CONFIGS: + raise SizingInputError("tier_id", f"Unknown tier {tier_id!r}") + if e_val <= 0: + raise SizingInputError("E", f"Equity E must be > 0, got {e_val}") + if e_star <= 0 or e_val > e_star: + raise SizingInputError("E_star", f"Must satisfy 0 < E <= E_star ({e_val}, {e_star})") + if h_val < 0: + raise SizingInputError("H", f"External capital H must be >= 0, got {h_val}") + if l_val < 0: + raise SizingInputError("L", f"Loss L must be >= 0, got {l_val}") + + with localcontext() as ctx: + ctx.prec = 28 + ctx.rounding = ROUND_HALF_EVEN + d_budget = Decimal(TIER_CONFIGS[tier_id]["D"]) + w_ref_eff = w_ref if w_ref is not None else (e_star + h_val) + if w_ref_eff - l_val <= 0: + raise SizingInputError("W_ref", "W_ref - L must be > 0") + if l_val >= d_budget * w_ref_eff: + cushion = Decimal("0") + else: + cushion = (d_budget * w_ref_eff - l_val) / (w_ref_eff - l_val) + ln_one_minus_shock = (Decimal("1") - Decimal("0.83")).ln() + bound_a = Decimal("3") * cushion + bound_b = Decimal("2") * cushion + bound_c = _m0_cap(cushion, ln_one_minus_shock) + subbound, x_ml = min( + [("a", bound_a), ("b", bound_b), ("c", bound_c)], + key=lambda item: item[1], + ) + return cushion, subbound, x_ml + + def compute_session_sizing( inputs: dict, active_control_state: str = "NORMAL", + fund_control_states: Mapping[str, str] | None = None, + tier_control_states: Mapping[str, tuple[str, Mapping[str, str] | None]] | None = None, ) -> dict: """Compute the 10-step policy_v0_pre notional sizing stack across all 3 tiers.""" with localcontext() as ctx: @@ -433,6 +522,13 @@ def compute_session_sizing( ln_one_minus_shock = (Decimal("1") - Decimal("0.83")).ln() conv_scale = Decimal("1") + (h_val / e_star) + _validate_control_state(active_control_state, "active_control_state") + if fund_control_states is not None: + if not isinstance(fund_control_states, Mapping): + raise SizingInputError("fund_control_states", "fund_control_states must be a mapping") + for fk, fv in fund_control_states.items(): + _validate_control_state(fv, f"fund_control_states.{fk}") + tiers_out: list[dict] = [] for tier_id in TIER_ORDER: tc = TIER_CONFIGS[tier_id] @@ -443,19 +539,14 @@ def compute_session_sizing( w_max = Decimal(tc["w_max"]) sigma_target = Decimal(tc["sigma_target"]) - # Cushion per U-01 §3.4 & DEMO-BRIEF - if l_val >= d_budget * w_ref: - cushion = Decimal("0") - else: - cushion = (d_budget * w_ref - l_val) / (w_ref - l_val) - - # Step 3: x_ML(c) = min(3c, 2c, M0(c)) - bound_a = Decimal("3") * cushion - bound_b = Decimal("2") * cushion - bound_c = _m0_cap(cushion, ln_one_minus_shock) - subbound, x_ml = min( - [("a", bound_a), ("b", bound_b), ("c", bound_c)], - key=lambda item: item[1], + # Cushion & Step 3 x_ML(c) = min(3c, 2c, M0(c)) per U-01 §3.4 & DEMO-BRIEF + cushion, subbound, x_ml = compute_tier_max_loss_fraction( + tier_id, + e_val=e_val, + e_star=e_star, + l_val=l_val, + h_val=h_val, + w_ref=w_ref, ) cap_23 = min(x_cap, x_ml) @@ -478,52 +569,126 @@ def compute_session_sizing( denom = beta_soxl if inst == "SOXL" else Decimal("1") x_pre[inst] = (s_i * cap_23 * v_i) / denom - # Step 7: Joint cap with OQ-1 resolution + t_acct_state = active_control_state + t_fund_states = fund_control_states + if tier_control_states is not None and tier_id in tier_control_states: + t_acct_state, t_fund_states = tier_control_states[tier_id] + _validate_control_state(t_acct_state, f"{tier_id}.control_state") + if t_fund_states is not None: + if not isinstance(t_fund_states, Mapping): + raise SizingInputError( + f"{tier_id}.fund_control_states", + "tier fund_control_states must be a mapping", + ) + for fk, fv in t_fund_states.items(): + _validate_control_state(fv, f"{tier_id}.fund_control_states.{fk}") + + eff_states: dict[str, str] = { + inst: _most_restrictive_sizing_state( + t_acct_state, + (t_fund_states or {}).get(inst), + ) + for inst in INSTRUMENT_ORDER + } + frozen_insts = { + inst + for inst in INSTRUMENT_ORDER + if eff_states[inst] in ("HALT", "ORDER-UNKNOWN") + } + + # Current weights and exposures for Step 9 mandatory bypass & frozen-holding reservation + w_cur_map = { + inst: (Decimal(q_pre_map[inst]) * fund_parsed[inst]["close_price"]) / e_val # type: ignore[operator] + for inst in INSTRUMENT_ORDER + } + x_cur_map = { + inst: (Decimal("3") * w_cur_map[inst]) / conv_scale + for inst in INSTRUMENT_ORDER + } + w_cur_sum = w_cur_map["TQQQ"] + w_cur_map["SOXL"] + + # Step 7: Joint cap with OQ-1 resolution, reserving any frozen (HALT / + # ORDER-UNKNOWN) holdings and excluding DE-RISK funds from active allocation. x_eff_joint = min(x_joint, x_ml) soxl_subcap_limit = x_eff_joint / Decimal("3") - soxl_beta_pre = beta_soxl * x_pre["SOXL"] - soxl_subcap_bound = soxl_beta_pre > soxl_subcap_limit - x_soxl_mid = min(soxl_beta_pre, soxl_subcap_limit) / beta_soxl - x_joint_beta = x_pre["TQQQ"] + beta_soxl * x_soxl_mid + w_ceil = min(w_max, Decimal("1.00")) + joint_cur_exceeded = (x_cur_map["TQQQ"] + beta_soxl * x_cur_map["SOXL"]) > x_eff_joint - if x_joint_beta <= x_eff_joint: + frozen_joint_beta = sum( + (beta_soxl if inst == "SOXL" else Decimal("1")) * x_cur_map[inst] + for inst in frozen_insts + ) + rem_joint = max(Decimal("0"), x_eff_joint - frozen_joint_beta) + active_insts = [ + inst + for inst in INSTRUMENT_ORDER + if inst not in frozen_insts and eff_states[inst] != "DE-RISK" + ] + soxl_beta_pre = beta_soxl * x_pre["SOXL"] + soxl_subcap_bound = ( + "SOXL" in active_insts and soxl_beta_pre > soxl_subcap_limit + ) + x_mid = { + inst: ( + min(soxl_beta_pre, soxl_subcap_limit) / beta_soxl + if inst == "SOXL" + else x_pre[inst] + ) + for inst in active_insts + } + active_joint_beta = sum( + (beta_soxl if inst == "SOXL" else Decimal("1")) * x_mid[inst] + for inst in active_insts + ) + if active_joint_beta <= rem_joint: alpha_joint = Decimal("1") - x_post = {"TQQQ": x_pre["TQQQ"], "SOXL": x_soxl_mid} + x_post_active = dict(x_mid) joint_cap_bound = False + elif rem_joint == 0 or active_joint_beta <= 0: + alpha_joint = Decimal("0") + x_post_active = {inst: Decimal("0") for inst in active_insts} + joint_cap_bound = True else: - alpha_joint = x_eff_joint / x_joint_beta - x_post = { - "TQQQ": alpha_joint * x_pre["TQQQ"], - "SOXL": alpha_joint * x_soxl_mid, - } + alpha_joint = rem_joint / active_joint_beta + x_post_active = {inst: alpha_joint * x_mid[inst] for inst in active_insts} joint_cap_bound = True + x_post = { + inst: ( + x_cur_map[inst] + if inst in frozen_insts + else x_post_active.get(inst, Decimal("0")) + ) + for inst in INSTRUMENT_ORDER + } # Step 8: Account fund weights & combined hard ceiling min(w_max, 1.00) - w_raw = { + frozen_w_sum = sum(w_cur_map[inst] for inst in frozen_insts) + rem_w_ceil = max(Decimal("0"), w_ceil - frozen_w_sum) + w_raw_active = { inst: (x_post[inst] / Decimal("3")) * conv_scale - for inst in INSTRUMENT_ORDER + for inst in active_insts } - w_ceil = min(w_max, Decimal("1.00")) - w_raw_sum = w_raw["TQQQ"] + w_raw["SOXL"] - if w_raw_sum > w_ceil and w_raw_sum > 0: - w_scale = w_ceil / w_raw_sum - w_target = {inst: w_raw[inst] * w_scale for inst in INSTRUMENT_ORDER} + w_raw_active_sum = sum(w_raw_active.values()) + if w_raw_active_sum > rem_w_ceil: w_max_bound = True + if rem_w_ceil == 0 or w_raw_active_sum <= 0: + w_target_active = {inst: Decimal("0") for inst in active_insts} + else: + w_scale = rem_w_ceil / w_raw_active_sum + w_target_active = { + inst: w_raw_active[inst] * w_scale for inst in active_insts + } else: - w_target = w_raw w_max_bound = False - - # Current weights and exposures for Step 9 mandatory bypass evaluation - w_cur_map = { - inst: (Decimal(q_pre_map[inst]) * fund_parsed[inst]["close_price"]) / e_val # type: ignore[operator] - for inst in INSTRUMENT_ORDER - } - x_cur_map = { - inst: (Decimal("3") * w_cur_map[inst]) / conv_scale + w_target_active = w_raw_active + w_target = { + inst: ( + w_cur_map[inst] + if inst in frozen_insts + else w_target_active.get(inst, Decimal("0")) + ) for inst in INSTRUMENT_ORDER } - w_cur_sum = w_cur_map["TQQQ"] + w_cur_map["SOXL"] - joint_cur_exceeded = (x_cur_map["TQQQ"] + beta_soxl * x_cur_map["SOXL"]) > x_eff_joint funds_out: list[dict] = [] for inst in INSTRUMENT_ORDER: @@ -540,14 +705,28 @@ def compute_session_sizing( kelly_cf_x = (s_i * min(x_cap, x_ml, x_k_c) * v_i) / denom kelly_would_bind = kelly_cf_x < x_p + eff_state = eff_states[inst] w_tgt = w_target[inst] - if active_control_state == "DE-RISK": + if eff_state == "DE-RISK": w_tgt_eff = Decimal("0") else: w_tgt_eff = w_tgt q_ideal = int((w_tgt_eff * e_val / p_ref).to_integral_value(rounding=ROUND_FLOOR)) q_pre_i = q_pre_map[inst] + no_new_risk_clamped = False + no_new_risk_active = ( + eff_state == "NO-NEW-RISK" + or t_acct_state == "NO-NEW-RISK" + or (t_fund_states or {}).get(inst) == "NO-NEW-RISK" + ) + if ( + no_new_risk_active + and eff_state not in ("HALT", "ORDER-UNKNOWN", "DE-RISK") + and q_ideal > q_pre_i + ): + q_ideal = q_pre_i + no_new_risk_clamped = True w_cur_i = w_cur_map[inst] cap_exceeded = ( @@ -556,15 +735,19 @@ def compute_session_sizing( or joint_cur_exceeded or (w_cur_sum > w_ceil) ) - breaker_forced_reduce = active_control_state in ("DE-RISK", "J1_TRIM") + breaker_forced_reduce = ( + eff_state in ("DE-RISK", "J1_TRIM") + or t_acct_state == "J1_TRIM" + or (t_fund_states or {}).get(inst) == "J1_TRIM" + ) mandatory_bypass = (q_ideal < q_pre_i) and (cap_exceeded or breaker_forced_reduce) in_band = abs(w_cur_i - w_tgt_eff) <= (b_band * w_tgt_eff) - if active_control_state == "HALT": + if eff_state in ("HALT", "ORDER-UNKNOWN"): delta_q_exec = 0 band_suppressed = False emerg_bypass = False - elif q_ideal == q_pre_i: + elif q_ideal == q_pre_i or no_new_risk_clamped: delta_q_exec = 0 band_suppressed = False emerg_bypass = False diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py new file mode 100644 index 0000000..5c5fadd --- /dev/null +++ b/tests/test_fuse_adapter.py @@ -0,0 +1,2345 @@ +"""Tests for digest-pinned vendored FUSE-1 adapter, tamper detection, V2 hwm_adjusted, and stub quarantine.""" + +from __future__ import annotations + +import importlib.util +import json +import os +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +_REPO_ROOT = Path(__file__).resolve().parents[1] +_SRC = str(_REPO_ROOT / "src") +if _SRC not in sys.path: + sys.path.insert(0, _SRC) + +from shadow.calendar_consumer import load_spec, resolve_session +from shadow.evaluator import ALL_BREAKER_IDS, StubEvaluator, StubProductionForbiddenError +from shadow.fuse_adapter import ( + DEFAULT_VENDOR_ENGINE_ROOT, + EngineIdentityError, + PINNED_FUSE_ENGINE_HASH, + PINNED_FUSE_SPEC_VERSION, + V2PayloadSchemaError, + VendoredFuseEvaluator, + build_fuse_validated_inputs, + resolve_aggregate_control_state, + verify_f1_entry_gates, + verify_vendored_engine_bundle, +) +from shadow.ledger import GENESIS_PREV_HASH, build_record_body +from shadow.manifest import compute_code_manifest_hash + + +def _valid_inputs() -> dict: + return { + "E": "50000", + "E_star": "50000", + "H": "0", + "L": "0", + "positions_source_record": { + "as_of": "2026-01-05T22:00:00.000Z", + "age_sessions": 0, + }, + "broker_reconciliation_source_record": { + "as_of": "2026-01-05T22:00:00.000Z", + "age_sessions": 0, + }, + "index_one_session_returns": {"NDX": 0.0, "SEMI": 0.0}, + "funds": { + "TQQQ": { + "s": "1", + "close_price": "50", + "q_pre": 100, + "sigma_forecast": "0.24", + "long_run_volatility": "0.24", + "modelled_fee": 0.0, + "modelled_financing": 0.0, + "fund_return": 0.0, + "index_return": 0.0, + }, + "SOXL": { + "s": "1", + "close_price": "40", + "q_pre": 100, + "sigma_forecast": "0.22", + "long_run_volatility": "0.24", + "modelled_fee": 0.0, + "modelled_financing": 0.0, + "fund_return": 0.0, + "index_return": 0.0, + }, + }, + } + + +class FuseAdapterTest(unittest.TestCase): + def test_entry_gates_and_read_only_vendoring_verified(self) -> None: + gates = verify_f1_entry_gates(require_read_only=False) + self.assertTrue(gates["ok"]) + self.assertTrue(gates["f1_a01_id_set_equal"]) + self.assertEqual(gates["f1_a03_base_cells"], "264/264") + self.assertEqual(gates["f1_a04_tier_repetitions"], "132/132") + self.assertEqual(gates["f1_a10_successor_cases"], "13/13") + self.assertEqual(gates["f1_a11_unresolved_fail_closed"], ["O5", "V5", "V7"]) + self.assertEqual(gates["engine_hash"], PINNED_FUSE_ENGINE_HASH) + self.assertEqual(gates["spec_version"], PINNED_FUSE_SPEC_VERSION) + + # Confirm zero __pycache__ polluted vendored dir + pycache_dirs = list(DEFAULT_VENDOR_ENGINE_ROOT.rglob("__pycache__")) + self.assertEqual(pycache_dirs, []) + + def test_one_byte_tamper_extra_file_and_corrupt_pyc_rejected_before_evaluate(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + copy_dir = Path(tmpdir) / "vendor" + shutil.copytree(DEFAULT_VENDOR_ENGINE_ROOT, copy_dir) + + # 1. Valid copy loads cleanly + ev = VendoredFuseEvaluator(vendor_root=copy_dir) + self.assertEqual(ev.engine_hash, PINNED_FUSE_ENGINE_HASH) + + # 2. Tamper 1 byte in existing .py AFTER load -> evaluate fails closed + target = copy_dir / "fuse_engine" / "canonical.py" + orig_bytes = target.read_bytes() + os.chmod(target, 0o644) + target.write_bytes(orig_bytes + b" ") + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + vin = build_fuse_validated_inputs( + _valid_inputs(), + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + with self.assertRaises(EngineIdentityError): + ev.evaluate( + PINNED_FUSE_SPEC_VERSION, + PINNED_FUSE_ENGINE_HASH, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + + # Restore file and verify clean + target.write_bytes(orig_bytes) + verify_vendored_engine_bundle(copy_dir) + + # 3. Extra file inside fuse_engine fails + extra = copy_dir / "fuse_engine" / "shim.py" + extra.write_text("# shim\n", encoding="utf-8") + with self.assertRaises(EngineIdentityError): + verify_vendored_engine_bundle(copy_dir) + extra.unlink() + + # 4. Corrupt __pycache__/*.pyc fails before evaluation + pyc_dir = copy_dir / "fuse_engine" / "__pycache__" + pyc_dir.mkdir() + tag = sys.implementation.cache_tag or "cpython-313" + bogus_pyc = pyc_dir / f"canonical.{tag}.pyc" + bogus_pyc.write_bytes(importlib.util.MAGIC_NUMBER + b"\x00" * 32) + with self.assertRaises(EngineIdentityError): + verify_vendored_engine_bundle(copy_dir) + + def test_zero_conformance_shims_and_hwm_adjusted_caller_contract(self) -> None: + ev = VendoredFuseEvaluator() + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + + # FUSE-1 rejects non-'shadow' mode directly without adapter coercion + vin = build_fuse_validated_inputs( + _valid_inputs(), + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + with self.assertRaises(ValueError): + ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "live", + vin, + {}, + None, + ) + + # Clean shadow run keeps unresolved V5/V7/O5 fail-closed without numeric shims + rows, eff, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(set(rows.keys()), set(ALL_BREAKER_IDS)) + self.assertEqual(resolve_aggregate_control_state(eff), "NORMAL") + for bid in ("V5", "V7", "O5"): + self.assertEqual(rows[bid]["reason"], "unresolved_fail_closed") + self.assertTrue(rows[bid]["would_have_tripped"]) + + # Caller V2 schema check rejects missing or non-bool hwm_adjusted BEFORE evaluate() + bad_missing_hwm = json.loads(json.dumps(vin)) + bad_missing_hwm["funds"]["TQQQ"]["corporate_action"] = { + "type": "split", + "ratio": 2, + "adjustment_complete": True, + "exact_reconciliation": True, + } + with self.assertRaises(V2PayloadSchemaError): + ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + bad_missing_hwm, + {}, + None, + ) + + bad_type_hwm = json.loads(json.dumps(vin)) + bad_type_hwm["funds"]["TQQQ"]["corporate_action"] = { + "type": "split", + "ratio": 2, + "adjustment_complete": True, + "exact_reconciliation": True, + "hwm_adjusted": "true", + } + with self.assertRaises(V2PayloadSchemaError): + ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + bad_type_hwm, + {}, + None, + ) + + # Explicit hwm_adjusted=False passes schema gate and trips V2 HALT in FUSE-1 + explicit_false = json.loads(json.dumps(vin)) + explicit_false["funds"]["TQQQ"]["corporate_action"] = { + "type": "split", + "ratio": 2, + "adjustment_complete": True, + "exact_reconciliation": True, + "hwm_adjusted": False, + } + r_false, scope_false, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + explicit_false, + {}, + None, + ) + self.assertEqual(r_false["V2"]["state"], "HALT") + self.assertEqual(r_false["V2"]["reason"], "reconciliation_mismatch") + self.assertEqual(resolve_aggregate_control_state(scope_false), "HALT") + + # Explicit hwm_adjusted=True reconciles cleanly + explicit_true = json.loads(json.dumps(vin)) + explicit_true["funds"]["TQQQ"]["corporate_action"] = { + "type": "split", + "ratio": 2, + "adjustment_complete": True, + "exact_reconciliation": True, + "hwm_adjusted": True, + } + r_true, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + explicit_true, + {}, + None, + ) + self.assertEqual(r_true["V2"]["state"], "NORMAL") + self.assertFalse(r_true["V2"]["would_have_tripped"]) + + def test_production_mode_quarantines_stub_evaluator_structurally(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + code_sha = compute_code_manifest_hash(_REPO_ROOT, calendar_version="csa22-v2") + with self.assertRaises(StubProductionForbiddenError): + build_record_body( + chain_id="prod-stub-deny", + sequence=0, + prev_record_sha256=GENESIS_PREV_HASH, + mode="production", + session_date="2026-01-05", + decision_timestamp_utc="2026-01-05T22:00:00.000Z", + session_inputs=_valid_inputs(), + calendar_session=cal, + code_version_sha=code_sha, + evaluator=StubEvaluator(), + calendar_spec=spec, + ) + + def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: + ev = VendoredFuseEvaluator() + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + bare_inputs = { + "E": "50000", + "E_star": "50000", + "H": "0", + "L": "0", + "funds": { + "TQQQ": {"s": "1", "close_price": "50", "q_pre": 100, "sigma_forecast": "0.24"}, + "SOXL": {"s": "1", "close_price": "40", "q_pre": 100, "sigma_forecast": "0.22"}, + }, + } + vin = build_fuse_validated_inputs( + bare_inputs, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertNotIn("positions", vin["source_records"]) + self.assertNotIn("broker_reconciliation", vin["source_records"]) + self.assertNotIn("index_returns", vin["source_records"]) + self.assertIsNone(vin["index_one_session_returns"]) + self.assertIsNone(vin["funds"]["TQQQ"]["fund_return"]) + self.assertIsNone(vin["funds"]["TQQQ"]["index_return"]) + + rows, eff, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NO-NEW-RISK") + self.assertEqual(rows["O1"]["reason"], "stale_or_missing_input") + self.assertEqual(resolve_aggregate_control_state(eff), "NO-NEW-RISK") + + # Real 1-session return (-11% on XNDX) computed from prior_closes + market_records trips L6 + crash_inputs = { + "E": "50000", + "E_star": "50000", + "H": "0", + "L": "0", + "positions_source_record": {"as_of": "2026-01-05T22:00:00.000Z", "age_sessions": 0}, + "broker_reconciliation_source_record": { + "as_of": "2026-01-05T22:00:00.000Z", + "age_sessions": 0, + }, + "prior_closes": { + "TQQQ": "50", + "SOXL": "40", + "QQQ": "500", + "XNDX": "100", + "SEMI": "100", + }, + "market_records": [ + { + "instrument": "TQQQ", + "normalized_value": "33.5", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "QQQ", + "normalized_value": "445", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "XNDX", + "normalized_value": "89", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SEMI", + "normalized_value": "100", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.044", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + ], + "funds": { + "TQQQ": {"s": "1", "close_price": "33.5", "q_pre": 100, "sigma_forecast": "0.24"}, + "SOXL": {"s": "1", "close_price": "40", "q_pre": 100, "sigma_forecast": "0.22"}, + }, + } + vin_crash = build_fuse_validated_inputs( + crash_inputs, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertAlmostEqual(vin_crash["index_one_session_returns"]["NDX"], -0.11, places=6) + rows_crash, eff_crash, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_crash, + {}, + None, + ) + self.assertEqual(rows_crash["L6"]["state"], "HALT") + self.assertEqual(resolve_aggregate_control_state(eff_crash), "HALT") + + def test_market_record_corporate_action_wired_into_v2(self) -> None: + ev = VendoredFuseEvaluator() + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + + def _with_ca(split_ratio: str, cash: str) -> dict: + inp = json.loads(json.dumps(_valid_inputs())) + inp["market_records"] = [ + { + "instrument": "TQQQ", + "normalized_value": "50", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + "corporate_action": { + "split_ratio": split_ratio, + "cash_per_share_usd": cash, + "ex_date": "2026-01-05", + }, + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + "corporate_action": {"split_ratio": "1", "cash_per_share_usd": "0", "ex_date": "2026-01-05"}, + }, + { + "instrument": "QQQ", + "normalized_value": "500", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.044", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + ] + return inp + + # Neutral split=1, cash=0 leaves V2 clean (None) + vin_clean = build_fuse_validated_inputs( + _with_ca("1", "0"), + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin_clean["funds"]["TQQQ"]["corporate_action"]) + rows_clean, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_clean, + {}, + None, + ) + self.assertEqual(rows_clean["V2"]["state"], "NORMAL") + + # Split factor 2 trips V2 HALT + vin_split = build_fuse_validated_inputs( + _with_ca("2", "0"), + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertEqual(vin_split["funds"]["TQQQ"]["corporate_action"]["type"], "split") + self.assertEqual(vin_split["funds"]["TQQQ"]["corporate_action"]["ratio"], 2.0) + rows_split, eff_split, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_split, + {}, + None, + ) + self.assertEqual(rows_split["V2"]["state"], "HALT") + self.assertEqual(rows_split["V2"]["reason"], "pending_corporate_action_TQQQ") + self.assertEqual(resolve_aggregate_control_state(eff_split), "HALT") + + # Cash distribution > 0 also trips V2 HALT + vin_div = build_fuse_validated_inputs( + _with_ca("1", "0.25"), + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertEqual(vin_div["funds"]["TQQQ"]["corporate_action"]["type"], "distribution") + rows_div, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_div, + {}, + None, + ) + self.assertEqual(rows_div["V2"]["state"], "HALT") + + def test_split_adjusted_fund_return_and_l4_one_session_loss_derivation(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + # 1. Reconciled 2-for-1 TQQQ split (50 -> 25) with omitted fund_return keeps V1 & V2 NORMAL + split_in = json.loads(json.dumps(_valid_inputs())) + split_in["prior_closes"] = {"TQQQ": "50", "SOXL": "40", "XNDX": "20000", "SEMI": "5000"} + split_in["current_index_closes"] = {"XNDX": "20000", "SEMI": "5000"} + split_in["funds"]["TQQQ"] = { + "s": "1", + "close_price": "25", + "q_pre": 200, + "sigma_forecast": "0.24", + "long_run_volatility": "0.24", + "modelled_fee": 0.0, + "modelled_financing": 0.0, + "hwm_adjusted": True, + "corporate_action": { + "type": "split", + "ratio": 2, + "ex_date": "2026-01-05", + "adjustment_complete": True, + "exact_reconciliation": True, + "hwm_adjusted": True, + }, + } + del split_in["funds"]["SOXL"]["fund_return"] + del split_in["funds"]["SOXL"]["index_return"] + del split_in["index_one_session_returns"] + vin_split = build_fuse_validated_inputs( + split_in, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertAlmostEqual(vin_split["funds"]["TQQQ"]["fund_return"], 0.0) + rows_split, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_split, + {}, + None, + ) + self.assertEqual(rows_split["V1"]["state"], "NORMAL") + self.assertEqual(rows_split["V2"]["state"], "NORMAL") + + # 2. prior_E=50000 -> E=48000 (no external flow) derives one_session_loss=0.04 and trips L4 + l4_loss_in = json.loads(json.dumps(_valid_inputs())) + l4_loss_in["prior_E"] = "50000" + l4_loss_in["E"] = "48000" + l4_loss_in["E_star"] = "50000" + l4_loss_in["L"] = "2000" + l4_loss_in["high_water_mark"] = "50000" + vin_l4 = build_fuse_validated_inputs( + l4_loss_in, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertAlmostEqual(vin_l4["one_session_loss"], 0.04) + rows_l4, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_l4, + {}, + None, + ) + self.assertEqual(rows_l4["L4"]["state"], "NO-NEW-RISK") + self.assertTrue(rows_l4["L4"]["latched"]) + + # 3. Omitting prior_E when L > 0 (not provably zero-loss genesis) fails closed via missing_input + missing_prior_in = json.loads(json.dumps(_valid_inputs())) + missing_prior_in["E"] = "48000" + missing_prior_in["E_star"] = "50000" + missing_prior_in["L"] = "2000" + vin_missing = build_fuse_validated_inputs( + missing_prior_in, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin_missing["one_session_loss"]) + rows_missing, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin_missing, + {}, + None, + ) + self.assertEqual(rows_missing["L4"]["state"], "NO-NEW-RISK") + self.assertEqual(rows_missing["L4"]["reason"], "missing_input") + + def test_o9_change_signals_forwarded_and_list_authorized_events_preserved(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + si_tier = _valid_inputs() + si_tier["tier"] = "GUARD" + si_tier["tier_change_event"] = {"from": "CORE", "to": "GUARD"} + rows_tier, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_tier, + cal, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + None, + ) + self.assertEqual(rows_tier["O9"]["state"], "HALT") + self.assertTrue(rows_tier["O9"]["would_have_tripped"]) + self.assertEqual(rows_tier["O9"]["reason"], "unauthorized_change") + + si_desc = _valid_inputs() + si_desc["o9_change_descriptors"] = [ + {"param": "single_fund_cap", "to": 0.45, "scope": "fund:TQQQ"} + ] + rows_desc, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_desc, + cal, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + None, + ) + self.assertEqual(rows_desc["O9"]["state"], "HALT") + self.assertTrue(rows_desc["O9"]["would_have_tripped"]) + self.assertEqual(rows_desc["O9"]["reason"], "unauthorized_change") + + si_clean = _valid_inputs() + prior_v1_latched = { + "V1": { + "TQQQ": { + "latched": True, + "trip_session": "2026-01-05", + "deviation": 0.08, + "session_returns": [], + } + } + } + rows_no_rearm, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_clean, + cal, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + prior_v1_latched, + [], + ) + self.assertEqual(rows_no_rearm["V1"]["state"], "NO-NEW-RISK") + self.assertEqual(rows_no_rearm["V1"]["reason"], "latched_prior_trip") + + rows_list_rearm, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_clean, + cal, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + prior_v1_latched, + [ + { + "type": "rearm", + "row": "V1", + "fund": "TQQQ", + "scope": "fund:TQQQ", + "session": "2026-01-06", + } + ], + ) + self.assertEqual(rows_list_rearm["V1"]["state"], "NORMAL") + self.assertFalse(rows_list_rearm["V1"]["would_have_tripped"]) + + def test_joint_exposure_scaling_o7_silence_flags_and_stale_calendar_rejected(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal6 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + # 1. Joint exposure is scaled into sizing-stack units (3x * beta / conv_scale) + si_exp = _valid_inputs() + vin_exp = build_fuse_validated_inputs( + si_exp, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + self.assertAlmostEqual(vin_exp["joint_exposure"], 33000.0, places=6) + rows_exp, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + vin_exp, + {}, + None, + ) + self.assertTrue(rows_exp["J1"]["would_have_tripped"]) + self.assertEqual(rows_exp["J1"]["reason"], "joint_cap_exceeded") + self.assertTrue(rows_exp["L0"]["would_have_tripped"]) + self.assertTrue(rows_exp["L0"]["outputs"]["cap_breached"]) + + si_conv = _valid_inputs() + si_conv["H"] = "10000" + vin_conv = build_fuse_validated_inputs( + si_conv, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + self.assertAlmostEqual(vin_conv["joint_exposure"], 27500.0, places=6) + + # 2. Explicit O7 runtime/monitor silence signals trip O7 even with fresh heartbeat + for flag in ("o7_runtime_silent", "o7_monitor_silent"): + si_o7 = _valid_inputs() + si_o7["last_heartbeat"] = "2026-01-06T22:00:00.000Z" + si_o7[flag] = True + vin_o7 = build_fuse_validated_inputs( + si_o7, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + rows_o7, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + vin_o7, + {}, + None, + ) + self.assertEqual(rows_o7["O7"]["state"], "NO-NEW-RISK") + self.assertTrue(rows_o7["O7"]["would_have_tripped"]) + self.assertEqual(rows_o7["O7"]["reason"], "dead_mans_switch") + + # 3. Stale calendar_session from another trade_date fails closed in O2 & O1 + cal_prev = resolve_session("XNYS", "2026-01-16", spec=spec) + si_cal = _valid_inputs() + vin_stale_cal = build_fuse_validated_inputs( + si_cal, + cal_prev, + policy_hash="p", + session_date="2026-01-19", + as_of="2026-01-19T22:00:00.000Z", + ) + self.assertIsNone(vin_stale_cal["session_calendar_status"]) + self.assertIsNone(vin_stale_cal["exchange_status"]) + self.assertNotIn("session_calendar", vin_stale_cal["source_records"]) + rows_stale_cal, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-19", + "2026-01-19T22:00:00.000Z", + "shadow", + vin_stale_cal, + {}, + None, + ) + self.assertTrue(rows_stale_cal["O2"]["would_have_tripped"]) + self.assertTrue(rows_stale_cal["O1"]["would_have_tripped"]) + + def test_valid_compiled_pycache_is_accepted_without_inherited_future_flags(self) -> None: + import marshal + import py_compile + + with tempfile.TemporaryDirectory() as tmpdir: + copy_dir = Path(tmpdir) / "vendor" + shutil.copytree(DEFAULT_VENDOR_ENGINE_ROOT, copy_dir) + src = copy_dir / "fuse_engine" / "__init__.py" + pyc_path = Path(importlib.util.cache_from_source(str(src))) + py_compile.compile(str(src), cfile=str(pyc_path), doraise=True) + verify_vendored_engine_bundle(copy_dir) + + # Same-size bytecode for altered source (changed docstring constant) is still rejected. + src_bytes = src.read_bytes() + altered = src_bytes.replace(b"FUSE-1 reference engine", b"FUSE-X reference engine", 1) + self.assertNotEqual(altered, src_bytes) + header = pyc_path.read_bytes()[:16] + pyc_path.write_bytes(header + marshal.dumps(compile(altered, str(src), "exec", dont_inherit=True))) + with self.assertRaises(EngineIdentityError): + verify_vendored_engine_bundle(copy_dir) + + def test_o5_settled_cash_alias_and_missing_v7_session_time_are_not_defaulted(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal6 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + def _rows(si: dict) -> dict: + rows, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + None, + ) + return rows + + o5_order = { + "settled_cash": "50000", + "o5_collar": "0.05", + "o5_symbol": "TQQQ", + "o5_order_size": 10, + "o5_side": "buy", + "o5_limit_price": "50", + "o5_reference_price": "50", + "o5_account": "stage_n_shadow", + } + si_cash_ok = _valid_inputs() + si_cash_ok.update(o5_order) + self.assertFalse(_rows(si_cash_ok)["O5"]["would_have_tripped"]) + + si_no_cash = _valid_inputs() + si_no_cash.update(o5_order) + si_no_cash.pop("settled_cash") + si_no_cash["o5_settled_cash"] = "0" + rows_no_cash = _rows(si_no_cash) + self.assertTrue(rows_no_cash["O5"]["would_have_tripped"]) + self.assertEqual(rows_no_cash["O5"]["reason"], "pre_trade_limit_violation") + + for null_key in ("settled_cash", "o5_settled_cash"): + si_null_cash = _valid_inputs() + si_null_cash.update(o5_order) + si_null_cash.pop("settled_cash") + si_null_cash[null_key] = None + rows_null_cash = _rows(si_null_cash) + self.assertTrue(rows_null_cash["O5"]["would_have_tripped"], null_key) + self.assertEqual(rows_null_cash["O5"]["reason"], "pre_trade_limit_violation", null_key) + + v7_obs = {"quote_staleness": 0.0, "spread_width": 0.001, "trading_pause": False} + si_v7_regular = _valid_inputs() + si_v7_regular["v7_spread_width"] = "0.01" + for fund in si_v7_regular["funds"].values(): + fund.update(v7_obs, session_time="regular") + self.assertFalse(_rows(si_v7_regular)["V7"]["would_have_tripped"]) + + si_v7_missing = _valid_inputs() + si_v7_missing["v7_spread_width"] = "0.01" + for fund in si_v7_missing["funds"].values(): + fund.update(v7_obs) + self.assertTrue(_rows(si_v7_missing)["V7"]["would_have_tripped"]) + + def test_o5_counter_aliases_h_for_o9_and_retier_loss_are_not_manufactured(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal6 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + def _rows(si: dict, authorized_events: object = None) -> dict: + rows, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + authorized_events, + ) + return rows + + # O5: alias-only session counters must not collide with manufactured zero canonical counters. + si_o5 = _valid_inputs() + si_o5.update( + { + "o5_collar": "0.05", + "o5_symbol": "TQQQ", + "o5_order_size": 10, + "o5_side": "buy", + "o5_limit_price": "50", + "o5_reference_price": "50", + "o5_account": "stage_n_shadow", + "settled_cash": "50000", + "o5_orders_today": 1, + "o5_max_orders_per_session": 10, + "o5_turnover_today": 500, + "o5_max_turnover_per_session": 10000, + } + ) + self.assertFalse(_rows(si_o5)["O5"]["would_have_tripped"]) + + # O5: explicitly unknown canonical counters are preserved, not defaulted to zero. + for null_counter, limit_key, limit_val in ( + ("session_turnover", "o5_max_turnover_per_session", 10000), + ("session_order_count", "o5_max_orders_per_session", 10), + ): + si_null = _valid_inputs() + si_null.update( + { + "o5_collar": "0.05", + "o5_symbol": "TQQQ", + "o5_order_size": 10, + "o5_side": "buy", + "o5_limit_price": "50", + "o5_reference_price": "50", + "o5_account": "stage_n_shadow", + "settled_cash": "50000", + limit_key: limit_val, + null_counter: None, + } + ) + rows_null = _rows(si_null) + self.assertTrue(rows_null["O5"]["would_have_tripped"], null_counter) + self.assertEqual(rows_null["O5"]["reason"], "pre_trade_limit_violation", null_counter) + + # O9: an authorized H change is checked against the live H used for sizing. + si_h = _valid_inputs() + si_h["H"] = "10000" + si_h["o9_change_descriptors"] = [{"param": "H", "to": "10000"}] + card = { + "type": "parameter_change_card", + "session": "2026-01-06", + "as_of": "2026-01-06T21:00:00.000Z", + "change_descriptors": [{"param": "H", "to": "10000"}], + } + rows_h = _rows(si_h, {"account": [card]}) + self.assertEqual(rows_h["O9"]["state"], "NORMAL") + self.assertFalse(rows_h["O9"]["would_have_tripped"]) + + # Re-tiered explicit payload: a one-session return fraction is not cumulative dollar loss L. + vin_retier = build_fuse_validated_inputs( + { + "tier": "balanced", + "fuse_inputs": { + "tier": "aggressive", + "bankroll": 45000, + "high_water_mark": 50000, + "H": "0", + "one_session_loss": 0.01, + }, + }, + None, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + self.assertEqual(vin_retier["tier"], "balanced") + self.assertAlmostEqual(vin_retier["max_loss_cap"], 6382.293860109469, places=6) + + def test_astra_p1_market_records_ca_interval_and_uncoerced_controls(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal6 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + sd = "2026-01-06" + as_of = "2026-01-06T22:00:00.000Z" + + def _vin(si: dict) -> dict: + return build_fuse_validated_inputs(si, cal6, policy_hash="p", session_date=sd, as_of=as_of) + + def _rows(si: dict) -> dict: + rows, _, _ = ev.evaluate(ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", _vin(si), {}, None) + return rows + + closes = {"TQQQ": "50", "SOXL": "40", "QQQ": "500", "XNDX": "20000", "SEMI": "5000", "SOFR": "0.045", "TBILL_3M": "0.044"} + + def _records(eff: str, **overrides: dict) -> list[dict]: + recs = [] + for inst, val in closes.items(): + rec = { + "instrument": inst, + "normalized_value": val, + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal6["spec_digest"], + # SOFR publishes T-1 (2026-01-05 for a 2026-01-06 decision). + "effective_session": "2026-01-05" if (inst == "SOFR" and eff == sd) else eff, + "retrieval_time_utc": "2026-01-06T21:30:00.000Z", + } + rec.update(overrides.get(inst, {})) + recs.append(rec) + return recs + + def _mkt_inputs(recs: list[dict]) -> dict: + si = _valid_inputs() + si.pop("index_one_session_returns", None) + for f in si["funds"].values(): + f.pop("fund_return", None) + f.pop("index_return", None) + si["market_records"] = recs + si["prior_closes"] = {"TQQQ": "50", "SOXL": "40", "XNDX": "20000", "SEMI": "5000", "SPX": "100"} + return si + + # P1-3: a previous session's eligible record with the same calendar digest is not current evidence. + vin_cur = _vin(_mkt_inputs(_records(sd))) + self.assertEqual(vin_cur["funds"]["TQQQ"]["fund_return"], 0.0) + vin_stale = _vin(_mkt_inputs(_records("2026-01-05"))) + self.assertIsNone(vin_stale["funds"]["TQQQ"]["fund_return"]) + self.assertIsNone(vin_stale["funds"]["TQQQ"]["index_return"]) + self.assertTrue(_rows(_mkt_inputs(_records("2026-01-05")))["O1"]["would_have_tripped"]) + # Rate series follow the feeder's exact freshness rule: SOFR at the T-1 publication day, + # T-bill at the session day or T-1. Never a later date, and never an older archived rate. + lagged_rates = _records(sd, SOFR={"effective_session": "2026-01-05"}, TBILL_3M={"effective_session": "2026-01-05"}) + self.assertEqual(_vin(_mkt_inputs(lagged_rates))["funds"]["TQQQ"]["fund_return"], 0.0) + self.assertFalse(_rows(_mkt_inputs(lagged_rates))["O1"]["would_have_tripped"]) + for bad_rate in ( + {"SOFR": {"effective_session": "2026-01-07"}}, + {"SOFR": {"effective_session": sd}}, + {"SOFR": {"effective_session": "2025-12-15"}}, + {"TBILL_3M": {"effective_session": "2025-12-15"}}, + ): + self.assertTrue(_rows(_mkt_inputs(_records(sd, **bad_rate)))["O1"]["would_have_tripped"], bad_rate) + + # P1(r2)-2: a record retrieved after the decision instant (or without a retrieval time) is + # look-ahead evidence in replay and is rejected even if marked eligible. + for retrieval in ("2026-01-06T22:00:00.001Z", None): + look_ahead = _records(sd, TQQQ={"retrieval_time_utc": retrieval}) + self.assertIsNone(_vin(_mkt_inputs(look_ahead))["funds"]["TQQQ"]["fund_return"], retrieval) + self.assertTrue(_rows(_mkt_inputs(look_ahead))["O1"]["would_have_tripped"], retrieval) + + # P1(r2)-6: the return uses the validated market close; a disagreeing caller close fails closed. + mkt_close_in = _mkt_inputs(_records(sd, TQQQ={"normalized_value": "55"})) + mkt_close_in["funds"]["TQQQ"].pop("close_price") + self.assertAlmostEqual(_vin(mkt_close_in)["funds"]["TQQQ"]["fund_return"], 0.1) + mkt_close_in["funds"]["TQQQ"]["close_price"] = "55" + self.assertAlmostEqual(_vin(mkt_close_in)["funds"]["TQQQ"]["fund_return"], 0.1) + mismatch_in = _mkt_inputs(_records(sd, TQQQ={"normalized_value": "55"})) + mismatch_in["funds"]["TQQQ"]["close_price"] = "50" + self.assertIsNone(_vin(mismatch_in)["funds"]["TQQQ"]["fund_return"]) + self.assertTrue(_rows(mismatch_in)["O1"]["would_have_tripped"]) + + # P1(r2)-4: a fund-payload CA and a distinct new feeder CA on the same bar fail closed. + ca_in = _mkt_inputs( + _records(sd, TQQQ={"corporate_action": {"split_ratio": "2", "cash_per_share_usd": "0", "ex_date": sd}}) + ) + ca_in["funds"]["TQQQ"]["corporate_action"] = { + "type": "distribution", + "cash_per_share_usd": 0.5, + "ex_date": "2026-01-02", + "adjustment_complete": True, + "exact_reconciliation": True, + "hwm_adjusted": True, + } + ca_in["funds"]["TQQQ"]["hwm_adjusted"] = True + # P1(r3)-1: rejected before any successor state (V2 never sees only one of the two). + from shadow.fuse_adapter import CorporateActionConflictError + + with self.assertRaises(CorporateActionConflictError): + _vin(ca_in) + same_ca = _mkt_inputs( + _records(sd, TQQQ={"corporate_action": {"split_ratio": "2", "cash_per_share_usd": "0", "ex_date": sd}}) + ) + same_ca["prior_closes"]["TQQQ"] = "100" + same_ca["funds"]["TQQQ"]["corporate_action"] = {"type": "split", "ratio": 2.0, "ex_date": sd} + self.assertAlmostEqual(_vin(same_ca)["funds"]["TQQQ"]["fund_return"], 0.0) + + # P1-4: an ineligible optional SPX bar must not derive an L6 index-crash return. + spx_bad = _records(sd) + [ + { + "instrument": "SPX", + "normalized_value": "80", + "eligibility": {"eligible": False, "reason": "stale_index_bar"}, + "calendar_spec_digest": cal6["spec_digest"], + "effective_session": sd, + "retrieval_time_utc": "2026-01-06T21:30:00.000Z", + } + ] + vin_spx_bad = _vin(_mkt_inputs(spx_bad)) + self.assertNotIn("SPX", vin_spx_bad["index_one_session_returns"] or {}) + self.assertNotEqual(_rows(_mkt_inputs(spx_bad))["L6"]["state"], "HALT") + spx_ok = _records(sd) + [ + { + "instrument": "SPX", + "normalized_value": "80", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal6["spec_digest"], + "effective_session": sd, + "retrieval_time_utc": "2026-01-06T21:30:00.000Z", + } + ] + self.assertAlmostEqual(_vin(_mkt_inputs(spx_ok))["index_one_session_returns"]["SPX"], -0.2) + + # P1-5: a corporate action dated before the return interval does not re-adjust V1's return. + def _split_inputs(ca: dict) -> dict: + si = _valid_inputs() + si["prior_closes"] = {"TQQQ": "25", "SOXL": "40", "XNDX": "20000", "SEMI": "5000"} + si["funds"]["TQQQ"].pop("fund_return", None) + si["funds"]["TQQQ"]["close_price"] = "25" + si["funds"]["TQQQ"]["corporate_action"] = dict( + {"type": "split", "ratio": 2, "adjustment_complete": True, "exact_reconciliation": True}, **ca + ) + return si + + # Friday 2026-01-02 split reconciled on Tuesday 2026-01-06: both closes are post-split. + self.assertEqual(_vin(_split_inputs({"ex_date": "2026-01-02"}))["funds"]["TQQQ"]["fund_return"], 0.0) + self.assertAlmostEqual(_vin(_split_inputs({"ex_date": sd}))["funds"]["TQQQ"]["fund_return"], 1.0) + self.assertIsNone(_vin(_split_inputs({}))["funds"]["TQQQ"]["fund_return"]) + + # P1(r2)-5: explicit null broker/cash observations are unknown evidence, not model values. + for fund_key in ("broker_position", "broker_value"): + si = _valid_inputs() + si["funds"]["TQQQ"][fund_key] = None + self.assertIsNone(_vin(si)["funds"]["TQQQ"][fund_key], fund_key) + self.assertTrue(_rows(si)["O3"]["would_have_tripped"], fund_key) + for cash_key in ("broker_cash", "positions_cash"): + si = _valid_inputs() + si[cash_key] = None + self.assertIsNone(_vin(si)[cash_key], cash_key) + self.assertTrue(_rows(si)["O3"]["would_have_tripped"], cash_key) + self.assertFalse(_rows(_valid_inputs())["O3"]["would_have_tripped"]) + + # P1(r2)-3: an unsupported kill_switch_tripped flag is rejected, never silently ignored. + si_kill = _valid_inputs() + si_kill["kill_switch_tripped"] = True + with self.assertRaisesRegex(ValueError, "authorized_events"): + _vin(si_kill) + rows_kill, _, _ = ev.evaluate( + ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", _vin(_valid_inputs()), {}, + {"account": [{"type": "kill_switch", "scope": "account", "session": sd, "as_of": as_of}]}, + ) + self.assertEqual(rows_kill["O8"]["state"], "HALT") + + # Default-substitution scan: explicit nulls / unknown values are never replaced by defaults. + for key in ("joint_exposure", "proposed_exposure", "reconciliation_tolerance"): + si = _valid_inputs() + si[key] = None + self.assertIsNone(_vin(si)[key], key) + si = _valid_inputs() + si["funds"]["TQQQ"]["exposure"] = None + si["funds"]["TQQQ"]["ledger_value"] = None + self.assertIsNone(_vin(si)["funds"]["TQQQ"]["exposure"]) + self.assertIsNone(_vin(si)["funds"]["TQQQ"]["ledger_value"]) + for bad_tier in (None, "turbo"): + si = _valid_inputs() + si["tier"] = bad_tier + vin_bad_tier = _vin(si) + self.assertIsNone(vin_bad_tier["tier_joint_cap"], bad_tier) + self.assertIsNone(vin_bad_tier["tier_loss_budget_D"], bad_tier) + retier_unknown = build_fuse_validated_inputs( + {"tier": "turbo", "fuse_inputs": {"tier": "aggressive", "bankroll": 45000, "high_water_mark": 50000, + "tier_joint_cap": 1.0, "max_loss_cap": 1.0, "tier_loss_budget_D": 0.4}}, + None, policy_hash="p", session_date=sd, as_of=as_of, + ) + for stale_key in ("tier_joint_cap", "max_loss_cap", "tier_loss_budget_D"): + self.assertNotIn(stale_key, retier_unknown) + retier_no_hwm = build_fuse_validated_inputs( + {"tier": "balanced", "fuse_inputs": {"tier": "aggressive", "bankroll": 45000, "H": "0", "max_loss_cap": 1.0}}, + None, policy_hash="p", session_date=sd, as_of=as_of, + ) + self.assertNotIn("max_loss_cap", retier_no_hwm) + + # P1(r3)-2: current_index_closes never overwrites a validated record; disagreement fails closed. + idx_in = _mkt_inputs(_records(sd, XNDX={"normalized_value": "17800"})) + self.assertAlmostEqual(_vin(idx_in)["index_one_session_returns"]["NDX"], -0.11) + idx_in["current_index_closes"] = {"XNDX": "20000"} + vin_idx = _vin(idx_in) + self.assertNotIn("NDX", vin_idx["index_one_session_returns"] or {}) + self.assertTrue(_rows(idx_in)["O1"]["would_have_tripped"]) + # With no record for an (optional) index, the override supplies its close. + idx_no_rec = _mkt_inputs(_records(sd)) + idx_no_rec["current_index_closes"] = {"SPX": "90"} + self.assertAlmostEqual(_vin(idx_no_rec)["index_one_session_returns"]["SPX"], -0.1) + # A missing REQUIRED record is not replaced by an override (fails closed). + idx_req_missing = _mkt_inputs([r for r in _records(sd) if r["instrument"] != "SEMI"]) + idx_req_missing["current_index_closes"] = {"SEMI": "4500"} + self.assertNotIn("SEMI", _vin(idx_req_missing)["index_one_session_returns"] or {}) + + # P1(r3)-3: a held fund with an unknown close has unknown ledger/broker values (no invented 0). + si_noclose = _valid_inputs() + si_noclose["funds"]["TQQQ"].pop("close_price") + vin_noclose = _vin(si_noclose) + for key in ("ledger_value", "broker_value", "exposure"): + self.assertIsNone(vin_noclose["funds"]["TQQQ"][key], key) + self.assertIsNone(vin_noclose["joint_exposure"]) + self.assertTrue(_rows(si_noclose)["O3"]["would_have_tripped"]) + si_flat = _valid_inputs() + si_flat["funds"]["TQQQ"].pop("close_price") + si_flat["funds"]["TQQQ"]["q_pre"] = 0 + self.assertEqual(_vin(si_flat)["funds"]["TQQQ"]["ledger_value"], 0.0) + + # P1(r3)-4: kill_switch_tripped is rejected at the evaluator boundary on the effective payload. + nested = _valid_inputs() + nested["fuse_inputs"] = dict(_vin(_valid_inputs()), kill_switch_tripped=True) + with self.assertRaisesRegex(ValueError, "authorized_events"): + ev.evaluate(ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", _vin(nested), {}, None) + + # P1(r3)-5: caller source records dated after as_of are dropped, so O1 fails closed. + for rec_key in ("positions_source_record", "broker_reconciliation_source_record"): + si_future = _valid_inputs() + si_future[rec_key] = {"as_of": "2026-01-07T22:00:00.000Z", "age_sessions": 0} + self.assertTrue(_rows(si_future)["O1"]["would_have_tripped"], rec_key) + + # P1(r3)-6: retrieval timestamps compare as aware instants, not strings. + offset_ok = _records(sd, TQQQ={"retrieval_time_utc": "2026-01-06T16:30:00-05:00"}) + self.assertEqual(_vin(_mkt_inputs(offset_ok))["funds"]["TQQQ"]["fund_return"], 0.0) + offset_late = _records(sd, TQQQ={"retrieval_time_utc": "2026-01-06T17:30:00-05:00"}) + self.assertIsNone(_vin(_mkt_inputs(offset_late))["funds"]["TQQQ"]["fund_return"]) + naive = _records(sd, TQQQ={"retrieval_time_utc": "2026-01-06T21:30:00"}) + self.assertIsNone(_vin(_mkt_inputs(naive))["funds"]["TQQQ"]["fund_return"]) + + # Safety pass (r4)-1: future-dated source records are dropped at the evaluator boundary on + # every path, including nested fuse_inputs and the direct payload. + future_src = {"as_of": "2026-01-07T22:00:00.000Z", "age_sessions": 0} + base_vin = _vin(_valid_inputs()) + self.assertFalse( + ev.evaluate(ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", base_vin, {}, None)[0]["O1"][ + "would_have_tripped" + ] + ) + nested_src = _valid_inputs() + nested_src["fuse_inputs"] = dict( + base_vin, source_records=dict(base_vin["source_records"], positions=future_src) + ) + rows_nested = ev.evaluate(ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", _vin(nested_src), {}, None)[0] + self.assertTrue(rows_nested["O1"]["would_have_tripped"]) + direct_src = dict(base_vin, source_records=dict(base_vin["source_records"], positions=future_src)) + direct_src["session_calendar_status"] = base_vin["session_calendar_status"] + rows_direct = ev.evaluate(ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", _vin(direct_src), {}, None)[0] + self.assertTrue(rows_direct["O1"]["would_have_tripped"]) + self.assertEqual(direct_src["source_records"]["positions"], future_src) + + # Safety pass (r4)-2: an unknown q_pre gives share_count None, so V2 cannot clear a pending + # action by matching an invented 0 against a caller-supplied broker position of 0. + cal5 = resolve_session("XNYS", "2026-01-05", spec=spec) + s1 = _valid_inputs() + s1["funds"]["TQQQ"]["corporate_action"] = { + "type": "split", "ratio": 2, "ex_date": "2026-01-05", + "adjustment_complete": False, "exact_reconciliation": False, + } + v1 = build_fuse_validated_inputs(s1, cal5, policy_hash="p", session_date="2026-01-05", as_of="2026-01-05T22:00:00.000Z") + _, _, pending_state = ev.evaluate( + ev.spec_version, ev.engine_hash, "p", "2026-01-05", "2026-01-05T22:00:00.000Z", "shadow", v1, {}, None + ) + self.assertIn("TQQQ", pending_state["V2"]["pending_adjustments"]) + s2 = _valid_inputs() + s2["funds"]["TQQQ"].pop("q_pre") + s2["funds"]["TQQQ"].update( + { + "broker_position": 0, + "ledger_value": 5000, + "broker_value": 5000, + "hwm_adjusted": True, + "corporate_action": { + "type": "split", "ratio": 2, "ex_date": "2026-01-05", "adjustment_complete": True, + "exact_reconciliation": True, "hwm_adjusted": True, + }, + } + ) + v2 = _vin(s2) + self.assertIsNone(v2["funds"]["TQQQ"]["share_count"]) + rows2, _, next2 = ev.evaluate(ev.spec_version, ev.engine_hash, "p", sd, as_of, "shadow", v2, pending_state, None) + self.assertNotEqual(rows2["V2"].get("reason"), "exact_reconciliation_auto_clear") + self.assertTrue(next2.get("V2")) + si_flat_q = _valid_inputs() + si_flat_q["funds"]["TQQQ"]["q_pre"] = 0 + self.assertEqual(_vin(si_flat_q)["funds"]["TQQQ"]["share_count"], 0) + + # P1-6: null policy hashes stay null so O6 fails closed (not the string "None"). + for key in ("loaded_policy_hash", "registered_policy_hash"): + si = _valid_inputs() + si[key] = None + self.assertIsNone(_vin(si)[key]) + self.assertTrue(_rows(si)["O6"]["would_have_tripped"], key) + + # P1-1: heartbeat provenance is explicit; the adapter default is labelled a self-heartbeat. + self.assertEqual(_vin(_valid_inputs())["heartbeat_source"], "adapter_self") + si_hb = _valid_inputs() + si_hb["last_heartbeat"] = "2026-01-06T21:59:30.000Z" + self.assertEqual(_vin(si_hb)["heartbeat_source"], "caller") + self.assertEqual(_vin(si_hb)["last_heartbeat"], "2026-01-06T21:59:30.000Z") + + # P1-1 (explicit evidence): a supplied null heartbeat or interval is not replaced by as_of / 60s. + for key in ("last_heartbeat", "scheduled_interval"): + si = _valid_inputs() + si[key] = None + self.assertIsNone(_vin(si)[key]) + self.assertTrue(_rows(si)["O7"]["would_have_tripped"], key) + + # P1-7: with no settled-cash evidence O5 does not treat total equity as settled cash. + si_buy = _valid_inputs() + si_buy.update( + { + "o5_collar": "0.05", + "o5_symbol": "TQQQ", + "o5_order_size": 10, + "o5_side": "buy", + "o5_limit_price": "50", + "o5_reference_price": "50", + "o5_account": "stage_n_shadow", + } + ) + self.assertIsNone(_vin(si_buy)["settled_cash"]) + rows_buy = _rows(si_buy) + self.assertTrue(rows_buy["O5"]["would_have_tripped"]) + self.assertEqual(rows_buy["O5"]["reason"], "pre_trade_limit_violation") + + def test_astra_p1_metadata_pinned_and_loader_executes_verified_source_only(self) -> None: + import marshal + + from shadow.fuse_adapter import PINNED_FUSE_METADATA_SHA256 + + self.assertIn("provenance.json", PINNED_FUSE_METADATA_SHA256) + self.assertIn("SH1-ACCEPTANCE.json", PINNED_FUSE_METADATA_SHA256) + with tempfile.TemporaryDirectory() as tmpdir: + # P1-8: provenance.json and SH1-ACCEPTANCE.json cannot be rewritten consistently. + for fname in ("SH1-ACCEPTANCE.json", "provenance.json", "spec.json"): + copy_dir = Path(tmpdir) / f"vendor_{fname}" + shutil.copytree(DEFAULT_VENDOR_ENGINE_ROOT, copy_dir) + target = copy_dir / "metadata" / fname + os.chmod(target, 0o644) + target.write_bytes(target.read_bytes().replace(b"{", b"{ ", 1)) + with self.assertRaises(EngineIdentityError, msg=fname): + verify_vendored_engine_bundle(copy_dir) + + # P1-9: a poisoned cache under PYTHONPYCACHEPREFIX is never executed. + copy_dir = Path(tmpdir) / "vendor_cache" + shutil.copytree(DEFAULT_VENDOR_ENGINE_ROOT, copy_dir) + prefix = Path(tmpdir) / "pycache_prefix" + prev_prefix = sys.pycache_prefix + sys.pycache_prefix = str(prefix) + try: + for py in sorted((copy_dir / "fuse_engine").glob("*.py")): + cfile = Path(importlib.util.cache_from_source(str(py.resolve()))) + cfile.parent.mkdir(parents=True, exist_ok=True) + poisoned = compile("raise RuntimeError('poisoned cache executed')\n", str(py), "exec") + header = importlib.util.MAGIC_NUMBER + (0).to_bytes(4, "little") + st = py.stat() + header += int(st.st_mtime).to_bytes(4, "little") + (st.st_size & 0xFFFFFFFF).to_bytes(4, "little") + cfile.write_bytes(header + marshal.dumps(poisoned)) + ev_cache = VendoredFuseEvaluator(vendor_root=copy_dir) + finally: + sys.pycache_prefix = prev_prefix + self.assertEqual(ev_cache.engine_hash, PINNED_FUSE_ENGINE_HASH) + + def test_half_day_eod_decision_maps_open_and_late_runs_are_rejected_by_scheduler_cutoff(self) -> None: + from shadow.scheduler import DrillSchedulerConfig, compute_session_deadlines + + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal_hd = resolve_session("XNYS", "2026-11-27", spec=spec) + self.assertEqual(cal_hd["session_state"], "half_day") + self.assertEqual(cal_hd["order_cutoff_utc"], "2026-11-27T18:00:00.000Z") + deadlines = compute_session_deadlines("2026-11-27", DrillSchedulerConfig(), calendar_session=cal_hd) + decision_utc = deadlines["scheduled_decision_instant_utc"] + # SH-1 half_day_run_time 14:30 ET is an EOD decision after the 13:00 ET order cutoff. + self.assertEqual(decision_utc, "2026-11-27T19:30:00.000Z") + self.assertGreater(decision_utc, cal_hd["order_cutoff_utc"]) + self.assertEqual(deadlines["decision_cutoff_utc"], "2026-11-27T20:00:00.000Z") + + ev = VendoredFuseEvaluator() + for as_of in (decision_utc, "2026-11-27T20:05:00.000Z"): + vin = build_fuse_validated_inputs( + _valid_inputs(), cal_hd, policy_hash="p", session_date="2026-11-27", as_of=as_of + ) + self.assertEqual(vin["session_calendar_status"], "open", as_of) + self.assertEqual(vin["exchange_status"], "open", as_of) + rows, _, _ = ev.evaluate( + ev.spec_version, ev.engine_hash, "p", "2026-11-27", as_of, "shadow", vin, {}, None + ) + self.assertFalse(rows["O2"]["would_have_tripped"], as_of) + # A late run (15:05 ET) is past the scheduler's half-day decision cutoff (15:00 ET): + # run_daily_drill_cycle rejects it as late_after_decision_cutoff before evaluation + # (covered end-to-end by test_scheduler.test_market_cutoff_separate_from_commitment_deadline), + # independent of O2. + self.assertGreater("2026-11-27T20:05:00.000Z", deadlines["decision_cutoff_utc"]) + + def test_o5_order_evidence_and_v1_five_session_history_forwarded(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal6 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + # 1. Pre-trade O5 order fields trigger violation when violating whitelist & pass when compliant + si_o5_bad = _valid_inputs() + si_o5_bad.update( + { + "o5_collar": "0.05", + "o5_symbol": "UVXY", + "o5_order_size": 10, + "o5_side": "buy", + "o5_account": "stage_n_shadow", + } + ) + rows_o5_bad, _, res_o5_bad = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_o5_bad, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + None, + ) + self.assertTrue(rows_o5_bad["O5"]["would_have_tripped"]) + self.assertEqual(rows_o5_bad["O5"]["reason"], "pre_trade_limit_violation") + self.assertEqual(res_o5_bad["O5"], {"rejection_count": 1, "last_rejection_session": "2026-01-06", "latched": False}) + + si_o5_ok = _valid_inputs() + si_o5_ok.update( + { + "o5_collar": "0.05", + "o5_symbol": "TQQQ", + "o5_order_size": 10, + "o5_side": "buy", + "o5_limit_price": "50", + "o5_reference_price": "50", + "o5_account": "stage_n_shadow", + "settled_cash": "50000", + } + ) + rows_o5_ok, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_o5_ok, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + None, + ) + self.assertFalse(rows_o5_ok["O5"]["would_have_tripped"]) + + # 2. Bootstrapped five_session_history is forwarded to V1 tracking deviation + si_v1 = _valid_inputs() + si_v1["funds"]["TQQQ"].update( + { + "fund_return": "0.005", + "index_return": "0.0", + "five_session_history": [ + {"fund_return": 0.005, "index_return": 0.0} for _ in range(4) + ], + } + ) + rows_v1, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + build_fuse_validated_inputs( + si_v1, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ), + {}, + None, + ) + self.assertEqual(rows_v1["V1"]["state"], "NO-NEW-RISK") + self.assertTrue(rows_v1["V1"]["latched"]) + self.assertEqual(rows_v1["V1"]["reason"], "tracking_deviation_exceeds_2_0pp") + + def test_fractional_broker_position_and_market_data_validation_preserved(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal6 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + # 1. Fractional broker_position is preserved (not truncated to int) so O3 catches mismatch + si_frac = _valid_inputs() + si_frac["funds"]["TQQQ"]["broker_position"] = "100.9" + vin_frac = build_fuse_validated_inputs( + si_frac, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + self.assertEqual(vin_frac["funds"]["TQQQ"]["share_count"], 100) + self.assertAlmostEqual(vin_frac["funds"]["TQQQ"]["broker_position"], 100.9, places=6) + rows_frac, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + vin_frac, + {}, + None, + ) + self.assertEqual(rows_frac["O3"]["state"], "HALT") + self.assertEqual(rows_frac["O3"]["reason"], "reconciliation_mismatch") + + # 2. Missing required market_record fails O1 closed even when caller supplies source_records.market_data + si_mkt = _valid_inputs() + cal_digest = str(cal6["spec_digest"]) + si_mkt["market_records"] = [ + { + "instrument": inst, + "normalized_value": 50.0, + "calendar_spec_digest": cal_digest, + "effective_session": "2026-01-06", + "retrieval_time_utc": "2026-01-06T21:30:00.000Z", + "eligibility": {"eligible": True}, + } + for inst in ("TQQQ", "SOXL", "QQQ", "XNDX", "SEMI", "SOFR") + ] + si_mkt["source_records"] = { + "market_data": {"as_of": "2026-01-06T22:00:00.000Z", "age_sessions": 0}, + "session_calendar": {"as_of": "2026-01-06T22:00:00.000Z", "age_sessions": 0}, + } + vin_mkt = build_fuse_validated_inputs( + si_mkt, + cal6, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + self.assertNotIn("market_data", vin_mkt["source_records"]) + rows_mkt, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + vin_mkt, + {}, + None, + ) + self.assertTrue(rows_mkt["O1"]["would_have_tripped"]) + + def test_v1_missing_fee_or_financing_fails_closed(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + for missing_key in ("modelled_fee", "modelled_financing"): + si = json.loads(json.dumps(_valid_inputs())) + si["funds"]["TQQQ"].pop(missing_key, None) + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin["funds"]["TQQQ"][missing_key]) + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["V1"]["state"], "NO-NEW-RISK") + self.assertEqual(rows["V1"]["reason"], "missing_input") + self.assertEqual(nxt.get("V1", {}).get("TQQQ", {}).get("five_session_history", []), []) + + def test_l6_benchmark_returns_derived_independently_of_missing_fund_return(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + si = json.loads(json.dumps(_valid_inputs())) + si.pop("index_one_session_returns", None) + si["prior_closes"] = {"XNDX": "100", "SEMI": "100", "SOXL": "40"} # omit TQQQ prior close + si["current_index_closes"] = {"XNDX": "90", "SEMI": "100"} + si["funds"]["TQQQ"].pop("fund_return", None) + si["funds"]["TQQQ"].pop("index_return", None) + si["funds"]["SOXL"]["fund_return"] = 0.0 + si["funds"]["SOXL"]["index_return"] = 0.0 + + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin["funds"]["TQQQ"]["fund_return"]) + self.assertIsNotNone(vin["index_one_session_returns"]) + self.assertAlmostEqual(vin["index_one_session_returns"]["NDX"], -0.1, places=6) + self.assertAlmostEqual(vin["index_one_session_returns"]["SEMI"], 0.0, places=6) + + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NO-NEW-RISK") + self.assertEqual(rows["L6"]["state"], "HALT") + self.assertTrue(rows["L6"]["latched"]) + self.assertEqual(rows["L6"]["reason"], "index_fall_10pct") + self.assertTrue(nxt["L6"]["latched"]) + + def test_l6_partial_benchmark_crash_latches_halt_when_other_benchmark_missing(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + si = json.loads(json.dumps(_valid_inputs())) + si.pop("index_one_session_returns", None) + si["prior_closes"] = {"TQQQ": "50", "SOXL": "40", "XNDX": "100", "SEMI": "200"} + si["current_index_closes"] = {"XNDX": "90"} # SEMI missing/ineligible + + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNotNone(vin["index_one_session_returns"]) + self.assertAlmostEqual(vin["index_one_session_returns"]["NDX"], -0.1, places=6) + self.assertNotIn("SEMI", vin["index_one_session_returns"]) + + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NO-NEW-RISK") + self.assertEqual(rows["L6"]["state"], "HALT") + self.assertTrue(rows["L6"]["latched"]) + self.assertEqual(rows["L6"]["reason"], "index_fall_10pct") + self.assertTrue(nxt["L6"]["latched"]) + + def test_split_with_cash_distribution_preserves_both_components_and_avoids_false_v1_latch(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + si = json.loads(json.dumps(_valid_inputs())) + si["prior_closes"] = {"TQQQ": "100", "SOXL": "40", "XNDX": "100", "SEMI": "100"} + si["funds"]["TQQQ"]["close_price"] = "49" + si["funds"]["TQQQ"].pop("fund_return", None) + si["funds"]["TQQQ"].pop("corporate_action", None) + si["funds"]["TQQQ"]["index_return"] = 0.0 + si["funds"]["TQQQ"]["modelled_fee"] = 0.0 + si["funds"]["TQQQ"]["modelled_financing"] = 0.0 + si["funds"]["SOXL"]["fund_return"] = 0.0 + si["funds"]["SOXL"]["index_return"] = 0.0 + si["funds"]["SOXL"]["modelled_fee"] = 0.0 + si["funds"]["SOXL"]["modelled_financing"] = 0.0 + si["market_records"] = [ + { + "instrument": "TQQQ", + "normalized_value": "49", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + "corporate_action": { + "split_ratio": "2", + "cash_per_share_usd": "1", + "ex_date": "2026-01-05", + }, + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + "corporate_action": {"split_ratio": "1", "cash_per_share_usd": "0", "ex_date": "2026-01-05"}, + }, + { + "instrument": "QQQ", + "normalized_value": "500", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + ] + + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + tqqq_ca = vin["funds"]["TQQQ"]["corporate_action"] + self.assertIsNotNone(tqqq_ca) + self.assertEqual(tqqq_ca["ratio"], 2.0) + self.assertEqual(tqqq_ca["cash_per_share_usd"], 1.0) + self.assertAlmostEqual(vin["funds"]["TQQQ"]["fund_return"], 0.0, places=9) + + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["V1"]["state"], "NORMAL") + self.assertFalse(rows["V1"]["latched"]) + self.assertFalse(nxt.get("V1", {}).get("latched", False)) + + def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + si = json.loads(json.dumps(_valid_inputs())) + si.pop("index_one_session_returns", None) + si["prior_closes"] = {"XNDX": "20000", "SEMI": "5000", "QQQ": "100"} + si["market_records"] = [ + { + "instrument": "TQQQ", + "normalized_value": "50", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "QQQ", + "normalized_value": "50", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + "corporate_action": {"split_ratio": "2", "ex_date": "2026-01-05"}, + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + ] + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNotNone(vin["index_one_session_returns"]) + self.assertNotIn("QQQ", vin["index_one_session_returns"]) + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NORMAL") + self.assertEqual(rows["L6"]["state"], "NORMAL") + self.assertFalse(nxt.get("L6", {}).get("latched", False)) + + def test_nonpositive_sigma_forecast_marks_vol_invalid_for_o1_rejection(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + for bad_sigma in ("0", "-0.1"): + with self.subTest(bad_sigma=bad_sigma): + si = json.loads(json.dumps(_valid_inputs())) + si["funds"]["TQQQ"]["sigma_forecast"] = bad_sigma + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertNotIn("volatility", vin["source_records"]) + self.assertNotIn("market_data", vin["source_records"]) + rows, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NO-NEW-RISK") + + def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + si = json.loads(json.dumps(_valid_inputs())) + si.pop("index_one_session_returns", None) + si["funds"]["TQQQ"].pop("index_return", None) + si["funds"]["TQQQ"]["fund_return"] = 0.0 + si["prior_closes"] = {"XNDX": "100", "SEMI": "5000"} + si["market_records"] = [ + { + "instrument": "TQQQ", + "normalized_value": "50", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "QQQ", + "normalized_value": "500", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "XNDX", + "normalized_value": "90", + "eligibility": {"eligible": False, "reason": "stale_benchmark_bar"}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + ] + + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin["funds"]["TQQQ"]["index_return"]) + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NO-NEW-RISK") + self.assertFalse(rows["V1"].get("latched", False)) + self.assertFalse(nxt.get("V1", {}).get("latched", False)) + self.assertNotEqual(rows["V1"].get("reason"), "tracking_deviation_exceeds_0_75pp") + + def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal = resolve_session("XNYS", "2026-01-05", spec=spec) + ev = VendoredFuseEvaluator() + + si = json.loads(json.dumps(_valid_inputs())) + si["prior_closes"] = {"TQQQ": "50", "SOXL": "40", "XNDX": "20000", "SEMI": "5000"} + si["funds"]["TQQQ"].pop("fund_return", None) + si["funds"]["TQQQ"]["close_price"] = "45" + si["funds"]["TQQQ"]["index_return"] = 0.0 + si["funds"]["TQQQ"]["modelled_fee"] = 0.0 + si["funds"]["TQQQ"]["modelled_financing"] = 0.0 + si["market_records"] = [ + { + "instrument": "TQQQ", + "normalized_value": "45", + "eligibility": {"eligible": False, "reason": "stale_fund_bar"}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", + }, + ] + + vin = build_fuse_validated_inputs( + si, + cal, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin["funds"]["TQQQ"]["fund_return"]) + rows, _, nxt = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin, + {}, + None, + ) + self.assertEqual(rows["O1"]["state"], "NO-NEW-RISK") + self.assertFalse(rows["V1"].get("latched", False)) + self.assertFalse(nxt.get("V1", {}).get("latched", False)) + self.assertNotEqual(rows["V1"].get("reason"), "tracking_deviation_exceeds_0_75pp") + + def test_ineligible_fund_corporate_action_is_excluded_from_v2_state(self) -> None: + spec = load_spec(_REPO_ROOT / "specs" / "csa22-v2") + cal1 = resolve_session("XNYS", "2026-01-05", spec=spec) + cal2 = resolve_session("XNYS", "2026-01-06", spec=spec) + ev = VendoredFuseEvaluator() + + si1 = json.loads(json.dumps(_valid_inputs())) + si1["funds"]["TQQQ"].pop("corporate_action", None) + si1["funds"]["TQQQ"]["close_price"] = "25" + si1["funds"]["TQQQ"]["fund_return"] = 0.0 + si1["funds"]["TQQQ"]["index_return"] = 0.0 + si1["market_records"] = [ + { + "instrument": "TQQQ", + "normalized_value": "25", + "eligibility": {"eligible": False, "reason": "stale_fund_bar"}, + "calendar_spec_digest": cal1["spec_digest"], + "corporate_action": {"split_ratio": "2", "ex_date": "2026-01-05"}, + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal1["spec_digest"], + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal1["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal1["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal1["spec_digest"], + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal1["spec_digest"], + }, + ] + vin1 = build_fuse_validated_inputs( + si1, + cal1, + policy_hash="p", + session_date="2026-01-05", + as_of="2026-01-05T22:00:00.000Z", + ) + self.assertIsNone(vin1["funds"]["TQQQ"]["corporate_action"]) + rows1, _, nxt1 = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-05", + "2026-01-05T22:00:00.000Z", + "shadow", + vin1, + {}, + None, + ) + self.assertEqual(rows1["O1"]["state"], "NO-NEW-RISK") + + si2 = json.loads(json.dumps(_valid_inputs())) + si2["positions_source_record"] = {"as_of": "2026-01-06T22:00:00.000Z", "age_sessions": 0} + si2["broker_reconciliation_source_record"] = { + "as_of": "2026-01-06T22:00:00.000Z", + "age_sessions": 0, + } + vin2 = build_fuse_validated_inputs( + si2, + cal2, + policy_hash="p", + session_date="2026-01-06", + as_of="2026-01-06T22:00:00.000Z", + ) + rows2, _, _ = ev.evaluate( + ev.spec_version, + ev.engine_hash, + "p", + "2026-01-06", + "2026-01-06T22:00:00.000Z", + "shadow", + vin2, + nxt1, + None, + ) + self.assertEqual(rows2["V2"]["state"], "NORMAL") + self.assertNotEqual(rows2["V2"].get("reason"), "pending_corporate_action_carried_TQQQ") + + def test_market_corporate_action_with_none_optional_fields_is_preserved(self) -> None: + from shadow.fuse_adapter import _map_market_corporate_action + + split_only = _map_market_corporate_action( + {"split_ratio": "2", "cash_per_share_usd": None, "ex_date": "2026-01-05"} + ) + self.assertIsNotNone(split_only) + assert split_only is not None + self.assertEqual(split_only["type"], "split") + self.assertEqual(split_only["ratio"], 2.0) + + dist_only = _map_market_corporate_action( + {"split_ratio": None, "cash_per_share_usd": "0.5", "ex_date": "2026-01-05"} + ) + self.assertIsNotNone(dist_only) + assert dist_only is not None + self.assertEqual(dist_only["type"], "distribution") + self.assertEqual(dist_only["cash_per_share_usd"], 0.5) + + def test_defensive_bounds_omitted_trade_date_and_clears_stale_max_loss_cap(self) -> None: + from decimal import Decimal + from shadow.fuse_adapter import ( + _apply_explicit_payload_tier, + _finite_number, + _map_calendar_statuses, + ) + + self.assertIsNone(_finite_number(Decimal("1e400"))) + self.assertEqual( + _map_calendar_statuses( + {"session_state": "regular", "is_trading_day": True, "blocks_eligibility": False}, + session_date="2026-01-05", + ), + (None, None), + ) + updated = _apply_explicit_payload_tier( + {"tier": "aggressive", "max_loss_cap": 12345.0}, + {"tier": "conservative"}, + policy_hash="a" * 64, + ) + self.assertEqual(updated["tier"], "conservative") + self.assertNotIn("max_loss_cap", updated) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sizing.py b/tests/test_sizing.py index 839acd8..5036f10 100644 --- a/tests/test_sizing.py +++ b/tests/test_sizing.py @@ -176,6 +176,14 @@ def test_canonical_decimal_str_formatting(self) -> None: self.assertEqual(canonical_decimal_str(Decimal("0.2000")), "0.2") with self.assertRaises(ValueError): canonical_decimal_str(Decimal("NaN")) + self.assertEqual(canonical_decimal_str(Decimal("0E-57")), "0") + for extreme in ( + Decimal("1e200000000"), + Decimal("1e-200000000"), + Decimal("1." + ("1" * 64)), + ): + with self.assertRaises(ValueError): + canonical_decimal_str(extreme) def test_missing_input_raises_sizing_error(self) -> None: bad = _make_inputs() @@ -435,6 +443,114 @@ def test_policy_config_hash_reflects_runtime_config_calendar_and_operational_fil self.assertNotEqual(policy_config_hash(repo_root=tmp_repo), base_policy, mod) target.write_text(orig, encoding="utf-8") + def test_halted_fund_holdings_reserved_against_joint_cap_and_weight_ceil(self) -> None: + # Codex P2 regression (PRRT_kwDOV2RNAc67oejF): balanced $50k with 500 TQQQ ($25k) under + # V2 fund-scoped HALT and 0 SOXL must reserve frozen TQQQ exposure so SOXL cannot buy. + overweight_halt = compute_session_sizing( + _make_inputs( + E="50000", + E_star="50000", + L="0", + p_tqqq="50", + q_pre_tqqq=500, + p_soxl="40", + q_pre_soxl=0, + ), + active_control_state="NORMAL", + fund_control_states={"TQQQ": "HALT", "SOXL": "NORMAL"}, + ) + bal_over = _tier(overweight_halt, "balanced") + self.assertEqual(_fund(bal_over, "TQQQ")["delta_q_exec"], 0) + self.assertEqual(_fund(bal_over, "SOXL")["q_ideal"], 0) + self.assertEqual(_fund(bal_over, "SOXL")["delta_q_exec"], 0) + + # Partial frozen TQQQ ($2,500 => x_cur = 0.15) leaves x_ML - 0.15 = 0.051289... headroom + partial_halt = compute_session_sizing( + _make_inputs( + E="50000", + E_star="50000", + L="0", + p_tqqq="50", + q_pre_tqqq=50, + p_soxl="40", + q_pre_soxl=0, + ), + active_control_state="NORMAL", + fund_control_states={"TQQQ": "HALT", "SOXL": "NORMAL"}, + ) + bal_part = _tier(partial_halt, "balanced") + soxl_part = _fund(bal_part, "SOXL") + tqqq_x_cur = Decimal("3") * (Decimal("2500") / Decimal("50000")) + total_beta_post = tqqq_x_cur + Decimal("1.5") * Decimal(soxl_part["x_post_joint"]) + self.assertLessEqual(total_beta_post, Decimal(bal_part["x_ML"]) + Decimal("0.000002")) + self.assertEqual(_fund(bal_part, "TQQQ")["delta_q_exec"], 0) + + def test_derisk_excluded_from_cap_without_frozen_and_tier_j1_trim_triggers_bypass(self) -> None: + # 1) When TQQQ is DE-RISK and frozen_insts is empty, SOXL keeps full headroom. + derisk_res = compute_session_sizing( + _make_inputs( + E="50000", + E_star="50000", + q_pre_tqqq=200, + q_pre_soxl=0, + ), + fund_control_states={"TQQQ": "DE-RISK", "SOXL": "NORMAL"}, + ) + bal_derisk = _tier(derisk_res, "balanced") + self.assertEqual(_fund(bal_derisk, "TQQQ")["w_target"], "0") + self.assertGreater(int(_fund(bal_derisk, "SOXL")["q_ideal"]), 0) + + # 2) Tier-level J1_TRIM triggers mandatory_bypass for a weight-reducing trade even inside +/-20% band. + # Compute baseline NORMAL balanced weight/q_pre slightly above target (inside 20% band) then trigger J1_TRIM on balanced tier. + base_normal = compute_session_sizing(_make_inputs(E="50000", E_star="50000")) + bal_norm = _tier(base_normal, "balanced") + q_target_tqqq = _fund(bal_norm, "TQQQ")["q_ideal"] + trim_res = compute_session_sizing( + _make_inputs( + E="50000", + E_star="50000", + q_pre_tqqq=int(q_target_tqqq) + 1, + ), + tier_control_states={"balanced": ("J1_TRIM", None)}, + ) + bal_trim = _tier(trim_res, "balanced") + self.assertEqual(_fund(bal_trim, "TQQQ")["delta_q_exec"], -1) + + def test_no_new_risk_clamp_holds_under_j1_trim_and_unknown_state_rejected(self) -> None: + # Rank-1 tie: J1_TRIM at tier/account level MUST NOT defeat fund NO-NEW-RISK buy clamp. + res = compute_session_sizing( + _make_inputs(E="50000", E_star="50000", q_pre_tqqq=0, q_pre_soxl=0), + active_control_state="NORMAL", + tier_control_states={"balanced": ("J1_TRIM", {"TQQQ": "NO-NEW-RISK", "SOXL": "NORMAL"})}, + ) + bal = _tier(res, "balanced") + self.assertEqual(_fund(bal, "TQQQ")["q_ideal"], 0) + self.assertEqual(_fund(bal, "TQQQ")["delta_q_exec"], 0) + self.assertGreater(_fund(bal, "SOXL")["q_ideal"], 0) + + for bad_kwargs in ( + {"active_control_state": "BOGUS"}, + {"fund_control_states": {"TQQQ": "NO_NEW_RISK"}}, + {"tier_control_states": {"balanced": ("NORMAL", {"SOXL": "UNKNOWN"})}}, + ): + with self.assertRaises(SizingInputError): + compute_session_sizing(_make_inputs(E="50000", E_star="50000"), **bad_kwargs) # type: ignore[arg-type] + + def test_code_manifest_hash_distinguishes_same_filename_config_paths(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + tmp_repo = Path(tmpdir) + (tmp_repo / "dir_a").mkdir() + (tmp_repo / "dir_b").mkdir() + cfg_a = tmp_repo / "dir_a" / "shared.json" + cfg_b = tmp_repo / "dir_b" / "shared.json" + payload = '{"calendar_version":"csa22-v2","mode":"drill"}\n' + cfg_a.write_text(payload, encoding="utf-8") + cfg_b.write_text(payload, encoding="utf-8") + self.assertNotEqual( + compute_code_manifest_hash(tmp_repo, config_path=cfg_a), + compute_code_manifest_hash(tmp_repo, config_path=cfg_b), + ) + if __name__ == "__main__": unittest.main()