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 + } + } + } +}