"""Read side: DuckDB over the live Parquet file set selected from the Postgres manifest (`lake_files`). Adjustments are applied at query time from `corporate_actions` (explicit, reproducible): split : multiply prices by Π(1/ratio) for splits with ex_date > bar session_date; divide volume by the same factor split_div : additionally multiply by Π(1 - div/prev_close) for dividends with ex_date > session_date (prev_close = last raw close strictly before ex_date in the requested data — if unavailable the dividend factor is skipped and reported in `adjustment_notes`). """ from __future__ import annotations import re from datetime import date from typing import Any import duckdb import pyarrow as pa from findata_core.db import connection from findata_schema import BARS_SCHEMA from findata_ingest.lake import Lake, live_files def _con(read_only: bool = True) -> duckdb.DuckDBPyConnection: import resource try: # scans over many Parquet files need file descriptors (macOS default soft limit is 256) soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) if soft < 65536: resource.setrlimit(resource.RLIMIT_NOFILE, (min(65536, hard), hard)) except (ValueError, OSError): pass con = duckdb.connect(database=":memory:", config={"threads": 4, "memory_limit": "4GB", "TimeZone": "UTC"}) return con def _arrow(con: duckdb.DuckDBPyConnection, sql: str, params: dict[str, Any] | None) -> pa.Table: try: rel = con.sql(sql, params=params) if params else con.sql(sql) return rel.to_arrow_table() except TypeError: # older duckdb without params= on sql() return con.execute(sql, params).fetch_arrow_table() def empty_bars() -> pa.Table: return pa.table({f.name: pa.array([], type=f.type) for f in BARS_SCHEMA}, schema=BARS_SCHEMA) def read_bars(dataset_id: str, symbols: list[str], start: date | None, end: date | None, version: int | None = None, limit: int | None = None, columns: list[str] | None = None, lake: Lake | None = None) -> tuple[pa.Table, dict[str, Any]]: lake = lake or Lake() with connection() as conn: files = live_files(conn, dataset_id, symbols, start, end, version) ver = conn.execute("SELECT current_version FROM datasets WHERE id=%s", (dataset_id,)).fetchone() meta = {"dataset_id": dataset_id, "version": version if version is not None else (ver["current_version"] if ver else None), "files_scanned": len(files)} if not files: return empty_bars(), meta paths = [str(lake.resolve(f["path"])) for f in files] con = _con() con.register("paths", pa.table({"p": paths})) cols = ", ".join(columns) if columns else "*" where = ["symbol_as_reported IN (SELECT UNNEST($syms))"] params: dict[str, Any] = {"syms": symbols} if start: where.append("session_date >= $start") params["start"] = start if end: where.append("session_date <= $end") params["end"] = end sql = f"SELECT {cols} FROM read_parquet($paths, union_by_name=true, hive_partitioning=false) WHERE {' AND '.join(where)} ORDER BY symbol_as_reported, timestamp_utc" params["paths"] = paths if limit: sql += f" LIMIT {int(limit) + 1}" tbl = _arrow(con, sql, params) meta["truncated"] = bool(limit and tbl.num_rows > limit) if limit and tbl.num_rows > limit: tbl = tbl.slice(0, limit) if not columns: tbl = tbl.cast(BARS_SCHEMA) return tbl, meta def apply_adjustment(table: pa.Table, adjustment: str, lake: Lake | None = None) -> tuple[pa.Table, list[str]]: """Return an adjusted copy of raw bars (`adjustment_type` column updated). Never mutates the lake.""" if adjustment in ("raw", None) or table.num_rows == 0: return table, [] import polars as pl df = pl.from_arrow(table) syms = df.get_column("symbol_as_reported").unique().to_list() iids = [f"firstrate:{df.filter(pl.col('symbol_as_reported') == s).get_column('asset_class')[0]}:{s}" for s in syms] with connection() as conn: acts = conn.execute("SELECT instrument_id, action_type, ex_date, value::float8 AS value FROM corporate_actions WHERE instrument_id = ANY(%s) ORDER BY ex_date", (iids,)).fetchall() notes: list[str] = [] if not acts: notes.append("no corporate actions on file for requested symbols") return df.with_columns(pl.lit(adjustment).alias("adjustment_type")).to_arrow().cast(BARS_SCHEMA), notes out_frames = [] for s in syms: sub = df.filter(pl.col("symbol_as_reported") == s).sort("timestamp_utc") iid = f"firstrate:{sub.get_column('asset_class')[0]}:{s}" factor = pl.Series("f", [1.0] * sub.height) sd = sub.get_column("session_date") for a in acts: if a["instrument_id"] != iid: continue if a["action_type"] == "split": f = 1.0 / float(a["value"]) factor = factor * pl.Series([f if d < a["ex_date"] else 1.0 for d in sd]) elif a["action_type"] == "dividend" and adjustment == "split_div": prev = sub.filter(pl.col("session_date") < a["ex_date"]).get_column("close") if prev.len() == 0: notes.append(f"{s}: dividend {a['ex_date']} skipped (no prior close in range)") continue f = 1.0 - float(a["value"]) / float(prev[-1]) factor = factor * pl.Series([f if d < a["ex_date"] else 1.0 for d in sd]) sub = sub.with_columns(factor.alias("_f")).with_columns( (pl.col("open") * pl.col("_f")).alias("open"), (pl.col("high") * pl.col("_f")).alias("high"), (pl.col("low") * pl.col("_f")).alias("low"), (pl.col("close") * pl.col("_f")).alias("close"), (pl.col("volume") / pl.col("_f")).alias("volume"), pl.lit(adjustment).alias("adjustment_type")).drop("_f") out_frames.append(sub) res = pl.concat(out_frames).sort(["symbol_as_reported", "timestamp_utc"]) return res.to_arrow().cast(BARS_SCHEMA), notes def run_sql(sql: str, max_rows: int, timeout_s: int, views: dict[str, Any] | None = None) -> tuple[pa.Table, dict[str, Any]]: """Sandboxed read-only SQL: DuckDB in-memory, external access limited to the registered dataset views.""" import re import threading forbidden = re.compile(r"\b(attach|copy|export|import|install|load|create|insert|update|delete|drop|alter|pragma|set|call|read_csv|read_json|read_text|glob|httpfs)\b", re.IGNORECASE) if forbidden.search(sql) or ";" in sql.strip().rstrip(";"): raise ValueError("only a single read-only SELECT statement is allowed") if not re.match(r"^\s*(select|with|describe|show|summarize|explain)\b", sql, re.IGNORECASE): raise ValueError("statement must start with SELECT / WITH") is_explain = bool(re.match(r"^\s*explain\b", sql, re.I)) con = _con() scoped_used: list[str] = [] dirs = [] for r in Lake().roots(): rr = str(r.resolve()).replace("'", "''") dirs += [f"'{rr}/curated'", f"'{rr}/_retired'"] con.execute(f"SET allowed_directories = [{', '.join(dirs)}]") for name, spec in (views or {}).items(): if not re.fullmatch(r"[a-z][a-z0-9_]*", name): raise ValueError(f"bad view name {name}") if name not in _referenced_views(sql, {name: spec}): continue # only materialize views the statement uses (directory globs are not free) if isinstance(spec, dict) and spec.get("sql"): fast = None if spec.get("dataset_id"): try: fast = scoped_view_sql(spec["dataset_id"], spec.get("kind", ""), extract_scope(sql), Lake()) except Exception: fast = None con.execute(f"CREATE VIEW {name} AS {fast or spec['sql']}") scoped_used.append(name if fast else f"{name} (full scan)") elif isinstance(spec, list) and spec: # legacy explicit file list lst = ", ".join("'" + g.replace("'", "''") + "'" for g in spec) con.execute(f"CREATE VIEW {name} AS SELECT * FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false)") else: con.execute(f"CREATE VIEW {name} AS SELECT * FROM (VALUES (NULL)) t(empty) WHERE false") con.execute("SET enable_external_access = false") timer = threading.Timer(timeout_s, con.interrupt) timer.start() try: body = sql.strip().rstrip(";") tbl = _arrow(con, body if is_explain else f"SELECT * FROM ({body}) q LIMIT {int(max_rows) + 1}", None) except duckdb.InterruptException as e: raise TimeoutError(f"query exceeded {timeout_s}s") from e finally: timer.cancel() truncated = tbl.num_rows > max_rows return tbl.slice(0, max_rows), {"truncated": truncated, "views": scoped_used} _views_cache: dict[str, Any] = {"at": 0.0, "value": None} def dataset_views() -> dict[str, dict[str, Any]]: """SQL views for the playground/assistant: one per dataset with data, built from Hive-style directory globs (`curated//{base,delta}/**`) so that DuckDB prunes partitions (`symbol=`, `year=`, `session_date=`, `underlying=`, `period=`) from the path instead of receiving millions of file names. The directory tree is the live set (retired files are moved out); files of an in-progress publication may be visible for a few minutes. Cached 5 minutes.""" import time if _views_cache["value"] is not None and time.monotonic() - _views_cache["at"] < 300: return _views_cache["value"] lake = Lake() out: dict[str, dict[str, Any]] = {} with connection() as conn: ds = conn.execute("SELECT id, kind FROM datasets WHERE kind IN ('market_bars','derived','options') AND current_version > 0").fetchall() for d in ds: root = lake.root_for(d["id"]) layouts = {} for layout in ("base", "delta"): ldir = root / "curated" / d["id"] / layout if ldir.exists() and next(ldir.rglob("*.parquet"), None) is not None: # skip emptied layouts layouts[layout] = str(ldir / "**" / "*.parquet").replace("'", "''") if not layouts: continue parts = [] if d["kind"] == "options": parts.append(f"SELECT * FROM read_parquet('{layouts['base']}', hive_partitioning=true)") else: if "base" in layouts: # partition columns symbol=, year= come from the path (pruned before any file is opened) parts.append(f"SELECT * FROM read_parquet('{layouts['base']}', hive_partitioning=true)") if "delta" in layouts: # session files: derive the same columns so UNION ALL BY NAME lines up parts.append(f"SELECT *, symbol_as_reported AS symbol, year(session_date)::BIGINT AS year " f"FROM read_parquet('{layouts['delta']}', hive_partitioning=false)") out[d["id"].replace(".", "_")] = {"sql": " UNION ALL BY NAME ".join(parts), "layouts": sorted(layouts), "root": str(root), "kind": d["kind"], "dataset_id": d["id"]} _views_cache.update(at=time.monotonic(), value=out) return out _SYM_RE = re.compile(r"\b(?:symbol|symbol_as_reported|underlying)\s*=\s*'([A-Za-z0-9.\-_]+)'", re.I) _SYM_IN_RE = re.compile(r"\b(?:symbol|symbol_as_reported|underlying)\s+IN\s*\(([^)]+)\)", re.I) _YEAR_RE = re.compile(r"\byear\s*=\s*(\d{4})\b", re.I) _YEAR_IN_RE = re.compile(r"\byear\s+IN\s*\(([^)]+)\)", re.I) _DATE_RE = re.compile(r"\b(?:session_date|trade_date)\s*(>=|<=|=|>|<)\s*(?:DATE\s*)?'(\d{4}-\d{2}-\d{2})'", re.I) _BETWEEN_RE = re.compile(r"\b(?:session_date|trade_date)\s+BETWEEN\s+(?:DATE\s*)?'(\d{4}-\d{2}-\d{2})'\s+AND\s+(?:DATE\s*)?'(\d{4}-\d{2}-\d{2})'", re.I) def extract_scope(sql: str) -> dict[str, Any]: """Pull simple equality/IN/range predicates on partition columns out of a statement so that the file list can be resolved from the catalog (indexed) instead of globbing hundreds of thousands of files.""" from datetime import date as _date syms: set[str] = {m.group(1).upper() for m in _SYM_RE.finditer(sql)} for m in _SYM_IN_RE.finditer(sql): syms |= {x.strip().strip("'\"").upper() for x in m.group(1).split(",") if x.strip()} years: set[int] = {int(m.group(1)) for m in _YEAR_RE.finditer(sql)} for m in _YEAR_IN_RE.finditer(sql): years |= {int(x) for x in re.findall(r"\d{4}", m.group(1))} start = end = None for op, d in _DATE_RE.findall(sql): dd = _date.fromisoformat(d) if op in (">=", ">", "="): start = dd if start is None else max(start, dd) if op in ("<=", "<", "="): end = dd if end is None else min(end, dd) for a, b in _BETWEEN_RE.findall(sql): start = max(start, _date.fromisoformat(a)) if start else _date.fromisoformat(a) end = min(end, _date.fromisoformat(b)) if end else _date.fromisoformat(b) if years: ys, ye = _date(min(years), 1, 1), _date(max(years), 12, 31) start = ys if start is None else max(start, ys) end = ye if end is None else min(end, ye) return {"symbols": sorted(syms), "start": start, "end": end} def scoped_view_sql(dataset_id: str, kind: str, scope: dict[str, Any], lake: Lake) -> str | None: """Explicit file list from the catalog for symbol-scoped statements (fast path). None → use the glob view.""" if not scope["symbols"] and not (scope["start"] or scope["end"]): return None with connection() as conn: files = live_files(conn, dataset_id, scope["symbols"] or None, scope["start"], scope["end"]) if len(files) > 20000: return None # too broad for an explicit list: directory scan instead if not files: return "SELECT * FROM (VALUES (NULL)) t(empty) WHERE false" lst = ", ".join("'" + str(lake.resolve(f["path"])).replace("'", "''") + "'" for f in files) if kind == "options": return (f"SELECT * EXCLUDE (filename), regexp_extract(filename, 'period=([^/]+)', 1) AS period " f"FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false, filename=true)") return (f"SELECT *, symbol_as_reported AS symbol, year(session_date)::BIGINT AS year " f"FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false)") def _referenced_views(sql: str, views: dict[str, Any]) -> list[str]: import re as _re low = sql.lower() return [name for name in views if _re.search(r"\b" + _re.escape(name) + r"\b", low)]