"""Rolling 6-month UTC Vault holdout fence & DuckDB connection budget.""" from __future__ import annotations import calendar import os import re from dataclasses import dataclass from datetime import datetime, timezone from typing import Literal, Mapping DataScope = Literal["vault_fenced", "vault_evaluation_only"] DEFAULT_DUCKDB_MEMORY_LIMIT = "6GB" DEFAULT_DUCKDB_THREADS = 4 DEFAULT_DUCKDB_TEMP_DIRECTORY = "/mnt/data/stockbot/tmp/duckdb" _DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$") _MEM_LIMIT_RE = re.compile(r"^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$") class MarketDataStoreValidationError(ValueError): """Raised when market-data query bounds, timestamps, or budgets are invalid.""" class VaultHoldoutFenceError(PermissionError): """Raised when a fenced query reaches or exceeds the rolling 6-month Vault cutoff.""" def __init__(self, from_bound: str, from_ms: int, vault_cutoff_ts: int) -> None: super().__init__( f'Query start "{from_bound}" ({from_ms}) reaches or exceeds Vault cutoff ({vault_cutoff_ts}).' ) self.from_bound = from_bound self.from_ms = from_ms self.vault_cutoff_ts = vault_cutoff_ts class VaultScopeNotAuthorizedError(PermissionError): """Raised when vault_evaluation_only is requested without operator authorization.""" @dataclass(frozen=True) class FencedTimeRange: from_ms: int to_ms: int as_of_ms: int scope: DataScope clamped_to: bool clamped_as_of: bool @property def from_micros(self) -> int: return self.from_ms * 1000 @property def to_micros(self) -> int: # Expand end-of-ms inclusive boundary to last microsecond (.999999) when ms ends in 999 return self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0) @property def as_of_micros(self) -> int: return self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0) @dataclass(frozen=True) class DuckDbConnectionBudget: memory_limit: str threads: int temp_directory: str @property def statements(self) -> tuple[str, str, str]: escaped = self.temp_directory.replace("'", "''") return ( f"SET memory_limit = '{self.memory_limit}';", f"SET threads = {self.threads};", f"SET temp_directory = '{escaped}';", ) def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int: if not isinstance(raw, str) or not raw: raise MarketDataStoreValidationError(f'Expected non-empty ISO-8601 string for "{field}".') m = _DATE_ONLY_RE.match(raw) if m: year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3)) if bound_kind == "start": dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc) else: dt = datetime(year, month, day, 23, 59, 59, 999000, tzinfo=timezone.utc) return int(dt.timestamp() * 1000) try: dt = datetime.fromisoformat(raw.replace("Z", "+00:00")) except ValueError as exc: raise MarketDataStoreValidationError( f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".' ) from exc if dt.tzinfo is None: raise MarketDataStoreValidationError( f'Naive timestamp without timezone offset is forbidden for "{field}": "{raw}".' ) dt_utc = dt.astimezone(timezone.utc) return int(dt_utc.timestamp() * 1000) def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int: """Computes rolling 6-month Vault cutoff (`max_ingested_ts - 6 calendar months` UTC).""" if isinstance(max_ingested_ts, int) and not isinstance(max_ingested_ts, bool): epoch_ms = max_ingested_ts elif isinstance(max_ingested_ts, str): epoch_ms = parse_timestamp_ms(max_ingested_ts, "start", "max_ingested_ts") elif isinstance(max_ingested_ts, datetime): if max_ingested_ts.tzinfo is None: raise MarketDataStoreValidationError("max_ingested_ts datetime must be timezone-aware.") epoch_ms = int(max_ingested_ts.astimezone(timezone.utc).timestamp() * 1000) else: raise MarketDataStoreValidationError("Invalid max_ingested_ts type.") dt = datetime.fromtimestamp(epoch_ms / 1000.0, tz=timezone.utc) total_months = dt.year * 12 + (dt.month - 1) - 6 target_year, target_month_zero = divmod(total_months, 12) target_month = target_month_zero + 1 max_day = calendar.monthrange(target_year, target_month)[1] target_day = min(dt.day, max_day) cutoff_dt = datetime( target_year, target_month, target_day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=timezone.utc, ) return int(cutoff_dt.timestamp() * 1000) def vault_cutoff_date_str(vault_cutoff_ts: int) -> str: return datetime.fromtimestamp(vault_cutoff_ts / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d") def apply_vault_fence( from_bound: str, to_bound: str, vault_cutoff_ts: int, as_of: str | None = None, scope: DataScope = "vault_fenced", vault_operator_authorized: bool = False, ) -> FencedTimeRange: from_ms = parse_timestamp_ms(from_bound, "start", "from") to_ms = parse_timestamp_ms(to_bound, "end", "to") if to_ms < from_ms: raise MarketDataStoreValidationError( f'Query end "{to_bound}" ({to_ms}) precedes start "{from_bound}" ({from_ms}).' ) if scope == "vault_evaluation_only": if not vault_operator_authorized: raise VaultScopeNotAuthorizedError( "Data scope 'vault_evaluation_only' requires explicit human operator authorization." ) as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of is not None else to_ms return FencedTimeRange( from_ms=from_ms, to_ms=to_ms, as_of_ms=as_of_ms, scope=scope, clamped_to=False, clamped_as_of=False, ) if scope != "vault_fenced": raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}") if from_ms >= vault_cutoff_ts: raise VaultHoldoutFenceError(from_bound, from_ms, vault_cutoff_ts) clamped_to = False if to_ms >= vault_cutoff_ts: to_ms = vault_cutoff_ts - 1 clamped_to = True clamped_as_of = False if as_of is None: as_of_ms = vault_cutoff_ts - 1 else: as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of_ms >= vault_cutoff_ts: as_of_ms = vault_cutoff_ts - 1 clamped_as_of = True return FencedTimeRange( from_ms=from_ms, to_ms=to_ms, as_of_ms=as_of_ms, scope="vault_fenced", clamped_to=clamped_to, clamped_as_of=clamped_as_of, ) def resolve_duckdb_budget( env: Mapping[str, str] | None = None, *, memory_limit: str | None = None, threads: int | None = None, temp_directory: str | None = None, ) -> DuckDbConnectionBudget: source = env if env is not None else os.environ mem = memory_limit or source.get("STOCK_BOT_DUCKDB_MEMORY_LIMIT") or DEFAULT_DUCKDB_MEMORY_LIMIT if not _MEM_LIMIT_RE.match(mem): raise MarketDataStoreValidationError(f"Invalid DuckDB memory_limit: {mem!r}") raw_threads = threads if threads is not None else int( source.get("STOCK_BOT_DUCKDB_THREADS", str(DEFAULT_DUCKDB_THREADS)) ) if not isinstance(raw_threads, int) or raw_threads < 1 or raw_threads > 64: raise MarketDataStoreValidationError(f"Invalid DuckDB threads: {raw_threads!r}") tmp_dir = ( temp_directory or source.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY") or DEFAULT_DUCKDB_TEMP_DIRECTORY ) if not tmp_dir or not tmp_dir.startswith("/"): raise MarketDataStoreValidationError(f"Invalid DuckDB temp_directory: {tmp_dir!r}") return DuckDbConnectionBudget(memory_limit=mem, threads=raw_threads, temp_directory=tmp_dir)