"""Versioned admission deadlines and fixed event leases for ETF signals. Missing policy metadata always means the original twenty-minute contract. The delayed policy admits a new evaluation strictly before window_end + 10m, then retains a legally admitted event until window_end + 30m. Neither deadline slides on delivery/retry, and both are capped by the 15:00 market close. """ from __future__ import annotations from datetime import datetime, timedelta from typing import Mapping from zoneinfo import ZoneInfo SHANGHAI = ZoneInfo("Asia/Shanghai") LEGACY_POLICY = "legacy-v1" DELAYED_POLICY = "etf-delayed-v2" SUPPORTED_POLICIES = frozenset({LEGACY_POLICY, DELAYED_POLICY}) def _version(value): if not isinstance(value, str) or value not in SUPPORTED_POLICIES: raise ValueError("unsupported timing_policy_version") return value def policy_version(value: Mapping) -> str: """Read explicit metadata; absence is legacy, never the deployment default.""" if not isinstance(value, Mapping): raise ValueError("timing policy metadata must be a mapping") return _version(value.get("timing_policy_version", LEGACY_POLICY)) def _end(value): if isinstance(value, str): value = datetime.fromisoformat(value.replace("Z", "+00:00")) if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None: raise ValueError("window_end must be timezone-aware") return value.astimezone(SHANGHAI) def lease_until(window_end, policy_version: str = LEGACY_POLICY) -> datetime: version = _version(policy_version) end = _end(window_end) minutes = 30 if version == DELAYED_POLICY else 20 close = end.replace(hour=15, minute=0, second=0, microsecond=0) return min(end + timedelta(minutes=minutes), close) def admission_until(window_end, policy_version: str = LEGACY_POLICY) -> datetime: version = _version(policy_version) end = _end(window_end) if version == LEGACY_POLICY: return lease_until(end, version) close = end.replace(hour=15, minute=0, second=0, microsecond=0) return min(end + timedelta(minutes=10), close)