325 lines
12 KiB
Python
325 lines
12 KiB
Python
"""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, timedelta, timezone
|
|
from pathlib import Path
|
|
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"
|
|
|
|
_EPOCH_UTC = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
|
_DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
|
|
_ISO_INSTANT_RE = re.compile(
|
|
r"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\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
|
|
from_micros: int | None = None
|
|
to_micros: int | None = None
|
|
as_of_micros: int | None = None
|
|
|
|
def __post_init__(self) -> None:
|
|
if self.from_micros is None:
|
|
object.__setattr__(self, "from_micros", self.from_ms * 1000)
|
|
if self.to_micros is None:
|
|
object.__setattr__(
|
|
self,
|
|
"to_micros",
|
|
self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0),
|
|
)
|
|
if self.as_of_micros is None:
|
|
object.__setattr__(
|
|
self,
|
|
"as_of_micros",
|
|
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 _datetime_to_epoch_micros(dt: datetime) -> int:
|
|
delta = dt.astimezone(timezone.utc) - _EPOCH_UTC
|
|
return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds
|
|
|
|
|
|
def epoch_micros_to_datetime(micros: int) -> datetime:
|
|
"""Converts exact UTC epoch microseconds to a timezone-aware UTC datetime without float rounding."""
|
|
return _EPOCH_UTC + timedelta(microseconds=micros)
|
|
|
|
|
|
def format_utc_iso_micros(micros: int) -> str:
|
|
"""Formats exact UTC epoch microseconds as ISO-8601 UTC string."""
|
|
dt = epoch_micros_to_datetime(micros)
|
|
if dt.microsecond % 1000 == 0:
|
|
ms = dt.microsecond // 1000
|
|
return dt.strftime("%Y-%m-%dT%H:%M:%S") + f".{ms:03d}Z"
|
|
return dt.strftime("%Y-%m-%dT%H:%M:%S") + f".{dt.microsecond:06d}Z"
|
|
|
|
|
|
def parse_timestamp_micros(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
|
|
"""Parses a UTC ISO-8601 date or timestamp into exact integer epoch microseconds."""
|
|
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))
|
|
try:
|
|
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, 999_999, tzinfo=timezone.utc)
|
|
except ValueError as exc:
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid calendar date for "{field}": "{raw}".'
|
|
) from exc
|
|
return _datetime_to_epoch_micros(dt)
|
|
|
|
im = _ISO_INSTANT_RE.match(raw)
|
|
if im:
|
|
year, month, day = int(im.group(1)), int(im.group(2)), int(im.group(3))
|
|
hour, minute, second = int(im.group(4)), int(im.group(5)), int(im.group(6))
|
|
frac = im.group(7)
|
|
micros = int(frac[:6].ljust(6, "0")) if frac is not None else 0
|
|
tz_token = im.group(8)
|
|
offset_micros = 0
|
|
if tz_token != "Z":
|
|
tz_sign = 1 if im.group(9) == "+" else -1
|
|
tz_hours = int(im.group(10))
|
|
tz_mins = int(im.group(11))
|
|
if tz_hours > 23 or tz_mins > 59:
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid timezone offset for "{field}": "{raw}".'
|
|
)
|
|
offset_micros = tz_sign * (tz_hours * 60 + tz_mins) * 60_000_000
|
|
try:
|
|
dt = datetime(year, month, day, hour, minute, second, micros, tzinfo=timezone.utc)
|
|
except ValueError as exc:
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
|
|
) from exc
|
|
return _datetime_to_epoch_micros(dt) - offset_micros
|
|
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
|
|
)
|
|
|
|
|
|
def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
|
|
return parse_timestamp_micros(raw, bound_kind, field) // 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 = _datetime_to_epoch_micros(max_ingested_ts) // 1000
|
|
else:
|
|
raise MarketDataStoreValidationError("Invalid max_ingested_ts type.")
|
|
|
|
dt = epoch_micros_to_datetime(epoch_ms * 1000)
|
|
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 _datetime_to_epoch_micros(cutoff_dt) // 1000
|
|
|
|
|
|
def vault_cutoff_date_str(vault_cutoff_ts: int) -> str:
|
|
return epoch_micros_to_datetime(vault_cutoff_ts * 1000).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:
|
|
if not isinstance(vault_cutoff_ts, int) or isinstance(vault_cutoff_ts, bool):
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid epoch millisecond timestamp for vault_cutoff_ts: {vault_cutoff_ts!r}."
|
|
)
|
|
from_micros = parse_timestamp_micros(from_bound, "start", "from")
|
|
to_micros = parse_timestamp_micros(to_bound, "end", "to")
|
|
if to_micros < from_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f'Query end "{to_bound}" ({to_micros // 1000}) precedes start "{from_bound}" ({from_micros // 1000}).'
|
|
)
|
|
|
|
if scope == "vault_evaluation_only":
|
|
if not vault_operator_authorized:
|
|
raise VaultScopeNotAuthorizedError(
|
|
"Data scope 'vault_evaluation_only' requires explicit human operator authorization."
|
|
)
|
|
as_of_micros = (
|
|
parse_timestamp_micros(as_of, "end", "as_of") if as_of is not None else to_micros
|
|
)
|
|
return FencedTimeRange(
|
|
from_ms=from_micros // 1000,
|
|
to_ms=to_micros // 1000,
|
|
as_of_ms=as_of_micros // 1000,
|
|
scope=scope,
|
|
clamped_to=False,
|
|
clamped_as_of=False,
|
|
from_micros=from_micros,
|
|
to_micros=to_micros,
|
|
as_of_micros=as_of_micros,
|
|
)
|
|
|
|
if scope != "vault_fenced":
|
|
raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}")
|
|
|
|
cutoff_micros = vault_cutoff_ts * 1000
|
|
max_allowed_micros = cutoff_micros - 1
|
|
|
|
if from_micros >= cutoff_micros:
|
|
raise VaultHoldoutFenceError(from_bound, from_micros // 1000, vault_cutoff_ts)
|
|
|
|
clamped_to = False
|
|
if to_micros >= cutoff_micros:
|
|
to_micros = max_allowed_micros
|
|
clamped_to = True
|
|
|
|
clamped_as_of = False
|
|
if as_of is None:
|
|
as_of_micros = max_allowed_micros
|
|
else:
|
|
as_of_micros = parse_timestamp_micros(as_of, "end", "as_of")
|
|
if as_of_micros >= cutoff_micros:
|
|
as_of_micros = max_allowed_micros
|
|
clamped_as_of = True
|
|
|
|
return FencedTimeRange(
|
|
from_ms=from_micros // 1000,
|
|
to_ms=to_micros // 1000,
|
|
as_of_ms=as_of_micros // 1000,
|
|
scope="vault_fenced",
|
|
clamped_to=clamped_to,
|
|
clamped_as_of=clamped_as_of,
|
|
from_micros=from_micros,
|
|
to_micros=to_micros,
|
|
as_of_micros=as_of_micros,
|
|
)
|
|
|
|
|
|
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)
|
|
|
|
|
|
def validate_curated_root(raw: str | Path) -> str:
|
|
"""Validates `curated_root` as an absolute POSIX path without quotes, semicolons, control chars, or globs."""
|
|
if isinstance(raw, Path):
|
|
value = str(raw)
|
|
elif isinstance(raw, str):
|
|
value = raw
|
|
else:
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid curated_root {raw!r}. Expected a non-empty absolute POSIX path."
|
|
)
|
|
|
|
if not value or not value.startswith("/"):
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid curated_root "{value}". Expected a non-empty absolute POSIX path.'
|
|
)
|
|
|
|
for ch in value:
|
|
code = ord(ch)
|
|
if code <= 0x1F or code == 0x7F or ch in ("'", ";", "*", "?", "[", "]"):
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid curated_root "{value}". Path must not contain control characters, quotes, semicolons, or glob characters (*, ?, [, ]).'
|
|
)
|
|
|
|
normalized = value.rstrip("/")
|
|
return normalized if normalized else "/"
|