From b26457c57fed43f6dbfd9388e49c2716007199ac Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:47:57 +0000 Subject: [PATCH 01/13] feat(fuse): add vendored FUSE-1 adapter and per-tier sizing isolation Add VendoredFuseEvaluator, which re-verifies the vendored engine digests before each evaluate() call, plus FUSE input translation, NO-NEW-RISK clamping and per-tier sizing controls. Register fuse_adapter in the code manifest, hash explicit scheduler config paths by their relative path, and record the SH-2 entry gates. Part 2 of the SH-2 split of #7. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- docs/sh2-entry-gates.md | 25 + src/shadow/fuse_adapter.py | 1501 +++++++++++++++ src/shadow/manifest.py | 10 +- src/shadow/sizing.py | 279 ++- tests/test_fuse_adapter.py | 1654 +++++++++++++++++ tests/test_sizing.py | 116 ++ .../fuse_engine/__init__.py | 133 ++ .../fuse_engine/canonical.py | 36 + .../fuse_engine/canonical_state.py | 776 ++++++++ .../fuse_engine/evaluator.py | 1309 +++++++++++++ .../fuse_engine/rows_loss.py | 646 +++++++ .../fuse_engine/rows_ops.py | 1545 +++++++++++++++ .../fuse_engine/rows_vehicle.py | 1123 +++++++++++ .../fuse_engine/state.py | 118 ++ .../metadata/FREEZE.json | 11 + .../metadata/SH1-ACCEPTANCE.json | 25 + .../metadata/disposition-register.json | 69 + .../metadata/provenance.json | 66 + .../metadata/result-bundle.json | 38 + .../metadata/spec.json | 336 ++++ 20 files changed, 9767 insertions(+), 49 deletions(-) create mode 100644 docs/sh2-entry-gates.md create mode 100644 src/shadow/fuse_adapter.py create mode 100644 tests/test_fuse_adapter.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/__init__.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical_state.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/evaluator.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_loss.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_ops.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_vehicle.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/state.py create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/FREEZE.json create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/SH1-ACCEPTANCE.json create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/disposition-register.json create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/provenance.json create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/result-bundle.json create mode 100644 vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/spec.json 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..d76e152 --- /dev/null +++ b/src/shadow/fuse_adapter.py @@ -0,0 +1,1501 @@ +"""Digest-pinned vendored FUSE-1 consumer adapter and entry-gate verifier.""" + +from __future__ import annotations + +import copy +import hashlib +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" + +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 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", optimize=optimize) + if marshal.dumps(pyc_code) != marshal.dumps(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, +) -> 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}") + + 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, + } + + +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" + spec = importlib.util.spec_from_file_location( + pkg_name, + init_path, + submodule_search_locations=[str(engine_dir)], + ) + 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") + + 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) + + +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 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 + + +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)) + elif not require_sizing_bankroll: + e_star_dec = e_dec + 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"))) + hwm_val = _finite_number( + payload.get( + "high_water_mark", + session_inputs.get("high_water_mark", session_inputs.get("E_star", bankroll_val)), + ) + ) + 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"] + elif payload.get("one_session_loss") is not None: + cap_inputs["L"] = payload["one_session_loss"] + 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: + 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") + + 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) + + tier = str(session_inputs.get("tier", "balanced")) + tier_cfg = TIER_CONFIGS.get(tier, TIER_CONFIGS["balanced"]) + 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: + 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 + for inst in req_series: + rec = by_inst.get(inst) + elig = rec.get("eligibility") if isinstance(rec, Mapping) and isinstance(rec.get("eligibility"), Mapping) else {} + bad_rec = ( + rec is None + or rec.get("normalized_value") is None + or not elig.get("eligible") + or (cal_digest is not None and rec.get("calendar_spec_digest") != cal_digest) + ) + 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 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(): + if v is not None: + cur_closes[str(k)] = v + + 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 + pos_val = (close_val * q_pre_val) if (close_val is not None and q_pre_val is not None) else 0.0 + if joint_exposure_dec is not None and conv_scale is not None: + 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")) + if ( + ca_obj is None + and not bad_market_payload + and symbol not in bad_market_insts + and symbol in by_inst + ): + ca_obj = _map_market_corporate_action( + by_inst[symbol].get("corporate_action") # type: ignore[arg-type] + ) + + # 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 fdata.get("close_price") is not None + ): + fund_ret_val = _compute_ca_adjusted_fund_return( + fdata.get("close_price"), + prior_closes.get(symbol), + ca_obj, + ) + 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 + + broker_pos_val = ( + _resolve_tier_quantity(fdata.get("broker_position"), tier) + if "broker_position" in fdata and fdata.get("broker_position") is not None + else q_pre_val + ) + fund_entry: dict[str, Any] = { + "symbol": symbol, + "exposure": _finite_number(fdata.get("exposure")) if fdata.get("exposure") is not None 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.get("session_time", "regular")), + "share_count": _preserve_numeric_quantity(q_pre_val) if q_pre_val is not None else 0, + "ledger_value": _finite_number(fdata.get("ledger_value")) if fdata.get("ledger_value") is not None else pos_val, + "broker_position": _preserve_numeric_quantity(broker_pos_val), + "broker_value": _finite_number(fdata.get("broker_value")) if fdata.get("broker_value") is not None 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, + } + source_records = {k: v for k, v in raw_source_records.items() if v is not None} + + 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.get("joint_exposure")) if session_inputs.get("joint_exposure") is not None else derived_joint_exposure, + "tier_joint_cap": tier_joint_cap, + "max_loss_cap": max_loss_cap, + "proposed_exposure": _finite_number(session_inputs.get("proposed_exposure")) if session_inputs.get("proposed_exposure") is not None 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, + "positions_cash": _finite_number(session_inputs.get("positions_cash")) if session_inputs.get("positions_cash") is not None else bankroll_val, + "broker_cash": _finite_number(session_inputs.get("broker_cash")) if session_inputs.get("broker_cash") is not None else bankroll_val, + "reconciliation_tolerance": _finite_number(session_inputs.get("reconciliation_tolerance")) if session_inputs.get("reconciliation_tolerance") is not None else 1.0, + "pending_orders": copy.deepcopy(session_inputs.get("pending_orders", {})), + "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.get("settled_cash")) if session_inputs.get("settled_cash") is not None else bankroll_val, + "session_order_count": int(session_inputs.get("session_order_count", 0)), + "session_turnover": _finite_number(session_inputs.get("session_turnover")) if session_inputs.get("session_turnover") is not None else 0.0, + "loaded_policy_hash": str(session_inputs.get("loaded_policy_hash", policy_hash)), + "registered_policy_hash": str(session_inputs.get("registered_policy_hash", policy_hash)), + "last_heartbeat": str(session_inputs.get("last_heartbeat", as_of)), + "scheduled_interval": _finite_number(session_inputs.get("scheduled_interval")) if session_inputs.get("scheduled_interval") is not None else 60.0, + "tier_loss_budget_D": _TIER_D_MAP.get(tier, 0.30), + "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"] + if session_inputs.get("kill_switch_tripped") is True: + out["kill_switch_tripped"] = True + 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]) + for key in ("tier_change_event", "o9_change_descriptors"): + if key in session_inputs: + out[key] = copy.deepcopy(session_inputs[key]) + 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}" + ) + + 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..758aa42 --- /dev/null +++ b/tests/test_fuse_adapter.py @@ -0,0 +1,1654 @@ +"""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"], + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "QQQ", + "normalized_value": "445", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "XNDX", + "normalized_value": "89", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "100", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.044", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + ], + "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"], + "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"], + "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"], + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.044", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + ] + 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, + "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_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", + } + ) + 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, + "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"], + "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"], + "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"], + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + ] + + 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"], + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "QQQ", + "normalized_value": "50", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + "corporate_action": {"split_ratio": "2", "ex_date": "2026-01-05"}, + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + ] + 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"], + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "QQQ", + "normalized_value": "500", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "XNDX", + "normalized_value": "90", + "eligibility": {"eligible": False, "reason": "stale_benchmark_bar"}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + ] + + 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"], + }, + { + "instrument": "SOXL", + "normalized_value": "40", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "XNDX", + "normalized_value": "20000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SEMI", + "normalized_value": "5000", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "SOFR", + "normalized_value": "0.045", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + { + "instrument": "TBILL_3M", + "normalized_value": "0.042", + "eligibility": {"eligible": True}, + "calendar_spec_digest": cal["spec_digest"], + }, + ] + + 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() diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/__init__.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/__init__.py new file mode 100644 index 0000000..03a61fc --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/__init__.py @@ -0,0 +1,133 @@ +"""FUSE-1 reference engine package. + +This package implements the pinned evaluator interface (BRIEF-FUSE-1 §5.1): + + evaluate(spec_version, engine_hash, policy_hash, session, as_of, mode, + validated_inputs, prior_row_state, authorized_events) + -> (rows_by_ID, effective_state_by_scope, next_row_state) + +The engine is a pure function: no I/O, no wall-clock, no randomness, no environment reads. +Identical inputs produce byte-identical outputs under canonical serialization. + +Row modules: +- rows_loss.py: L0-L6 (Loss rows) +- rows_vehicle.py: V1-V7 (Vehicle rows) +- rows_ops.py: O1-O9, J1 (Data/operations rows) +""" + +import hashlib +import importlib.util +import marshal +import re +import sys +import types +from pathlib import Path + +_EXPECTED_ENGINE_FILES = ( + '__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$') + + +def _verify_pyc_matches_source(pyc_path: Path, src_path: Path, src_bytes: bytes, rel: str, cache_tag: str, optimize: int) -> None: + """Verify a cached .pyc matches expected magic/tag, source hash/size, and compiled bytecode.""" + pyc_bytes = pyc_path.read_bytes() + if len(pyc_bytes) < 16 or pyc_bytes[:4] != importlib.util.MAGIC_NUMBER: + raise RuntimeError(f"Invalid or mismatched .pyc magic header in engine directory: {rel!r}") + if sys.implementation.cache_tag and cache_tag != sys.implementation.cache_tag: + raise RuntimeError(f"Unexpected Python cache tag in engine directory: {rel!r}") + + bitfield = int.from_bytes(pyc_bytes[4:8], 'little') + if bitfield & ~0b11: + raise RuntimeError(f"Invalid .pyc bitfield in engine directory: {rel!r}") + if bitfield & 0b01: + if pyc_bytes[8:16] != importlib.util.source_hash(src_bytes): + raise RuntimeError(f"Tampered hash-based .pyc in engine directory: {rel!r}") + else: + pyc_size = int.from_bytes(pyc_bytes[12:16], 'little') + if pyc_size != (len(src_bytes) & 0xffffffff): + raise RuntimeError(f"Mismatched .pyc source size in engine directory: {rel!r}") + + try: + pyc_code = marshal.loads(pyc_bytes[16:]) + except Exception as exc: + raise RuntimeError(f"Corrupt .pyc code payload in engine directory: {rel!r}") from exc + + if not isinstance(pyc_code, types.CodeType) or not isinstance(pyc_code.co_filename, str): + raise RuntimeError(f"Invalid .pyc code object in engine directory: {rel!r}") + norm_fn = pyc_code.co_filename.replace('\\', '/') + if norm_fn != src_path.name and not norm_fn.endswith('/' + src_path.name): + raise RuntimeError(f"Unexpected .pyc co_filename in engine directory: {rel!r}") + + expected_code = compile(src_bytes, pyc_code.co_filename, 'exec', optimize=optimize) + if marshal.dumps(pyc_code) != marshal.dumps(expected_code): + raise RuntimeError(f"Tampered .pyc bytecode mismatch in engine directory: {rel!r}") + + +def _verify_and_hash_engine_dir(engine_dir: Path) -> str: + """Verify engine files & __pycache__ bytecode before submodule imports; return framed SHA-256.""" + py_files: list[Path] = [] + rel_py_paths: list[str] = [] + pyc_entries: list[tuple[Path, str, str, str, int]] = [] + 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 RuntimeError(f"Unexpected symlink in engine directory: {rel!r}") + if entry.is_dir(): + if rel != '__pycache__': + raise RuntimeError(f"Unexpected subdirectory in engine directory: {rel!r}") + continue + if not entry.is_file(): + raise RuntimeError(f"Unexpected non-regular file in engine directory: {rel!r}") + if entry.parent == engine_dir: + if rel not in _EXPECTED_ENGINE_FILES: + raise RuntimeError(f"Unexpected artifact in engine directory: {rel!r}") + py_files.append(entry) + rel_py_paths.append(rel) + elif entry.parent == engine_dir / '__pycache__': + m = _PYCACHE_RE.match(entry.name) + if not m or m.group(1) not in _EXPECTED_ENGINE_STEMS: + raise RuntimeError(f"Unexpected __pycache__ artifact in engine directory: {rel!r}") + opt = int(m.group(3)) if m.group(3) else 0 + pyc_entries.append((entry, rel, m.group(1), m.group(2), opt)) + else: + raise RuntimeError(f"Unexpected nested artifact in engine directory: {rel!r}") + + if rel_py_paths != list(_EXPECTED_ENGINE_FILES): + raise RuntimeError( + f"Unexpected engine file set: expected={list(_EXPECTED_ENGINE_FILES)!r}, got={rel_py_paths!r}" + ) + + src_by_stem: dict[str, tuple[Path, bytes]] = {} + hasher = hashlib.sha256() + for py_file, rel_path in zip(py_files, rel_py_paths): + rel_bytes = rel_path.encode('utf-8') + data = py_file.read_bytes() + src_by_stem[py_file.stem] = (py_file, data) + 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) + + return hasher.hexdigest() + + +# Verify directory, bytecode cache, and source integrity BEFORE importing evaluator or submodules +_CANONICAL_ENGINE_HASH = _verify_and_hash_engine_dir(Path(__file__).resolve().parent) + +from .evaluator import evaluate + +__all__ = ['evaluate'] +__version__ = 'fuse-eval-spec/v1' diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical.py new file mode 100644 index 0000000..8f7baa3 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical.py @@ -0,0 +1,36 @@ +"""Canonical serialization for FUSE-1 reference engine. + +Per §5.2 and §5.3: identical inputs produce byte-identical outputs under +canonical JSON serialization (sorted keys, compact separators, no trailing whitespace). +""" + +import json +import math +from typing import Any, Optional + + +def finite_float(value: Any) -> Optional[float]: + """Convert non-bool numeric value to finite float, else return None.""" + if value is None or isinstance(value, bool): + return None + try: + num = float(value) + except (TypeError, ValueError): + return None + if math.isnan(num) or math.isinf(num): + return None + return num + + +def canonical_json(obj: Any) -> str: + """Serialize object to canonical JSON format. + + Uses sorted keys and compact separators for deterministic serialization. + Per §5.2: identical inputs must produce byte-identical canonical JSON. + """ + return json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + + +def canonical_hash_input(obj: Any) -> bytes: + """Convert object to bytes for hashing via canonical JSON.""" + return canonical_json(obj).encode('utf-8') diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical_state.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical_state.py new file mode 100644 index 0000000..83bc2bc --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/canonical_state.py @@ -0,0 +1,776 @@ +"""Canonical state management per Q6 adjudication ruling. + +All state reads and writes use the golden nested row objects directly. +Retired private aliases: V2_pending, V4_counter, V4_last_increment_session, +V5_counter, V5_escalated, O4_pending, O5_counter, O5_last_rejection_session, +{row}_counter, {row}_latch. + +Canonical state keys: +- V2.pending_adjustments[fund], V2.latched_mismatches[fund] +- V4[fund].clearing_counter, V4[fund].last_session_below_threshold +- V5[fund].consecutive_beyond_tolerance, V5[fund].escalated +- O5.rejection_count, O5.last_rejection_session, O5.latched +- O4[symbol].original_order_id, O4[symbol].status +- L2.latched, L2.trip_session +- V1[fund].latched, V1[fund].trip_session, V1[fund].deviation +- O1.fresh_session_count, O1.last_session +- L3.latched, L3.trip_session, L3.cooling_off_until, L3.loss_record +- L5.fresh_session_count +""" + +from typing import Any, Dict, Optional +from .canonical import finite_float + + +# V2 canonical state accessors + + +_CA_NUMERIC_FIELDS = {'ratio', 'amount', 'dividend', 'cash_amount', 'distribution_amount', 'factor', 'price', 'split_ratio'} + + +def canonical_ca_identity(ca_obj: Any) -> Optional[Dict[str, Any]]: + """Return normalized corporate-action identity keeping strings exact and excluding completion flags.""" + if not isinstance(ca_obj, dict) or not ca_obj.get('type'): + return None + volatile = {'adjustment_complete', 'exact_reconciliation', 'hwm_adjusted', 'awaiting_reconciliation'} + ident: Dict[str, Any] = {} + for k in sorted(ca_obj.keys()): + if k in volatile: + continue + v = ca_obj[k] + if isinstance(v, bool): + ident[k] = v + elif isinstance(v, (int, float)): + num = finite_float(v) + ident[k] = num if num is not None else v + elif k in _CA_NUMERIC_FIELDS and isinstance(v, str): + num = finite_float(v) + ident[k] = num if num is not None else v.strip() + elif isinstance(v, str): + ident[k] = v.strip() + else: + ident[k] = v + return ident + + +def ca_identity_matches( + stored_ident: Optional[Dict[str, Any]], + fallback_item: Optional[Dict[str, Any]], + incoming_ca: Any, +) -> bool: + """Match an incoming corporate action strictly against stored canonical identity (or fallback item).""" + inc_ident = canonical_ca_identity(incoming_ca) + if inc_ident is None: + return False + if isinstance(stored_ident, dict) and stored_ident.get('type'): + return inc_ident == stored_ident + if not isinstance(fallback_item, dict): + return False + if fallback_item.get('type') != inc_ident.get('type'): + return False + p_ratio = fallback_item.get('ratio') + c_ratio = inc_ident.get('ratio') + if p_ratio is None: + return c_ratio is None + p_num = finite_float(p_ratio) + c_num = finite_float(c_ratio) + return p_num is not None and c_num is not None and p_num == c_num + +def get_v2_pending_adjustment(prior_state: Optional[Dict], fund: str) -> Optional[Dict]: + """Get pending adjustment for a fund from V2.pending_adjustments.""" + if not prior_state or 'V2' not in prior_state: + return None + pending = prior_state['V2'].get('pending_adjustments', {}) + return pending.get(fund) + + +def set_v2_pending_adjustment(next_state: Dict, fund: str, adjustment: Dict) -> None: + """Set pending adjustment in V2.pending_adjustments[fund].""" + if 'V2' not in next_state: + next_state['V2'] = {} + if 'pending_adjustments' not in next_state['V2']: + next_state['V2']['pending_adjustments'] = {} + next_state['V2']['pending_adjustments'][fund] = adjustment + + +def clear_v2_pending_adjustment(next_state: Dict, fund: str) -> None: + """Clear pending adjustment for a fund. + + Per golden target-state projections, V2 is serialized as {} when empty, not absent. + """ + if 'V2' not in next_state: + next_state['V2'] = {} + if 'pending_adjustments' in next_state['V2'] and fund in next_state['V2']['pending_adjustments']: + del next_state['V2']['pending_adjustments'][fund] + if not next_state['V2']['pending_adjustments']: + del next_state['V2']['pending_adjustments'] + if 'pending_action_identities' in next_state['V2'] and fund in next_state['V2']['pending_action_identities']: + del next_state['V2']['pending_action_identities'][fund] + if not next_state['V2']['pending_action_identities']: + del next_state['V2']['pending_action_identities'] + # Keep empty V2:{} per golden projections + + +def get_v2_latched_mismatch(prior_state: Optional[Dict], fund: str) -> Optional[Dict]: + """Get latched mismatch for a fund from V2.latched_mismatches.""" + if not prior_state or 'V2' not in prior_state: + return None + mismatches = prior_state['V2'].get('latched_mismatches', {}) + return mismatches.get(fund) + + +def get_v2_latched_mismatch_action(prior_state: Optional[Dict], fund: str) -> Optional[Dict]: + """Get normalized corporate-action identity for a latched V2 mismatch.""" + if not prior_state or 'V2' not in prior_state: + return None + actions = prior_state['V2'].get('latched_mismatch_actions', {}) + val = actions.get(fund) + return val if isinstance(val, dict) else None + + +def set_v2_latched_mismatch(next_state: Dict, fund: str, mismatch: Dict) -> None: + """Set latched mismatch in V2.latched_mismatches[fund].""" + if 'V2' not in next_state: + next_state['V2'] = {} + if 'latched_mismatches' not in next_state['V2']: + next_state['V2']['latched_mismatches'] = {} + next_state['V2']['latched_mismatches'][fund] = mismatch + + +def set_v2_latched_mismatch_action(next_state: Dict, fund: str, action_identity: Dict) -> None: + """Persist normalized corporate-action identity alongside V2.latched_mismatches[fund].""" + if 'V2' not in next_state: + next_state['V2'] = {} + if 'latched_mismatch_actions' not in next_state['V2']: + next_state['V2']['latched_mismatch_actions'] = {} + next_state['V2']['latched_mismatch_actions'][fund] = action_identity + + +def get_v2_pending_identities(prior_state: Optional[Dict], fund: str) -> Optional[Dict]: + """Get normalized corporate-action identities for pending primary/queued V2 items.""" + if not prior_state or 'V2' not in prior_state: + return None + identities = prior_state['V2'].get('pending_action_identities', {}) + val = identities.get(fund) + return val if isinstance(val, dict) else None + + +def set_v2_pending_identities(next_state: Dict, fund: str, identities: Dict) -> None: + """Persist normalized corporate-action identities alongside V2.pending_adjustments[fund].""" + if 'V2' not in next_state: + next_state['V2'] = {} + if 'pending_action_identities' not in next_state['V2']: + next_state['V2']['pending_action_identities'] = {} + next_state['V2']['pending_action_identities'][fund] = identities + + +def clear_v2_latched_mismatch(next_state: Dict, fund: str) -> None: + """Clear latched mismatch for a fund. + + Per golden target-state projections, V2 is serialized as {} when empty, not absent. + """ + if 'V2' not in next_state: + next_state['V2'] = {} + if 'latched_mismatches' in next_state['V2'] and fund in next_state['V2']['latched_mismatches']: + del next_state['V2']['latched_mismatches'][fund] + if not next_state['V2']['latched_mismatches']: + del next_state['V2']['latched_mismatches'] + if 'latched_mismatch_actions' in next_state['V2'] and fund in next_state['V2']['latched_mismatch_actions']: + del next_state['V2']['latched_mismatch_actions'][fund] + if not next_state['V2']['latched_mismatch_actions']: + del next_state['V2']['latched_mismatch_actions'] + # Keep empty V2:{} per golden projections + + +# V4 canonical state accessors + +def get_v4_state(prior_state: Optional[Dict], fund: str) -> Dict: + """Get V4 state for a fund. Returns dict with clearing_counter and last_session_below_threshold. + + Present entry with counter=0 means active after trip (distinct from absent=inactive). + """ + if not prior_state or 'V4' not in prior_state: + return {'clearing_counter': None, 'last_session_below_threshold': None} + + fund_state = prior_state['V4'].get(fund, {}) + return { + 'clearing_counter': fund_state.get('clearing_counter'), + 'last_session_below_threshold': fund_state.get('last_session_below_threshold') + } + + +def set_v4_state(next_state: Dict, fund: str, counter: int, last_session: Optional[str]) -> None: + """Set V4 state for a fund. Counter and last_session together. + + At count 10, caller should remove the fund entry instead of storing count 10. + """ + if 'V4' not in next_state: + next_state['V4'] = {} + next_state['V4'][fund] = { + 'clearing_counter': counter, + 'last_session_below_threshold': last_session + } + + +def clear_v4_state(next_state: Dict, fund: str) -> None: + """Remove V4 fund entry (after clearing at count 10). + + Per golden target-state projections, V4 is serialized as {} when empty, not absent. + """ + if 'V4' not in next_state: + next_state['V4'] = {} + if fund in next_state['V4']: + del next_state['V4'][fund] + + +# V5 canonical state accessors + +def get_v5_state(prior_state: Optional[Dict], fund: str) -> Dict: + """Get V5 state for a fund. Returns dict with counter, escalated flag, and last_session.""" + if not prior_state or 'V5' not in prior_state: + return {'consecutive_beyond_tolerance': 0, 'escalated': False, 'last_session': None} + + fund_state = prior_state['V5'].get(fund, {}) + return { + 'consecutive_beyond_tolerance': fund_state.get('consecutive_beyond_tolerance', 0), + 'escalated': fund_state.get('escalated', False), + 'last_session': fund_state.get('last_session') + } + + +def set_v5_state(next_state: Dict, fund: str, count: int, escalated: bool, session: str) -> None: + """Set V5 state for a fund. + + Q6 requires sufficient session identity for replay and duplicate evaluations. + """ + if 'V5' not in next_state: + next_state['V5'] = {} + next_state['V5'][fund] = { + 'consecutive_beyond_tolerance': count, + 'escalated': escalated, + 'last_session': session + } + + +def clear_v5_state(next_state: Dict, fund: str) -> None: + """Clear V5 escalation state for a fund (Q4 authorized re-arm).""" + if 'V5' not in next_state: + next_state['V5'] = {} + if fund in next_state['V5']: + del next_state['V5'][fund] + + +# O5 canonical state accessors + +def get_o5_state(prior_state: Optional[Dict]) -> Dict: + """Get O5 account-level state. Returns dict with rejection_count, last_session, latched.""" + if not prior_state or 'O5' not in prior_state: + return {'rejection_count': 0, 'last_rejection_session': None, 'latched': False} + + o5 = prior_state['O5'] + return { + 'rejection_count': o5.get('rejection_count', 0), + 'last_rejection_session': o5.get('last_rejection_session'), + 'latched': o5.get('latched', False) + } + + +def set_o5_state(next_state: Dict, count: int, last_session: Optional[str], latched: bool) -> None: + """Set O5 account-level state.""" + next_state['O5'] = { + 'rejection_count': count, + 'last_rejection_session': last_session, + 'latched': latched + } + + +# O4 canonical state accessors + +def get_o4_pending_order(prior_state: Optional[Dict], symbol: str) -> Optional[Dict]: + """Get O4 pending order state for a symbol. Returns dict with original_order_id and status.""" + if not prior_state or 'O4' not in prior_state: + return None + + symbol_state = prior_state['O4'].get(symbol, {}) + if 'original_order_id' not in symbol_state: + return None + + return { + 'original_order_id': symbol_state['original_order_id'], + 'status': symbol_state.get('status', 'unknown') + } + + +def set_o4_pending_order(next_state: Dict, symbol: str, order_id: str, status: str = 'unknown') -> None: + """Set O4 pending order state for a symbol.""" + if 'O4' not in next_state: + next_state['O4'] = {} + next_state['O4'][symbol] = { + 'original_order_id': order_id, + 'status': status + } + + +def clear_o4_pending_order(next_state: Dict, symbol: str) -> None: + """Clear O4 pending order for a symbol (after resolution). + + Per golden target-state projections, O4 is serialized as {} when empty, not absent. + """ + if 'O4' not in next_state: + next_state['O4'] = {} + if symbol in next_state['O4']: + del next_state['O4'][symbol] + + +# L2 canonical state accessors + +def get_l2_latch(prior_state: Optional[Dict]) -> Optional[Dict]: + """Get L2 latch state. Returns dict with latched and trip_session.""" + if not prior_state or 'L2' not in prior_state: + return None + + l2 = prior_state['L2'] + if not l2.get('latched'): + return None + + return { + 'latched': True, + 'trip_session': l2.get('trip_session') + } + + +def set_l2_latch(next_state: Dict, trip_session: str) -> None: + """Set L2 latch state.""" + next_state['L2'] = { + 'latched': True, + 'trip_session': trip_session + } + + +def clear_l2_latch(next_state: Dict) -> None: + """Clear L2 latch state (Q4 authorized re-arm).""" + next_state['L2'] = {} + + +# V1 canonical state accessors + +def get_v1_history(prior_state: Optional[Dict], fund: str) -> list: + """Get V1 rolling session return history for a fund.""" + if not prior_state or 'V1' not in prior_state: + return [] + fund_state = prior_state['V1'].get(fund, {}) + history = fund_state.get('session_returns', []) + return list(history) if isinstance(history, list) else [] + + +def set_v1_history(next_state: Dict, fund: str, history: list) -> None: + """Persist V1 rolling session return history for a fund.""" + if 'V1' not in next_state: + next_state['V1'] = {} + if fund not in next_state['V1']: + next_state['V1'][fund] = {} + next_state['V1'][fund]['session_returns'] = history + + +def get_v1_latch(prior_state: Optional[Dict], fund: str) -> Optional[Dict]: + """Get V1 latch state for a fund. Returns dict with latched, trip_session, deviation.""" + if not prior_state or 'V1' not in prior_state: + return None + + fund_state = prior_state['V1'].get(fund, {}) + if not fund_state.get('latched'): + return None + + return { + 'latched': True, + 'trip_session': fund_state.get('trip_session'), + 'deviation': fund_state.get('deviation') + } + + +def set_v1_latch(next_state: Dict, fund: str, trip_session: str, deviation: float) -> None: + """Set V1 latch state for a fund.""" + if 'V1' not in next_state: + next_state['V1'] = {} + existing = next_state['V1'].get(fund, {}) + entry = { + 'latched': True, + 'trip_session': trip_session, + 'deviation': deviation + } + if 'session_returns' in existing: + entry['session_returns'] = existing['session_returns'] + next_state['V1'][fund] = entry + + +def clear_v1_latch(next_state: Dict, fund: str) -> None: + """Clear V1 latch state for a fund (Q4 authorized re-arm). + + Serializes as {"V1":{}} for one-target case per Q4 requirement. + """ + if 'V1' not in next_state: + next_state['V1'] = {} + if fund in next_state['V1']: + del next_state['V1'][fund] + # Keep empty V1:{} for target-state projection + + +# O1 canonical state accessors + +def get_o1_fresh_state(prior_state: Optional[Dict]) -> Dict: + """Get O1 fresh-session state.""" + if not prior_state or 'O1' not in prior_state: + return {'fresh_session_count': 0, 'last_session': None, 'last_tripped_session': None} + + o1 = prior_state['O1'] + return { + 'fresh_session_count': o1.get('fresh_session_count', 0), + 'last_session': o1.get('last_session'), + 'last_tripped_session': o1.get('last_tripped_session') + } + + +def set_o1_fresh_state( + next_state: Dict, + count: int, + session: str, + last_tripped_session: Optional[str] = None +) -> None: + """Set O1 fresh-session state.""" + entry = { + 'fresh_session_count': count, + 'last_session': session + } + if last_tripped_session is not None: + entry['last_tripped_session'] = last_tripped_session + next_state['O1'] = entry + + +# L3 canonical state accessors + +def get_l3_latch(prior_state: Optional[Dict]) -> Optional[Dict]: + """Get L3 latch and loss record.""" + if not prior_state or 'L3' not in prior_state: + return None + + l3 = prior_state['L3'] + if not l3.get('latched'): + return None + + return { + 'latched': True, + 'trip_session': l3.get('trip_session'), + 'cooling_off_until': l3.get('cooling_off_until'), + 'loss_record': l3.get('loss_record') + } + + +def set_l3_latch(next_state: Dict, trip_session: str, cooling_off_until: str, loss_record: Dict) -> None: + """Set L3 latch with cooling-off period and durable loss record.""" + next_state['L3'] = { + 'latched': True, + 'trip_session': trip_session, + 'cooling_off_until': cooling_off_until, + 'loss_record': loss_record + } + + +def clear_l3_lock(next_state: Dict, loss_record: Dict) -> None: + """Clear L3 active lock after cooling-off, preserve loss record.""" + next_state['L3'] = { + 'latched': False, + 'loss_record': loss_record + } + + +# L5 canonical state accessors + +def get_l5_state(prior_state: Optional[Dict]) -> Dict: + """Get L5 interlock state (active session persistence + fresh counter).""" + if not prior_state or 'L5' not in prior_state: + return {'active': False, 'trip_session': None, 'fresh_session_count': 0} + l5 = prior_state['L5'] + if not isinstance(l5, dict): + return {'active': False, 'trip_session': None, 'fresh_session_count': 0} + return { + 'active': bool(l5.get('active') or l5.get('latched')), + 'trip_session': l5.get('trip_session'), + 'fresh_session_count': l5.get('fresh_session_count', 0) + } + + +def set_l5_active_trip(next_state: Dict, trip_session: str) -> None: + """Persist L5 active halt state for remainder of trading session.""" + next_state['L5'] = { + 'active': True, + 'trip_session': trip_session, + 'fresh_session_count': 0 + } + + +def get_l5_fresh_count(prior_state: Optional[Dict]) -> int: + """Get L5 fresh-session counter.""" + if not prior_state or 'L5' not in prior_state: + return 0 + return prior_state['L5'].get('fresh_session_count', 0) + + +def set_l5_fresh_count(next_state: Dict, count: int) -> None: + """Set L5 fresh-session counter.""" + if 'L5' not in next_state: + next_state['L5'] = {} + next_state['L5']['fresh_session_count'] = count + + +def canonical_session_date(session: Optional[str], as_of: Optional[str] = None) -> Optional[str]: + """Return canonical trading-session identity: prefer session, fallback to as_of[:10].""" + if isinstance(session, str) and session.strip(): + return session.strip() + if isinstance(as_of, str) and len(as_of.strip()) >= 10: + return as_of.strip()[:10] + return None + + +def event_matches_row(event: Dict[str, Any], row_id: str) -> bool: + """Match row/row_id on an event, rejecting conflicting dual tags (row != row_id).""" + ev_row = event.get('row') + ev_row_id = event.get('row_id') + if ev_row is not None and ev_row_id is not None and ev_row != ev_row_id: + return False + target = ev_row if ev_row is not None else ev_row_id + return target == row_id + + +def event_date_matches( + event: Dict[str, Any], + session: Optional[str] = None, + as_of: Optional[str] = None, + require_date: bool = True, +) -> bool: + """Validate event session/as_of date against canonical session identity per Q4.""" + cur_date = canonical_session_date(session, as_of) + ev_session = event.get('session') + ev_as_of = event.get('as_of') + has_session = isinstance(ev_session, str) and bool(ev_session.strip()) + has_as_of = isinstance(ev_as_of, str) and len(ev_as_of.strip()) >= 10 + if ev_session is not None and not has_session: + return False + if ev_as_of is not None and not has_as_of: + return False + if require_date and not (has_session or has_as_of): + return False + if has_session and cur_date is not None and ev_session.strip() != cur_date: + return False + if has_as_of and cur_date is not None and ev_as_of.strip()[:10] != cur_date: + return False + return True + + +def matches_account_rearm( + authorized_events: Optional[Any], + row_id: str, + session: Optional[str] = None, + as_of: Optional[str] = None, + require_date: bool = True, +) -> Optional[Dict[str, Any]]: + """Return matching account-scoped rearm event per Q4 (row, session/as_of, account scope).""" + if not authorized_events: + return None + if isinstance(authorized_events, list): + events_list = authorized_events + elif isinstance(authorized_events, dict): + events_list = authorized_events.get('account', []) + else: + return None + + for event in events_list: + if not isinstance(event, dict): + continue + if event.get('type') != 'rearm': + continue + if not event_matches_row(event, row_id): + continue + # Reject fund/symbol/joint scoped cards on account-level latches + if event.get('fund') or event.get('symbol'): + continue + if 'scope' in event and event.get('scope') != 'account': + continue + if not event_date_matches(event, session=session, as_of=as_of, require_date=require_date): + continue + return event + return None + + +def _matches_scoped_rearm( + authorized_events: Optional[Any], + row_id: str, + target_field: str, + forbidden_field: str, + target_val: str, + session: Optional[str] = None, + as_of: Optional[str] = None, + require_date: bool = True, +) -> Optional[Dict[str, Any]]: + """Return matching scoped (fund/symbol) rearm event per Q4.""" + if not authorized_events: + return None + scope = f'{target_field}:{target_val}' + if isinstance(authorized_events, list): + events_list = authorized_events + elif isinstance(authorized_events, dict): + events_list = authorized_events.get(scope, []) + else: + return None + + for event in events_list: + if not isinstance(event, dict): + continue + if event.get('type') != 'rearm': + continue + if not event_matches_row(event, row_id): + continue + if event.get(forbidden_field): + continue + if event.get(target_field) != target_val: + continue + if 'scope' in event and event.get('scope') != scope: + continue + if not event_date_matches(event, session=session, as_of=as_of, require_date=require_date): + continue + return event + return None + + +def matches_fund_rearm( + authorized_events: Optional[Any], + row_id: str, + fund: str, + session: Optional[str] = None, + as_of: Optional[str] = None, + require_date: bool = True, +) -> Optional[Dict[str, Any]]: + """Return matching fund-scoped rearm event per Q4 (row, fund, fund scope, date).""" + return _matches_scoped_rearm( + authorized_events, row_id, 'fund', 'symbol', fund, + session=session, as_of=as_of, require_date=require_date, + ) + + +def matches_symbol_rearm( + authorized_events: Optional[Any], + row_id: str, + symbol: str, + session: Optional[str] = None, + as_of: Optional[str] = None, + require_date: bool = True, +) -> Optional[Dict[str, Any]]: + """Return matching symbol-scoped rearm event per Q4 (row, symbol, symbol scope, date).""" + return _matches_scoped_rearm( + authorized_events, row_id, 'symbol', 'fund', symbol, + session=session, as_of=as_of, require_date=require_date, + ) + + +def matches_o8_clear( + authorized_events: Optional[Any], + session: Optional[str] = None, + as_of: Optional[str] = None, + require_date: bool = True, +) -> Optional[Dict[str, Any]]: + """Return matching owner kill-switch clear/rearm event per Q4.""" + if not authorized_events: + return None + if isinstance(authorized_events, list): + events_list = authorized_events + elif isinstance(authorized_events, dict): + events_list = authorized_events.get('account', []) + else: + return None + + for event in events_list: + if not isinstance(event, dict): + continue + ev_type = event.get('type') + if ev_type == 'rearm': + if not event_matches_row(event, 'O8'): + continue + elif ev_type == 'kill_switch_clear': + if event.get('row') is not None or event.get('row_id') is not None: + if not event_matches_row(event, 'O8'): + continue + else: + continue + if event.get('fund') or event.get('symbol'): + continue + if 'scope' in event and event.get('scope') != 'account': + continue + if not event_date_matches(event, session=session, as_of=as_of, require_date=require_date): + continue + return event + return None + + +# General latch accessors for rows using old state.py pattern (L4, L6, V3) +# These can read from either old {row}_latch format or canonical format + +def get_account_latch(prior_state: Optional[Dict], row_id: str) -> Optional[Dict]: + """Get account-level latch for a row (L3/L4/L6). + + Reads from canonical {row}.latched format or falls back to old {row}_latch. + """ + if not prior_state: + return None + + # Try canonical format first + if row_id in prior_state: + row_state = prior_state[row_id] + if row_state.get('latched'): + return { + 'latched': True, + 'trip_session': row_state.get('trip_session'), + 'details': row_state.get('details', {}) + } + + return None + + +def set_account_latch(next_state: Dict, row_id: str, trip_session: str, details: Dict = None) -> None: + """Set account-level latch in canonical format.""" + next_state[row_id] = { + 'latched': True, + 'trip_session': trip_session, + 'details': details or {} + } + + +def get_fund_latch(prior_state: Optional[Dict], row_id: str, fund: str) -> Optional[Dict]: + """Get fund-level latch for a row (V3). + + Reads from canonical {row}.{fund}.latched format or falls back to old {row}_latch. + """ + if not prior_state: + return None + + # Try canonical format first + if row_id in prior_state: + row_state = prior_state[row_id] + fund_state = row_state.get(fund, {}) + if fund_state.get('latched'): + return { + 'latched': True, + 'trip_session': fund_state.get('trip_session'), + 'details': fund_state.get('details', {}) + } + + return None + + +def set_fund_latch(next_state: Dict, row_id: str, fund: str, trip_session: str, details: Dict = None) -> None: + """Set fund-level latch in canonical format.""" + if row_id not in next_state: + next_state[row_id] = {} + next_state[row_id][fund] = { + 'latched': True, + 'trip_session': trip_session, + 'details': details or {} + } diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/evaluator.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/evaluator.py new file mode 100644 index 0000000..6cdb8e9 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/evaluator.py @@ -0,0 +1,1309 @@ +"""FUSE-1 reference engine evaluator. + +Implements the §5.1 signature with all 24 rows fully evaluated. +""" + +import copy +from datetime import date, timedelta +from pathlib import Path +from typing import Any, Dict, Optional +from . import _EXPECTED_ENGINE_FILES, _verify_and_hash_engine_dir + +# Re-verify directory & __pycache__ bytecode integrity BEFORE importing any row submodules +_CANONICAL_ENGINE_HASH = _verify_and_hash_engine_dir(Path(__file__).resolve().parent) + +from . import rows_loss +from . import rows_vehicle +from . import rows_ops +from . import state as st +from . import canonical_state as cst +from .canonical import finite_float + + +_compute_canonical_engine_hash_from_dir = _verify_and_hash_engine_dir + + +def _compute_canonical_engine_hash() -> str: + """Compute canonical SHA-256 of verified src/fuse_engine/*.py source files (§5.3).""" + return _verify_and_hash_engine_dir(Path(__file__).resolve().parent) + + +def compute_engine_hash() -> str: + """Return precomputed canonical engine bundle SHA-256 (zero runtime I/O in evaluate).""" + return _CANONICAL_ENGINE_HASH + + +def _fund_sort_key(symbol: str) -> tuple[int, str]: + """Deterministic canonical fund order preserving [TQQQ, SOXL] legacy order (§0.4).""" + if symbol == 'TQQQ': + return (0, symbol) + if symbol == 'SOXL': + return (1, symbol) + return (2, symbol) + + +# The 24 named row IDs per §4.3 +ROW_IDS = [ + "L0", "L1", "L2", "L3", "L4", "L5", "L6", + "V1", "V2", "V3", "V4", "V5", "V6", "V7", + "O1", "O2", "O3", "O4", "O5", "O6", "O7", "O8", "O9", + "J1" +] + + +def evaluate( + spec_version: str, + engine_hash: str, + policy_hash: str, + session: str, + as_of: str, + mode: str, + validated_inputs: Dict[str, Any], + prior_row_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]] +) -> tuple[Dict[str, Any], Dict[str, str], Dict[str, Any]]: + """Evaluate all 24 breaker rows and return effective state. + + Args: + spec_version: Version of the breaker specification + engine_hash: SHA-256 of the canonical engine bundle + policy_hash: Hash of the loaded policy configuration + session: Session identifier (YYYY-MM-DD) + as_of: Evaluation timestamp (ISO 8601) + mode: Enforcement mode ('shadow' in FUSE-1) + validated_inputs: All required inputs for breaker evaluation + prior_row_state: State from previous evaluation (latches, counters) + authorized_events: Human re-arms, tier changes, owner commands + + Returns: + (rows_by_ID, effective_state_by_scope, next_row_state) tuple where: + - rows_by_ID: dict with 24 row IDs, each with state/would_have_tripped/kind/latched/reason + outputs + - effective_state_by_scope: precedence-resolved state per scope + - next_row_state: complete successor state for next evaluation + """ + # A10 / §5.1: Validate spec_version and FUSE-1 shadow-only mode contract + if spec_version != 'fuse-eval-spec/v1': + raise ValueError(f"Unsupported spec_version: {spec_version!r}; expected 'fuse-eval-spec/v1'") + if mode != 'shadow': + raise ValueError(f"FUSE-1 operates in shadow mode only; forbidden mode={mode!r}") + + # §5.2 / §5.3: Use precomputed canonical engine hash (zero file I/O); reject mismatched 64-hex pinned digests + canonical_engine_hash = _CANONICAL_ENGINE_HASH + if ( + isinstance(engine_hash, str) and + len(engine_hash) == 64 and + all(c in '0123456789abcdefABCDEF' for c in engine_hash) and + engine_hash.lower() != canonical_engine_hash + ): + raise ValueError( + f"engine_hash mismatch: caller={engine_hash}, actual={canonical_engine_hash}" + ) + + # Reject malformed non-None, non-dict prior_row_state rather than silently resetting latches to {} + if prior_row_state is None: + prior_row_state = {} + elif not isinstance(prior_row_state, dict): + raise ValueError( + f"Invalid prior_row_state: expected dict or None, got {type(prior_row_state).__name__}" + ) + if authorized_events is None: + authorized_events = {} + if validated_inputs is None or not isinstance(validated_inputs, dict): + validated_inputs = {} + + # Initialize next_row_state + next_row_state = st.init_next_state() + + # Get funds safely (null/non-dict guards prevent AttributeError on public evaluate()) + raw_funds = validated_inputs.get('funds') + funds = raw_funds if isinstance(raw_funds, dict) else {} + fund_symbols = sorted(funds.keys(), key=_fund_sort_key) + + # Build scopes: enumerate symbols from funds, proposed order symbols, pending_orders, AND durable O4 (Q6 wiring) + all_symbols_set = set(fund_symbols) + order_symbols_list = [] + invalid_order_symbol = False + for sym_key in ('o5_symbol', 'symbol'): + if sym_key in validated_inputs and validated_inputs[sym_key] is not None: + raw_sym = validated_inputs[sym_key] + if isinstance(raw_sym, str) and raw_sym.strip(): + cleaned_sym = raw_sym.strip() + if cleaned_sym not in order_symbols_list: + order_symbols_list.append(cleaned_sym) + else: + invalid_order_symbol = True + order_symbols = sorted(order_symbols_list) + all_symbols_set.update(order_symbols) + _CASH_ETF_SYMBOLS = frozenset({'BIL'}) + missing_vehicle_order_symbols = [ + sym for sym in order_symbols + if sym not in funds and sym not in _CASH_ETF_SYMBOLS + ] + eval_fund_symbols = sorted( + set(fund_symbols) | set(missing_vehicle_order_symbols), + key=_fund_sort_key, + ) + + raw_pending_orders = validated_inputs.get('pending_orders') + malformed_pending_orders = ( + 'pending_orders' in validated_inputs and not isinstance(raw_pending_orders, dict) + ) + pending_orders = raw_pending_orders if isinstance(raw_pending_orders, dict) else {} + all_symbols_set.update(pending_orders.keys()) + # Add symbols from durable O4 state + prior_o4 = prior_row_state.get('O4') + if isinstance(prior_o4, dict): + all_symbols_set.update(prior_o4.keys()) + if malformed_pending_orders and not all_symbols_set: + all_symbols_set.add('__pending_orders__') + all_symbols = sorted(all_symbols_set) + + # Also track any prior restricted funds (V1/V2/V3/V4/V5 escalated) omitted from current funds dict + prior_latched_funds = set() + if prior_row_state: + for fn, fstate in (prior_row_state.get('V1') or {}).items(): + if isinstance(fstate, dict) and fstate.get('latched') and fn not in eval_fund_symbols: + prior_latched_funds.add(fn) + prior_v2 = prior_row_state.get('V2') or {} + if isinstance(prior_v2, dict): + for fn, mstate in (prior_v2.get('latched_mismatches') or {}).items(): + if mstate and fn not in eval_fund_symbols: + prior_latched_funds.add(fn) + for fn, pstate in (prior_v2.get('pending_adjustments') or {}).items(): + if pstate and fn not in eval_fund_symbols: + prior_latched_funds.add(fn) + for fn, v3state in (prior_row_state.get('V3') or {}).items(): + if isinstance(v3state, dict) and v3state.get('latched') and fn not in eval_fund_symbols: + prior_latched_funds.add(fn) + for fn, v4state in (prior_row_state.get('V4') or {}).items(): + if isinstance(v4state, dict) and v4state.get('clearing_counter') is not None and fn not in eval_fund_symbols: + prior_latched_funds.add(fn) + for fn, v5state in (prior_row_state.get('V5') or {}).items(): + if isinstance(v5state, dict) and fn not in eval_fund_symbols and ( + v5state.get('escalated') or (v5state.get('consecutive_beyond_tolerance') or 0) >= 40 + ): + prior_latched_funds.add(fn) + + scopes = ['account'] + for symbol in eval_fund_symbols: + scopes.append(f'fund:{symbol}') + for symbol in sorted(prior_latched_funds): + if symbol not in eval_fund_symbols: + scopes.append(f'fund:{symbol}') + for symbol in all_symbols: + scopes.append(f'symbol:{symbol}') + scopes.append('joint') + + # Initialize rows_by_ID + rows_by_ID = {} + + # ==== LOSS ROWS (L0-L6) - Account scope ==== + + # L0 - exposure limit + l0_result = rows_loss.evaluate_L0(validated_inputs, prior_row_state, authorized_events) + rows_by_ID['L0'] = l0_result + + # L1 - drawdown D/3 interlock + l1_result = rows_loss.evaluate_L1(validated_inputs, prior_row_state, authorized_events) + rows_by_ID['L1'] = l1_result + + # L2 - drawdown 2D/3 breaker (canonical format per Q6) + l2_result = rows_loss.evaluate_L2(validated_inputs, prior_row_state, authorized_events, session=session, as_of=as_of) + rows_by_ID['L2'] = l2_result + if l2_result['latched']: + # Preserve original trip_session if already latched (§4.4 rule 3: persistence) + prior_latch = cst.get_l2_latch(prior_row_state) + trip_session = prior_latch['trip_session'] if prior_latch else session + cst.set_l2_latch(next_row_state, trip_session) + elif l2_result['reason'] == 'authorized_rearm': + # Q4: clear latch on authorized re-arm - serialize as {"L2":{}} + cst.clear_l2_latch(next_row_state) + + # L3 - drawdown D breaker (canonical format per Q6; A07.3 durable loss_record & trip_session) + l3_result = rows_loss.evaluate_L3(validated_inputs, prior_row_state, authorized_events, session=session, as_of=as_of) + rows_by_ID['L3'] = l3_result + if l3_result['latched']: + # Preserve original trip_session, cooling_off_until, and loss_record if already latched + prior_latch = cst.get_l3_latch(prior_row_state) + if prior_latch: + trip_session = prior_latch['trip_session'] + cooling_off_until = prior_latch.get('cooling_off_until', trip_session) + loss_record = prior_latch.get('loss_record') + else: + trip_session = session + try: + cooling_off_until = (date.fromisoformat(session) + timedelta(days=30)).isoformat() + except ValueError: + cooling_off_until = session + hwm_raw = validated_inputs.get('high_water_mark') + bk_raw = validated_inputs.get('bankroll') + hwm_val = finite_float(hwm_raw) + bk_val = finite_float(bk_raw) + dd = (hwm_val - bk_val) / hwm_val if (hwm_val is not None and bk_val is not None and hwm_val > 0.0) else None + loss_record = { + 'bankroll': bk_val, + 'high_water_mark': hwm_val, + 'tier': validated_inputs.get('tier'), + 'drawdown': dd + } + cst.set_l3_latch(next_row_state, trip_session, cooling_off_until, loss_record) + elif l3_result['reason'] == 'authorized_rearm': + # Q4: clear lock after cooling-off, preserve loss_record + prior_latch = cst.get_l3_latch(prior_row_state) + loss_record = prior_latch['loss_record'] if prior_latch and 'loss_record' in prior_latch else {} + cst.clear_l3_lock(next_row_state, loss_record) + elif prior_row_state and isinstance(prior_row_state.get('L3'), dict) and prior_row_state['L3'].get('loss_record') is not None: + # Loss record is never cleared (§4.3 L3) + cst.clear_l3_lock(next_row_state, prior_row_state['L3']['loss_record']) + + market_closed = ( + validated_inputs.get('session_calendar_status') in ('holiday', 'closed', 'market_closed') or + validated_inputs.get('exchange_status') in ('holiday', 'closed', 'market_closed') + ) + + # L4 - one-session loss D/10 breaker (canonical per Q6; A07.3 preserve original trip_session) + l4_result = rows_loss.evaluate_L4( + validated_inputs, prior_row_state, authorized_events, + session=session, as_of=as_of, market_closed=market_closed, + ) + rows_by_ID['L4'] = l4_result + if l4_result['latched']: + prior_latch = cst.get_account_latch(prior_row_state, 'L4') + trip_session = prior_latch['trip_session'] if prior_latch and prior_latch.get('trip_session') else cst.canonical_session_date(session, as_of) + cst.set_account_latch(next_row_state, 'L4', trip_session) + elif l4_result['reason'] == 'authorized_rearm': + next_row_state['L4'] = {} + + # L5 - market halt L1/L2 interlock (persists through remainder of trading session) + l5_result = rows_loss.evaluate_L5(validated_inputs, prior_row_state, authorized_events, session, as_of=as_of) + rows_by_ID['L5'] = l5_result + prior_l5 = cst.get_l5_state(prior_row_state) + l5_cur_date = cst.canonical_session_date(session, as_of) + if l5_result['reason'] == 'market_halt_level_1_or_2': + cst.set_l5_active_trip(next_row_state, l5_cur_date) + elif l5_result['reason'] == 'clearing_period': + cst.set_l5_active_trip(next_row_state, prior_l5['trip_session'] or l5_cur_date) + elif l5_result['reason'] == 'invalid_input': + if prior_l5['active'] and ( + (prior_l5['trip_session'] is not None and prior_l5['trip_session'] == l5_cur_date) + or (prior_l5['trip_session'] is None and prior_l5['fresh_session_count'] < 1) + ): + cst.set_l5_active_trip(next_row_state, prior_l5['trip_session'] or l5_cur_date) + else: + cst.set_l5_fresh_count(next_row_state, 0) + elif prior_l5['active']: + next_row_state['L5'] = {} + else: + cst.set_l5_fresh_count(next_row_state, prior_l5['fresh_session_count'] + 1) + + # Pre-compute O3 reconciliation state so L6 re-arm refuses if O3 reconciliation fails + o3_result = rows_ops.evaluate_O3(validated_inputs, prior_row_state, authorized_events, session=session, as_of=as_of) + o3_failed = o3_result['would_have_tripped'] or o3_result['state'] != 'NORMAL' + + # L6 - market halt L3 or 10% index fall breaker (canonical per Q6; rearm requires reconciliation) + l6_result = rows_loss.evaluate_L6( + validated_inputs, prior_row_state, authorized_events, + session=session, as_of=as_of, o3_failed=o3_failed, market_closed=market_closed, + ) + rows_by_ID['L6'] = l6_result + if l6_result['latched']: + prior_latch = cst.get_account_latch(prior_row_state, 'L6') + trip_session = prior_latch['trip_session'] if prior_latch and prior_latch.get('trip_session') else session + cst.set_account_latch(next_row_state, 'L6', trip_session) + elif l6_result['reason'] == 'authorized_rearm': + next_row_state['L6'] = {} + + # ==== VEHICLE ROWS (V1-V7) - Fund/symbol scope ==== + + # Initialize fund-level outputs + v1_outputs = {} + v2_outputs = {} + v3_outputs = {} + v4_outputs = {} + v5_outputs = {} + v6_outputs = {} + v7_outputs = {} + + raw_quotes = validated_inputs.get('quotes') + raw_symbols = validated_inputs.get('symbols') + + for symbol in eval_fund_symbols: + fund_inputs = funds[symbol] if (symbol in funds and isinstance(funds[symbol], dict)) else {} + + # V1 - tracking deviation (canonical format per Q6; 1-session and 5-session per §4.3/§6) + v1_result = rows_vehicle.evaluate_V1( + fund_inputs, prior_row_state, authorized_events, symbol, + session=session, market_closed=market_closed, as_of=as_of, + ) + session_returns = v1_result.pop('_session_returns', None) + v1_outputs[symbol] = v1_result + if session_returns is not None: + cst.set_v1_history(next_row_state, symbol, session_returns) + if v1_result['latched']: + # Preserve original trip_session and deviation if already latched (§4.4 rule 3) + prior_latch = cst.get_v1_latch(prior_row_state, symbol) + if prior_latch: + trip_session = prior_latch['trip_session'] + deviation = prior_latch['deviation'] + else: + trip_session = session + deviation = v1_result.get('deviation', 0.0) + cst.set_v1_latch(next_row_state, symbol, trip_session, deviation) + elif v1_result['reason'] == 'authorized_rearm': + # Q4: clear latch on authorized re-arm - serialize as {"V1":{}} + cst.clear_v1_latch(next_row_state, symbol) + + # V2 - corporate action (validate top-level, fund-level, AND corporate_action hwm_adjusted independently) + v2_inputs = dict(fund_inputs) + if 'hwm_adjusted' in validated_inputs: + v2_inputs['_top_hwm_adjusted'] = validated_inputs['hwm_adjusted'] + v2_result = rows_vehicle.evaluate_V2( + v2_inputs, prior_row_state, authorized_events, symbol, + session=session, as_of=as_of, + ) + v2_reconcile_target = v2_result.pop('_v2_reconcile_target', None) + v2_mismatch_target = v2_result.pop('_v2_mismatch_target', None) + v2_clear_mismatch_only = v2_result.pop('_v2_clear_mismatch_only', False) + v2_enqueue_pending = v2_result.pop('_v2_enqueue_pending', False) + v2_outputs[symbol] = v2_result + + # B1: Store V2 latches and finite-sanitized mismatch details (SUC-02) - canonical format per Q6 + if v2_result['latched']: + # For new reconciliation_mismatch, store finite mismatch details + action identity + if v2_result['reason'] == 'reconciliation_mismatch': + corporate_action = fund_inputs.get('corporate_action', {}) + lv_clean = finite_float(fund_inputs.get('ledger_value')) + bv_clean = finite_float(fund_inputs.get('broker_value')) + mismatch_amt = abs(lv_clean - bv_clean) if (lv_clean is not None and bv_clean is not None) else None + mismatch_details = { + 'type': corporate_action.get('type') if isinstance(corporate_action, dict) else 'unknown', + 'ledger_value': lv_clean, + 'broker_value': bv_clean, + 'mismatch': mismatch_amt + } + cst.set_v2_latched_mismatch(next_row_state, symbol, mismatch_details) + ca_ident = cst.canonical_ca_identity(corporate_action) + if ca_ident is not None: + cst.set_v2_latched_mismatch_action(next_row_state, symbol, ca_ident) + # For persisting latch (latched_prior_mismatch), carry forward details + action identity + elif v2_result['reason'] == 'latched_prior_mismatch': + prior_mismatch = cst.get_v2_latched_mismatch(prior_row_state, symbol) + if prior_mismatch: + cst.set_v2_latched_mismatch(next_row_state, symbol, prior_mismatch) + prior_mismatch_action = cst.get_v2_latched_mismatch_action(prior_row_state, symbol) + if prior_mismatch_action: + cst.set_v2_latched_mismatch_action(next_row_state, symbol, prior_mismatch_action) + else: + # Clear mismatch latch on Q4 re-arm even if carried pending actions remain + if v2_result['reason'] == 'authorized_rearm' or v2_clear_mismatch_only: + cst.clear_v2_latched_mismatch(next_row_state, symbol) + + # Update pending state (B1 canonical format per Q6; never drop unrelated queued/primary items) + prior_pending = cst.get_v2_pending_adjustment(prior_row_state, symbol) + prior_identities = cst.get_v2_pending_identities(prior_row_state, symbol) + + def _drop_pending_target(pending_obj: Dict[str, Any], target: Any) -> Optional[Dict[str, Any]]: + updated = copy.deepcopy(pending_obj) + if target == 'primary': + q_list = list(updated.get('queued_actions') or []) + if not q_list: + return None + promoted = q_list.pop(0) + new_p = { + 'type': promoted.get('type'), + 'ratio': promoted.get('ratio'), + 'awaiting_reconciliation': True + } + if q_list: + new_p['queued_actions'] = q_list + return new_p + if isinstance(target, tuple) and target[0] == 'queued': + q_list = list(updated.get('queued_actions') or []) + idx_to_pop = target[1] + if 0 <= idx_to_pop < len(q_list): + q_list.pop(idx_to_pop) + if q_list: + updated['queued_actions'] = q_list + else: + updated.pop('queued_actions', None) + return updated + return updated + + def _drop_identity_target(ident_obj: Optional[Dict[str, Any]], target: Any) -> Optional[Dict[str, Any]]: + if not isinstance(ident_obj, dict): + return None + updated_id = copy.deepcopy(ident_obj) + q_ids = list(updated_id.get('queued') or []) + if target == 'primary': + if not q_ids: + return None + promoted_id = q_ids.pop(0) + res_id: Dict[str, Any] = {'primary': promoted_id} + if q_ids: + res_id['queued'] = q_ids + return res_id + if isinstance(target, tuple) and target[0] == 'queued': + idx_to_pop = target[1] + if 0 <= idx_to_pop < len(q_ids): + q_ids.pop(idx_to_pop) + if q_ids: + updated_id['queued'] = q_ids + else: + updated_id.pop('queued', None) + return updated_id + return updated_id + + def _merge_pending_action( + existing_pending: Optional[Dict[str, Any]], + existing_idents: Optional[Dict[str, Any]], + ca_obj: Any, + ) -> tuple: + inc_ident = cst.canonical_ca_identity(ca_obj) + if existing_pending: + merged = copy.deepcopy(existing_pending) + merged_idents = copy.deepcopy(existing_idents) if isinstance(existing_idents, dict) else {} + if isinstance(ca_obj, dict) and ca_obj.get('type'): + inc_type = ca_obj.get('type') + inc_ratio = ca_obj.get('ratio') + inc_ratio_num = finite_float(inc_ratio) + prim_ratio_num = finite_float(merged.get('ratio')) + ratio_matches_prim = ( + inc_ratio_num == prim_ratio_num + if (inc_ratio_num is not None or prim_ratio_num is not None) + else inc_ratio == merged.get('ratio') + ) + if isinstance(merged_idents.get('primary'), dict) and inc_ident is not None: + matches_primary = (inc_ident == merged_idents['primary']) + else: + matches_primary = (inc_type == merged.get('type') and ratio_matches_prim) + q_list = list(merged.get('queued_actions') or []) + q_ids = list(merged_idents.get('queued') or []) + matches_queued = False + for idx_q, q in enumerate(q_list): + if not isinstance(q, dict): + continue + if idx_q < len(q_ids) and isinstance(q_ids[idx_q], dict) and inc_ident is not None: + if inc_ident == q_ids[idx_q]: + matches_queued = True + break + else: + q_r_num = finite_float(q.get('ratio')) + r_eq = ( + inc_ratio_num == q_r_num + if (inc_ratio_num is not None or q_r_num is not None) + else inc_ratio == q.get('ratio') + ) + if q.get('type') == inc_type and r_eq: + matches_queued = True + break + if not matches_primary and not matches_queued: + q_list.append({'type': inc_type, 'ratio': inc_ratio}) + merged['queued_actions'] = q_list + if inc_ident is not None: + while len(q_ids) < len(q_list) - 1: + q_ids.append(None) + q_ids.append(inc_ident) + merged_idents['queued'] = q_ids + return merged, (merged_idents if merged_idents else None) + if isinstance(ca_obj, dict) and ca_obj.get('type'): + pending_obj = { + 'type': ca_obj.get('type'), + 'ratio': ca_obj.get('ratio'), + 'awaiting_reconciliation': True + } + idents_obj = {'primary': inc_ident} if inc_ident is not None else None + return pending_obj, idents_obj + return None, None + + corporate_action = fund_inputs.get('corporate_action') + if v2_result['reason'] == 'reconciliation_mismatch': + if prior_pending: + if v2_mismatch_target is not None: + remaining_pending = _drop_pending_target(prior_pending, v2_mismatch_target) + remaining_idents = _drop_identity_target(prior_identities, v2_mismatch_target) + if remaining_pending is not None: + cst.set_v2_pending_adjustment(next_row_state, symbol, remaining_pending) + if remaining_idents is not None: + cst.set_v2_pending_identities(next_row_state, symbol, remaining_idents) + else: + cst.clear_v2_pending_adjustment(next_row_state, symbol) + else: + cst.set_v2_pending_adjustment(next_row_state, symbol, copy.deepcopy(prior_pending)) + if prior_identities is not None: + cst.set_v2_pending_identities(next_row_state, symbol, copy.deepcopy(prior_identities)) + elif v2_result['reason'] in ['pending_corporate_action', 'pending_corporate_action_carried']: + if v2_reconcile_target is not None and prior_pending: + remaining_pending = _drop_pending_target(prior_pending, v2_reconcile_target) + remaining_idents = _drop_identity_target(prior_identities, v2_reconcile_target) + if remaining_pending is not None: + cst.set_v2_pending_adjustment(next_row_state, symbol, remaining_pending) + if remaining_idents is not None: + cst.set_v2_pending_identities(next_row_state, symbol, remaining_idents) + else: + cst.clear_v2_pending_adjustment(next_row_state, symbol) + else: + merged_pending, merged_idents = _merge_pending_action(prior_pending, prior_identities, corporate_action) + if merged_pending is not None: + cst.set_v2_pending_adjustment(next_row_state, symbol, merged_pending) + if merged_idents is not None: + cst.set_v2_pending_identities(next_row_state, symbol, merged_idents) + elif v2_result['reason'] in ('exact_reconciliation_auto_clear', 'authorized_rearm'): + # Clear pending on exact reconciliation or authorized re-arm (only when no pending remained) + cst.clear_v2_pending_adjustment(next_row_state, symbol) + elif v2_enqueue_pending: + # Distinct/new corporate action announced while mismatch latch is active -> keep pending queue + merged_pending, merged_idents = _merge_pending_action(prior_pending, prior_identities, corporate_action) + if merged_pending is not None: + cst.set_v2_pending_adjustment(next_row_state, symbol, merged_pending) + if merged_idents is not None: + cst.set_v2_pending_identities(next_row_state, symbol, merged_idents) + else: + if prior_pending: + cst.set_v2_pending_adjustment(next_row_state, symbol, copy.deepcopy(prior_pending)) + if prior_identities is not None: + cst.set_v2_pending_identities(next_row_state, symbol, copy.deepcopy(prior_identities)) + + # V3 - fund event (canonical format per Q6) + v3_result = rows_vehicle.evaluate_V3( + fund_inputs, prior_row_state, authorized_events, symbol, + session=session, as_of=as_of, + ) + v3_outputs[symbol] = v3_result + if v3_result['latched']: + # Preserve original trip_session if already latched (§4.4 rule 3: persistence) + prior_latch = cst.get_fund_latch(prior_row_state, 'V3', symbol) + trip_session = prior_latch['trip_session'] if prior_latch else session + details = {'reason': v3_result['reason'], 'fund_event': v3_result.get('fund_event')} + cst.set_fund_latch(next_row_state, 'V3', symbol, trip_session, details) + elif v3_result['reason'] == 'authorized_rearm': + if 'V3' not in next_row_state: + next_row_state['V3'] = {} + + # V4 - extreme volatility (B4 canonical format per Q6; closed/holiday skips increment) + v4_result = rows_vehicle.evaluate_V4( + fund_inputs, prior_row_state, authorized_events, symbol, session, + market_closed=market_closed + ) + preserve_v4_session = v4_result.pop('_preserve_prior_v4_session', False) + v4_outputs[symbol] = v4_result + # Update V4 state based on result reason - counter now in outputs + if preserve_v4_session: + prior_v4 = cst.get_v4_state(prior_row_state, symbol) + if prior_v4['clearing_counter'] is not None: + cst.set_v4_state( + next_row_state, symbol, + prior_v4['clearing_counter'], + prior_v4['last_session_below_threshold'] + ) + elif v4_result['reason'] == 'volatility_at_or_above_2x': + # Initial trip: volatility HIGH, no "last session below threshold" yet + counter = v4_result.get('outputs', {}).get('clearing_counter', 0) + cst.set_v4_state(next_row_state, symbol, counter, None) + elif v4_result['reason'] == 'volatility_below_2x_but_not_yet_cleared': + # Clearing phase: record this session as below threshold + counter = v4_result.get('outputs', {}).get('clearing_counter', 0) + cst.set_v4_state(next_row_state, symbol, counter, session) + elif v4_result['reason'] == 'cleared_after_ten_sessions': + # At count 10, report 10 and remove the fund entry per Q1 + cst.clear_v4_state(next_row_state, symbol) + elif v4_result['reason'] == 'missing_input': + # A07.1: Missing forecast earns zero clearing credit but MUST preserve active V4 counter + prior_v4 = cst.get_v4_state(prior_row_state, symbol) + if prior_v4['clearing_counter'] is not None: + cst.set_v4_state( + next_row_state, symbol, + prior_v4['clearing_counter'], + prior_v4['last_session_below_threshold'] + ) + + # V5 - decay monitor (B5 canonical format per Q6; fallback to top-level policy v5_tolerance) + v5_inputs = fund_inputs if 'v5_tolerance' in fund_inputs else {**fund_inputs, 'v5_tolerance': validated_inputs.get('v5_tolerance')} + v5_result = rows_vehicle.evaluate_V5( + v5_inputs, prior_row_state, authorized_events, symbol, session, + as_of=as_of, market_closed=market_closed, + ) + preserve_v5_session = v5_result.pop('_preserve_prior_v5_session', False) + v5_outputs[symbol] = v5_result + # Update V5 state - preserve prior state across omitted/missing/unresolved/invalid/closed checks without inventing last_session + prior_v5_raw = (prior_row_state.get('V5') or {}).get(symbol) if isinstance(prior_row_state, dict) else None + if v5_result['reason'] == 'authorized_rearm': + cst.clear_v5_state(next_row_state, symbol) + elif ( + preserve_v5_session + or symbol not in funds + or v5_result['reason'] in ('missing_input', 'unresolved_fail_closed', 'invalid_input') + or (v5_result['outputs']['escalated_to_v1'] and v5_result['outputs']['excess_shortfall'] is None) + ): + if isinstance(prior_v5_raw, dict) and (prior_v5_raw or v5_result['outputs']['escalated_to_v1']): + if 'V5' not in next_row_state: + next_row_state['V5'] = {} + preserved_entry = copy.deepcopy(prior_v5_raw) + if v5_result['outputs']['escalated_to_v1']: + preserved_entry.setdefault( + 'consecutive_beyond_tolerance', + v5_result['outputs']['consecutive_sessions_beyond_tolerance'], + ) + preserved_entry['escalated'] = True + next_row_state['V5'][symbol] = preserved_entry + else: + new_count = v5_result['outputs']['consecutive_sessions_beyond_tolerance'] + escalated = v5_result['outputs']['escalated_to_v1'] + cst.set_v5_state(next_row_state, symbol, new_count, escalated, session) + + # V6 - carrying cost + v6_result = rows_vehicle.evaluate_V6(fund_inputs, prior_row_state, authorized_events, symbol) + v6_outputs[symbol] = v6_result + + # V7 - quote/liquidity (for fund missing from funds, inspect quotes/symbols lookup; inherit v7_spread_width) + if symbol in funds: + v7_base = fund_inputs + elif isinstance(raw_quotes, dict) and isinstance(raw_quotes.get(symbol), dict): + v7_base = raw_quotes[symbol] + elif isinstance(raw_symbols, dict) and isinstance(raw_symbols.get(symbol), dict): + v7_base = raw_symbols[symbol] + else: + v7_base = {} + v7_inputs = v7_base if 'v7_spread_width' in v7_base else {**v7_base, 'v7_spread_width': validated_inputs.get('v7_spread_width')} + v7_result = rows_vehicle.evaluate_V7(v7_inputs, prior_row_state, authorized_events, symbol) + v7_outputs[symbol] = v7_result + + # V7 also evaluates remaining proposed order symbols outside eval_fund_symbols (e.g. cash ETFs like BIL) + for sym in order_symbols: + if sym in eval_fund_symbols: + continue + sym_quote = {} + if isinstance(raw_quotes, dict) and isinstance(raw_quotes.get(sym), dict): + sym_quote = raw_quotes[sym] + elif isinstance(raw_symbols, dict) and isinstance(raw_symbols.get(sym), dict): + sym_quote = raw_symbols[sym] + v7_order_inputs = ( + sym_quote + if 'v7_spread_width' in sym_quote + else {**sym_quote, 'v7_spread_width': validated_inputs.get('v7_spread_width')} + ) + v7_outputs[sym] = rows_vehicle.evaluate_V7( + v7_order_inputs, prior_row_state, authorized_events, sym + ) + if invalid_order_symbol: + v7_outputs['__invalid_order_symbol__'] = { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'invalid_input', + 'fund': '__invalid_order_symbol__', + } + + # Aggregate vehicle rows into single row outputs + rows_by_ID['V1'] = aggregate_fund_row(v1_outputs) + rows_by_ID['V2'] = aggregate_fund_row(v2_outputs) + rows_by_ID['V3'] = aggregate_fund_row(v3_outputs) + rows_by_ID['V4'] = aggregate_fund_row(v4_outputs) + # V5, V6 are diagnostic with structured row-level outputs (Fix 2) + # V7 is symbol-scoped interlock (not diagnostic) + rows_by_ID['V5'] = aggregate_diagnostic_row(v5_outputs) + rows_by_ID['V6'] = aggregate_diagnostic_row(v6_outputs) + rows_by_ID['V7'] = aggregate_fund_row(v7_outputs, symbol_scoped=True, emit_scope_keys=False) + + # V2, V4, V5 state now written inline using canonical accessors per Q6 + + # ==== OPERATIONS ROWS (O1-O9, J1) ==== + + # O1 - required inputs stale/missing (B3; same-day stale->fresh cannot clear mid-session) + o1_result = rows_ops.evaluate_O1(validated_inputs, prior_row_state, authorized_events, session, as_of=as_of) + rows_by_ID['O1'] = o1_result + o1_state = cst.get_o1_fresh_state(prior_row_state) + o1_cur_date = cst.canonical_session_date(session, as_of) + if o1_result['reason'] == 'clearing_period': + cst.set_o1_fresh_state( + next_row_state, 0, o1_cur_date, + last_tripped_session=o1_state.get('last_tripped_session') or o1_cur_date + ) + elif not o1_result['would_have_tripped']: + if o1_state.get('last_session') == o1_cur_date and o1_state.get('fresh_session_count', 0) == 0: + # Stale->fresh transition within the same session must NOT count as a full clean session + cst.set_o1_fresh_state(next_row_state, 0, o1_cur_date) + elif o1_state.get('last_session') == o1_cur_date: + cst.set_o1_fresh_state(next_row_state, o1_state['fresh_session_count'], o1_cur_date) + else: + fresh_count = o1_state['fresh_session_count'] + 1 + cst.set_o1_fresh_state(next_row_state, fresh_count, o1_cur_date) + else: + # Operational stale/missing trip records last_tripped_session so same-day recovery cannot clear + if o1_result['reason'] == 'stale_or_missing_input': + cst.set_o1_fresh_state(next_row_state, 0, o1_cur_date, last_tripped_session=o1_cur_date) + else: + cst.set_o1_fresh_state(next_row_state, 0, o1_cur_date) + + # O2 - session calendar + o2_result = rows_ops.evaluate_O2(validated_inputs, prior_row_state, authorized_events) + rows_by_ID['O2'] = o2_result + + # O3 - reconciliation mismatch (already evaluated before L6) + rows_by_ID['O3'] = o3_result + if o3_result['latched']: + # Preserve original trip_session if already latched (§4.4 rule 3: persistence) + prior_latch = cst.get_account_latch(prior_row_state, 'O3') + trip_session = prior_latch['trip_session'] if prior_latch else session + cst.set_account_latch(next_row_state, 'O3', trip_session) + elif o3_result['reason'] == 'authorized_rearm': + next_row_state['O3'] = {} + + # O4 - order timeout (canonical format per Q6, enumerate from all sources) + o4_outputs = {} + restart_marker = validated_inputs.get('restart_marker') + + for symbol in all_symbols: + # Build order input for this symbol safely even if funds[symbol] is missing/non-dict + order_input = {} + if symbol in funds and isinstance(funds[symbol], dict): + order_input = funds[symbol].copy() + + # Add pending order if present + if symbol in pending_orders: + order_input['o4_pending_order'] = pending_orders[symbol] + + # Forward restart_marker into O4 evaluation (Q6) + if restart_marker: + order_input['restart_marker'] = restart_marker + + o4_result = rows_ops.evaluate_O4( + order_input, prior_row_state, authorized_events, symbol, + session=session, as_of=as_of, + ) + + if malformed_pending_orders: + prior_pending = cst.get_o4_pending_order(prior_row_state, symbol) + if prior_pending: + # Never allow malformed pending_orders to clear an active prior O4 lock + order_id = prior_pending['original_order_id'] + status = prior_pending.get('status', 'unknown') + latched = True + elif o4_result.get('original_order_id'): + # Record newly reported timed-out/malformed fund o4_pending_order even when top-level pending_orders failed + order_id = o4_result['original_order_id'] + status = 'unknown' + latched = bool(o4_result.get('latched')) + else: + order_id = None + status = 'unknown' + latched = False + + o4_out = { + 'state': 'ORDER-UNKNOWN', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': latched, + 'reason': 'malformed_pending_orders', + 'symbol': symbol, + } + if order_id: + o4_out['original_order_id'] = order_id + cst.set_o4_pending_order(next_row_state, symbol, order_id, status) + o4_outputs[symbol] = o4_out + continue + + o4_outputs[symbol] = o4_result + + # Store O4 state using canonical accessors (Q6) + if o4_result.get('original_order_id'): + order_id = o4_result['original_order_id'] + status = 'unknown' + cst.set_o4_pending_order(next_row_state, symbol, order_id, status) + elif o4_result['reason'] in ('original_order_terminal_status_received', 'order_filled', 'authorized_rearm'): + # Clear resolved order + cst.clear_o4_pending_order(next_row_state, symbol) + + rows_by_ID['O4'] = aggregate_fund_row(o4_outputs, symbol_scoped=True) + + # O5 - pre-trade limits (B2 canonical format per Q6) + o5_result = rows_ops.evaluate_O5(validated_inputs, prior_row_state, authorized_events, session, as_of=as_of) + rows_by_ID['O5'] = o5_result + # O5 state: preserve session rejection count & latch across mixed PASS/REJECT checks in same session + if o5_result['reason'] == 'authorized_rearm': + next_row_state['O5'] = {} + elif o5_result['would_have_tripped']: + count = o5_result.get('rejection_count_this_session', 1) + latched = o5_result['latched'] + cst.set_o5_state(next_row_state, count, session, latched) + else: + prior_o5 = cst.get_o5_state(prior_row_state) + if prior_o5['last_rejection_session'] == session and (prior_o5['rejection_count'] > 0 or prior_o5['latched']): + cst.set_o5_state(next_row_state, prior_o5['rejection_count'], session, prior_o5['latched']) + + # O6 - policy hash mismatch (canonical format per Q6) + o6_result = rows_ops.evaluate_O6(validated_inputs, prior_row_state, authorized_events, session=session, as_of=as_of) + rows_by_ID['O6'] = o6_result + if o6_result['latched']: + # Preserve original trip_session if already latched (§4.4 rule 3: persistence) + prior_latch = cst.get_account_latch(prior_row_state, 'O6') + trip_session = prior_latch['trip_session'] if prior_latch else session + cst.set_account_latch(next_row_state, 'O6', trip_session) + elif o6_result['reason'] == 'authorized_rearm': + next_row_state['O6'] = {} + + # O7 - dead man's switch (canonical format per Q6) + o7_result = rows_ops.evaluate_O7(validated_inputs, prior_row_state, authorized_events, as_of=as_of, session=session) + rows_by_ID['O7'] = o7_result + if o7_result['latched']: + # Preserve original trip_session if already latched (§4.4 rule 3: persistence) + prior_latch = cst.get_account_latch(prior_row_state, 'O7') + trip_session = prior_latch['trip_session'] if prior_latch else session + cst.set_account_latch(next_row_state, 'O7', trip_session) + elif o7_result['reason'] == 'authorized_rearm': + next_row_state['O7'] = {} + + # O8 - kill switch (persists latch ONLY when fired/active; omits O8 from clean next_row_state) + o8_result = rows_ops.evaluate_O8( + validated_inputs, prior_row_state, authorized_events, session=session, as_of=as_of + ) + rows_by_ID['O8'] = o8_result + if o8_result['latched']: + prior_latch = cst.get_account_latch(prior_row_state, 'O8') + trip_session = prior_latch['trip_session'] if prior_latch and prior_latch.get('trip_session') else cst.canonical_session_date(session, as_of) + next_row_state['O8'] = {'latched': True, 'trip_session': trip_session} + elif o8_result['reason'] == 'authorized_rearm': + next_row_state['O8'] = {} + + # O9 - unauthorized parameter change (canonical format per Q6) + o9_result = rows_ops.evaluate_O9(validated_inputs, prior_row_state, authorized_events, session=session, as_of=as_of) + rows_by_ID['O9'] = o9_result + if o9_result['latched']: + # Preserve original trip_session if already latched (§4.4 rule 3: persistence) + prior_latch = cst.get_account_latch(prior_row_state, 'O9') + trip_session = prior_latch['trip_session'] if prior_latch else session + cst.set_account_latch(next_row_state, 'O9', trip_session) + elif o9_result['reason'] == 'authorized_rearm': + next_row_state['O9'] = {} + + # J1 - joint exposure limit + j1_result = rows_ops.evaluate_J1(validated_inputs, prior_row_state, authorized_events) + rows_by_ID['J1'] = j1_result + + # Preserve durable scope state for funds/symbols not in current inputs (Q6 & A07.2) + # V1, V2, V3, V4, V5, O4 state must survive across calls even when scope is absent + if prior_row_state: + # Preserve V1 state (latches and 5-session history) for absent funds, and reflect active latches + for fund in sorted(prior_row_state.get('V1', {}).keys()): + v1_fund_state = prior_row_state['V1'][fund] + if fund not in eval_fund_symbols and isinstance(v1_fund_state, dict) and v1_fund_state: + if 'V1' not in next_row_state: + next_row_state['V1'] = {} + if fund not in next_row_state['V1']: + next_row_state['V1'][fund] = copy.deepcopy(v1_fund_state) + if v1_fund_state.get('latched'): + v1_outputs[fund] = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip', + 'fund': fund + } + + # Preserve V2 latched mismatches, pending adjustments, and their action identities for absent funds + prior_v2 = prior_row_state.get('V2', {}) + if isinstance(prior_v2, dict): + prior_mism_actions = prior_v2.get('latched_mismatch_actions', {}) + prior_pend_idents = prior_v2.get('pending_action_identities', {}) + for fund in sorted(prior_v2.get('latched_mismatches', {}).keys()): + mismatch = prior_v2['latched_mismatches'][fund] + if fund not in eval_fund_symbols and mismatch: + cst.set_v2_latched_mismatch(next_row_state, fund, mismatch) + if isinstance(prior_mism_actions, dict) and isinstance(prior_mism_actions.get(fund), dict): + cst.set_v2_latched_mismatch_action(next_row_state, fund, copy.deepcopy(prior_mism_actions[fund])) + v2_outputs[fund] = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': True, + 'reason': 'latched_prior_mismatch', + 'fund': fund + } + for fund in sorted(prior_v2.get('pending_adjustments', {}).keys()): + pending = prior_v2['pending_adjustments'][fund] + if fund not in eval_fund_symbols and pending: + cst.set_v2_pending_adjustment(next_row_state, fund, pending) + if isinstance(prior_pend_idents, dict) and isinstance(prior_pend_idents.get(fund), dict): + cst.set_v2_pending_identities(next_row_state, fund, copy.deepcopy(prior_pend_idents[fund])) + if fund not in v2_outputs: + v2_outputs[fund] = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'pending_corporate_action_carried', + 'fund': fund + } + + # Preserve V3 latches for absent funds + for fund in sorted(prior_row_state.get('V3', {}).keys()): + v3_fund_state = prior_row_state['V3'][fund] + if fund not in eval_fund_symbols and isinstance(v3_fund_state, dict) and v3_fund_state.get('latched'): + if 'V3' not in next_row_state: + next_row_state['V3'] = {} + if fund not in next_row_state['V3']: + next_row_state['V3'][fund] = v3_fund_state + v3_outputs[fund] = { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip', + 'fund': fund + } + + # Preserve V4 state and active restrictions for funds omitted from current inputs (A08) + if 'V4' in prior_row_state: + if 'V4' not in next_row_state: + next_row_state['V4'] = {} + for fund in sorted(prior_row_state['V4'].keys()): + v4_fund_state = prior_row_state['V4'][fund] + if fund not in eval_fund_symbols: + if fund not in next_row_state['V4']: + next_row_state['V4'][fund] = copy.deepcopy(v4_fund_state) + if isinstance(v4_fund_state, dict) and v4_fund_state.get('clearing_counter') is not None: + v4_outputs[fund] = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'volatility_below_2x_but_not_yet_cleared', + 'fund': fund, + 'outputs': {'clearing_counter': v4_fund_state['clearing_counter']} + } + + # Preserve V5 state and escalated restrictions (or clear on Q4 re-arm) for funds omitted from current inputs + if 'V5' in prior_row_state and isinstance(prior_row_state['V5'], dict): + if 'V5' not in next_row_state: + next_row_state['V5'] = {} + for fund in sorted(prior_row_state['V5'].keys()): + if fund in eval_fund_symbols: + continue + v5_fund_state = prior_row_state['V5'][fund] + is_esc_omitted = isinstance(v5_fund_state, dict) and ( + bool(v5_fund_state.get('escalated')) or ( + isinstance(v5_fund_state.get('consecutive_beyond_tolerance'), (int, float)) + and not isinstance(v5_fund_state.get('consecutive_beyond_tolerance'), bool) + and v5_fund_state.get('consecutive_beyond_tolerance') >= 40 + ) + ) + if is_esc_omitted and cst.matches_fund_rearm( + authorized_events, 'V5', fund, session=session, as_of=as_of, require_date=True + ) is not None: + cst.clear_v5_state(next_row_state, fund) + v5_outputs[fund] = { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'authorized_rearm', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': 0, + 'escalated_to_v1': False, + 'disposition': 'authorized_rearm', + }, + } + continue + if fund not in next_row_state['V5']: + next_row_state['V5'][fund] = copy.deepcopy(v5_fund_state) + if is_esc_omitted: + cnt = v5_fund_state.get('consecutive_beyond_tolerance') + preserved_cnt = cnt if isinstance(cnt, int) and not isinstance(cnt, bool) and cnt >= 40 else 40 + v5_outputs[fund] = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'escalated_to_v1_treatment', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': preserved_cnt, + 'escalated_to_v1': True, + 'disposition': 'escalated_to_v1', + }, + } + + # Re-aggregate V1/V2/V3/V4/V5 if absent restricted/escalated funds were carried into outputs + if prior_latched_funds: + rows_by_ID['V1'] = aggregate_fund_row(v1_outputs) + rows_by_ID['V2'] = aggregate_fund_row(v2_outputs) + rows_by_ID['V3'] = aggregate_fund_row(v3_outputs) + rows_by_ID['V4'] = aggregate_fund_row(v4_outputs) + rows_by_ID['V5'] = aggregate_diagnostic_row(v5_outputs) + + # O4 already preserved via symbol enumeration (all_symbols includes prior O4 keys) + + # ==== PRECEDENCE RESOLUTION ==== + # Per §4.1: HALT > ORDER-UNKNOWN > DE-RISK > NO-NEW-RISK > NORMAL + # Account HALT dominates all narrower scopes + + effective_state_by_scope = {} + + # Precedence order + precedence = ['HALT', 'ORDER-UNKNOWN', 'DE-RISK', 'NO-NEW-RISK', 'NORMAL'] + + # First, resolve account scope to check for dominance (Q5) + account_states = [] + for row_id in ['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'O1', 'O2', 'O3', 'O5', 'O6', 'O7', 'O8', 'O9']: + row_result = rows_by_ID[row_id] + account_states.append(row_result['state']) + + account_state = 'NORMAL' + for state in precedence: + if state in account_states: + account_state = state + break + + effective_state_by_scope['account'] = account_state + + # A08 / Q5: Account HALT dominates every narrower scope (§4.1), including joint + if account_state == 'HALT': + for scope in scopes: + effective_state_by_scope[scope] = 'HALT' + else: + # Account not HALT - resolve each scope independently + for scope in scopes: + if scope == 'account': + continue # Already resolved above + + states_for_scope = [] + + if scope.startswith('fund:'): + symbol = scope.split(':')[1] + # Fund-scoped rows + if symbol in v1_outputs: + states_for_scope.append(v1_outputs[symbol]['state']) + if symbol in v2_outputs: + states_for_scope.append(v2_outputs[symbol]['state']) + if symbol in v3_outputs: + states_for_scope.append(v3_outputs[symbol]['state']) + if symbol in v4_outputs: + states_for_scope.append(v4_outputs[symbol]['state']) + if symbol in v5_outputs: + states_for_scope.append(v5_outputs[symbol]['state']) + elif scope.startswith('symbol:'): + symbol = scope.split(':')[1] + # Symbol-scoped rows (O4, V7) + if symbol in o4_outputs: + states_for_scope.append(o4_outputs[symbol]['state']) + if symbol in v7_outputs: + states_for_scope.append(v7_outputs[symbol]['state']) + elif scope == 'joint': + # Joint-scoped rows + states_for_scope.append(j1_result['state']) + + # Resolve by precedence + effective_state = 'NORMAL' + for state in precedence: + if state in states_for_scope: + effective_state = state + break + + effective_state_by_scope[scope] = effective_state + + # G6 (F1-A10 / §5.3): Bind spec_version, canonical engine_hash, and shadow safety assertions + next_row_state['spec_version'] = spec_version + next_row_state['engine_hash'] = canonical_engine_hash + next_row_state['enforcement_mode'] = 'shadow_would_have_tripped' + next_row_state['loss_breakers_armed'] = False + + return (rows_by_ID, effective_state_by_scope, next_row_state) + + +def aggregate_fund_row( + fund_outputs: Dict[str, Dict[str, Any]], + symbol_scoped: bool = False, + emit_scope_keys: bool = True +) -> Dict[str, Any]: + """Aggregate per-fund row outputs into a single row output. + + For fund-scoped rows, returns the most restrictive state across all funds. + """ + if not fund_outputs: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } + + # Order-independent deterministic key traversal (canonical order across dict permutations) + ordered_keys = sorted(fund_outputs.keys()) if symbol_scoped else sorted(fund_outputs.keys(), key=_fund_sort_key) + sample = fund_outputs[ordered_keys[0]] + kind = sample['kind'] + + # Aggregate: take most restrictive state (Fix 2: single-token reason) + precedence = ['HALT', 'ORDER-UNKNOWN', 'DE-RISK', 'NO-NEW-RISK', 'NORMAL'] + most_restrictive = 'NORMAL' + any_tripped = False + any_latched = False + reasons = [] + affected_funds = [] + + for symbol in ordered_keys: + result = fund_outputs[symbol] + state = result['state'] + if precedence.index(state) < precedence.index(most_restrictive): + most_restrictive = state + if result['would_have_tripped']: + any_tripped = True + affected_funds.append(symbol) + if result.get('latched'): + any_latched = True + if result['reason'] != 'none': + reasons.append((symbol, result['reason'])) + + # Determine single reason token (Fix 2 + Fix 3: golden expects single token with fund suffix where applicable) + if not reasons: + reason = 'none' + elif len(reasons) == 1: + symbol, base_reason = reasons[0] + needs_suffix = (len(fund_outputs) > 1 and + base_reason in ['pending_corporate_action', 'pending_corporate_action_carried']) + reason = f'{base_reason}_{symbol}' if needs_suffix else base_reason + else: + unique_reasons = set(r for _, r in reasons) + if len(unique_reasons) == 1: + reason = next(iter(unique_reasons)) + for symbol in ordered_keys: + if reason.endswith(f'_{symbol}'): + reason = reason[:-len(f'_{symbol}')] + break + else: + reason = ', '.join(f"{sym}:{r}" for sym, r in reasons) + + # Build aggregate output + aggregate = { + 'state': most_restrictive, + 'would_have_tripped': any_tripped, + 'kind': kind, + 'latched': any_latched, + 'reason': reason + } + + # Include per-fund outputs in deterministic order whenever any fund emits outputs + if any('outputs' in fund_outputs[symbol] for symbol in ordered_keys): + if len(ordered_keys) == 1: + single_fund = ordered_keys[0] + aggregate['outputs'] = copy.deepcopy(fund_outputs[single_fund].get('outputs', {})) + else: + aggregate['outputs'] = { + symbol: copy.deepcopy(fund_outputs[symbol].get('outputs', {})) + for symbol in ordered_keys + } + + # For fund/symbol-scoped rows, include affected funds/symbols + if emit_scope_keys: + if len(ordered_keys) == 1: + single_key = ordered_keys[0] + single_result = fund_outputs[single_key] + if symbol_scoped: + aggregate['symbol'] = single_result.get('symbol', single_key) + if affected_funds: + aggregate['symbols'] = affected_funds + else: + aggregate['fund'] = single_result.get('fund', single_key) + elif affected_funds: + if symbol_scoped: + aggregate['symbols'] = affected_funds + else: + already_suffixed = any(reason.endswith(f'_{s}') for s in affected_funds) + if len(affected_funds) == 1 and not already_suffixed: + aggregate['fund'] = affected_funds[0] + elif len(affected_funds) > 1: + aggregate['funds'] = affected_funds + + # G1.3: Preserve declared successor evidence fields (deviation, original_order_id) + if len(ordered_keys) == 1: + single_fund = ordered_keys[0] + single_result = fund_outputs[single_fund] + + if 'deviation' in single_result: + aggregate['deviation'] = single_result['deviation'] + + if 'original_order_id' in single_result: + aggregate['original_order_id'] = single_result['original_order_id'] + + return aggregate + + +def aggregate_diagnostic_row(fund_outputs: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: + """Aggregate diagnostic rows (V5, V6) in a deterministic, dict-order-independent manner.""" + if not fund_outputs: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'none' + } + + ordered_keys = sorted(fund_outputs.keys(), key=_fund_sort_key) + precedence = ['HALT', 'ORDER-UNKNOWN', 'DE-RISK', 'NO-NEW-RISK', 'NORMAL'] + disposition_rank = { + 'UNRESOLVED-FAIL-CLOSED': 0, + 'beyond_tolerance': 1, + 'missing_data': 2, + 'invalid_data': 2, + 'authorized_rearm': 3, + 'benign': 4, + } + + def _diagnostic_severity(sym: str) -> tuple: + res = fund_outputs[sym] + outs = res.get('outputs', {}) + disp = outs.get('disposition', 'benign') + return ( + precedence.index(res['state']), + 0 if res.get('would_have_tripped') else 1, + 0 if outs.get('escalated_to_v1') else 1, + 0 if outs.get('notify') else 1, + 0 if outs.get('exceeded') else 1, + disposition_rank.get(disp, 4), + 0 if res.get('reason', 'none') != 'none' else 1, + -(outs.get('consecutive_sessions_beyond_tolerance') or 0), + _fund_sort_key(sym), + ) + + worst_sym = min(ordered_keys, key=_diagnostic_severity) + worst_result = fund_outputs[worst_sym] + kind = worst_result['kind'] + + most_restrictive = worst_result['state'] + any_tripped = any(fund_outputs[s]['would_have_tripped'] for s in ordered_keys) + + raw_reason = worst_result.get('reason', 'none') + reason = raw_reason[:-len(f'_{worst_sym}')] if raw_reason.endswith(f'_{worst_sym}') else raw_reason + + aggregate = { + 'state': most_restrictive, + 'would_have_tripped': any_tripped, + 'kind': kind, + 'latched': False, # Diagnostics don't latch + 'reason': reason + } + + if 'outputs' in worst_result: + agg_outputs = copy.deepcopy(worst_result['outputs']) + if 'notify' in agg_outputs: + agg_outputs['notify'] = any( + bool(fund_outputs[s].get('outputs', {}).get('notify')) + for s in ordered_keys + ) + if 'exceeded' in agg_outputs: + agg_outputs['exceeded'] = any( + bool(fund_outputs[s].get('outputs', {}).get('exceeded')) + for s in ordered_keys + ) + aggregate['outputs'] = agg_outputs + + if len(ordered_keys) == 1: + single_fund = ordered_keys[0] + aggregate['fund'] = fund_outputs[single_fund].get('fund', single_fund) + + return aggregate diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_loss.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_loss.py new file mode 100644 index 0000000..5b92800 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_loss.py @@ -0,0 +1,646 @@ +"""Loss breaker rows L0-L6 per BRIEF-FUSE-1 §4.3 Table A. + +All loss rows operate on bankroll basis, flow-adjusted and split-adjusted. +Thresholds are fractions of D (tier loss budget). +""" + +from datetime import date +from typing import Any, Dict, Optional +from . import state as st +from . import canonical_state as cst +from .canonical import finite_float + + +# Tier loss budgets (D) per spec §4.3 and spec.json +TIER_D = { + 'conservative': 0.15, + 'balanced': 0.30, + 'aggressive': 0.50 +} + + +def evaluate_L0(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """L0: Exposure limited to maximum-loss cap (standing limit). + + Kind: limit (symmetric, automatic) + Scope: account + State contribution: none (outputs only) + Required inputs: joint_exposure, max_loss_cap, proposed_exposure + """ + # Required finite non-negative inputs - fail closed on missing/NaN/inf/bool/negative (§4.4 rule 3, §5.2) + joint_exposure = finite_float(inputs.get('joint_exposure')) + max_loss_cap = finite_float(inputs.get('max_loss_cap')) + proposed_exposure = finite_float(inputs.get('proposed_exposure')) + + if ( + joint_exposure is None or max_loss_cap is None or proposed_exposure is None or + joint_exposure < 0.0 or max_loss_cap < 0.0 or proposed_exposure < 0.0 + ): + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'limit', + 'latched': False, + 'reason': 'missing_input', + 'outputs': { + 'cap': None, + 'cap_breached': True, + 'increases_blocked': True + } + } + + # Evaluate limit + cap_breached = joint_exposure > max_loss_cap + increases_blocked = proposed_exposure > max_loss_cap + + # Fix 4: tier_change re-based evaluation - report limits but don't trip + # O9 handles enforcement of unauthorized tier changes + tier_change_event = inputs.get('tier_change_event') + if tier_change_event: + # Re-based: report new tier limits in outputs but don't trip + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'limit', + 'latched': False, + 'reason': 'none', + 'outputs': { + 'cap': max_loss_cap, + 'cap_breached': cap_breached, + 'increases_blocked': increases_blocked + } + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': cap_breached or increases_blocked, + 'kind': 'limit', + 'latched': False, + 'reason': 'breached' if (cap_breached or increases_blocked) else 'none', + 'outputs': { + 'cap': max_loss_cap, + 'cap_breached': cap_breached, + 'increases_blocked': increases_blocked + } + } + + +def evaluate_L1(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """L1: Drawdown reaches D/3 → notify and lock against loosening. + + Kind: interlock + Scope: account + State contribution: none (but locks tier/H/HWM) + Clearing: Clears when drawdown is back under D/3 + """ + bankroll = finite_float(inputs.get('bankroll')) + high_water_mark = finite_float(inputs.get('high_water_mark')) + tier = inputs.get('tier') + + # Fail closed on missing, NaN, inf, bool, or out-of-range inputs + if bankroll is None or high_water_mark is None or bankroll < 0.0 or high_water_mark <= 0.0 or tier is None: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'missing_input', + 'outputs': { + 'locked_against_loosening': True, + 'notify': True + } + } + + # Get tier D and threshold + D = TIER_D.get(tier) + if D is None: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'missing_input', + 'outputs': { + 'locked_against_loosening': True, + 'notify': True + } + } + + threshold = D / 3.0 + + # Calculate drawdown + drawdown = (high_water_mark - bankroll) / high_water_mark if high_water_mark > 0 else 0.0 + + # Check trigger + triggered = drawdown >= threshold + + return { + 'state': 'NORMAL', + 'would_have_tripped': triggered, + 'kind': 'interlock', + 'latched': False, + 'reason': 'drawdown_threshold' if triggered else 'none', + 'outputs': { + 'locked_against_loosening': triggered, + 'notify': triggered + } + } + + +def evaluate_L2(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """L2: Drawdown reaches 2D/3 → NO-NEW-RISK. + + Kind: breaker + Scope: account + State contribution: NO-NEW-RISK + Clearing: Owner re-arms via authorized_events (canonical format per Q6) + """ + # Check for prior latch from canonical format (SUC-12) + prior_latch = cst.get_l2_latch(prior_state) + if prior_latch: + rearm = cst.matches_account_rearm( + authorized_events, 'L2', session=session, as_of=as_of, require_date=True, + ) is not None + + if rearm: + # Q4 short-circuit: re-arm wins, return authorized_rearm WITHOUT re-evaluating + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' + } + + # Stay latched without re-arm + # Stay latched - check for specific latched conditions + flow_event = inputs.get('flow_event') + tier_change_event = inputs.get('tier_change_event') + + # Determine specific latched reason (SUC-12) + if flow_event and flow_event.get('type') == 'deposit': + reason = 'latched_survives_deposit' + elif tier_change_event: + reason = 'latched_survives_tier_change' + else: + reason = 'latched_prior_trip' + + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': reason + } + + # Evaluate trigger + bankroll = finite_float(inputs.get('bankroll')) + high_water_mark = finite_float(inputs.get('high_water_mark')) + tier = inputs.get('tier') + + # Fail closed on missing, NaN, inf, bool, or out-of-range inputs + if bankroll is None or high_water_mark is None or bankroll < 0.0 or high_water_mark <= 0.0 or tier is None: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + + # Get tier D and threshold + D = TIER_D.get(tier) + if D is None: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + + threshold = 2.0 * D / 3.0 + + # Calculate drawdown + drawdown = (high_water_mark - bankroll) / high_water_mark if high_water_mark > 0 else 0.0 + + # Check trigger (inclusive per spec: "reaches 2D/3 (inclusive)") + triggered = drawdown >= threshold + + if not triggered: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } + + # Trip and latch (SUC-12 step 1: specific reason) + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'drawdown_at_2D_over_3' + } + + +def evaluate_L3(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """L3: Drawdown reaches D → DE-RISK to zero, then locked flat. + + Kind: breaker + Scope: account + State contribution: DE-RISK + Clearing: Owner card with 30-day cooling-off; loss record not cleared (canonical per Q6) + """ + # Check for prior latch from canonical format + prior_latch = cst.get_l3_latch(prior_state) + if prior_latch: + rearm = False + cooling_off_days_remaining = 30 + + cur_date_str = cst.canonical_session_date(session, as_of) + trip_date_str = prior_latch.get('trip_session') or prior_latch.get('trip_date') + if cur_date_str and trip_date_str: + try: + days_elapsed = (date.fromisoformat(cur_date_str) - date.fromisoformat(trip_date_str)).days + cooling_off_days_remaining = max(0, 30 - max(0, days_elapsed)) + except ValueError: + cooling_off_days_remaining = 30 + + matched_event = cst.matches_account_rearm( + authorized_events, 'L3', session=session, as_of=as_of, require_date=True + ) + if matched_event is not None: + rearm = True + + if rearm and cooling_off_days_remaining == 0: + # Q4 short-circuit after 30-day cooling-off: clear active lock, preserve loss record + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm', + 'outputs': { + 'cooling_off_days_remaining': 0, + 'locked_flat': False, + 'loss_record_cleared': False + } + } + + # Stay latched + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip', + 'outputs': { + 'cooling_off_days_remaining': cooling_off_days_remaining, + 'locked_flat': True, + 'loss_record_cleared': False + } + } + + bankroll = finite_float(inputs.get('bankroll')) + high_water_mark = finite_float(inputs.get('high_water_mark')) + tier = inputs.get('tier') + + # Fail closed on missing or non-finite inputs + if bankroll is None or high_water_mark is None or bankroll < 0.0 or high_water_mark <= 0.0 or tier is None: + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input', + 'outputs': { + 'cooling_off_days_remaining': 30, + 'locked_flat': True, + 'loss_record_cleared': False + } + } + + # Get tier D + D = TIER_D.get(tier) + if D is None: + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input', + 'outputs': { + 'cooling_off_days_remaining': 30, + 'locked_flat': True, + 'loss_record_cleared': False + } + } + + # Calculate drawdown + drawdown = (high_water_mark - bankroll) / high_water_mark if high_water_mark > 0 else 0.0 + + # Check trigger + triggered = drawdown >= D + + if not triggered: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none', + 'outputs': { + 'cooling_off_days_remaining': 0, + 'locked_flat': False, + 'loss_record_cleared': False + } + } + + # Trip and latch + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'drawdown_threshold', + 'outputs': { + 'cooling_off_days_remaining': 30, + 'locked_flat': True, + 'loss_record_cleared': False + } + } + + +def evaluate_L4(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None, + market_closed: bool = False) -> Dict[str, Any]: + """L4: One-session loss reaches D/10 → NO-NEW-RISK. + + Kind: breaker + Scope: account + State contribution: NO-NEW-RISK + Clearing: Owner acknowledges, not before next session (canonical per Q6) + """ + # Check for prior latch from canonical format + prior_latch = cst.get_account_latch(prior_state, 'L4') + if prior_latch: + rearm = False + matched_event = cst.matches_account_rearm( + authorized_events, 'L4', session=session, as_of=as_of, require_date=True, + ) + if matched_event is not None and not market_closed: + # Next session minimum computed strictly from persisted trading session (never as_of UTC midnight) + cur_date = cst.canonical_session_date(session, as_of) + trip_sess = prior_latch.get('trip_session') + if cur_date and trip_sess and cur_date > trip_sess: + rearm = True + + if rearm: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' + } + + # Stay latched + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + # Evaluate trigger + one_session_loss = finite_float(inputs.get('one_session_loss')) + tier = inputs.get('tier') + + # Fail closed on missing, NaN, inf, bool, negative, or invalid tier + if one_session_loss is None or one_session_loss < 0.0 or tier is None: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + + # Get tier D and threshold + D = TIER_D.get(tier) + if D is None: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + + threshold = D / 10.0 + + # Check trigger + triggered = one_session_loss >= threshold + + if not triggered: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } + + # Trip and latch + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'one_session_loss_threshold' + } + + +def _parse_market_halt_level(raw: Any) -> tuple: + """Validate optional market_halt_level; only None or exact int in {0, 1, 2, 3} is valid.""" + if raw is None: + return None, False + if isinstance(raw, bool) or not isinstance(raw, int) or raw not in (0, 1, 2, 3): + return None, True + return raw, False + + +def evaluate_L5(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], session: str, + as_of: Optional[str] = None) -> Dict[str, Any]: + """L5: Market-wide trading halt Level 1 or 2 → NO-NEW-RISK for rest of session. + + Kind: interlock + Scope: account + State contribution: NO-NEW-RISK + Clearing: Persists through remainder of trading session; clears on subsequent clean session (canonical per Q6) + """ + prior_l5 = cst.get_l5_state(prior_state) + cur_date = cst.canonical_session_date(session, as_of) + + halt_level, invalid_halt_level = _parse_market_halt_level(inputs.get('market_halt_level')) + triggered = halt_level in (1, 2) + + if triggered: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'market_halt_level_1_or_2' + } + + if invalid_halt_level: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'invalid_input' + } + + if prior_l5['active']: + # Same trading session as L5 trip -> remains NO-NEW-RISK for rest of session + if prior_l5['trip_session'] is not None and prior_l5['trip_session'] == cur_date: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'clearing_period' + } + # Legacy synthetic latched L5 without trip_session clears after one clean session + if prior_l5['trip_session'] is None and prior_l5['fresh_session_count'] < 1: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'clearing_period' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock', + 'latched': False, + 'reason': 'none' + } + + +def evaluate_L6(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None, + o3_failed: bool = False, + market_closed: bool = False) -> Dict[str, Any]: + """L6: Market-wide Level 3 halt OR one-session fall ≥10% in either index → HALT. + + Kind: breaker + Scope: account + State contribution: HALT + Clearing: Owner re-arms after reconciliation (canonical per Q6) + """ + prior_latch = cst.get_account_latch(prior_state, 'L6') + if prior_latch: + rearm = ( + (not o3_failed) and + cst.matches_account_rearm( + authorized_events, 'L6', session=session, as_of=as_of, require_date=True, + ) is not None + ) + + if rearm: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' + } + + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + # Evaluate trigger + halt_level, invalid_halt_level = _parse_market_halt_level(inputs.get('market_halt_level')) + index_returns = inputs.get('index_one_session_returns') + + level_3_halt = halt_level == 3 + + # Check ALL indices in index_one_session_returns; never abort past an invalid earlier entry. + # Require >= 2 valid benchmark index returns on non-closed sessions when dict is supplied + # (note: missing.L6 in frozen v2 golden-table.json requires None -> NORMAL until v3 refreeze). + index_fall = False + invalid_index_data = False + missing_index_data = False + if index_returns is not None: + if not isinstance(index_returns, dict): + invalid_index_data = True + else: + if not market_closed and len(index_returns) < 2: + missing_index_data = True + for index in sorted(index_returns.keys()): + ret = index_returns[index] + r_val = finite_float(ret) + if r_val is None: + invalid_index_data = True + elif r_val <= -0.10: + index_fall = True + + if level_3_halt: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'level_3_halt' + } + if index_fall: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'index_fall_10pct' + } + if invalid_halt_level or invalid_index_data or missing_index_data: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'invalid_input' if (invalid_halt_level or invalid_index_data) else 'missing_input' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_ops.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_ops.py new file mode 100644 index 0000000..6ba7e4c --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_ops.py @@ -0,0 +1,1545 @@ +"""Data and operations rows O1-O9, J1 per BRIEF-FUSE-1 §4.3 Table C.""" + +import math +from decimal import Decimal, InvalidOperation +from datetime import datetime, timezone +from typing import Any, Dict, Optional, List +from . import state as st +from . import canonical_state as cst +from .canonical import finite_float + + +def _to_decimal(value: Any) -> Optional[Decimal]: + """Convert finite non-bool numeric value/string to exact Decimal, or return None.""" + if finite_float(value) is None: + return None + try: + return Decimal(value.strip()) if isinstance(value, str) else Decimal(str(value)) + except (InvalidOperation, ValueError): + return None + + +def _resolve_o5_alias( + inputs: Dict[str, Any], + keys: tuple, + kind: str, +) -> tuple: + """Resolve an O5 input alias group uniformly; detect missing/invalid/conflicting values. + + Returns (resolved_value, present_non_none, conflict_or_invalid). + """ + entries = [(k, inputs[k]) for k in keys if k in inputs and inputs[k] is not None] + if not entries: + return None, False, False + parsed = [] + for _, raw in entries: + if kind == 'decimal': + d = _to_decimal(raw) + if d is None: + return None, True, True + parsed.append(d) + elif kind == 'lower_str': + if not isinstance(raw, str) or not raw.strip(): + return None, True, True + parsed.append(raw.strip().lower()) + elif kind == 'str': + if not isinstance(raw, str) or not raw.strip(): + return None, True, True + parsed.append(raw.strip()) + elif kind == 'str_list': + if not isinstance(raw, list) or not all(isinstance(x, str) and x.strip() for x in raw): + return None, True, True + parsed.append(tuple(sorted({x.strip() for x in raw}))) + else: + parsed.append(raw) + first = parsed[0] + if any(item != first for item in parsed[1:]): + return None, True, True + if kind == 'str_list': + return list(first), True, False + return first, True, False + + +def _parse_iso_ts(value: Any) -> Optional[datetime]: + """Parse ISO-8601 timestamp normalized to UTC, or return None.""" + if not isinstance(value, str) or not value.strip(): + return None + try: + dt = datetime.fromisoformat(value.strip()) + except ValueError: + return None + if dt.tzinfo is None: + return dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc) + + +def _is_valid_age(age: Any) -> bool: + """Return True iff age_sessions is a finite non-bool number in [0, 1].""" + val = finite_float(age) + return val is not None and 0.0 <= val <= 1.0 + + +def evaluate_O1(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], session: str, + as_of: Optional[str] = None) -> Dict[str, Any]: + """O1: Required input missing, stale, or invalid → NO-NEW-RISK. + + Kind: interlock + Scope: account + State contribution: NO-NEW-RISK + Clearing: Clears after one session of fresh data + Mechanism B3: fail closed when ANY required source is missing/NaN/stale + """ + # B3: Check source records for missing, non-finite, negative, or stale (> 1 session) + source_records = inputs.get('source_records') + if not isinstance(source_records, dict): + source_records = {} + + # Required source records + required_source_names = [ + 'market_data', + 'index_returns', + 'volatility', + 'positions', + 'broker_reconciliation', + 'session_calendar' + ] + + missing_source_records = [] + missing_toplevel_fields = [] + + for source_name in required_source_names: + source_record = source_records.get(source_name) + if not isinstance(source_record, dict): + missing_source_records.append(source_name) + continue + + if not _is_valid_age(source_record.get('age_sessions')): + missing_source_records.append(source_name) + + # Validate tier unconditionally + if inputs.get('tier') is None: + missing_toplevel_fields.append('tier') + + # Validate required account-level numerical evidence whenever operational/portfolio + # payload is present (removing the 4-field bypass while preserving isolated + # source_records-only SUC-05 source enumeration). + has_operational_payload = ( + 'funds' in inputs or + any(k in inputs for k in ( + 'bankroll', 'high_water_mark', 'joint_exposure', 'max_loss_cap', + 'positions_cash', 'broker_cash', 'index_one_session_returns', + 'proposed_exposure', 'one_session_loss', 'session_calendar_status', + 'exchange_status', 'loaded_policy_hash', 'registered_policy_hash', + )) + ) + + cal_status = inputs.get('session_calendar_status') if 'session_calendar_status' in inputs else inputs.get('calendar_state') + exch_status = inputs.get('exchange_status') + closed_tokens = ('holiday', 'closed', 'market_closed') + open_explicit = (cal_status == 'open' or exch_status == 'open') + is_closed = ( + cal_status in closed_tokens or + exch_status in closed_tokens or + (inputs.get('market_closed') is True and cal_status is None and exch_status is None) + ) + if open_explicit and not (cal_status in closed_tokens or exch_status in closed_tokens): + is_closed = False + + if has_operational_payload: + required_values = ['bankroll', 'high_water_mark', 'joint_exposure', 'max_loss_cap'] + for key in required_values: + value = inputs.get(key) + if value is None or isinstance(value, bool): + missing_toplevel_fields.append(key) + continue + try: + val = float(value) + if math.isnan(val) or math.isinf(val) or val < 0: + missing_toplevel_fields.append(key) + except (TypeError, ValueError): + missing_toplevel_fields.append(key) + + if not is_closed and ( + 'index_one_session_returns' in inputs or + cal_status == 'open' or + exch_status == 'open' + ): + idx_rets = inputs.get('index_one_session_returns') + if ( + not isinstance(idx_rets, dict) or + len(idx_rets) < 2 or + any(finite_float(v) is None for v in idx_rets.values()) + ): + missing_toplevel_fields.append('index_one_session_returns') + + # B3: If ANY source or field is missing/stale/non-finite, fail closed + has_issues = bool(missing_source_records or missing_toplevel_fields) + + if has_issues: + if len(missing_source_records) == 1 and not missing_toplevel_fields and not has_operational_payload: + reason = f'missing_required_source_{missing_source_records[0]}' + else: + reason = 'stale_or_missing_input' + + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': reason + } + + # Same-session stale->fresh does NOT clear within the same trading session + cur_date = cst.canonical_session_date(session, as_of) + prior_o1 = cst.get_o1_fresh_state(prior_state) + if prior_o1.get('last_tripped_session') is not None and prior_o1.get('last_tripped_session') == cur_date: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'clearing_period' + } + + # All required inputs present and fresh (SUC-05 step 7) + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock', + 'latched': False, + 'reason': 'none' + } + + +VALID_CALENDAR_STATUSES = {'open', 'closed', 'holiday', 'half_day', 'half_day_cutoff', 'market_closed'} +CLOSED_CALENDAR_STATUSES = {'closed', 'holiday', 'half_day', 'half_day_cutoff', 'market_closed'} + + +def evaluate_O2(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """O2: Session calendar closed/holiday/disagreement → no order. + + Kind: interlock + Scope: account + State contribution: Order suppression (no control state) + """ + # Evaluate trigger + calendar_status = inputs.get('session_calendar_status') + exchange_status = inputs.get('exchange_status') + + # Fail closed on missing inputs + if calendar_status is None or exchange_status is None: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'missing_input' + } + + # Whitelist valid calendar/exchange status tokens (reject unrecognized tokens like "n/a") + if ( + not isinstance(calendar_status, str) or + not isinstance(exchange_status, str) or + calendar_status not in VALID_CALENDAR_STATUSES or + exchange_status not in VALID_CALENDAR_STATUSES + ): + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'invalid_input' + } + + # Check triggers (Fix 3: half_day also uses market_closed reason) + is_market_closed = calendar_status in CLOSED_CALENDAR_STATUSES or exchange_status in ('closed', 'holiday', 'market_closed') + disagreement = calendar_status != exchange_status + + if is_market_closed or disagreement: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'market_closed' if is_market_closed else 'calendar_disagreement' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock', + 'latched': False, + 'reason': 'none' + } + + +def evaluate_O3(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """O3: Position/cash mismatch beyond tolerance → HALT. + + Kind: breaker + Scope: account + State contribution: HALT + Clearing: Owner re-arms after reconciliation + """ + # Check for prior latch (canonical format per Q6) + prior_latch = cst.get_account_latch(prior_state, 'O3') + if prior_latch: + rearm = cst.matches_account_rearm( + authorized_events, 'O3', session=session, as_of=as_of, require_date=True, + ) is not None + + if not rearm: + # Stay latched + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + # Evaluate trigger using positions and broker reconciliation (explicit tolerance required) + positions_cash = finite_float(inputs.get('positions_cash')) + broker_cash = finite_float(inputs.get('broker_cash')) + reconciliation_tolerance = finite_float(inputs.get('reconciliation_tolerance')) + + # Fail closed if cash or fund positions or tolerance is missing/empty/non-finite/negative + if ( + 'funds' not in inputs or + not isinstance(inputs.get('funds'), dict) or + len(inputs['funds']) == 0 or + positions_cash is None or broker_cash is None or + reconciliation_tolerance is None or reconciliation_tolerance < 0.0 + ): + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + + funds = inputs['funds'] + + # Check cash reconciliation + cash_mismatch = abs(positions_cash - broker_cash) > reconciliation_tolerance + + # Check fund position reconciliation (BOTH share counts and market values required for each fund) + position_mismatch = False + if not isinstance(funds, dict): + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + for symbol, fund_data in sorted(funds.items()): + if not isinstance(fund_data, dict): + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + ledger_value = finite_float(fund_data.get('ledger_value')) + broker_value = finite_float(fund_data.get('broker_value')) + share_count = finite_float(fund_data.get('share_count')) + broker_pos = finite_float(fund_data.get('broker_position')) + if ledger_value is None or broker_value is None or share_count is None or broker_pos is None: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + if abs(ledger_value - broker_value) > reconciliation_tolerance or share_count != broker_pos: + position_mismatch = True + break + + # Check trigger + if cash_mismatch or position_mismatch: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'reconciliation_mismatch' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } + + +def evaluate_O4(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], symbol: str, + session: Optional[str] = None, as_of: Optional[str] = None) -> Dict[str, Any]: + """O4: Order timeout → ORDER-UNKNOWN for that symbol. + + Kind: interlock_or_breaker + Scope: symbol + State contribution: ORDER-UNKNOWN + Clearing: Clears on definitive status for the ORIGINAL order or owner Q4 re-arm; + otherwise latches + Mechanism B6: ORDER-UNKNOWN keyed to original order identity + """ + scope = f'symbol:{symbol}' + + # B6: Check for prior ORDER-UNKNOWN with original order identity (canonical per Q6) + restart_marker = inputs.get('restart_marker', False) + prior_pending = cst.get_o4_pending_order(prior_state, symbol) + + # Get current pending order status safely even if pending_orders is None or malformed + po_map = inputs.get('pending_orders') + raw_po = po_map.get(symbol) if isinstance(po_map, dict) else None + pending_order = inputs['o4_pending_order'] if 'o4_pending_order' in inputs else raw_po + + # If no pending order input (or empty dict) + if pending_order is None or (isinstance(pending_order, dict) and not pending_order): + # B6: Check if we have a prior pending order (allow dated symbol-scoped Q4 re-arm to clear) + if prior_pending: + if cst.matches_symbol_rearm( + authorized_events, 'O4', symbol, session=session, as_of=as_of, require_date=True + ) is not None: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'authorized_rearm', + 'symbol': symbol + } + return { + 'state': 'ORDER-UNKNOWN', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'awaiting_original_order_status', + 'symbol': symbol, + 'original_order_id': prior_pending['original_order_id'] + } + # No pending order + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'none', + 'symbol': symbol + } + + # Validate pending_order structure and assign durable unidentified_order_id when absent + if not isinstance(pending_order, dict): + return { + 'state': 'ORDER-UNKNOWN', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': True, + 'reason': 'missing_input', + 'symbol': symbol, + 'original_order_id': prior_pending['original_order_id'] if prior_pending else f'unidentified_order_{symbol}', + } + + order_id = pending_order.get('order_id') + status = pending_order.get('status') + timed_out = pending_order.get('timeout', False) or pending_order.get('timed_out', False) + terminal_statuses = ('filled', 'cancelled', 'canceled', 'rejected', 'expired') + has_valid_order_id = isinstance(order_id, str) and bool(order_id.strip()) + is_terminal = status in terminal_statuses + + # B6: If we have a prior pending order, check if this is the same order + if prior_pending: + prior_order_id = prior_pending.get('original_order_id') + unidentified_prior = isinstance(prior_order_id, str) and prior_order_id.startswith('unidentified_order_') + + # Missing/mismatched order_id keeps the original order restricted in ORDER-UNKNOWN + if unidentified_prior or not has_valid_order_id or order_id != prior_order_id: + reason = 'awaiting_original_order_status_after_restart' if restart_marker else 'awaiting_original_order_status' + return { + 'state': 'ORDER-UNKNOWN', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': reason, + 'symbol': symbol, + 'original_order_id': prior_order_id + } + + # Same order - check if we have definitive terminal status + # B6: Only recognized terminal statuses clear ORDER-UNKNOWN (ignore unvalidated terminal flags) + if is_terminal: + # Clears (SUC-09 step 4) + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'original_order_terminal_status_received', + 'symbol': symbol + } + + # B6: Unrecognized status does NOT clear ORDER-UNKNOWN (SUC-09 step 3) + # Still waiting for definitive status + is_unrecognized = not is_terminal and status not in ['pending', 'submitted', 'accepted'] + reason = 'unrecognized_status_for_original_order' if is_unrecognized else 'awaiting_original_order_status' + if restart_marker: + reason = 'awaiting_original_order_status_after_restart' + + return { + 'state': 'ORDER-UNKNOWN', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': reason, + 'symbol': symbol, + 'original_order_id': prior_order_id + } + + # No prior pending: identified order already reporting definitive terminal status does not enter timeout + if has_valid_order_id and is_terminal: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'none', + 'symbol': symbol + } + + # No prior pending - check if current order timed out (SUC-09 step 1) + if timed_out: + eff_order_id = order_id if (isinstance(order_id, str) and order_id.strip()) else f'unidentified_order_{symbol}' + return { + 'state': 'ORDER-UNKNOWN', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'order_timeout', + 'symbol': symbol, + 'original_order_id': eff_order_id + } + + # No timeout + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'none', + 'symbol': symbol + } + + +def evaluate_O5(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], session: str, + as_of: Optional[str] = None) -> Dict[str, Any]: + """O5: Pre-trade limit violation → reject; third rejection in session → HALT. + + Kind: breaker + Scope: account + State contribution: HALT on third rejection + Clearing: Owner re-arms + Mechanism B2: rejection count is per-session (canonical format per Q6), + third rejection latches HALT + Required inputs: o5_collar (or fail closed) + """ + # Get prior O5 state from canonical format + o5_state = cst.get_o5_state(prior_state) + prior_latched = o5_state['latched'] + prior_count = o5_state['rejection_count'] + last_rejection_session = o5_state['last_rejection_session'] + + # Check for prior latch (SUC-04: third rejection); clear on Q4 rearm then evaluate current session + rearm_cleared = False + if prior_latched: + rearm = cst.matches_account_rearm( + authorized_events, 'O5', session=session, as_of=as_of, require_date=True + ) is not None + + if not rearm: + # Stay latched (SUC-04 step 4) + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_third_rejection', + 'rejection_count_this_session': prior_count # Emit per Q6 + } + + # Q4: authorized re-arm clears O5 latch and counter, then still validates current-session order inputs + rearm_cleared = True + prior_count = 0 + last_rejection_session = session + + # B2: New session resets a free counter; latch survives + if last_rejection_session != session: + rejection_count = 0 + else: + rejection_count = prior_count + + # Evaluate trigger - fail closed if collar unresolved or invalid (NaN/inf/bool/negative) per §4.5 / A11 + o5_collar = inputs.get('o5_collar') + if o5_collar is None or o5_collar == 'unresolved': + new_count = rejection_count + 1 + if new_count >= 3: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'third_rejection_in_session', + 'rejection_count_this_session': new_count + } + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': False, + 'reason': 'unresolved_fail_closed', + 'rejection_count_this_session': new_count + } + + collar_pct = finite_float(o5_collar) + if collar_pct is None or collar_pct < 0.0: + new_count = rejection_count + 1 + if new_count >= 3: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'third_rejection_in_session', + 'rejection_count_this_session': new_count + } + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': False, + 'reason': 'invalid_input', + 'rejection_count_this_session': new_count + } + + # Check other pre-trade limits via unified alias resolution + exact Decimal arithmetic + violations = [] + + symbol, symbol_present, symbol_conflict = _resolve_o5_alias(inputs, ('o5_symbol', 'symbol'), 'str') + whitelist, whitelist_present, whitelist_conflict = _resolve_o5_alias( + inputs, ('symbol_whitelist', 'o5_symbol_whitelist'), 'str_list' + ) + order_size, qty_present, qty_conflict = _resolve_o5_alias( + inputs, ('o5_order_size', 'order_size', 'o5_order_qty', 'order_qty', 'qty'), 'decimal' + ) + side, side_present, side_conflict = _resolve_o5_alias(inputs, ('o5_side', 'side', 'order_side'), 'lower_str') + ov_dec, ov_present, ov_conflict = _resolve_o5_alias(inputs, ('o5_order_value', 'order_value'), 'decimal') + unit_price_dec, unit_price_present, unit_price_conflict = _resolve_o5_alias( + inputs, + ('o5_order_price', 'o5_limit_price', 'limit_price', 'order_price', 'unit_price', 'o5_unit_price', 'price'), + 'decimal', + ) + ref_price_dec, ref_price_present, ref_price_conflict = _resolve_o5_alias( + inputs, ('o5_reference_price', 'reference_price'), 'decimal' + ) + account, acct_present, acct_conflict = _resolve_o5_alias(inputs, ('account', 'o5_account'), 'str') + account_whitelist, acct_wl_present, acct_wl_conflict = _resolve_o5_alias( + inputs, ('account_whitelist', 'o5_account_whitelist'), 'str_list' + ) + + order_present = any(( + symbol_present, symbol_conflict, + qty_present, qty_conflict, + side_present, side_conflict, + ov_present, ov_conflict, + unit_price_present, unit_price_conflict, + ref_price_present, ref_price_conflict, + )) + + explicit_null_symbol_whitelist = ( + ('symbol_whitelist' in inputs and inputs['symbol_whitelist'] is None) or + ('o5_symbol_whitelist' in inputs and inputs['o5_symbol_whitelist'] is None) + ) + if not whitelist_present and not whitelist_conflict and not explicit_null_symbol_whitelist: + whitelist = ['TQQQ', 'SOXL'] + empty_explicit_symbol_whitelist = ( + (whitelist_present and isinstance(whitelist, list) and len(whitelist) == 0) + and order_present + ) + if ( + symbol_conflict or + whitelist_conflict or + explicit_null_symbol_whitelist or + empty_explicit_symbol_whitelist or + (order_present and (symbol is None or not symbol.strip())) or + (symbol is not None and (not isinstance(whitelist, list) or symbol not in whitelist)) + ): + violations.append('symbol_not_whitelisted') + + # Fail closed on conflicting, non-finite, or <= 0 quantities + if qty_conflict or (qty_present and (order_size is None or order_size <= Decimal('0'))): + violations.append('invalid_order_size') + explicit_null_whitelist = ( + ('account_whitelist' in inputs and inputs['account_whitelist'] is None) or + ('o5_account_whitelist' in inputs and inputs['o5_account_whitelist'] is None) + ) + invalid_whitelist = ( + acct_wl_conflict or + not isinstance(account_whitelist, list) or + not any(isinstance(a, str) and a.strip() for a in account_whitelist) + ) + explicit_null_account = ( + ('account' in inputs and inputs['account'] is None) or + ('o5_account' in inputs and inputs['o5_account'] is None) + ) + if ( + acct_conflict or + explicit_null_whitelist or + (acct_wl_present and invalid_whitelist) or + (acct_present and (invalid_whitelist or account not in account_whitelist)) or + (order_present and (not acct_present or explicit_null_account or invalid_whitelist or account not in account_whitelist)) + ): + violations.append('account_not_whitelisted') + + # Long only: require explicit buy/sell direction on active orders; allow reducing sells within existing long position + if side_conflict or (order_present and side is None): + violations.append('not_long_only') + elif side is not None: + if side == 'buy': + pass + elif side == 'sell': + funds_map = inputs.get('funds') + sym_data = funds_map.get(symbol) if (isinstance(funds_map, dict) and symbol is not None) else None + held_raw = None + if isinstance(sym_data, dict): + held_raw = sym_data.get('share_count') + if held_raw is None: + held_raw = sym_data.get('position') + held_shares_dec = _to_decimal(held_raw) + if not ( + not qty_conflict and + order_size is not None and order_size > Decimal('0') and + held_shares_dec is not None and held_shares_dec > Decimal('0') and + order_size <= held_shares_dec + ): + violations.append('not_long_only') + else: + violations.append('not_long_only') + + # Within settled cash (canonical 'settled_cash' wins cleanly over 'o5_settled_cash'; exact Decimal arithmetic) + eff_price_dec = ( + unit_price_dec + if (unit_price_present and not unit_price_conflict and unit_price_dec is not None) + else ref_price_dec + ) + derived_notional = None + notional_invalid = False + if (qty_present or qty_conflict) and (unit_price_present or unit_price_conflict or ref_price_present or ref_price_conflict): + if ( + qty_conflict or unit_price_conflict or ref_price_conflict or + order_size is None or order_size <= Decimal('0') or + eff_price_dec is None or eff_price_dec < Decimal('0') + ): + notional_invalid = True + else: + derived_notional = order_size * eff_price_dec + + settled_cash_raw = inputs['settled_cash'] if 'settled_cash' in inputs else inputs.get('o5_settled_cash') + sc_dec = _to_decimal(settled_cash_raw) + explicit_buy = side_conflict or (side == 'buy') or (side is None and (qty_present or qty_conflict)) + + if ov_conflict or (ov_present and (ov_dec is None or ov_dec < Decimal('0'))): + violations.append('exceeds_settled_cash' if side != 'sell' else 'invalid_order_value') + elif side != 'sell': + if notional_invalid or unit_price_conflict or ref_price_conflict: + violations.append('exceeds_settled_cash') + elif ov_present or derived_notional is not None: + if explicit_buy and ov_dec is not None and ( + ov_dec <= Decimal('0') or + (derived_notional is not None and ov_dec < derived_notional) + ): + violations.append('exceeds_settled_cash') + else: + if ov_dec is not None and derived_notional is not None: + eff_order_val = max(ov_dec, derived_notional) + elif ov_dec is not None: + eff_order_val = ov_dec + else: + eff_order_val = derived_notional + if eff_order_val is None or sc_dec is None or sc_dec < Decimal('0') or eff_order_val > sc_dec: + violations.append('exceeds_settled_cash') + elif explicit_buy: + violations.append('exceeds_settled_cash') + + # Maximum order size (enforce explicit qty AND implied_qty = order_value / eff_price whenever order_value or no qty) + max_order_size_val, msize_present, msize_conflict = _resolve_o5_alias( + inputs, ('o5_max_order_size', 'max_order_size'), 'decimal' + ) + if msize_conflict or (msize_present and (max_order_size_val is None or max_order_size_val < Decimal('0'))): + violations.append('exceeds_max_order_size') + elif max_order_size_val is not None and (order_present or qty_present or qty_conflict): + qty_bad = ( + (qty_present or qty_conflict) and + (qty_conflict or order_size is None or order_size <= Decimal('0') or order_size > max_order_size_val) + ) + ov_bad = ( + (ov_present or ov_conflict or not (qty_present or qty_conflict)) and + ( + ov_conflict or not ov_present or ov_dec is None or ov_dec <= Decimal('0') or + unit_price_conflict or ref_price_conflict or + eff_price_dec is None or eff_price_dec <= Decimal('0') or + ov_dec > max_order_size_val * eff_price_dec + ) + ) + if qty_bad or ov_bad: + violations.append('exceeds_max_order_size') + + # Maximum orders per session (fail closed on missing/null counter when order_present, or conflicting/invalid values) + orders_today, orders_present, orders_conflict = _resolve_o5_alias( + inputs, ('o5_orders_today', 'session_order_count', 'orders_today'), 'decimal' + ) + max_orders, max_orders_present, max_orders_conflict = _resolve_o5_alias( + inputs, ('o5_max_orders_per_session', 'max_orders_per_session'), 'decimal' + ) + if ( + orders_conflict or max_orders_conflict or + (orders_present and (orders_today is None or orders_today < Decimal('0'))) or + (max_orders_present and (max_orders is None or max_orders < Decimal('0'))) + ): + violations.append('exceeds_max_orders') + elif max_orders is not None: + if order_present and not orders_present: + violations.append('exceeds_max_orders') + else: + ot = orders_today if orders_present else Decimal('0') + if ot >= max_orders: + violations.append('exceeds_max_orders') + + # Turnover limit (fail closed on missing/null counter when order_present, invalid aliases, or projected turnover overrun) + turnover_today, turnover_present, turnover_conflict = _resolve_o5_alias( + inputs, ('o5_turnover_today', 'session_turnover', 'turnover_today'), 'decimal' + ) + max_turnover, max_turnover_present, max_turnover_conflict = _resolve_o5_alias( + inputs, ('o5_max_turnover_per_session', 'max_turnover_per_session'), 'decimal' + ) + if ( + turnover_conflict or max_turnover_conflict or + (turnover_present and (turnover_today is None or turnover_today < Decimal('0'))) or + (max_turnover_present and (max_turnover is None or max_turnover < Decimal('0'))) + ): + violations.append('exceeds_max_turnover') + elif max_turnover is not None: + if order_present: + if not turnover_present: + violations.append('exceeds_max_turnover') + else: + tt = turnover_today + if ov_dec is not None and derived_notional is not None: + proposed_notional = max(ov_dec, derived_notional) + elif ov_dec is not None: + proposed_notional = ov_dec + else: + proposed_notional = derived_notional + if ( + ov_conflict or + (ov_present and (ov_dec is None or ov_dec < Decimal('0'))) or + qty_conflict or + (qty_present and (order_size is None or order_size <= Decimal('0'))) or + notional_invalid or unit_price_conflict or ref_price_conflict or + proposed_notional is None or proposed_notional < Decimal('0') or + (tt + proposed_notional) > max_turnover + ): + violations.append('exceeds_max_turnover') + elif turnover_present and turnover_today > max_turnover: + violations.append('exceeds_max_turnover') + + # Price collar (always enforce on active orders via exact Decimal arithmetic against collar_pct) + if order_present or unit_price_present or unit_price_conflict or ref_price_present or ref_price_conflict: + collar_dec = _to_decimal(o5_collar) + if ( + unit_price_conflict or ref_price_conflict or + unit_price_dec is None or ref_price_dec is None or + unit_price_dec <= Decimal('0') or ref_price_dec <= Decimal('0') or + collar_dec is None or collar_dec < Decimal('0') + ): + violations.append('invalid_price') + else: + lower_bound = ref_price_dec * (Decimal('1') - collar_dec) + upper_bound = ref_price_dec * (Decimal('1') + collar_dec) + if unit_price_dec < lower_bound or unit_price_dec > upper_bound: + violations.append('outside_price_collar') + + # If any violations, count as rejection + if violations: + new_count = rejection_count + 1 + + if new_count >= 3: + # Third rejection - latch HALT (SUC-04) + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'third_rejection_in_session', + 'rejection_count_this_session': new_count # Emit per Q6 + } + + # First or second rejection + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': False, + 'reason': 'pre_trade_limit_violation', + 'rejection_count_this_session': new_count # Emit per Q6 + } + + # No violations (preserve session rejection count across intervening passing checks) + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' if rearm_cleared else 'none', + 'rejection_count_this_session': rejection_count + } + + +def evaluate_O6(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """O6: Policy/config hash mismatch → HALT. + + Kind: breaker + Scope: account + State contribution: HALT + Clearing: Owner re-arms + """ + # Check for prior latch (canonical format per Q6) + prior_latch = cst.get_account_latch(prior_state, 'O6') + if prior_latch: + rearm = cst.matches_account_rearm( + authorized_events, 'O6', session=session, as_of=as_of, require_date=True, + ) is not None + + if not rearm: + # Stay latched + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + # Evaluate trigger - require non-empty string policy hashes + loaded_hash = inputs.get('loaded_policy_hash') + registered_hash = inputs.get('registered_policy_hash') + + # Fail closed on missing or blank/non-string policy hashes + if ( + not isinstance(loaded_hash, str) or not loaded_hash.strip() or + not isinstance(registered_hash, str) or not registered_hash.strip() + ): + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'missing_input' + } + + # Check trigger + if loaded_hash != registered_hash: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'policy_hash_mismatch' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } + + +def evaluate_O7(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], as_of: Optional[str] = None, + session: Optional[str] = None) -> Dict[str, Any]: + """O7: Dead-man's switch → NO-NEW-RISK until human re-arm (§4.3 / spec.json:262). + + Kind: breaker + Scope: account + State contribution: NO-NEW-RISK + Clearing: Human re-arm + """ + # Check for prior latch (canonical format per Q6) + prior_latch = cst.get_account_latch(prior_state, 'O7') + if prior_latch: + rearm = cst.matches_account_rearm( + authorized_events, 'O7', session=session, as_of=as_of, require_date=True + ) is not None + + if rearm: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' + } + + # Stay latched at account-level NO-NEW-RISK + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + # Evaluate trigger: explicit silence flags OR missing/invalid/stale heartbeat > 1 scheduled_interval + runtime_silent = bool(inputs.get('o7_runtime_silent', False)) + monitor_silent = bool(inputs.get('o7_monitor_silent', False)) + + heartbeat_stale = False + raw_hb = inputs.get('last_heartbeat') + raw_interval = inputs.get('scheduled_interval') + hb_dt = _parse_iso_ts(raw_hb) + as_of_dt = _parse_iso_ts(as_of) + interval = finite_float(raw_interval) + if hb_dt is None or as_of_dt is None or interval is None or interval <= 0.0: + heartbeat_stale = True + else: + elapsed = (as_of_dt - hb_dt).total_seconds() + if elapsed < 0.0 or elapsed > interval: + heartbeat_stale = True + + # Check trigger + if runtime_silent or monitor_silent or heartbeat_stale: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'dead_mans_switch' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none' + } + + +def evaluate_O8(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """O8: Kill switch → HALT. + + Kind: owner + Scope: account + State contribution: HALT + Clearing: Owner command via authorized_events + """ + events_list = [] + if isinstance(authorized_events, list): + events_list = authorized_events + elif isinstance(authorized_events, dict): + events_list = authorized_events.get('account', []) + + # Check for active owner kill_switch command in authorized_events + kill_command = False + for event in events_list: + if not isinstance(event, dict) or event.get('type') != 'kill_switch': + continue + if event.get('fund') or event.get('symbol'): + continue + if 'scope' in event and event.get('scope') != 'account': + continue + if not cst.event_date_matches(event, session=session, as_of=as_of, require_date=False): + continue + kill_command = True + break + + if kill_command: + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'owner', + 'latched': True, + 'reason': 'kill_switch' + } + + # Check persisted O8 latch (requires explicit Q4-validated clear/rearm event) + prior_latch = cst.get_account_latch(prior_state, 'O8') + if prior_latch: + cleared = cst.matches_o8_clear( + authorized_events, session=session, as_of=as_of, require_date=True + ) is not None + if cleared: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'owner', + 'latched': False, + 'reason': 'authorized_rearm' + } + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'owner', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'owner', + 'latched': False, + 'reason': 'none' + } + + +def evaluate_O9(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """O9: Parameter change without owner card → HALT. + + Kind: breaker + Scope: account + State contribution: HALT + Clearing: Owner re-arms + """ + # Check for prior latch (canonical format per Q6); clear on Q4 rearm then evaluate current session + rearm_cleared = False + prior_latch = cst.get_account_latch(prior_state, 'O9') + if prior_latch: + rearm = cst.matches_account_rearm( + authorized_events, 'O9', session=session, as_of=as_of, require_date=True + ) is not None + + if not rearm: + # Stay latched + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip' + } + + rearm_cleared = True + + # Check for parameter changes (Fix 4: tier_change detection) + change_descriptors = inputs.get('o9_change_descriptors') + tier_change_event = inputs.get('tier_change_event') + + # Check for any change signal + has_change = bool(change_descriptors) or bool(tier_change_event) + + if not has_change: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' if rearm_cleared else 'none' + } + + # Validate each privileged change kind independently against authorized_events + events_list = [] + if isinstance(authorized_events, list): + events_list = authorized_events + elif isinstance(authorized_events, dict): + events_list = authorized_events.get('account', []) + + def _parse_event_scope(event_or_desc: Dict[str, Any]) -> tuple: + """Return (ok, target_scope_or_none) for card or descriptor scope tags.""" + ev_fund = event_or_desc.get('fund') + ev_symbol = event_or_desc.get('symbol') + has_scope = 'scope' in event_or_desc + ev_scope = event_or_desc.get('scope') + if ev_fund is not None and (not isinstance(ev_fund, str) or not ev_fund.strip()): + return False, None + if ev_symbol is not None and (not isinstance(ev_symbol, str) or not ev_symbol.strip()): + return False, None + if ev_fund is not None and ev_symbol is not None and ev_fund.strip() != ev_symbol.strip(): + return False, None + target = ev_fund.strip() if isinstance(ev_fund, str) else (ev_symbol.strip() if isinstance(ev_symbol, str) else None) + if has_scope: + if not isinstance(ev_scope, str) or not ev_scope.strip(): + return False, None + sc = ev_scope.strip() + if sc == 'account': + if target is not None: + return False, None + elif sc.startswith('fund:') or sc.startswith('symbol:'): + sc_target = sc.split(':', 1)[1].strip() + if not sc_target or (target is not None and target != sc_target): + return False, None + target = sc_target + else: + return False, None + return True, target + + def _card_row_date_ok(event: Any) -> bool: + if not isinstance(event, dict): + return False + if 'row' in event or 'row_id' in event: + if not cst.event_matches_row(event, 'O9'): + return False + return cst.event_date_matches(event, session=session, as_of=as_of, require_date=True) + + def _tier_card_scope_date_ok(event: Any) -> bool: + if not _card_row_date_ok(event): + return False + if event.get('fund') or event.get('symbol'): + return False + if 'scope' in event and event.get('scope') != 'account': + return False + return True + + def _param_card_scope_date_ok(event: Any) -> tuple: + if not _card_row_date_ok(event): + return False, None + return _parse_event_scope(event) + + def _extract_tier_target(obj: Any) -> Optional[str]: + if not isinstance(obj, dict): + return None + for k in ('to', 'new', 'target', 'new_tier'): + v = obj.get(k) + if isinstance(v, str) and v.strip(): + return v.strip() + return None + + tier_authorized = True + if tier_change_event: + target_tier = _extract_tier_target(tier_change_event) + live_tier = inputs.get('tier') + from_tier = tier_change_event.get('from') if isinstance(tier_change_event, dict) else None + tier_live_ok = ( + isinstance(target_tier, str) and + isinstance(live_tier, str) and + live_tier.strip() == target_tier + ) + tier_authorized = tier_live_ok and any( + _tier_card_scope_date_ok(event) and + event.get('type') == 'tier_change_card' and + event.get('from') is not None and + event.get('from') == from_tier and + _extract_tier_target(event) == target_tier + for event in events_list + ) + + def _extract_descriptor_targets_strict(desc: Any, default_scope: Optional[str] = None) -> Optional[List[tuple]]: + if isinstance(desc, list): + if not desc: + return None + targets: List[tuple] = [] + for item in desc: + item_targets = _extract_descriptor_targets_strict(item, default_scope=default_scope) + if not item_targets: + return None + targets.extend(item_targets) + return targets + if not isinstance(desc, dict) or not desc: + return None + + scope_ok, local_scope = _parse_event_scope(desc) + if not scope_ok: + return None + if default_scope is not None and local_scope is not None and default_scope != local_scope: + return None + eff_scope = local_scope if local_scope is not None else default_scope + + if any(k in desc for k in ('param', 'parameter', 'field', 'name')): + param_name = desc.get('param') or desc.get('parameter') or desc.get('field') or desc.get('name') + if not isinstance(param_name, str) or not param_name.strip(): + return None + pname = param_name.strip() + if pname in ('limits', 'funds'): + return None + for val_key in ('to', 'new_value', 'new', 'target', 'value'): + if val_key in desc and desc[val_key] is not None: + return [(pname, desc[val_key], eff_scope)] + return None + + targets: List[tuple] = [] + meta_keys = {'from', 'card_id', 'reason', 'note', 'fund', 'symbol', 'scope', 'session', 'as_of'} + for k, v in desc.items(): + if k in meta_keys: + continue + if k == 'limits': + if not isinstance(v, dict) or not v: + return None + sub = _extract_descriptor_targets_strict(v, default_scope=eff_scope) + if not sub: + return None + targets.extend(sub) + elif k == 'funds': + if not isinstance(v, dict) or not v: + return None + for f_sym, f_val in v.items(): + if not isinstance(f_sym, str) or not f_sym.strip() or not isinstance(f_val, dict) or not f_val: + return None + if eff_scope is not None and eff_scope != f_sym.strip(): + return None + sub = _extract_descriptor_targets_strict(f_val, default_scope=f_sym.strip()) + if not sub: + return None + targets.extend(sub) + elif isinstance(v, dict): + found_val = False + for val_key in ('to', 'new_value', 'new', 'target', 'value'): + if val_key in v and v[val_key] is not None: + targets.append((k, v[val_key], eff_scope)) + found_val = True + break + if not found_val: + return None + else: + if v is None: + return None + targets.append((k, v, eff_scope)) + return targets if targets else None + + def _single_card_covers_descriptors(card_desc: Any, required: Any) -> bool: + def _dict_covers(c_item: Any, r_item: Any) -> bool: + if not isinstance(c_item, dict) or not isinstance(r_item, dict): + return False + for k, v in r_item.items(): + if k in ('fund', 'symbol', 'scope'): + continue + if k not in c_item or c_item[k] != v: + return False + return True + + if isinstance(required, dict): + return _dict_covers(card_desc, required) + if isinstance(required, list): + if isinstance(card_desc, list): + return all(any(_dict_covers(c_item, req_item) for c_item in card_desc) for req_item in required) + return len(required) == 1 and _dict_covers(card_desc, required[0]) + return card_desc == required + + account_only_fields = { + 'max_loss_cap', 'tier_joint_cap', 'tier', 'high_water_mark', + 'h_value', 'H', 'tier_loss_budget_D', 'o5_collar', 'reconciliation_tolerance', + } + overridable_policy_fields = { + 'v7_spread_width', 'v5_tolerance', 'v6_threshold', + } + known_o9_policy_fields = account_only_fields | overridable_policy_fields + + def _values_match(live_val: Any, target_val: Any) -> bool: + if isinstance(live_val, bool) or isinstance(target_val, bool): + return type(live_val) is type(target_val) and live_val == target_val + t_num = finite_float(target_val) + l_num = finite_float(live_val) + if t_num is not None or l_num is not None: + return t_num is not None and l_num is not None and t_num == l_num + return live_val == target_val + + def _targets_cover(card_targets: List[tuple], req_targets: List[tuple]) -> bool: + for req_field, req_val, req_scope in req_targets: + if not any( + c_field == req_field and c_scope == req_scope and _values_match(c_val, req_val) + for c_field, c_val, c_scope in card_targets + ): + return False + return True + + def _targets_match_live_inputs(targets: List[tuple]) -> bool: + funds_map = inputs.get('funds') if isinstance(inputs.get('funds'), dict) else {} + for field_name, target_val, target_scope in targets: + if target_scope is not None: + if field_name in account_only_fields: + return False + if funds_map and target_scope not in funds_map: + return False + fund_dict = funds_map.get(target_scope) + if field_name == 'v6_threshold': + if not isinstance(fund_dict, dict) or field_name not in fund_dict: + return False + live_val = fund_dict[field_name] + elif isinstance(fund_dict, dict) and field_name in fund_dict: + live_val = fund_dict[field_name] + elif field_name in inputs: + live_val = inputs[field_name] + elif field_name in known_o9_policy_fields: + return False + else: + continue + if not _values_match(live_val, target_val): + return False + else: + if field_name == 'v6_threshold': + if not funds_map: + return False + if not all( + isinstance(f_data, dict) and field_name in f_data and _values_match(f_data[field_name], target_val) + for f_data in funds_map.values() + ): + return False + continue + if field_name in inputs: + live_val = inputs[field_name] + if not _values_match(live_val, target_val): + return False + elif field_name in overridable_policy_fields: + # Without a top-level value, EVERY configured fund must explicitly match target_val + if not funds_map: + return False + if not all( + isinstance(f_data, dict) and field_name in f_data and _values_match(f_data[field_name], target_val) + for f_data in funds_map.values() + ): + return False + elif field_name in known_o9_policy_fields: + return False + + if field_name in overridable_policy_fields: + for f_data in funds_map.values(): + if isinstance(f_data, dict) and field_name in f_data: + if not _values_match(f_data[field_name], target_val): + return False + return True + + params_authorized = True + if change_descriptors: + # Require explicit target value on every descriptor AND one Q4-validated card matching effective runtime values + desc_targets = _extract_descriptor_targets_strict(change_descriptors) + if not desc_targets: + params_authorized = False + else: + params_authorized = False + for event in events_list: + card_ok, card_scope = _param_card_scope_date_ok(event) + if not card_ok or event.get('type') != 'parameter_change_card': + continue + card_desc = event.get('change_descriptors') + card_targets = _extract_descriptor_targets_strict(card_desc, default_scope=card_scope) + if not card_targets: + continue + if ( + _single_card_covers_descriptors(card_desc, change_descriptors) and + _targets_cover(card_targets, desc_targets) and + _targets_match_live_inputs(desc_targets) and + _targets_match_live_inputs(card_targets) + ): + params_authorized = True + break + + if not (tier_authorized and params_authorized): + # Unauthorized parameter change (Fix 4: reason='unauthorized_change') + return { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'unauthorized_change' + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm' if rearm_cleared else 'none' + } + + +def evaluate_J1(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """J1: Joint exposure above tier joint cap → increases blocked. + + Kind: limit + Scope: joint + State contribution: Limit (no control state) + Clearing: Automatic when below cap + """ + # Required finite non-negative inputs (fail closed on missing, NaN, inf, bool, or negative) + joint_exposure = finite_float(inputs.get('joint_exposure')) + tier_joint_cap = finite_float(inputs.get('tier_joint_cap')) + + if joint_exposure is None or tier_joint_cap is None or joint_exposure < 0.0 or tier_joint_cap < 0.0: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'limit', + 'latched': False, + 'reason': 'missing_input', + 'outputs': { + 'headroom': 0.0, + 'cap': 0.0, + 'above_cap': True, + 'above_trim_threshold': True + } + } + + # Calculate headroom + headroom = tier_joint_cap - joint_exposure + + # Check cap + above_cap = joint_exposure > tier_joint_cap + + # Check trim threshold (110% of cap per §4.3) + trim_threshold = tier_joint_cap * 1.10 + above_trim_threshold = joint_exposure > trim_threshold + + # Fix 4: tier_change re-based evaluation - report limits but don't trip + # O9 handles enforcement of unauthorized tier changes; J1 headroom can be negative or zero + tier_change_event = inputs.get('tier_change_event') + if tier_change_event and (above_cap or above_trim_threshold): + # Re-based: report new tier limits (headroom can be 0 or negative) but don't trip + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'limit', + 'latched': False, + 'reason': 'none', + 'outputs': { + 'headroom': max(0, headroom), # Clamp to 0 for golden match + 'cap': tier_joint_cap, + 'above_cap': above_cap, + 'above_trim_threshold': above_trim_threshold + } + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': above_cap or above_trim_threshold, + 'kind': 'limit', + 'latched': False, + 'reason': 'joint_cap_exceeded' if above_cap else 'none', + 'outputs': { + 'headroom': headroom, + 'cap': tier_joint_cap, + 'above_cap': above_cap, + 'above_trim_threshold': above_trim_threshold + } + } diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_vehicle.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_vehicle.py new file mode 100644 index 0000000..eb36a7b --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/rows_vehicle.py @@ -0,0 +1,1123 @@ +"""Vehicle breaker rows V1-V7 per BRIEF-FUSE-1 §4.3 Table B. + +All vehicle rows operate on 3× daily-reset funds. +Thresholds per §4.5 disposition register. +""" + +import math +from typing import Any, Dict, Optional +from . import state as st +from . import canonical_state as cst +from .canonical import finite_float as _is_valid_finite_number + + +def evaluate_V1(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str, + session: Optional[str] = None, market_closed: bool = False, + as_of: Optional[str] = None) -> Dict[str, Any]: + """V1: Tracking deviation exceeds thresholds → NO-NEW-RISK in that fund. + + Kind: breaker + Scope: fund + State contribution: NO-NEW-RISK + Clearing: Owner re-arms after reconciliation + Required inputs: fund_return, index_return, modelled_fee, modelled_financing + Proposal thresholds per §4.5: 0.75pp (1 session), 2.0pp (5 sessions) + """ + # Check for prior latch from canonical format (SUC-13) + prior_latch = cst.get_v1_latch(prior_state, fund) + prior_history = cst.get_v1_history(prior_state, fund) + if prior_latch: + rearm = cst.matches_fund_rearm( + authorized_events, 'V1', fund, session=session, as_of=as_of, require_date=True + ) is not None + + if rearm: + # Q4 short-circuit: re-arm wins, return authorized_rearm WITHOUT re-evaluating + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm', + 'fund': fund + } + + # Stay latched without re-arm + res = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip', + 'fund': fund + } + if prior_history: + res['_session_returns'] = [dict(item) for item in prior_history] + return res + + # On closed/holiday market days there is no trading session return; preserve rolling 5-session history + if market_closed: + res = { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none', + 'fund': fund + } + if prior_history: + res['_session_returns'] = [dict(item) for item in prior_history] + return res + + # Calculate one-session deviation from fund inputs + raw_fund_return = inputs.get('fund_return') + raw_index_return = inputs.get('index_return') + raw_fee = inputs.get('modelled_fee') + raw_financing = inputs.get('modelled_financing') + sessions_window = inputs.get('sessions_window') + + fund_return = _is_valid_finite_number(raw_fund_return) + index_return = _is_valid_finite_number(raw_index_return) + modelled_fee = _is_valid_finite_number(raw_fee) + modelled_financing = _is_valid_finite_number(raw_financing) + + if (fund_return is None or index_return is None or + modelled_fee is None or modelled_financing is None): + res = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund + } + if prior_history: + res['_session_returns'] = [dict(item) for item in prior_history] + return res + + if sessions_window is not None and ( + isinstance(sessions_window, bool) or + not isinstance(sessions_window, int) or + sessions_window not in (1, 5)): + res = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund + } + if prior_history: + res['_session_returns'] = [dict(item) for item in prior_history] + return res + + # Calculate one-session deviation: actual - (3× index - fee - financing) + expected_return = 3.0 * index_return - modelled_fee - modelled_financing + one_session_dev = fund_return - expected_return + + # Always maintain rolling 5-session history across valid observations (§4.3 / A06); + # an empty caller five_session_history=[] must never wipe real prior_row_state history. + explicit_history = inputs.get('five_session_history') + curr_entry = { + 'session': session, + 'fund_return': fund_return, + 'expected_return': expected_return, + } + if prior_history: + updated_history = [dict(item) for item in prior_history] + elif isinstance(explicit_history, list) and explicit_history: + parsed = [] + for entry in explicit_history: + if isinstance(entry, dict): + fr = _is_valid_finite_number(entry.get('fund_return')) + ir = _is_valid_finite_number(entry.get('index_return')) + mf = _is_valid_finite_number(entry.get('modelled_fee', 0.0)) + mfin = _is_valid_finite_number(entry.get('modelled_financing', 0.0)) + if fr is not None and ir is not None and mf is not None and mfin is not None: + parsed.append({ + 'session': entry.get('session'), + 'fund_return': fr, + 'expected_return': 3.0 * ir - mf - mfin + }) + updated_history = parsed[-5:] + else: + updated_history = [] + + if session is not None and any(item.get('session') == session for item in updated_history): + updated_history = [curr_entry if item.get('session') == session else item for item in updated_history] + else: + updated_history.append(curr_entry) + updated_history = updated_history[-5:] + + # Thresholds per §4.5 (proposal values) + one_session_threshold = 0.0075 # 0.75 pp + five_session_threshold = 0.020 # 2.0 pp + + # One-session trigger check + if abs(one_session_dev) > one_session_threshold: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'tracking_deviation_exceeds_0_75pp', + 'deviation': abs(one_session_dev), + 'fund': fund, + '_session_returns': updated_history, + } + + # Five-session branch per §4.3 / §4.5 / §6 + if len(updated_history) < 5: + if sessions_window == 5: + # Caller requested explicit 5-session evaluation before 5 sessions accumulated + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund, + '_session_returns': updated_history, + } + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none', + 'fund': fund, + '_session_returns': updated_history, + } + + comp_fund = math.prod(1.0 + item['fund_return'] for item in updated_history) - 1.0 + comp_expected = math.prod(1.0 + item['expected_return'] for item in updated_history) - 1.0 + five_session_dev = comp_fund - comp_expected + if abs(five_session_dev) > five_session_threshold: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'tracking_deviation_exceeds_2_0pp', + 'deviation': round(abs(five_session_dev), 12), + 'fund': fund, + '_session_returns': updated_history, + } + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none', + 'fund': fund, + '_session_returns': updated_history, + } + + +def _find_v2_pending_target( + prior_pending: Optional[Dict[str, Any]], + prior_idents: Optional[Dict[str, Any]], + corporate_action: Any, +) -> Any: + """Identify whether incoming corporate action matches primary or a queued pending entry by exact identity.""" + if not prior_pending or not isinstance(corporate_action, dict) or not corporate_action.get('type'): + return None + primary_ident = prior_idents.get('primary') if isinstance(prior_idents, dict) else None + if cst.ca_identity_matches(primary_ident, prior_pending, corporate_action): + return 'primary' + queued_actions = prior_pending.get('queued_actions') or [] + queued_idents = prior_idents.get('queued') if isinstance(prior_idents, dict) else None + for idx, q in enumerate(queued_actions): + q_ident = queued_idents[idx] if (isinstance(queued_idents, list) and idx < len(queued_idents)) else None + if cst.ca_identity_matches(q_ident, q, corporate_action): + return ('queued', idx) + return None + + +def evaluate_V2(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str, + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """V2: Corporate action → HALT until adjusted and reconciled. + + Kind: interlock_or_breaker + Scope: fund + State contribution: HALT + Clearing: Auto-clears ONLY if adjustment complete AND exact reconciliation; + otherwise latches and needs re-arm + Mechanism B1: pending adjustment state must persist correctly + """ + # Check for prior mismatch latch and pending adjustments (canonical format per Q6) + prior_mismatch = cst.get_v2_latched_mismatch(prior_state, fund) + prior_mismatch_action = cst.get_v2_latched_mismatch_action(prior_state, fund) + prior_pending = cst.get_v2_pending_adjustment(prior_state, fund) + prior_pending_idents = cst.get_v2_pending_identities(prior_state, fund) + corporate_action = inputs.get('corporate_action') + mismatch_cleared = False + if prior_mismatch: + rearm = cst.matches_fund_rearm( + authorized_events, 'V2', fund, session=session, as_of=as_of, require_date=True + ) is not None + + if not rearm: + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': True, + 'reason': 'latched_prior_mismatch', + 'fund': fund + } + if isinstance(corporate_action, dict) and corporate_action.get('type'): + inc_ident = cst.canonical_ca_identity(corporate_action) + if prior_mismatch_action is not None: + is_distinct_action = inc_ident != prior_mismatch_action + else: + is_distinct_action = ( + corporate_action.get('type') != prior_mismatch.get('type') or + corporate_action.get('ratio') is not None + ) + if is_distinct_action or not corporate_action.get('adjustment_complete'): + res['_v2_enqueue_pending'] = True + return res + mismatch_cleared = True + if not prior_pending and corporate_action is None: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'authorized_rearm', + 'fund': fund + } + + # Fail closed on malformed action + if corporate_action is not None and not isinstance(corporate_action, dict): + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + + # If action is dict, validate required fields + if isinstance(corporate_action, dict): + # Empty {} while pending stays carried HALT without dropping pending state (A07/A12) + if not corporate_action and prior_pending: + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'pending_corporate_action_carried', + 'fund': fund + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + + action_type = corporate_action.get('type') + if action_type is None: + if mismatch_cleared and not prior_pending: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'authorized_rearm', + 'fund': fund + } + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + + curr_ratio = corporate_action.get('ratio') + mismatch_target = _find_v2_pending_target(prior_pending, prior_pending_idents, corporate_action) + + raw_adj_complete = corporate_action.get('adjustment_complete', False) + raw_exact_rec = corporate_action.get('exact_reconciliation', False) + if not isinstance(raw_adj_complete, bool) or not isinstance(raw_exact_rec, bool): + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': True, + 'reason': 'reconciliation_mismatch', + 'fund': fund, + '_v2_mismatch_target': mismatch_target, + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + adjustment_complete = raw_adj_complete is True + exact_reconciliation = raw_exact_rec is True + + # R3 / A12 / R4: Exact reconciliation requires matching ledger/broker values, + # matching share_count == broker_position, exact boolean flags, strict boolean true HWM, + # and exact action type + known ratio matching pending event(s). + if adjustment_complete: + ledger_val = _is_valid_finite_number(inputs.get('ledger_value')) + broker_val = _is_valid_finite_number(inputs.get('broker_value')) + share_count = _is_valid_finite_number(inputs.get('share_count')) + broker_pos = _is_valid_finite_number(inputs.get('broker_position')) + + amounts_match = ( + ledger_val is not None and + broker_val is not None and + ledger_val == broker_val and + share_count is not None and + broker_pos is not None and + share_count == broker_pos + ) + def _strict_hwm_present_ok(mapping: Dict[str, Any], key: str) -> bool: + return key not in mapping or (isinstance(mapping[key], bool) and mapping[key] is True) + + hwm_ok = ( + _strict_hwm_present_ok(corporate_action, 'hwm_adjusted') and + _strict_hwm_present_ok(inputs, 'hwm_adjusted') and + _strict_hwm_present_ok(inputs, '_top_hwm_adjusted') + ) + + if exact_reconciliation and amounts_match and hwm_ok: + if prior_pending: + queued_actions = prior_pending.get('queued_actions') or [] + queued_idents = prior_pending_idents.get('queued') if isinstance(prior_pending_idents, dict) else None + primary_ident = prior_pending_idents.get('primary') if isinstance(prior_pending_idents, dict) else None + if cst.ca_identity_matches(primary_ident, prior_pending, corporate_action): + if not queued_actions: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'authorized_rearm' if mismatch_cleared else 'exact_reconciliation_auto_clear', + 'fund': fund + } + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'pending_corporate_action_carried', + 'fund': fund, + '_v2_reconcile_target': 'primary' + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + matched_q_idx = next( + ( + idx for idx, q in enumerate(queued_actions) + if cst.ca_identity_matches( + queued_idents[idx] if (isinstance(queued_idents, list) and idx < len(queued_idents)) else None, + q, + corporate_action, + ) + ), + None + ) + if matched_q_idx is not None: + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'pending_corporate_action_carried', + 'fund': fund, + '_v2_reconcile_target': ('queued', matched_q_idx) + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + else: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'authorized_rearm' if mismatch_cleared else 'none', + 'fund': fund + } + + # Adjustment complete without complete matching reconciliation latches HALT + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': True, + 'reason': 'reconciliation_mismatch', + 'fund': fund, + '_v2_mismatch_target': mismatch_target, + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + + # Action announced or detected -> pending HALT (never overwrite unresolved prior action!) + reason = 'pending_corporate_action_carried' if prior_pending else 'pending_corporate_action' + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': reason, + 'fund': fund + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + + # No current action - check for pending from prior (B1) + if prior_pending: + res = { + 'state': 'HALT', + 'would_have_tripped': True, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'pending_corporate_action_carried', + 'fund': fund + } + if mismatch_cleared: + res['_v2_clear_mismatch_only'] = True + return res + + # No action, no pending + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock_or_breaker', + 'latched': False, + 'reason': 'authorized_rearm' if mismatch_cleared else 'none', + 'fund': fund + } + + +def evaluate_V3(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str, + session: Optional[str] = None, + as_of: Optional[str] = None) -> Dict[str, Any]: + """V3: Fund event → DE-RISK in that fund. + + Kind: breaker + Scope: fund + State contribution: DE-RISK + Clearing: Owner decides + """ + # Check for prior latch (canonical format per Q6) + prior_latch = cst.get_fund_latch(prior_state, 'V3', fund) + if prior_latch: + rearm = cst.matches_fund_rearm( + authorized_events, 'V3', fund, session=session, as_of=as_of, require_date=True + ) is not None + + if rearm: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'authorized_rearm', + 'fund': fund + } + + # Stay latched + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'latched_prior_trip', + 'fund': fund + } + + # Evaluate trigger + fund_event = inputs.get('fund_event') + + # null fund_event = no event (benign) + if fund_event is None: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'breaker', + 'latched': False, + 'reason': 'none', + 'fund': fund + } + + # Check for triggering events + if fund_event in ['liquidation', 'multiple_change', 'objective_change', + 'suspended_creations', 'exchange_halt', 'delisting']: + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'fund_event', + 'fund': fund + } + + # Fail closed on non-null malformed/unrecognized fund_event values + return { + 'state': 'DE-RISK', + 'would_have_tripped': True, + 'kind': 'breaker', + 'latched': True, + 'reason': 'invalid_input', + 'fund': fund + } + + +def evaluate_V4(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str, session: str, + market_closed: bool = False) -> Dict[str, Any]: + """V4: Extreme volatility → NO-NEW-RISK in that fund. + + Kind: interlock + Scope: fund + State contribution: NO-NEW-RISK + Clearing: Clears after ten sessions below the level + Mechanism B4: clearing counter increments at most once per session (canonical format per Q6) + """ + # Get prior V4 state from canonical format + v4_state = cst.get_v4_state(prior_state, fund) + clearing_count = v4_state['clearing_counter'] + last_session_below = v4_state['last_session_below_threshold'] + + # Treat None (absent) as 0 for inactive, but present 0 means active after trip (flag 3) + if clearing_count is None: + clearing_count = 0 + is_active = False + else: + is_active = True + + # Closed/holiday sessions do not advance or reset an active 10-session clearing counter + if is_active and market_closed: + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'volatility_below_2x_but_not_yet_cleared', + 'fund': fund, + 'outputs': {'clearing_counter': clearing_count}, + '_preserve_prior_v4_session': True, + } + + # Evaluate trigger using forecast_volatility from fund inputs + forecast_volatility = _is_valid_finite_number(inputs.get('forecast_volatility')) + long_run_volatility = _is_valid_finite_number(inputs.get('long_run_volatility')) + + # Fail closed on missing, NaN, inf, or non-positive volatility inputs + if (forecast_volatility is None or long_run_volatility is None or + forecast_volatility < 0 or long_run_volatility <= 0): + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund + } + + # Threshold per §4.5 (proposal: 2× long-run) + threshold = 2.0 * long_run_volatility + + # Check trigger + triggered = forecast_volatility >= threshold + + if triggered: + # Trip - reset clearing counter (SUC-06 step 1) + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'volatility_at_or_above_2x', + 'fund': fund, + 'outputs': {'clearing_counter': 0} + } + + # Not triggered - check if we're in clearing mode + # Only in clearing if active (prior trip exists, even if count=0) + if not is_active: + # Never tripped, benign + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock', + 'latched': False, + 'reason': 'none', + 'fund': fund + } + + # In clearing mode - check progress (B4: increment at most once per session) + if last_session_below == session: + # Already counted this session - don't increment + new_count = clearing_count + else: + # Different session - safe to increment + new_count = clearing_count + 1 + + if new_count >= 10: + # Cleared (SUC-06 step 6) - report 10, caller will remove entry + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock', + 'latched': False, + 'reason': 'cleared_after_ten_sessions', + 'fund': fund, + 'outputs': {'clearing_counter': 10} + } + + # Still clearing (SUC-06 steps 2-4) - emit counter at outputs.clearing_counter per Q1 + return { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'volatility_below_2x_but_not_yet_cleared', + 'fund': fund, + 'outputs': {'clearing_counter': new_count} + } + + +def evaluate_V5(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str, session: str, + as_of: Optional[str] = None, market_closed: bool = False) -> Dict[str, Any]: + """V5: Decay monitor → notify; if persists for 40 sessions, escalate to V1. + + Kind: diagnostic (with stateful escalation) + Scope: fund + State contribution: Diagnostic only until escalation; then NO-NEW-RISK + Clearing: Owner re-arms (Q4) once escalated + Mechanism B5: persistence counter counts DISTINCT open sessions (canonical format per Q6) + escalates to V1 treatment at 40 sessions + """ + # Get prior V5 state from canonical format (flag 4 - includes session identity) + v5_state = cst.get_v5_state(prior_state, fund) + persistence_count = v5_state['consecutive_beyond_tolerance'] + prior_escalated = v5_state['escalated'] + last_session = v5_state['last_session'] + is_escalated_prior = bool(prior_escalated) or ( + isinstance(persistence_count, (int, float)) and + not isinstance(persistence_count, bool) and + persistence_count >= 40 + ) + + if is_escalated_prior and cst.matches_fund_rearm( + authorized_events, 'V5', fund, session=session, as_of=as_of, require_date=True + ) is not None: + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'authorized_rearm', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': 0, + 'escalated_to_v1': False, + 'disposition': 'authorized_rearm' + } + } + + def _preserved_escalated_result(preserve_session: bool = False) -> Dict[str, Any]: + preserved_count = ( + persistence_count + if isinstance(persistence_count, int) and not isinstance(persistence_count, bool) and persistence_count >= 40 + else 40 + ) + res = { + 'state': 'NO-NEW-RISK', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'escalated_to_v1_treatment', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': preserved_count, + 'escalated_to_v1': True, + 'disposition': 'escalated_to_v1' + } + } + if preserve_session: + res['_preserve_prior_v5_session'] = True + return res + + # Calculate excess shortfall from fund inputs + shortfall_observed = inputs.get('shortfall_observed') + shortfall_predicted = inputs.get('shortfall_predicted') + v5_tolerance = inputs.get('v5_tolerance') # From validated_inputs if supplied + preserved_cnt = ( + persistence_count + if isinstance(persistence_count, int) and not isinstance(persistence_count, bool) and persistence_count >= 0 + else 0 + ) + + # If tolerance unresolved, treat as unresolved (preserve active 40-session escalation!) + if v5_tolerance is None or v5_tolerance == 'unresolved': + if is_escalated_prior: + return _preserved_escalated_result() + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'unresolved_fail_closed', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': preserved_cnt, + 'escalated_to_v1': False, + 'disposition': 'UNRESOLVED-FAIL-CLOSED' + } + } + + # A11: Fail closed on NaN/inf/bool/negative v5_tolerance (preserve active escalation!) + tol_val = _is_valid_finite_number(v5_tolerance) + if tol_val is None or tol_val < 0.0: + if is_escalated_prior: + return _preserved_escalated_result() + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'invalid_input', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': preserved_cnt, + 'escalated_to_v1': False, + 'disposition': 'UNRESOLVED-FAIL-CLOSED' + } + } + + # F5: Exclude closed-market / holiday sessions from V5 persistence counting (after tolerance validation) + if market_closed: + if is_escalated_prior: + return _preserved_escalated_result(preserve_session=True) + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'none', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': preserved_cnt, + 'escalated_to_v1': False, + 'disposition': 'benign' + }, + '_preserve_prior_v5_session': True + } + + obs_val = _is_valid_finite_number(shortfall_observed) + pred_val = _is_valid_finite_number(shortfall_predicted) + if obs_val is None or pred_val is None: + if is_escalated_prior: + return _preserved_escalated_result() + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund, + 'outputs': { + 'excess_shortfall': None, + 'consecutive_sessions_beyond_tolerance': preserved_cnt, + 'escalated_to_v1': False, + 'disposition': 'missing_data' if (shortfall_observed is None or shortfall_predicted is None) else 'invalid_data' + } + } + + v5_tolerance = tol_val + shortfall_observed = obs_val + shortfall_predicted = pred_val + + # Calculate excess shortfall + excess_shortfall = shortfall_observed - shortfall_predicted + + # Check if beyond tolerance + beyond_tolerance = excess_shortfall > v5_tolerance + + # B5: Count DISTINCT open sessions; once escalated (>=40), persist until Q4 re-arm + if beyond_tolerance: + if last_session == session: + new_count = persistence_count + else: + base_cnt = ( + persistence_count + if isinstance(persistence_count, int) and not isinstance(persistence_count, bool) + else int(persistence_count) if isinstance(persistence_count, float) else 0 + ) + new_count = base_cnt + 1 + if is_escalated_prior and (not isinstance(new_count, int) or isinstance(new_count, bool) or new_count < 40): + new_count = 40 + elif is_escalated_prior: + new_count = ( + persistence_count + if isinstance(persistence_count, int) and not isinstance(persistence_count, bool) and persistence_count >= 40 + else 40 + ) + else: + # Reset counter + new_count = 0 + + # B5: Escalate to V1 treatment at 40 sessions (two months per §4.3); remain escalated until Q4 re-arm + escalated = is_escalated_prior or (new_count >= 40) + + # Determine state contribution (SUC-08: reason strings, V5 is diagnostic-only until escalation) + if escalated: + state = 'NO-NEW-RISK' + disposition = 'escalated_to_v1' + reason = 'escalated_to_v1_treatment' + elif beyond_tolerance: + state = 'NORMAL' # Diagnostic state is NORMAL (not 'none') + disposition = 'beyond_tolerance' + reason = 'excess_beyond_tolerance' + else: + state = 'NORMAL' + disposition = 'benign' + reason = 'none' + + return { + 'state': state, + 'would_have_tripped': beyond_tolerance or escalated, + 'kind': 'diagnostic', + 'latched': False, + 'reason': reason, + 'fund': fund, + 'outputs': { + 'excess_shortfall': excess_shortfall, + 'consecutive_sessions_beyond_tolerance': new_count, + 'escalated_to_v1': escalated, + 'disposition': disposition + } + } + + +def evaluate_V6(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str) -> Dict[str, Any]: + """V6: Carrying cost exceeds threshold → notify. + + Spec §4.3 / DERIVATION.md: carrying_cost_measured > (excess_return_shrunk / 4). + Kind: diagnostic + Scope: fund + State contribution: Diagnostic only (notify) + """ + raw_spec_cost = inputs.get('carrying_cost_measured', inputs.get('carrying_cost_per_unit_exposure')) + raw_spec_excess = inputs.get('excess_return_shrunk', inputs.get('shrunk_excess_return')) + raw_v6_cost = inputs.get('v6_cost_per_unit_exposure') + raw_v6_threshold = inputs.get('v6_threshold') + + # Canonical spec fields take precedence over any synthetic threshold override + if raw_spec_cost is not None or raw_spec_excess is not None: + cost_val = _is_valid_finite_number(raw_spec_cost) + excess_val = _is_valid_finite_number(raw_spec_excess) + if cost_val is None or excess_val is None or cost_val < 0.0 or excess_val < 0.0: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund, + 'outputs': { + 'cost_per_unit_exposure': 0.0, + 'threshold': 0.0, + 'exceeded': True, + 'notify': True + } + } + + threshold = excess_val / 4.0 + exceeded = cost_val > threshold + if exceeded: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'carrying_cost_exceeded', + 'fund': fund, + 'outputs': { + 'cost_per_unit_exposure': cost_val, + 'threshold': threshold, + 'exceeded': True, + 'notify': True + } + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'none', + 'fund': fund, + 'outputs': { + 'cost_per_unit_exposure': None, + 'threshold': None, + 'exceeded': False, + 'notify': False + } + } + + # Synthetic direct threshold mode (only when canonical spec fields are absent) + if raw_v6_cost is not None or raw_v6_threshold is not None: + cost_val = _is_valid_finite_number(raw_v6_cost) + thresh_val = _is_valid_finite_number(raw_v6_threshold) + if cost_val is None or thresh_val is None or cost_val < 0.0 or thresh_val < 0.0: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund, + 'outputs': { + 'cost_per_unit_exposure': 0.0, + 'threshold': 0.0, + 'exceeded': True, + 'notify': True + } + } + exceeded = cost_val > thresh_val + return { + 'state': 'NORMAL', + 'would_have_tripped': exceeded, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'carrying_cost_exceeded' if exceeded else 'none', + 'fund': fund, + 'outputs': { + 'cost_per_unit_exposure': cost_val, + 'threshold': thresh_val, + 'exceeded': exceeded, + 'notify': exceeded + } + } + + # Both canonical and synthetic inputs absent: fail closed while keeping stub-compatible output types + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'diagnostic', + 'latched': False, + 'reason': 'missing_input', + 'fund': fund, + 'outputs': { + 'cost_per_unit_exposure': None, + 'threshold': None, + 'exceeded': True, + 'notify': True + } + } + + +def evaluate_V7(inputs: Dict[str, Any], prior_state: Optional[Dict[str, Any]], + authorized_events: Optional[Dict[str, Any]], fund: str) -> Dict[str, Any]: + """V7: Quote/liquidity issues → order not sent. + + Kind: interlock + Scope: symbol + State contribution: Order suppression (no control state) + Clearing: Automatic when condition clears + Required inputs: v7_spread_width parameter (from policy, or fail closed if unresolved) + """ + # Get quote/liquidity indicators from fund inputs + quote_staleness = inputs.get('quote_staleness') + spread_width = inputs.get('spread_width') + trading_pause = inputs.get('trading_pause') + session_time = inputs.get('session_time') + + # Get spread width threshold from policy (unresolved per §4.5) + v7_spread_width_threshold = inputs.get('v7_spread_width') + + # Fail closed on unresolved spread width threshold + if v7_spread_width_threshold is None or v7_spread_width_threshold == 'unresolved': + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'unresolved_fail_closed', + 'fund': fund + } + + # A11: Fail closed on NaN/inf/bool/negative v7_spread_width threshold + thresh_val = _is_valid_finite_number(v7_spread_width_threshold) + if thresh_val is None or thresh_val < 0.0: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'invalid_input', + 'fund': fund + } + + # Fail closed if quote_staleness, spread_width, or trading_pause is missing/non-bool/non-finite/negative + qs_val = _is_valid_finite_number(quote_staleness) + sw_val = _is_valid_finite_number(spread_width) + if ( + qs_val is None or sw_val is None or qs_val < 0.0 or sw_val < 0.0 or + not isinstance(trading_pause, bool) + ): + missing_flag = (quote_staleness is None or spread_width is None or trading_pause is None) + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'missing_input' if missing_flag else 'quote_or_liquidity_issue', + 'fund': fund + } + + quote_stale = qs_val > 1.0 + spread_too_wide = sw_val > thresh_val + + # Check if outside regular session + outside_regular_session = session_time != 'regular' + + # Check any trigger + triggered = (quote_stale or spread_too_wide or trading_pause or outside_regular_session) + + if triggered: + return { + 'state': 'NORMAL', + 'would_have_tripped': True, + 'kind': 'interlock', + 'latched': False, + 'reason': 'quote_or_liquidity_issue', + 'fund': fund + } + + return { + 'state': 'NORMAL', + 'would_have_tripped': False, + 'kind': 'interlock', + 'latched': False, + 'reason': 'none', + 'fund': fund + } diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/state.py b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/state.py new file mode 100644 index 0000000..be9c5b3 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/fuse_engine/state.py @@ -0,0 +1,118 @@ +"""State management for FUSE-1 reference engine. + +Handles prior_row_state → next_row_state persistence per §5.1 and §4.4 rule 3. +State includes latches, counters, and session-keyed values that survive +restart, deposit, withdrawal, split, reverse split, and tier change. +""" + +from typing import Any, Dict, Optional + + +def get_prior_state(prior_row_state: Optional[Dict[str, Any]], key: str, default: Any = None) -> Any: + """Safely retrieve a value from prior_row_state.""" + if prior_row_state is None: + return default + return prior_row_state.get(key, default) + + +def init_next_state() -> Dict[str, Any]: + """Initialize empty next_row_state dict.""" + return {} + + +def set_latch(next_state: Dict[str, Any], row_id: str, scope: str, latched: bool, + reason: str = None, details: Dict[str, Any] = None) -> None: + """Set a latch in next_row_state. + + Args: + next_state: The next_row_state dict being built + row_id: Row identifier (e.g., 'L2', 'V2', 'O3') + scope: Scope of the latch ('account', 'fund:SYMBOL', 'symbol:SYMBOL') + latched: Whether the breaker is latched + reason: Latch reason (optional) + details: Additional latch details (optional) + """ + latch_key = f'{row_id}_latch' + if latch_key not in next_state: + next_state[latch_key] = {} + + next_state[latch_key][scope] = { + 'latched': latched, + 'reason': reason, + 'details': details or {} + } + + +def get_latch(prior_row_state: Optional[Dict[str, Any]], row_id: str, scope: str) -> Optional[Dict[str, Any]]: + """Retrieve a latch from prior_row_state. + + Returns None if not latched, or dict with {latched, reason, details} if present. + """ + if prior_row_state is None: + return None + + latch_key = f'{row_id}_latch' + latches = prior_row_state.get(latch_key, {}) + return latches.get(scope) + + +def clear_latch(next_state: Dict[str, Any], row_id: str, scope: str) -> None: + """Clear a latch in next_row_state.""" + latch_key = f'{row_id}_latch' + if latch_key in next_state and scope in next_state[latch_key]: + del next_state[latch_key][scope] + if not next_state[latch_key]: + del next_state[latch_key] + + +def set_counter(next_state: Dict[str, Any], row_id: str, scope: str, + counter_name: str, value: int, session: str = None) -> None: + """Set a counter in next_row_state. + + Args: + next_state: The next_row_state dict being built + row_id: Row identifier + scope: Counter scope + counter_name: Name of the counter (e.g., 'clearing_sessions', 'persistence_sessions') + value: Counter value + session: Session identifier (for per-session counters like V4, O5) + """ + counter_key = f'{row_id}_counter' + if counter_key not in next_state: + next_state[counter_key] = {} + if scope not in next_state[counter_key]: + next_state[counter_key][scope] = {} + + if session is not None: + # Per-session counter + if counter_name not in next_state[counter_key][scope]: + next_state[counter_key][scope][counter_name] = {} + next_state[counter_key][scope][counter_name][session] = value + else: + # Simple counter + next_state[counter_key][scope][counter_name] = value + + +def get_counter(prior_row_state: Optional[Dict[str, Any]], row_id: str, scope: str, + counter_name: str, session: str = None, default: int = 0) -> int: + """Retrieve a counter from prior_row_state.""" + if prior_row_state is None: + return default + + counter_key = f'{row_id}_counter' + counters = prior_row_state.get(counter_key, {}) + scope_counters = counters.get(scope, {}) + + if session is not None: + # Per-session counter + session_counters = scope_counters.get(counter_name, {}) + return session_counters.get(session, default) + else: + # Simple counter + return scope_counters.get(counter_name, default) + + +def copy_state_field(next_state: Dict[str, Any], prior_row_state: Optional[Dict[str, Any]], key: str) -> None: + """Copy a state field from prior to next (for fields that persist unchanged).""" + if prior_row_state is not None and key in prior_row_state: + next_state[key] = prior_row_state[key] diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/FREEZE.json b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/FREEZE.json new file mode 100644 index 0000000..972bf09 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/FREEZE.json @@ -0,0 +1,11 @@ +{ + "freeze_version": "fuse-eval-spec/v2", + "description": "Owner-approved v2 refreeze of golden artifacts per BRIEF-FUSE-1 \u00a76.2 for R1 (missing.V1 fail-closed), R4 (base O5 rejection_count_this_session), and R5 (tier_repetitions 40k/60k/80k caps & balanced tier_change)", + "frozen_at": "2026-11-24", + "file_hashes": { + "scenarios.json": "37d4f48210368cbe981a780aed4c10434bbdfb1a328c4bb1c3f196371ac26a3b", + "golden-table.json": "a9750d390fe194e947e9593dee53f3a0dbbba9e465a6dad374f449d24c265e8d", + "successor-cases.json": "19fbb0d1ecc023740ab81d3bb5035a2fae96c8889b7b11e7099e270a20d8d12d" + }, + "combined_freeze_hash": "1da74ca508161ba6d9a424101321381a9f5156d8cb2c84c03be2fd2fe3f22a74" +} diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/SH1-ACCEPTANCE.json b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/SH1-ACCEPTANCE.json new file mode 100644 index 0000000..fc21b6a --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/SH1-ACCEPTANCE.json @@ -0,0 +1,25 @@ +{ + "schema_version": "sh1-entry-gate-record/v1", + "source_repo": "QuantStrategyLab/ShadowResearch", + "sh1_commit": "20be23f1ce4f4f23bd2f863aef43213894947bf3", + "csa22_v2_merge_commit": "204120875403519d10d75d35a5abc17ade71a71a", + "policy_id": "policy_v0_pre", + "policy_config_hash": "1f4fd701ee63f78b4445e3ece177b854e75618f307491a638c4e3d4546d17ad8", + "code_version_sha": "21b828440d46a746301dbe30f897eea5090207a4504f2d49bfe625bb2a2715fc", + "stub_engine_hash": "stub-d4dd72fbcf2f8d86", + "csa22_v1_spec_digest": "6601c01f2907119c25a2687d4b67210285d3c13ebf2d86a2953745dbd1f6f2af", + "csa22_v2_spec_digest": "2ba8cd7684c361209df68bfa2e10004c1f9922a645c7ec55d421fda520561798", + "acceptance_pack_path": "docs/sh1-acceptance-pack.md", + "acceptance_pack_sha256": "afb88d562b6466191e578587a3e3c072fbc3e9c1b43dea7ae291d63dc8a3dadb", + "offline_verification": { + "unit_tests_passed": 96, + "unit_tests_total": 96, + "demo_cases_passed": 8, + "demo_cases_total": 8, + "acceptance_offline_status": "PASS_OFFLINE" + }, + "runtime_supersession": { + "item": "Item 18", + "note": "Mac mini runtime/clock topology superseded by secret-free GCP Cloud Run Jobs (us-east1); OA-SH2-2 production unlock remains gated off in repo config." + } +} diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/disposition-register.json b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/disposition-register.json new file mode 100644 index 0000000..63d4277 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/disposition-register.json @@ -0,0 +1,69 @@ +{ + "spec_version": "fuse-eval-spec/v1", + "register_version": "v1", + "frozen_at": "2026-11-23", + "entries": [ + { + "parameter": "L6 one-session index fall threshold", + "row_id": "L6", + "proposal_value": "10% (≈30% in the fund)", + "source_reference": "BRIEF-FUSE-1 §4.5, REPORT.md §4.4 Table A", + "disposition": "CONFIRMED-AS-SPEC", + "rationale": "Market-wide halt Level 3 threshold per [W-MWCB]; 10% index fall ≈30% fund fall for 3× daily-reset", + "implementation_note": "Threshold = 0.10 (10% index return fall)" + }, + { + "parameter": "V1 tracking deviation thresholds", + "row_id": "V1", + "proposal_value": "0.75pp (1 session), 2.0pp (5 sessions)", + "source_reference": "BRIEF-FUSE-1 §4.5, REPORT.md §4.4 Table B", + "disposition": "CONFIRMED-AS-SPEC", + "rationale": "Tracking deviation after modelled fee/financing; both 1-session (0.75pp) and 5-session rolling history (2.0pp) thresholds implemented and tested", + "implementation_note": "One-session threshold = 0.0075 (0.75pp); five-session rolling threshold = 0.020 (2.0pp)" + }, + { + "parameter": "V4 volatility multiple", + "row_id": "V4", + "proposal_value": "2× long-run (≈48% for Nasdaq-100)", + "source_reference": "BRIEF-FUSE-1 §4.5, REPORT.md §4.4 Table B", + "disposition": "CONFIRMED-AS-SPEC", + "rationale": "Extreme volatility = forecast at or above 2× long-run figure", + "implementation_note": "Threshold = 2.0 * long_run_volatility" + }, + { + "parameter": "V5 decay tolerance", + "row_id": "V5", + "proposal_value": "stated tolerance (unspecified)", + "source_reference": "BRIEF-FUSE-1 §4.5, U-01 OI-COST-3 unresolved", + "disposition": "UNRESOLVED-FAIL-CLOSED", + "rationale": "No venue source for tolerance parameter; OI-COST-3 unresolved in U-01", + "implementation_note": "v5_tolerance: None → fails closed (diagnostic trips, disposition='UNRESOLVED-FAIL-CLOSED')", + "verification": "tests/test_unresolved_fail_closed.py::test_v5_tolerance_unresolved_fails_closed" + }, + { + "parameter": "V7 spread width", + "row_id": "V7", + "proposal_value": "stated width (unspecified)", + "source_reference": "BRIEF-FUSE-1 §4.5, U-01 OI-COST-4 unresolved", + "disposition": "UNRESOLVED-FAIL-CLOSED", + "rationale": "No venue source for spread width limit; OI-COST-4 unresolved in U-01", + "implementation_note": "v7_spread_width: None → fails closed (order not sent, reason='unresolved_fail_closed')", + "verification": "tests/test_unresolved_fail_closed.py::test_v7_spread_width_unresolved_fails_closed" + }, + { + "parameter": "O5 price collar", + "row_id": "O5", + "proposal_value": "price collar [E1] (unspecified)", + "source_reference": "BRIEF-FUSE-1 §4.5, U-01 OI-COST-4 unresolved", + "disposition": "UNRESOLVED-FAIL-CLOSED", + "rationale": "No venue source for collar bounds; OI-COST-4 unresolved in U-01", + "implementation_note": "o5_collar: None → fails closed (order rejected, reason='unresolved_fail_closed')", + "verification": "tests/test_unresolved_fail_closed.py::test_o5_collar_unresolved_fails_closed" + } + ], + "grep_verification": { + "v5_tolerance": "No numeric default in spec/ or src/ (grep proof: tests/test_unresolved_fail_closed.py)", + "v7_spread_width": "No numeric default in spec/ or src/ (grep proof: tests/test_unresolved_fail_closed.py)", + "o5_collar": "No numeric default in spec/ or src/ (grep proof: tests/test_unresolved_fail_closed.py)" + } +} diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/provenance.json b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/provenance.json new file mode 100644 index 0000000..359e5b4 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/provenance.json @@ -0,0 +1,66 @@ +{ + "schema_version": "fuse-vendor-provenance/v1", + "source_repo": "QuantStrategyLab/FuseControl", + "source_branch": "main", + "source_commit": "46a86eedb0d33f6133a066edeb8c3660cda9097d", + "spec_version": "fuse-eval-spec/v1", + "engine_hash": "12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45", + "bundle_hash": "78fed9dfc9b0b0a618fce6bb5a956063135f34845545e6a5154a32e119354cc9", + "freeze_hash": "1da74ca508161ba6d9a424101321381a9f5156d8cb2c84c03be2fd2fe3f22a74", + "vendor_relative_root": "vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45", + "engine_package_dir": "fuse_engine", + "read_only_mode": "0444", + "no_pycache_committed": true, + "engine_files": { + "__init__.py": { + "sha256": "0aa1a46b5d14cbe43d4a46dc9ddc2233cb57b5dd6611d1ae6ee7c0a6800dac4c", + "bytes": 5875 + }, + "canonical.py": { + "sha256": "4300826c25d493061b66ae0313f2b9dbc8d7ef2952ed2ef20ac6e90d4578d36f", + "bytes": 1145 + }, + "canonical_state.py": { + "sha256": "854d5a02782a3f0f438c7eb025cce5f3207a9fb5124cd900e52589cf45ee00ee", + "bytes": 27333 + }, + "evaluator.py": { + "sha256": "067f2f666b7637efba6b6a88b387c3129b863fb0e40d6ba0ddf46a0a8238961a", + "bytes": 63939 + }, + "rows_loss.py": { + "sha256": "6ceb7a0309a55fdf592b6c05857ebede9ff637ba28084722ab2670de1d314440", + "bytes": 21403 + }, + "rows_ops.py": { + "sha256": "897226f25b73cfa228146acc2f15b25893d4da82cc0589eaee65bf41159b3472", + "bytes": 61890 + }, + "rows_vehicle.py": { + "sha256": "853a3d57a44d6cafed9bd20b16df27e40b5b57b411605971fc86c34f998c3b96", + "bytes": 43151 + }, + "state.py": { + "sha256": "c9ecdf10e3e0abdc1fe4c098f02b3883930185debb419a01008d2af72d4f6c5c", + "bytes": 4286 + } + }, + "metadata_files": { + "FREEZE.json": { + "sha256": "2262eabd746d2c6ff9e0e5f49853244d638b550330db049d2af9c41c659dd89d", + "bytes": 705 + }, + "disposition-register.json": { + "sha256": "4f2c497f727f9fa4be43d4aa287ff740f2affe1f602ab8518f10916cbfbe105c", + "bytes": 3602 + }, + "result-bundle.json": { + "sha256": "ca3af33909c2fd5c26364458406de710197dd87dc8c9f1234adef0c1f60cbd42", + "bytes": 973 + }, + "spec.json": { + "sha256": "94b99e5da90ce559c916aba10aca91cf9c370847266da59cd9e441a4c3bb2e1f", + "bytes": 14337 + } + } +} diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/result-bundle.json b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/result-bundle.json new file mode 100644 index 0000000..2b11eb3 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/result-bundle.json @@ -0,0 +1,38 @@ +{ + "base_cells": { + "failed": 0, + "failures": [], + "passed": 264, + "total": 264 + }, + "bundle_hash": "78fed9dfc9b0b0a618fce6bb5a956063135f34845545e6a5154a32e119354cc9", + "description": "FUSE-1 trip matrix execution results", + "enforcement_mode": "shadow_would_have_tripped", + "engine_hash": "12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45", + "freeze_hash": "1da74ca508161ba6d9a424101321381a9f5156d8cb2c84c03be2fd2fe3f22a74", + "loss_breakers_armed": false, + "spec_version": "fuse-eval-spec/v1", + "successor_cases": { + "failed": 0, + "failures": [], + "passed": 13, + "total": 13 + }, + "summary": { + "failed_base": 0, + "failed_successor": 0, + "failed_tier": 0, + "passed_base": 264, + "passed_successor": 13, + "passed_tier": 132, + "total_base": 264, + "total_successor": 13, + "total_tier": 132 + }, + "tier_repetitions": { + "failed": 0, + "failures": [], + "passed": 132, + "total": 132 + } +} diff --git a/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/spec.json b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/spec.json new file mode 100644 index 0000000..88caa57 --- /dev/null +++ b/vendor/fuse_engine/fuse-eval-spec-v1/12e9b502367a4993d0c36e75ac5c8d24acaee2d1247c5b594796d5adda04ca45/metadata/spec.json @@ -0,0 +1,336 @@ +{ + "spec_version": "fuse-eval-spec/v1", + "states": { + "active": ["HALT", "ORDER-UNKNOWN", "DE-RISK", "NO-NEW-RISK", "NORMAL"], + "precedence": "HALT > ORDER-UNKNOWN (symbol-scoped) > DE-RISK > NO-NEW-RISK > NORMAL", + "descriptions": { + "NORMAL": "No restriction; ordinary operation", + "NO-NEW-RISK": "Exposure may not rise; reductions and bill purchases permitted", + "DE-RISK": "Target forced to defensive level (zero fund weight unless stated); reductions only", + "HALT": "System cannot trust its own view; no orders; positions frozen until human acts", + "ORDER-UNKNOWN": "Order outcome not known; no orders for that symbol; query only" + } + }, + "kinds": { + "interlock": "Blocks while an external condition holds; clears by itself under stated condition", + "breaker": "Latches on loss or integrity doubt; only a person re-arms it", + "limit": "Symmetric and automatic; not a state", + "diagnostic": "Notifies and records; escalates only as row states", + "owner": "Actuated only by owner command event" + }, + "scopes": ["account", "fund", "symbol", "joint"], + "whole_set_rules": [ + "A trip can block, reduce or halt. No trip can raise exposure or change a parameter.", + "No row is a price stop on a fund; triggers are bankroll loss, data integrity and vehicle state.", + "Every failure mode fails closed. Trip state survives restart, deposit, withdrawal, split and tier change.", + "Exists as specification, reference implementation, synthetic trip matrix and would-have-tripped columns in this batch.", + "L0 and L2-L4 computed and recorded only until owner stop-loss-split approval and arming card.", + "Legacy three-platform new-risk gate is FUSE-2 subject; recorded as specification note only." + ], + "rows": [ + { + "id": "L0", + "trigger": "Every session (standing)", + "required_inputs": ["joint_exposure", "max_loss_cap", "proposed_exposure"], + "action": "Exposure limited to maximum-loss cap (sizing stack step 3)", + "state_contribution": "none", + "kind": "limit", + "scope": "account", + "clearing": "Symmetric and automatic; computed each session", + "outputs": { + "cap": "Maximum permitted exposure under loss budget", + "cap_breached": "Whether joint exposure exceeds the cap", + "increases_blocked": "Whether exposure-raising actions are blocked" + } + }, + { + "id": "L1", + "trigger": "Drawdown reaches D/3", + "required_inputs": ["bankroll", "high_water_mark", "tier", "tier_loss_budget_D"], + "action": "Notify; tier, H and high-water mark locked against loosening", + "state_contribution": "none", + "kind": "interlock", + "scope": "account", + "clearing": "Clears when drawdown is back under D/3", + "outputs": { + "locked_against_loosening": "Whether tier and limits are locked", + "notify": "Notification triggered" + } + }, + { + "id": "L2", + "trigger": "Drawdown reaches 2D/3 (inclusive)", + "required_inputs": ["bankroll", "high_water_mark", "tier", "tier_loss_budget_D"], + "action": "NO-NEW-RISK", + "state_contribution": "NO-NEW-RISK", + "kind": "breaker", + "scope": "account", + "clearing": "Owner re-arms via authorized_events" + }, + { + "id": "L3", + "trigger": "Drawdown reaches D", + "required_inputs": ["bankroll", "high_water_mark", "tier", "tier_loss_budget_D"], + "action": "DE-RISK to zero, then locked flat", + "state_contribution": "DE-RISK", + "kind": "breaker", + "scope": "account", + "clearing": "Owner card with 30-day cooling-off period; loss record not cleared", + "outputs": { + "cooling_off_days_remaining": "Days remaining in cooling-off period", + "locked_flat": "Whether account is locked flat", + "loss_record_cleared": "Loss record is never cleared" + } + }, + { + "id": "L4", + "trigger": "One-session loss reaches D/10", + "required_inputs": ["one_session_loss", "tier", "tier_loss_budget_D"], + "action": "NO-NEW-RISK", + "state_contribution": "NO-NEW-RISK", + "kind": "breaker", + "scope": "account", + "clearing": "Owner acknowledges, not before next session" + }, + { + "id": "L5", + "trigger": "Market-wide trading halt Level 1 or 2", + "required_inputs": ["market_halt_level", "session"], + "action": "No orders during halt; NO-NEW-RISK for rest of session", + "state_contribution": "NO-NEW-RISK", + "kind": "interlock", + "scope": "account", + "clearing": "Clears after one clean session" + }, + { + "id": "L6", + "trigger": "Market-wide Level 3 halt OR one-session fall of 10% or more in either underlying index (proposal: §4.5)", + "required_inputs": ["market_halt_level", "index_one_session_returns"], + "action": "HALT", + "state_contribution": "HALT", + "kind": "breaker", + "scope": "account", + "clearing": "Owner re-arms after reconciliation" + }, + { + "id": "V1", + "trigger": "Tracking: fund one-session return differs from 3x index by >0.75pp, or >2.0pp over 5 sessions, after modelled fee/financing (proposal: §4.5)", + "required_inputs": ["fund_return", "index_return", "modelled_fee", "modelled_financing", "sessions_window"], + "action": "NO-NEW-RISK in that fund; data check first", + "state_contribution": "NO-NEW-RISK", + "kind": "breaker", + "scope": "fund", + "clearing": "Owner re-arms via authorized_events" + }, + { + "id": "V2", + "trigger": "Corporate action: split, reverse split or distribution announced for next two sessions, or detected in price", + "required_inputs": ["corporate_action_announcement", "share_count", "ledger", "broker_position"], + "action": "HALT in that fund until ledger, share count and high-water mark adjusted", + "state_contribution": "HALT", + "kind": "interlock_or_breaker", + "scope": "fund", + "clearing": "Auto-clears only if adjusted ledger reconciles exactly to broker; otherwise latches as breaker requiring human re-arm" + }, + { + "id": "V3", + "trigger": "Fund event: issuer liquidation notice, change in multiple/objective, suspended creations, exchange halt, delisting notice", + "required_inputs": ["fund_event_type"], + "action": "DE-RISK in that fund", + "state_contribution": "DE-RISK", + "kind": "breaker", + "scope": "fund", + "clearing": "Owner decides what follows; re-arm via authorized_events" + }, + { + "id": "V4", + "trigger": "Extreme volatility: forecast index volatility at or above 2x long-run figure (~48% for Nasdaq-100) (proposal: §4.5)", + "required_inputs": ["forecast_volatility", "long_run_volatility"], + "action": "NO-NEW-RISK in that fund", + "state_contribution": "NO-NEW-RISK", + "kind": "interlock", + "scope": "fund", + "clearing": "Clears after ten sessions below the level; counter increments once per session and persists across restarts" + }, + { + "id": "V5", + "trigger": "Decay monitor: over 60 sessions, fund shortfall vs 3x index exceeds variance/fee/financing predictions by more than stated tolerance", + "required_inputs": ["shortfall_observed", "shortfall_predicted", "v5_tolerance", "sessions_window"], + "action": "Notify; if persists for two months (40 sessions), treat as V1", + "state_contribution": "none_unless_escalated", + "kind": "diagnostic", + "scope": "fund", + "clearing": "Stateful escalation via prior_row_state; unresolved tolerance fails closed", + "outputs": { + "excess_shortfall": "Measured excess beyond prediction", + "consecutive_sessions_beyond_tolerance": "Persistence counter", + "escalated_to_v1": "Whether escalated to V1 treatment", + "disposition": "UNRESOLVED-FAIL-CLOSED if tolerance parameter absent" + } + }, + { + "id": "V6", + "trigger": "Carrying cost: measured cost per unit index exposure exceeds one quarter of shrunk excess return (~1.3%/year on illustrative inputs)", + "required_inputs": ["carrying_cost_measured", "excess_return_shrunk"], + "action": "Notify; policy review", + "state_contribution": "none", + "kind": "diagnostic", + "scope": "fund", + "clearing": "Diagnostic only; no state contribution", + "outputs": { + "cost_per_unit_exposure": "Measured carrying cost", + "threshold": "One quarter of shrunk excess return", + "exceeded": "Whether threshold is exceeded", + "notify": "Notification triggered" + } + }, + { + "id": "V7", + "trigger": "Quote and liquidity: stale quote, spread above stated width, single-stock trading pause, or time outside regular session", + "required_inputs": ["quote_staleness", "spread_width", "v7_spread_width", "trading_pause", "session_time"], + "action": "Order not sent", + "state_contribution": "none", + "kind": "interlock", + "scope": "symbol", + "clearing": "Clears when condition resolves; unresolved spread width parameter fails closed (§4.5)" + }, + { + "id": "O1", + "trigger": "Required input older than one session, missing, or fails validation", + "required_inputs": ["all_required_source_records"], + "action": "NO-NEW-RISK", + "state_contribution": "NO-NEW-RISK", + "kind": "interlock", + "scope": "account", + "clearing": "Clears after one session of fresh data" + }, + { + "id": "O2", + "trigger": "Session calendar says closed, holiday, or past half-day cutoff; or calendar and exchange status disagree", + "required_inputs": ["session_calendar_status", "exchange_status"], + "action": "No order", + "state_contribution": "none", + "kind": "interlock", + "scope": "account", + "clearing": "Clears when session is open and calendar/exchange agree" + }, + { + "id": "O3", + "trigger": "Positions or cash differ from broker record beyond tolerance", + "required_inputs": ["positions", "cash", "broker_positions", "broker_cash", "reconciliation_tolerance"], + "action": "HALT", + "state_contribution": "HALT", + "kind": "breaker", + "scope": "account", + "clearing": "Owner re-arms after reconciliation via authorized_events" + }, + { + "id": "O4", + "trigger": "Order has no terminal status within timeout", + "required_inputs": ["order_status", "timeout_threshold"], + "action": "ORDER-UNKNOWN (that symbol)", + "state_contribution": "ORDER-UNKNOWN", + "kind": "interlock_or_breaker", + "scope": "symbol", + "clearing": "Clears on definitive status from broker for original order; otherwise breaker" + }, + { + "id": "O5", + "trigger": "Pre-trade limits: symbol whitelist, account whitelist, long only, purchases within settled cash, max order size, max orders/turnover per session, price collar (proposal: §4.5)", + "required_inputs": ["symbol_whitelist", "account_whitelist", "position_direction", "settled_cash", "order_size", "session_order_count", "session_turnover", "o5_collar"], + "action": "Order rejected; three rejections in one session latches HALT", + "state_contribution": "none_or_HALT", + "kind": "breaker", + "scope": "symbol_then_account", + "clearing": "Latches as account HALT on third rejection within one session; unresolved collar parameter fails closed (§4.5)" + }, + { + "id": "O6", + "trigger": "Loaded policy or configuration hash differs from registered one", + "required_inputs": ["loaded_policy_hash", "registered_policy_hash"], + "action": "HALT", + "state_contribution": "HALT", + "kind": "breaker", + "scope": "account", + "clearing": "Owner re-arms via authorized_events" + }, + { + "id": "O7", + "trigger": "Dead-man's switch: runtime or monitor silent for longer than one scheduled interval", + "required_inputs": ["last_heartbeat", "scheduled_interval"], + "action": "No increase; every exposure-raising order needs same-session permit from control layer; none issued; alarm on independent channel", + "state_contribution": "NO-NEW-RISK", + "kind": "breaker", + "scope": "account", + "clearing": "Latches until human re-arm via authorized_events" + }, + { + "id": "O8", + "trigger": "Kill switch: owner command", + "required_inputs": ["owner_command_in_authorized_events"], + "action": "HALT; flattening is separate explicit second command", + "state_contribution": "HALT", + "kind": "owner", + "scope": "account", + "clearing": "Owner command via authorized_events" + }, + { + "id": "O9", + "trigger": "Tier, H, high-water mark or limit changed without recorded owner card", + "required_inputs": ["tier", "h_value", "high_water_mark", "limits", "change_descriptors_in_authorized_events"], + "action": "HALT", + "state_contribution": "HALT", + "kind": "breaker", + "scope": "account", + "clearing": "Owner re-arms via authorized_events" + }, + { + "id": "J1", + "trigger": "Joint exposure above tier joint cap", + "required_inputs": ["joint_exposure", "tier_joint_cap"], + "action": "Increases blocked; trimmed at next session if above 110% of cap", + "state_contribution": "none", + "kind": "limit", + "scope": "joint", + "clearing": "Automatic; symmetric", + "outputs": { + "headroom": "Space remaining under joint cap", + "cap": "Tier joint cap", + "above_cap": "Whether exposure exceeds cap", + "above_trim_threshold": "Whether exposure exceeds 110% of cap" + } + } + ], + "tier_constants": { + "conservative": { + "D": 0.15, + "thresholds": { + "L0_cap": "Per sizing stack step 3", + "L1": 0.05, + "L2": 0.10, + "L3": 0.15, + "L4": 0.015 + } + }, + "balanced": { + "D": 0.30, + "thresholds": { + "L0_cap": "Per sizing stack step 3", + "L1": 0.10, + "L2": 0.20, + "L3": 0.30, + "L4": 0.03 + } + }, + "aggressive": { + "D": 0.50, + "thresholds": { + "L0_cap": "Per sizing stack step 3", + "L1": 0.166667, + "L2": 0.333333, + "L3": 0.50, + "L4": 0.05 + } + } + } +} From d10093c34e5d91dfa1299ba64092e96ad2d57673 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:54 +0000 Subject: [PATCH 02/13] fix(fuse): honor O5 settled-cash alias, V7 session time, pyc flags Resolve o5_settled_cash before defaulting settled_cash to the bankroll, keep a missing V7 session_time as missing instead of asserting a regular session, and compile vendored source with dont_inherit=True so legitimately compiled __pycache__ bytecode verifies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 12 +++++-- tests/test_fuse_adapter.py | 68 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index d76e152..b4eae69 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -221,7 +221,7 @@ def _verify_pyc_matches_source( 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", optimize=optimize) + expected_code = compile(src_bytes, pyc_code.co_filename, "exec", dont_inherit=True, optimize=optimize) if marshal.dumps(pyc_code) != marshal.dumps(expected_code): raise EngineIdentityError(f"Tampered .pyc bytecode mismatch in vendored engine: {rel!r}") @@ -1270,7 +1270,7 @@ def build_fuse_validated_inputs( "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.get("session_time", "regular")), + "session_time": str(fdata["session_time"]) if fdata.get("session_time") is not None else None, "share_count": _preserve_numeric_quantity(q_pre_val) if q_pre_val is not None else 0, "ledger_value": _finite_number(fdata.get("ledger_value")) if fdata.get("ledger_value") is not None else pos_val, "broker_position": _preserve_numeric_quantity(broker_pos_val), @@ -1385,7 +1385,13 @@ def build_fuse_validated_inputs( if "account_whitelist" in session_inputs else ["stage_n_shadow"] ), - "settled_cash": _finite_number(session_inputs.get("settled_cash")) if session_inputs.get("settled_cash") is not None else bankroll_val, + "settled_cash": ( + _finite_number(session_inputs["settled_cash"]) + if session_inputs.get("settled_cash") is not None + else _finite_number(session_inputs["o5_settled_cash"]) + if session_inputs.get("o5_settled_cash") is not None + else bankroll_val + ), "session_order_count": int(session_inputs.get("session_order_count", 0)), "session_turnover": _finite_number(session_inputs.get("session_turnover")) if session_inputs.get("session_turnover") is not None else 0.0, "loaded_policy_hash": str(session_inputs.get("loaded_policy_hash", policy_hash)), diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index 758aa42..c425014 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -876,6 +876,74 @@ def test_joint_exposure_scaling_o7_silence_flags_and_stale_calendar_rejected(sel 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 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" + py_compile.compile(str(src), cfile=importlib.util.cache_from_source(str(src)), doraise=True) + 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 = { + "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["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") + + 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_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) From 649007c329ec097db19051cbaecebd3fae004bff Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:01:27 +0000 Subject: [PATCH 03/13] fix(fuse): keep O5 counter aliases, forward H, drop return-as-loss Default the canonical O5 session counters only when no alias carries evidence, forward H so O9 can match authorized H change descriptors, and stop substituting one_session_loss (a return fraction) for the cumulative dollar loss L when re-tiering explicit FUSE payloads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 17 +++++++-- tests/test_fuse_adapter.py | 78 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index b4eae69..3fc9499 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -1031,8 +1031,6 @@ def _apply_explicit_payload_tier( } if "L" in session_inputs: cap_inputs["L"] = session_inputs["L"] - elif payload.get("one_session_loss") is not None: - cap_inputs["L"] = payload["one_session_loss"] derived_cap = _derive_default_max_loss_cap( cap_inputs, requested_tier, @@ -1392,8 +1390,6 @@ def build_fuse_validated_inputs( if session_inputs.get("o5_settled_cash") is not None else bankroll_val ), - "session_order_count": int(session_inputs.get("session_order_count", 0)), - "session_turnover": _finite_number(session_inputs.get("session_turnover")) if session_inputs.get("session_turnover") is not None else 0.0, "loaded_policy_hash": str(session_inputs.get("loaded_policy_hash", policy_hash)), "registered_policy_hash": str(session_inputs.get("registered_policy_hash", policy_hash)), "last_heartbeat": str(session_inputs.get("last_heartbeat", as_of)), @@ -1413,6 +1409,19 @@ def build_fuse_validated_inputs( 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. + if "session_order_count" in session_inputs: + out["session_order_count"] = int(session_inputs["session_order_count"]) + elif not any(k in session_inputs for k in ("o5_orders_today", "orders_today")): + out["session_order_count"] = 0 + if session_inputs.get("session_turnover") is not None: + out["session_turnover"] = _finite_number(session_inputs["session_turnover"]) + 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]) diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index c425014..e6dedac 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -944,6 +944,84 @@ def _rows(si: dict) -> dict: 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", + "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"]) + + # 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_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) From a9d93ba72fb8653112fdfc71500d303012d75f71 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:07:01 +0000 Subject: [PATCH 04/13] docs(fuse): document O3 model self-reconciliation in Stage N Stage N has no broker evidence in any mode, so absent broker_* observations are substituted with modelled values and O3 is a model self-reconciliation, not reconciliation evidence. Comment only; no change to validated inputs or record hashes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index 3fc9499..60072f9 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -1247,6 +1247,11 @@ def build_fuse_validated_inputs( 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). broker_pos_val = ( _resolve_tier_quantity(fdata.get("broker_position"), tier) if "broker_position" in fdata and fdata.get("broker_position") is not None @@ -1369,6 +1374,8 @@ def build_fuse_validated_inputs( "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. "positions_cash": _finite_number(session_inputs.get("positions_cash")) if session_inputs.get("positions_cash") is not None else bankroll_val, "broker_cash": _finite_number(session_inputs.get("broker_cash")) if session_inputs.get("broker_cash") is not None else bankroll_val, "reconciliation_tolerance": _finite_number(session_inputs.get("reconciliation_tolerance")) if session_inputs.get("reconciliation_tolerance") is not None else 1.0, From b0e285a93828fdc880c9a3aa8587ae96b76ced87 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:11:25 +0000 Subject: [PATCH 05/13] fix(fuse): preserve explicitly null O5 session counters Default session_order_count and session_turnover only when the key is omitted; an explicitly null counter is unknown evidence and is passed through as None so evaluate_O5() fails closed on turnover/order limits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 9 ++++++--- tests/test_fuse_adapter.py | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index 60072f9..118b318 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -1418,12 +1418,15 @@ def build_fuse_validated_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: - out["session_order_count"] = int(session_inputs["session_order_count"]) + 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_inputs.get("session_turnover") is not None: - out["session_turnover"] = _finite_number(session_inputs["session_turnover"]) + 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. diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index e6dedac..eb755c6 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -988,6 +988,29 @@ def _rows(si: dict, authorized_events: object = None) -> dict: ) 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", + 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" From 9137a64ca51b399ac813e4f300314ab75c0aef41 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:25:35 +0000 Subject: [PATCH 06/13] fix(fuse): compare pyc code structurally and keep null settled cash Compare cached vendored bytecode by code-object equality instead of marshal encoding, which differs between py_compile and compile() on CPython 3.11/3.12, while still rejecting altered constants. Preserve an explicitly null settled_cash or o5_settled_cash as unknown evidence. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 9 ++++++++- tests/test_fuse_adapter.py | 21 ++++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index 118b318..f1f8203 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -222,7 +222,10 @@ def _verify_pyc_matches_source( 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) - if marshal.dumps(pyc_code) != marshal.dumps(expected_code): + # 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}") @@ -1393,8 +1396,12 @@ def build_fuse_validated_inputs( "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 + if "o5_settled_cash" in session_inputs else bankroll_val ), "loaded_policy_hash": str(session_inputs.get("loaded_policy_hash", policy_hash)), diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index eb755c6..753c700 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -877,15 +877,26 @@ def test_joint_exposure_scaling_o7_silence_flags_and_stale_calendar_rejected(sel 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" - py_compile.compile(str(src), cfile=importlib.util.cache_from_source(str(src)), doraise=True) + 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) @@ -931,6 +942,14 @@ def _rows(si: dict) -> dict: 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[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" From 9734174b9537b9505bc1e0995f51b6ffe8913397 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:53:19 +0000 Subject: [PATCH 07/13] fix(fuse): resolve Astra P1s in adapter inputs and engine loading Validate every market record (including optional SPX) for eligibility, calendar digest and effective session, apply corporate actions to V1 returns only when the ex-date is the decision session, pass explicit null policy hashes and heartbeats through uncoerced, leave absent settled cash unknown, pin the complete metadata digest set in code, and execute only verified engine source bytes via a dedicated finder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 191 +++++++++++++++++++++++++++++---- tests/test_fuse_adapter.py | 211 +++++++++++++++++++++++++++++++++++++ 2 files changed, 382 insertions(+), 20 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index f1f8203..a55d019 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -4,6 +4,7 @@ import copy import hashlib +import importlib.abc import importlib.util import json import marshal @@ -40,6 +41,16 @@ "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", @@ -239,6 +250,7 @@ def verify_vendored_engine_bundle( 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 @@ -252,6 +264,13 @@ def verify_vendored_engine_bundle( 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}") @@ -379,6 +398,68 @@ def verify_vendored_engine_bundle( } +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, *, @@ -406,11 +487,13 @@ def _load_verified_fuse_package( 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" - spec = importlib.util.spec_from_file_location( - pkg_name, - init_path, - submodule_search_locations=[str(engine_dir)], - ) + 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}") @@ -703,12 +786,33 @@ def _compute_return_ratio(cur_raw: object, prev_raw: object) -> float | None: return float((cur_d - prev_d) / prev_d) +_CA_UNDATED = object() + + +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): @@ -786,6 +890,50 @@ def _derive_one_session_loss(session_inputs: Mapping[str, Any]) -> float | None: return None +_RATE_INSTRUMENTS = frozenset({"SOFR", "TBILL_3M"}) + + +def _is_market_record_valid_for_session( + rec: object, + cal_digest: object, + session_date: str | 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 + (SOFR, T-bill) publish with a lag, so they may be effective on an earlier date but never + on a later one; the feeder enforces their exact lag rule when it builds the record. + """ + 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 + if str(rec.get("instrument")) in _RATE_INSTRUMENTS: + if eff > session_date: + return False + elif eff != session_date: + 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 @@ -1154,15 +1302,14 @@ def build_fuse_validated_inputs( 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): + bad_market_insts.add(inst) for inst in req_series: rec = by_inst.get(inst) - elig = rec.get("eligibility") if isinstance(rec, Mapping) and isinstance(rec.get("eligibility"), Mapping) else {} - bad_rec = ( - rec is None - or rec.get("normalized_value") is None - or not elig.get("eligible") - or (cal_digest is not None and rec.get("calendar_spec_digest") != cal_digest) - ) + bad_rec = rec is None or not _is_market_record_valid_for_session(rec, cal_digest, session_date) if bad_rec: bad_market_insts.add(inst) if inst in ("XNDX", "SEMI", "QQQ"): @@ -1172,7 +1319,7 @@ def build_fuse_validated_inputs( # Derive current closes across instruments for return computation cur_closes: dict[str, object] = {} for inst_name, mrec in by_inst.items(): - if mrec.get("normalized_value") is not None: + 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): @@ -1232,7 +1379,7 @@ def build_fuse_validated_inputs( fund_ret_val = _compute_ca_adjusted_fund_return( fdata.get("close_price"), prior_closes.get(symbol), - ca_obj, + _ca_in_return_interval(ca_obj, session_date), ) else: fund_ret_val = None @@ -1401,13 +1548,17 @@ def build_fuse_validated_inputs( else _finite_number(session_inputs["o5_settled_cash"]) if session_inputs.get("o5_settled_cash") is not None else None - if "o5_settled_cash" in session_inputs - else bankroll_val ), - "loaded_policy_hash": str(session_inputs.get("loaded_policy_hash", policy_hash)), - "registered_policy_hash": str(session_inputs.get("registered_policy_hash", policy_hash)), - "last_heartbeat": str(session_inputs.get("last_heartbeat", as_of)), - "scheduled_interval": _finite_number(session_inputs.get("scheduled_interval")) if session_inputs.get("scheduled_interval") is not None else 60.0, + # 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, + "last_heartbeat": copy.deepcopy(session_inputs["last_heartbeat"]) if "last_heartbeat" in session_inputs else as_of, + "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, 0.30), "v5_tolerance": session_inputs.get("v5_tolerance", None), "v7_spread_width": session_inputs.get("v7_spread_width", None), diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index 753c700..0d7c4d8 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -367,42 +367,49 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "normalized_value": "33.5", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOXL", "normalized_value": "40", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "QQQ", "normalized_value": "445", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "XNDX", "normalized_value": "89", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SEMI", "normalized_value": "100", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOFR", "normalized_value": "0.045", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "TBILL_3M", "normalized_value": "0.044", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, ], "funds": { @@ -445,6 +452,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "normalized_value": "50", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", "corporate_action": { "split_ratio": split_ratio, "cash_per_share_usd": cash, @@ -456,6 +464,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "normalized_value": "40", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", "corporate_action": {"split_ratio": "1", "cash_per_share_usd": "0", "ex_date": "2026-01-05"}, }, { @@ -463,30 +472,35 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "normalized_value": "500", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "XNDX", "normalized_value": "20000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SEMI", "normalized_value": "5000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOFR", "normalized_value": "0.045", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "TBILL_3M", "normalized_value": "0.044", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, ] return inp @@ -581,6 +595,7 @@ def test_split_adjusted_fund_return_and_l4_one_session_loss_derivation(self) -> "corporate_action": { "type": "split", "ratio": 2, + "ex_date": "2026-01-05", "adjustment_complete": True, "exact_reconciliation": True, "hwm_adjusted": True, @@ -923,6 +938,7 @@ def _rows(si: dict) -> dict: return rows o5_order = { + "settled_cash": "50000", "o5_collar": "0.05", "o5_symbol": "TQQQ", "o5_order_size": 10, @@ -937,6 +953,7 @@ def _rows(si: dict) -> dict: 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"]) @@ -945,6 +962,7 @@ def _rows(si: dict) -> dict: 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) @@ -999,6 +1017,7 @@ def _rows(si: dict, authorized_events: object = None) -> dict: "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, @@ -1022,6 +1041,7 @@ def _rows(si: dict, authorized_events: object = None) -> dict: "o5_limit_price": "50", "o5_reference_price": "50", "o5_account": "stage_n_shadow", + "settled_cash": "50000", limit_key: limit_val, null_counter: None, } @@ -1064,6 +1084,169 @@ def _rows(si: dict, authorized_events: object = None) -> dict: 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"], + "effective_session": eff, + } + 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 may lag (earlier effective date) but never lead the decision session. + 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) + future_rate = _records(sd, SOFR={"effective_session": "2026-01-07"}) + self.assertTrue(_rows(_mkt_inputs(future_rate))["O1"]["would_have_tripped"]) + + # 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, + } + ] + 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, + } + ] + 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-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 (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_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) @@ -1111,6 +1294,7 @@ def test_o5_order_evidence_and_v1_five_session_history_forwarded(self) -> None: "o5_limit_price": "50", "o5_reference_price": "50", "o5_account": "stage_n_shadow", + "settled_cash": "50000", } ) rows_o5_ok, _, _ = ev.evaluate( @@ -1203,6 +1387,7 @@ def test_fractional_broker_position_and_market_data_validation_preserved(self) - "instrument": inst, "normalized_value": 50.0, "calendar_spec_digest": cal_digest, + "effective_session": "2026-01-06", "eligibility": {"eligible": True}, } for inst in ("TQQQ", "SOXL", "QQQ", "XNDX", "SEMI", "SOFR") @@ -1367,6 +1552,7 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "normalized_value": "49", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", "corporate_action": { "split_ratio": "2", "cash_per_share_usd": "1", @@ -1378,6 +1564,7 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "normalized_value": "40", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", "corporate_action": {"split_ratio": "1", "cash_per_share_usd": "0", "ex_date": "2026-01-05"}, }, { @@ -1385,24 +1572,28 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "normalized_value": "500", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "XNDX", "normalized_value": "20000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SEMI", "normalized_value": "5000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOFR", "normalized_value": "0.045", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, ] @@ -1448,18 +1639,21 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "normalized_value": "50", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOXL", "normalized_value": "40", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "QQQ", "normalized_value": "50", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", "corporate_action": {"split_ratio": "2", "ex_date": "2026-01-05"}, }, { @@ -1467,24 +1661,28 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "normalized_value": "20000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SEMI", "normalized_value": "5000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOFR", "normalized_value": "0.045", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "TBILL_3M", "normalized_value": "0.042", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, ] vin = build_fuse_validated_inputs( @@ -1558,42 +1756,49 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "normalized_value": "50", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOXL", "normalized_value": "40", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "QQQ", "normalized_value": "500", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "XNDX", "normalized_value": "90", "eligibility": {"eligible": False, "reason": "stale_benchmark_bar"}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SEMI", "normalized_value": "5000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOFR", "normalized_value": "0.045", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "TBILL_3M", "normalized_value": "0.042", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, ] @@ -1639,36 +1844,42 @@ def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> No "normalized_value": "45", "eligibility": {"eligible": False, "reason": "stale_fund_bar"}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOXL", "normalized_value": "40", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "XNDX", "normalized_value": "20000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SEMI", "normalized_value": "5000", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "SOFR", "normalized_value": "0.045", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, { "instrument": "TBILL_3M", "normalized_value": "0.042", "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], + "effective_session": "2026-01-05", }, ] From f85af8542ada97cd0fd86e5f16c958694bee4f22 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:00:55 +0000 Subject: [PATCH 08/13] fix(fuse): label adapter self-heartbeat with heartbeat_source Record heartbeat_source="adapter_self" when the adapter defaults the O7 heartbeat to as_of, and "caller" when session inputs supply it, so a self-attested heartbeat is never mistaken for liveness evidence. The ledger-supplied heartbeat follows in part 4 (#13). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 9 +++++++++ tests/test_fuse_adapter.py | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index a55d019..2e10d68 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -1553,7 +1553,16 @@ def build_fuse_validated_inputs( # 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 diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index 0d7c4d8..80506cb 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -1184,6 +1184,13 @@ def _split_inputs(ca: dict) -> dict: 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() From c221b30508e1e81a343f0f95c016c4b88158dae0 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:05:35 +0000 Subject: [PATCH 09/13] docs(fuse): document EOD half-day O2 mapping and pin it with a test SH-2 decisions are end-of-day, so every trading day, half days included, maps to `open`; FuseControl's half_day_cutoff is a pre-trade rule. Pin that the 2026-11-27 14:30 ET half-day decision maps to open with O2 clear, and that late runs are the scheduler cutoff's job. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 9 +++++++++ tests/test_fuse_adapter.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index 2e10d68..700c62f 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -697,6 +697,15 @@ def _map_calendar_statuses( 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" diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index 80506cb..5156e0a 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -1254,6 +1254,37 @@ def test_astra_p1_metadata_pinned_and_loader_executes_verified_source_only(self) 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) From 052c107575fdf38806a9b9a9b001e7752158794e Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:16:08 +0000 Subject: [PATCH 10/13] fix(fuse): resolve Astra round-2 P1s and default substitutions Apply the feeder's exact rate freshness rule, reject records retrieved after the decision instant, reject the ineffective kill_switch_tripped flag, fail closed on conflicting corporate actions and on caller closes that disagree with the validated market close, and pass explicit nulls (broker, cash, exposures, tolerance, proposal) through as missing. Unknown tiers and missing high-water marks no longer fall back to balanced or bankroll defaults. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 192 +++++++++++++++++++++++++++++-------- tests/test_fuse_adapter.py | 165 +++++++++++++++++++++++++++++-- 2 files changed, 309 insertions(+), 48 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index 700c62f..d155f0b 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -798,6 +798,23 @@ def _compute_return_ratio(cur_raw: object, prev_raw: object) -> float | None: _CA_UNDATED = object() +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. @@ -902,16 +919,53 @@ def _derive_one_session_loss(session_inputs: Mapping[str, Any]) -> float | None: _RATE_INSTRUMENTS = frozenset({"SOFR", "TBILL_3M"}) +_EXPECTED_RATE_DAY_CACHE: dict[tuple[str, str], str | None] = {} + + +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 - (SOFR, T-bill) publish with a lag, so they may be effective on an earlier date but never - on a later one; the feeder enforces their exact lag rule when it builds the record. + 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 @@ -924,11 +978,18 @@ def _is_market_record_valid_for_session( eff = rec.get("effective_session") if not isinstance(eff, str) or _parse_valid_ymd(eff) is None: return False - if str(rec.get("instrument")) in _RATE_INSTRUMENTS: - if eff > session_date: + 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: + retrieved = rec.get("retrieval_time_utc") + if not isinstance(retrieved, str) or not retrieved or retrieved > as_of: + return False return True @@ -1086,8 +1147,6 @@ def _derive_default_max_loss_cap( 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)) - elif not require_sizing_bankroll: - e_star_dec = e_dec else: return None @@ -1170,10 +1229,11 @@ def _apply_explicit_payload_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", bankroll_val)), + session_inputs.get("high_water_mark", session_inputs.get("E_star")), ) ) if bankroll_val is not None: @@ -1202,6 +1262,10 @@ def _apply_explicit_payload_tier( 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) @@ -1242,6 +1306,13 @@ def build_fuse_validated_inputs( """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: @@ -1258,8 +1329,10 @@ def build_fuse_validated_inputs( direct = copy.deepcopy(dict(session_inputs)) return _apply_explicit_payload_tier(direct, session_inputs, policy_hash=policy_hash) - tier = str(session_inputs.get("tier", "balanced")) - tier_cfg = TIER_CONFIGS.get(tier, TIER_CONFIGS["balanced"]) + # 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")) @@ -1271,7 +1344,7 @@ def build_fuse_validated_inputs( 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: + 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 @@ -1314,11 +1387,15 @@ def build_fuse_validated_inputs( # 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): + 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) + 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"): @@ -1366,15 +1443,35 @@ def build_fuse_validated_inputs( # Wire feeder market_records[].corporate_action into V2 when fund payload does not override it ca_obj = copy.deepcopy(fdata.get("corporate_action")) - if ( - ca_obj is None - and not bad_market_payload - and symbol not in bad_market_insts - and symbol in by_inst - ): - ca_obj = _map_market_corporate_action( - by_inst[symbol].get("corporate_action") # type: ignore[arg-type] - ) + 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, so fail + # closed rather than silently dropping the new event. + ca_conflict = True + mkt_ok = False + + # 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 + if fdata.get("close_price") is not None and ( + _sizing_decimal(fdata.get("close_price")) is None + or _sizing_decimal(mkt_close) is None + or _sizing_decimal(fdata.get("close_price")) != _sizing_decimal(mkt_close) + ): + 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: @@ -1383,10 +1480,12 @@ def build_fuse_validated_inputs( not bad_market_payload and symbol not in bad_market_insts and symbol in prior_closes - and fdata.get("close_price") is not None + and close_for_return is not None + and not ca_conflict + and not close_mismatch ): fund_ret_val = _compute_ca_adjusted_fund_return( - fdata.get("close_price"), + close_for_return, prior_closes.get(symbol), _ca_in_return_interval(ca_obj, session_date), ) @@ -1411,14 +1510,15 @@ def build_fuse_validated_inputs( # 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.get("broker_position"), tier) - if "broker_position" in fdata and fdata.get("broker_position") is not None + (_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.get("exposure")) if fdata.get("exposure") is not None else pos_val, + "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")), @@ -1434,9 +1534,13 @@ def build_fuse_validated_inputs( "trading_pause": fdata.get("trading_pause"), "session_time": str(fdata["session_time"]) if fdata.get("session_time") is not None else None, "share_count": _preserve_numeric_quantity(q_pre_val) if q_pre_val is not None else 0, - "ledger_value": _finite_number(fdata.get("ledger_value")) if fdata.get("ledger_value") is not None else pos_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.get("broker_value")) if fdata.get("broker_value") is not None else 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")), } @@ -1522,10 +1626,14 @@ def build_fuse_validated_inputs( "tier": tier, "bankroll": bankroll_val, "high_water_mark": hwm_val, - "joint_exposure": _finite_number(session_inputs.get("joint_exposure")) if session_inputs.get("joint_exposure") is not None else derived_joint_exposure, + "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, - "proposed_exposure": _finite_number(session_inputs.get("proposed_exposure")) if session_inputs.get("proposed_exposure") is not None else derived_joint_exposure, + # 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, @@ -1535,10 +1643,20 @@ def build_fuse_validated_inputs( "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. - "positions_cash": _finite_number(session_inputs.get("positions_cash")) if session_inputs.get("positions_cash") is not None else bankroll_val, - "broker_cash": _finite_number(session_inputs.get("broker_cash")) if session_inputs.get("broker_cash") is not None else bankroll_val, - "reconciliation_tolerance": _finite_number(session_inputs.get("reconciliation_tolerance")) if session_inputs.get("reconciliation_tolerance") is not None else 1.0, - "pending_orders": copy.deepcopy(session_inputs.get("pending_orders", {})), + # 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 @@ -1577,15 +1695,13 @@ def build_fuse_validated_inputs( if "scheduled_interval" in session_inputs else 60.0 ), - "tier_loss_budget_D": _TIER_D_MAP.get(tier, 0.30), + "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"] - if session_inputs.get("kill_switch_tripped") is True: - out["kill_switch_tripped"] = True for o7_key in ("o7_runtime_silent", "o7_monitor_silent"): if o7_key in session_inputs: out[o7_key] = bool(session_inputs[o7_key]) diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index 5156e0a..72bc2f5 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -368,6 +368,7 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "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", @@ -375,6 +376,7 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "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", @@ -382,6 +384,7 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "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", @@ -389,6 +392,7 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "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", @@ -396,13 +400,15 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "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-05", + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, { "instrument": "TBILL_3M", @@ -410,6 +416,7 @@ def test_no_silent_synthesis_of_sources_or_zero_returns(self) -> None: "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, ], "funds": { @@ -453,6 +460,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "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, @@ -465,6 +473,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "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"}, }, { @@ -473,6 +482,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "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", @@ -480,6 +490,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "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", @@ -487,13 +498,15 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "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-05", + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, { "instrument": "TBILL_3M", @@ -501,6 +514,7 @@ def _with_ca(split_ratio: str, cash: str) -> dict: "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 @@ -1108,7 +1122,9 @@ def _records(eff: str, **overrides: dict) -> list[dict]: "normalized_value": val, "eligibility": {"eligible": True}, "calendar_spec_digest": cal6["spec_digest"], - "effective_session": eff, + # 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) @@ -1131,11 +1147,58 @@ def _mkt_inputs(recs: list[dict]) -> dict: 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 may lag (earlier effective date) but never lead the decision session. + # 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) - future_rate = _records(sd, SOFR={"effective_session": "2026-01-07"}) - self.assertTrue(_rows(_mkt_inputs(future_rate))["O1"]["would_have_tripped"]) + 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 + self.assertIsNone(_vin(ca_in)["funds"]["TQQQ"]["fund_return"]) + self.assertTrue(_rows(ca_in)["O1"]["would_have_tripped"]) + 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) + [ @@ -1145,6 +1208,7 @@ def _mkt_inputs(recs: list[dict]) -> dict: "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)) @@ -1157,6 +1221,7 @@ def _mkt_inputs(recs: list[dict]) -> dict: "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) @@ -1177,6 +1242,59 @@ def _split_inputs(ca: dict) -> dict: 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-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() @@ -1426,6 +1544,7 @@ def test_fractional_broker_position_and_market_data_validation_preserved(self) - "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") @@ -1591,6 +1710,7 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "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", @@ -1603,6 +1723,7 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "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"}, }, { @@ -1611,6 +1732,7 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "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", @@ -1618,6 +1740,7 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "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", @@ -1625,13 +1748,15 @@ def test_split_with_cash_distribution_preserves_both_components_and_avoids_false "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-05", + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, ] @@ -1678,6 +1803,7 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "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", @@ -1685,6 +1811,7 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "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", @@ -1692,6 +1819,7 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "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"}, }, { @@ -1700,6 +1828,7 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "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", @@ -1707,13 +1836,15 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "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-05", + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, { "instrument": "TBILL_3M", @@ -1721,6 +1852,7 @@ def test_qqq_forward_split_does_not_leak_into_l6_index_crash_inputs(self) -> Non "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( @@ -1795,6 +1927,7 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "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", @@ -1802,6 +1935,7 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "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", @@ -1809,6 +1943,7 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "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", @@ -1816,6 +1951,7 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "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", @@ -1823,13 +1959,15 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "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-05", + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, { "instrument": "TBILL_3M", @@ -1837,6 +1975,7 @@ def test_ineligible_benchmark_price_is_excluded_from_v1_return_derivation(self) "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, ] @@ -1883,6 +2022,7 @@ def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> No "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", @@ -1890,6 +2030,7 @@ def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> No "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", @@ -1897,6 +2038,7 @@ def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> No "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", @@ -1904,13 +2046,15 @@ def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> No "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-05", + "effective_session": "2026-01-02", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, { "instrument": "TBILL_3M", @@ -1918,6 +2062,7 @@ def test_ineligible_fund_price_is_excluded_from_v1_return_derivation(self) -> No "eligibility": {"eligible": True}, "calendar_spec_digest": cal["spec_digest"], "effective_session": "2026-01-05", + "retrieval_time_utc": "2026-01-05T21:30:00.000Z", }, ] From 94f9aa49d923559d4c3046ff4eb685d776747544 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:20:44 +0000 Subject: [PATCH 11/13] fix(fuse): compare caller and market closes by decimal value The close-mismatch guard must compare values, not the strict sizing parser (which rejects floats by design), so a float and a canonical decimal string for the same close are treated as equal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index d155f0b..eb87c97 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -798,6 +798,17 @@ def _compute_return_ratio(cur_raw: object, prev_raw: object) -> float | None: _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): @@ -1465,10 +1476,10 @@ def build_fuse_validated_inputs( 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 ( - _sizing_decimal(fdata.get("close_price")) is None - or _sizing_decimal(mkt_close) is None - or _sizing_decimal(fdata.get("close_price")) != _sizing_decimal(mkt_close) + caller_close_dec is None or mkt_close_dec is None or caller_close_dec != mkt_close_dec ): close_mismatch = True mkt_ok = False From cd7a2c1c7e94824d1e434ab491be1e2e903ced6d Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:32:26 +0000 Subject: [PATCH 12/13] fix(fuse): resolve Astra round-3 safety P1s in adapter and evaluator Reject conflicting corporate actions before any successor state, never let current_index_closes override a validated record, propagate unknown held-position values into reconciliation and aggregates, reject kill_switch_tripped on the effective payload at the evaluator boundary, drop source records dated after the decision instant, and compare timestamps as aware instants rather than strings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 96 +++++++++++++++++++++++++++++++------- tests/test_fuse_adapter.py | 56 +++++++++++++++++++++- 2 files changed, 134 insertions(+), 18 deletions(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index eb87c97..a8805f6 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -100,6 +100,10 @@ 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.""" @@ -933,6 +937,29 @@ def _derive_one_session_loss(session_inputs: Mapping[str, Any]) -> float | None: _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. @@ -997,10 +1024,8 @@ def _is_market_record_valid_for_session( return False elif eff != session_date: return False - if as_of is not None: - retrieved = rec.get("retrieval_time_utc") - if not isinstance(retrieved, str) or not retrieved or retrieved > as_of: - return False + if as_of is not None and not _not_after(rec.get("retrieval_time_utc"), as_of): + return False return True @@ -1421,8 +1446,20 @@ def build_fuse_validated_inputs( cur_idx_override = session_inputs.get("current_index_closes") if isinstance(cur_idx_override, Mapping): for k, v in cur_idx_override.items(): - if v is not None: - cur_closes[str(k)] = v + 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]] = {} @@ -1444,12 +1481,23 @@ def build_fuse_validated_inputs( 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 - pos_val = (close_val * q_pre_val) if (close_val is not None and q_pre_val is not None) else 0.0 + # 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: - beta_dec = _FUND_EXPOSURE_BETA.get(symbol, Decimal("1")) - joint_exposure_dec += ( - _LEVERAGE_MULTIPLE * beta_dec * Decimal(str(pos_val)) - ) / conv_scale + 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 @@ -1464,10 +1512,13 @@ def build_fuse_validated_inputs( 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, so fail - # closed rather than silently dropping the new event. - ca_conflict = True - mkt_ok = False + # 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). @@ -1630,7 +1681,13 @@ def build_fuse_validated_inputs( if cal_ok else None, } - source_records = {k: v for k, v in raw_source_records.items() if v is not 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] = { @@ -1808,6 +1865,13 @@ def evaluate( 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" + ) validate_v2_reconciliation_payload(validated_inputs) auth_events_arg: dict | list | None diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index 72bc2f5..e3bf2a3 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -1191,8 +1191,11 @@ def _mkt_inputs(recs: list[dict]) -> dict: "hwm_adjusted": True, } ca_in["funds"]["TQQQ"]["hwm_adjusted"] = True - self.assertIsNone(_vin(ca_in)["funds"]["TQQQ"]["fund_return"]) - self.assertTrue(_rows(ca_in)["O1"]["would_have_tripped"]) + # 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}}) ) @@ -1295,6 +1298,55 @@ def _split_inputs(ca: dict) -> dict: ) 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"]) + # 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() From f75ca8b7dcd24340ab1d9a7bcdd2e03e36b12842 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:49:20 +0000 Subject: [PATCH 13/13] fix(fuse): guard source dates at evaluator, keep unknown shares None Drop source records dated after the decision instant at the evaluator boundary so nested fuse_inputs and direct payloads are covered, and pass an unknown ledger quantity as share_count None (0 only for an explicitly flat position) so O3/V2 cannot clear on an invented zero. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdGvqQh5k2bkN5Eiuq --- src/shadow/fuse_adapter.py | 27 +++++++++++++++++- tests/test_fuse_adapter.py | 57 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/src/shadow/fuse_adapter.py b/src/shadow/fuse_adapter.py index a8805f6..f79d26f 100644 --- a/src/shadow/fuse_adapter.py +++ b/src/shadow/fuse_adapter.py @@ -1595,7 +1595,9 @@ def build_fuse_validated_inputs( "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, - "share_count": _preserve_numeric_quantity(q_pre_val) if q_pre_val is not None else 0, + # 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": ( @@ -1798,6 +1800,28 @@ def build_fuse_validated_inputs( 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.""" @@ -1872,6 +1896,7 @@ def evaluate( "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 diff --git a/tests/test_fuse_adapter.py b/tests/test_fuse_adapter.py index e3bf2a3..5c5fadd 100644 --- a/tests/test_fuse_adapter.py +++ b/tests/test_fuse_adapter.py @@ -1347,6 +1347,63 @@ def _split_inputs(ca: dict) -> dict: 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()