T-213: M2.4b — Add Python stockbot register_signal, batch feature runner, and M2 MarketDataStore methods

This commit is contained in:
Studio 2026-12-05 14:21:52 -05:00
parent 0da283e67f
commit 0cd1f815c8
2 changed files with 327 additions and 36 deletions

View file

@ -1957,6 +1957,41 @@ def _validate_polars_feature_output(result: Any) -> pl.DataFrame:
return df return df
def _has_existing_feature_partitions(version_dir: str) -> bool:
if not os.path.isdir(version_dir):
return False
for _root, _dirs, files in os.walk(version_dir):
for name in files:
if name.endswith(".parquet") and not name.startswith("."):
return True
return False
def _verify_existing_version_metadata(
*,
meta_path: str,
ref: str,
definition_hash: str,
) -> None:
try:
with open(meta_path, "r", encoding="utf-8") as fh:
payload = json.load(fh)
except Exception as exc:
raise FeatureLibraryError(
"FEATURE_VERSION_IMMUTABLE",
f'Published feature "{ref}" has unreadable version metadata at "{meta_path}".',
cause=exc,
ref=ref,
) from exc
existing_hash = payload.get("definition_hash") if isinstance(payload, dict) else None
if not isinstance(existing_hash, str) or existing_hash != definition_hash:
raise FeatureLibraryError(
"FEATURE_VERSION_IMMUTABLE",
f'Feature "{ref}" is already published on disk with a different definition hash; bump the feature version instead of overwriting.',
ref=ref,
)
def _verify_or_persist_version_definition( def _verify_or_persist_version_definition(
*, *,
version_dir: str, version_dir: str,
@ -1965,31 +2000,32 @@ def _verify_or_persist_version_definition(
defn: FeatureDefinition, defn: FeatureDefinition,
persist: bool, persist: bool,
) -> bool: ) -> bool:
"""Checks on-disk version immutability metadata and optionally persists it atomically. """Checks on-disk version immutability metadata and atomically claims it if absent.
Returns True when `_definition.json` is verified on disk with matching `definition_hash`. Rejects existing published Parquet partitions that lack a verified `_definition.json`
(e.g. sidecar-free partitions from another writer), and uses POSIX create-if-absent
hard-link (`os.link`) so concurrent first-time writers race safely and always verify
the winning definition hash before publishing any partition.
""" """
meta_path = os.path.join(version_dir, "_definition.json") meta_path = os.path.join(version_dir, "_definition.json")
if os.path.exists(meta_path): if os.path.exists(meta_path):
try: _verify_existing_version_metadata(
with open(meta_path, "r", encoding="utf-8") as fh: meta_path=meta_path, ref=ref, definition_hash=definition_hash
payload = json.load(fh) )
except Exception as exc:
raise FeatureLibraryError(
"FEATURE_VERSION_IMMUTABLE",
f'Published feature "{ref}" has unreadable version metadata at "{meta_path}".',
cause=exc,
ref=ref,
) from exc
existing_hash = payload.get("definition_hash") if isinstance(payload, dict) else None
if not isinstance(existing_hash, str) or existing_hash != definition_hash:
raise FeatureLibraryError(
"FEATURE_VERSION_IMMUTABLE",
f'Feature "{ref}" is already published on disk with a different definition hash; bump the feature version instead of overwriting.',
ref=ref,
)
return True return True
if _has_existing_feature_partitions(version_dir):
if os.path.exists(meta_path):
_verify_existing_version_metadata(
meta_path=meta_path, ref=ref, definition_hash=definition_hash
)
return True
raise FeatureLibraryError(
"FEATURE_VERSION_IMMUTABLE",
f'Feature "{ref}" already has published Parquet partitions at "{version_dir}" without verified version metadata ("_definition.json"); bump the feature version instead of overwriting or adopting unverified partitions.',
ref=ref,
)
if not persist: if not persist:
return False return False
@ -2006,14 +2042,24 @@ def _verify_or_persist_version_definition(
with open(tmp_meta, "w", encoding="utf-8") as fh: with open(tmp_meta, "w", encoding="utf-8") as fh:
json.dump(metadata, fh, sort_keys=True, separators=(",", ":")) json.dump(metadata, fh, sort_keys=True, separators=(",", ":"))
fh.write("\n") fh.write("\n")
os.replace(tmp_meta, meta_path) fh.flush()
except Exception: os.fsync(fh.fileno())
try:
os.link(tmp_meta, meta_path)
return True
except FileExistsError:
pass
finally:
if os.path.exists(tmp_meta): if os.path.exists(tmp_meta):
try: try:
os.remove(tmp_meta) os.remove(tmp_meta)
except OSError: except OSError:
pass pass
raise
# Another writer won the atomic create-if-absent claim; verify the winning hash.
_verify_existing_version_metadata(
meta_path=meta_path, ref=ref, definition_hash=definition_hash
)
return True return True

View file

@ -10,6 +10,8 @@ import json
import math import math
import shutil import shutil
import subprocess import subprocess
import threading
from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime, timezone from datetime import date, datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Any, Mapping, Sequence from typing import Any, Mapping, Sequence
@ -1017,6 +1019,35 @@ def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak
_build_bars_and_events_fixtures(curated) _build_bars_and_events_fixtures(curated)
budget = _make_budget(tmp_path) budget = _make_budget(tmp_path)
# Extend 2025 bars with an April 1 bar (after the 2025-03-15 macro release) alongside
# the Jan 2 bars (before the 2025-03-15 release) and Jul 2 post-Vault bar.
bars_2025_existing = pl.read_parquet(curated / "bars_1d" / "year=2025" / "part.parquet")
bars_2025_apr = pl.DataFrame(
{
"listing_id": [1],
"session_date": [date(2025, 4, 1)],
"ts": [datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)],
"open": [11.5],
"high": [12.2],
"low": [11.4],
"close": [12.0],
"volume": [1300.0],
"vwap": [12.0],
"currency": ["USD"],
"source": ["eod"],
"known_at": [datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)],
},
schema_overrides={
"listing_id": pl.Int32,
"ts": pl.Datetime("us", "UTC"),
"known_at": pl.Datetime("us", "UTC"),
},
)
_write_parquet_via_duckdb(
pl.concat([bars_2025_existing, bars_2025_apr]),
curated / "bars_1d" / "year=2025" / "part.parquet",
)
# Macro releases across 2023 (prior history), 2024, 2025 pre-Vault, and 2025 post-Vault # Macro releases across 2023 (prior history), 2024, 2025 pre-Vault, and 2025 post-Vault
macro_df = pl.DataFrame( macro_df = pl.DataFrame(
{ {
@ -1047,16 +1078,29 @@ def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak
seen_macro_counts: list[int] = [] seen_macro_counts: list[int] = []
def _latest_macro_regime_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: def _asof_macro_regime_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame:
macro_rows = inputs["macro"].sort("known_at").collect() macro_rows = (
inputs["macro"]
.select(
pl.col("known_at").alias("macro_known_at"),
pl.col("value").cast(pl.Float64).alias("macro_value"),
)
.sort("macro_known_at")
.collect()
)
seen_macro_counts.append(macro_rows.height) seen_macro_counts.append(macro_rows.height)
latest_val = float(macro_rows.get_column("value")[-1]) bars = inputs["bars_1d"].select("listing_id", "ts").sort("ts").collect()
bars = inputs["bars_1d"].collect() joined = bars.join_asof(
return bars.select( macro_rows,
left_on="ts",
right_on="macro_known_at",
strategy="backward",
)
return joined.select(
pl.col("listing_id"), pl.col("listing_id"),
pl.col("ts"), pl.col("ts"),
pl.col("ts").alias("known_at"), pl.max_horizontal("ts", "macro_known_at").alias("known_at"),
pl.lit(latest_val).cast(pl.Float64).alias("value"), pl.col("macro_value").alias("value"),
) )
defn = register_signal( defn = register_signal(
@ -1067,8 +1111,8 @@ def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak
inputs=("bars_1d", "macro"), inputs=("bars_1d", "macro"),
warmup_bars=0, warmup_bars=0,
known_at_rule="max_input_known_at", known_at_rule="max_input_known_at",
polars_fn=_latest_macro_regime_fn, polars_fn=_asof_macro_regime_fn,
expression="latest(macro.value)", expression="asof(macro.value)",
registry=create_feature_registry(), registry=create_feature_registry(),
).definition ).definition
@ -1093,8 +1137,16 @@ def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak
) )
assert out_2024.height > 0 assert out_2024.height > 0
assert all(v == pytest.approx(2.0) for v in out_2024["value"].to_list()) assert all(v == pytest.approx(2.0) for v in out_2024["value"].to_list())
assert out_2025.height > 0
assert all(v == pytest.approx(99.0) for v in out_2025["value"].to_list()) # In 2025, Jan 2 bars precede the 2025-03-15 release so they must still see 2.0 (not 99.0);
# only the Apr 1 bar (after 2025-03-15) sees 99.0, and the post-Vault Jul 2 bar is excluded.
jan_2025 = out_2025.filter(pl.col("ts") == datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc))
apr_2025 = out_2025.filter(pl.col("ts") == datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc))
assert jan_2025.height == 3
assert all(v == pytest.approx(2.0) for v in jan_2025["value"].to_list())
assert apr_2025.height == 1
assert apr_2025["value"].to_list() == pytest.approx([99.0])
assert out_2025.height == 4
def test_run_feature_batch_persists_definition_hash_and_blocks_cross_registry_overwrite( def test_run_feature_batch_persists_definition_hash_and_blocks_cross_registry_overwrite(
@ -1225,9 +1277,202 @@ def test_polars_batch_post_publication_failure_wraps_in_batch_write_failed_with_
assert err.value.completed_writes[0].output_path.endswith( assert err.value.completed_writes[0].output_path.endswith(
"features/fail_year2/v1/year=2024/part.parquet" "features/fail_year2/v1/year=2024/part.parquet"
) )
assert isinstance(err.value.cause, FeatureLibraryError) assert isinstance(err.value.__cause__, FeatureLibraryError)
assert err.value.cause.code == "INVALID_SQL_PROJECTION" assert err.value.__cause__.code == "INVALID_SQL_PROJECTION"
assert err.value.__cause__ is err.value.cause
def test_run_feature_batch_rejects_sidecar_free_ts_partitions(tmp_path: Path) -> None:
curated = tmp_path / "curated"
_build_bars_and_events_fixtures(curated)
budget = _make_budget(tmp_path)
vault_cutoff_date = "2025-07-01"
vault_cutoff_ms = parse_timestamp_micros(vault_cutoff_date, "start", "cutoff") // 1000
# Materialize ret_1d@v1 year=2024 using the TypeScript batch runner (no _definition.json sidecar)
bun_bin = shutil.which("bun")
assert bun_bin is not None, "bun is required for TypeScript sidecar-free fixture"
year_2024_dir = curated / "features" / "ret_1d" / "v1" / "year=2024"
year_2024_dir.mkdir(parents=True, exist_ok=True)
script = f"""
import {{ openDuckDbMarketDataStore }} from './libs/data/duckdb/src/index.ts';
import {{ RET_1D_V1, runFeatureBatch }} from './libs/research/src/feature-library.ts';
const curatedRoot = {json.dumps(str(curated))};
const vaultCutoffTs = {vault_cutoff_ms};
const opened = await openDuckDbMarketDataStore({{
curatedRoot,
vaultCutoffTs,
env: {{
STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB',
STOCKBOT_DUCKDB_THREADS: '2',
STOCKBOT_DUCKDB_TEMP_DIRECTORY: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))},
STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))},
}},
}});
try {{
await runFeatureBatch(
RET_1D_V1,
{{ curatedRoot, fromYear: 2024, toYear: 2024, vaultCutoffDate: {json.dumps(vault_cutoff_date)} }},
opened.executor,
);
}} finally {{
await opened.close();
}}
"""
subprocess.run(
[bun_bin, "-e", script],
cwd=str(REPO_ROOT),
capture_output=True,
text=True,
check=True,
)
ts_part_2024 = year_2024_dir / "part.parquet"
meta_file = curated / "features" / "ret_1d" / "v1" / "_definition.json"
part_2025 = curated / "features" / "ret_1d" / "v1" / "year=2025" / "part.parquet"
assert ts_part_2024.exists()
assert not meta_file.exists()
original_2024_bytes = ts_part_2024.read_bytes()
# Promoting a revised Python formula under ret_1d@v1 for 2025 must fail closed
revised_ret = register_signal(
name="ret_1d",
version=1,
family="technical",
kind="polars",
inputs=("bars_1d",),
warmup_bars=1,
known_at_rule="bar_close",
polars_fn=lambda inp: inp["bars_1d"].select(
pl.col("listing_id"),
pl.col("ts"),
pl.col("ts").alias("known_at"),
(pl.col("close") * 0.0).cast(pl.Float64).alias("value"),
),
expression="0.0",
registry=create_feature_registry(),
).definition
with pytest.raises(FeatureLibraryError) as err:
run_feature_batch(
revised_ret,
curated_root=curated,
from_year=2025,
to_year=2025,
vault_cutoff_date=vault_cutoff_date,
budget=budget,
)
assert err.value.code == "FEATURE_VERSION_IMMUTABLE"
assert not meta_file.exists()
assert not part_2025.exists()
assert ts_part_2024.read_bytes() == original_2024_bytes
def test_run_feature_batch_atomic_version_claim_blocks_competing_first_writes(
tmp_path: Path,
) -> None:
curated = tmp_path / "curated"
_build_bars_and_events_fixtures(curated)
vault_cutoff_date = "2025-07-01"
barrier = threading.Barrier(2, timeout=10.0)
def _fn_a(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame:
barrier.wait()
return (
inputs["bars_1d"]
.select(
pl.col("listing_id"),
pl.col("ts"),
pl.col("ts").alias("known_at"),
pl.col("close").cast(pl.Float64).alias("value"),
)
.collect()
)
def _fn_b(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame:
barrier.wait()
return (
inputs["bars_1d"]
.select(
pl.col("listing_id"),
pl.col("ts"),
pl.col("ts").alias("known_at"),
(pl.col("close") * 2.0).cast(pl.Float64).alias("value"),
)
.collect()
)
reg_a = register_signal(
name="close_race",
version=1,
family="technical",
kind="polars",
inputs=("bars_1d",),
warmup_bars=0,
known_at_rule="bar_close",
polars_fn=_fn_a,
expression="close",
registry=create_feature_registry(),
)
reg_b = register_signal(
name="close_race",
version=1,
family="technical",
kind="polars",
inputs=("bars_1d",),
warmup_bars=0,
known_at_rule="bar_close",
polars_fn=_fn_b,
expression="close * 2.0",
registry=create_feature_registry(),
)
def _run_writer(
defn: FeatureDefinition, year: int, tag: str
) -> tuple[str, Any]:
try:
manifest = run_feature_batch(
defn,
curated_root=curated,
from_year=year,
to_year=year,
vault_cutoff_date=vault_cutoff_date,
budget=_make_budget(tmp_path / tag),
)
return ("ok", manifest)
except FeatureLibraryError as exc:
return ("err", exc)
with ThreadPoolExecutor(max_workers=2) as pool:
fut_a = pool.submit(_run_writer, reg_a.definition, 2024, "a")
fut_b = pool.submit(_run_writer, reg_b.definition, 2025, "b")
res_a = fut_a.result()
res_b = fut_b.result()
outcomes = [res_a, res_b]
winners = [payload for status, payload in outcomes if status == "ok"]
losers = [payload for status, payload in outcomes if status == "err"]
assert len(winners) == 1
assert len(losers) == 1
assert isinstance(losers[0], FeatureLibraryError)
assert losers[0].code == "FEATURE_VERSION_IMMUTABLE"
winner_manifest = winners[0]
version_dir = curated / "features" / "close_race" / "v1"
meta_payload = json.loads((version_dir / "_definition.json").read_text(encoding="utf-8"))
assert meta_payload["definition_hash"] == winner_manifest.definition_hash
part_2024 = version_dir / "year=2024" / "part.parquet"
part_2025 = version_dir / "year=2025" / "part.parquet"
if winner_manifest.definition_hash == reg_a.definition_hash:
assert part_2024.exists()
assert not part_2025.exists()
else:
assert winner_manifest.definition_hash == reg_b.definition_hash
assert part_2025.exists()
assert not part_2024.exists()
leftover_tmp = [p for p in version_dir.rglob("*.tmp")]
assert leftover_tmp == []
def test_sdk_exports() -> None: def test_sdk_exports() -> None: