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:08:52 -05:00
parent 5859857ace
commit 0da283e67f
4 changed files with 649 additions and 63 deletions

View file

@ -1828,7 +1828,6 @@ def plan_feature_batch(
vault_cutoff_date=vault_cutoff_date,
)
known_at_upper_iso = format_utc_iso_micros(vault_ceiling_micros)
writes: list[PlannedFeatureWrite] = []
for year in range(valid_from, last_planned_year + 1):
@ -1838,6 +1837,7 @@ def plan_feature_batch(
) * 1_000_000 + 999_999
effective_ts_end_micros = min(year_end_micros, vault_ceiling_micros)
ts_upper_iso = format_utc_iso_micros(effective_ts_end_micros)
known_at_upper_iso = ts_upper_iso
output_path = _join_curated_path(
valid_root, f"features/{defn.name}/v{defn.version}/year={year}/part.parquet"
@ -1957,6 +1957,66 @@ def _validate_polars_feature_output(result: Any) -> pl.DataFrame:
return df
def _verify_or_persist_version_definition(
*,
version_dir: str,
ref: str,
definition_hash: str,
defn: FeatureDefinition,
persist: bool,
) -> bool:
"""Checks on-disk version immutability metadata and optionally persists it atomically.
Returns True when `_definition.json` is verified on disk with matching `definition_hash`.
"""
meta_path = os.path.join(version_dir, "_definition.json")
if os.path.exists(meta_path):
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,
)
return True
if not persist:
return False
os.makedirs(version_dir, exist_ok=True)
tmp_meta = os.path.join(version_dir, f"._definition.{os.getpid()}.{uuid.uuid4().hex}.tmp")
metadata = {
"ref": ref,
"name": defn.name,
"version": defn.version,
"kind": defn.kind,
"definition_hash": definition_hash,
}
try:
with open(tmp_meta, "w", encoding="utf-8") as fh:
json.dump(metadata, fh, sort_keys=True, separators=(",", ":"))
fh.write("\n")
os.replace(tmp_meta, meta_path)
except Exception:
if os.path.exists(tmp_meta):
try:
os.remove(tmp_meta)
except OSError:
pass
raise
return True
def run_feature_batch(
defn: FeatureDefinition,
*,
@ -1970,6 +2030,8 @@ def run_feature_batch(
Creates parent `year=YYYY` directories, writes each year to a staging file in the same
directory via a budgeted UTC DuckDB connection, and atomically publishes via `os.replace`.
Persists and verifies `<curated_root>/features/<name>/v<version>/_definition.json` so a
different definition cannot silently overwrite an already-published version across runs.
Raises `FeatureLibraryError('BATCH_WRITE_FAILED')` with `failed_year`, `completed_years`,
and `completed_writes` on failure.
"""
@ -1986,6 +2048,14 @@ def run_feature_batch(
def_hash = feature_definition_hash(defn)
sorted_inputs = tuple(sorted(validated.normalized_inputs))
resolved_budget = budget or resolve_duckdb_budget()
version_dir = _join_curated_path(valid_root, f"features/{defn.name}/v{defn.version}")
definition_persisted = _verify_or_persist_version_definition(
version_dir=version_dir,
ref=ref,
definition_hash=def_hash,
defn=defn,
persist=False,
)
os.makedirs(resolved_budget.temp_directory, exist_ok=True)
con = duckdb.connect(":memory:")
@ -2038,6 +2108,15 @@ def run_feature_batch(
finally:
con.unregister("__polars_feature_out")
if not definition_persisted:
definition_persisted = _verify_or_persist_version_definition(
version_dir=version_dir,
ref=ref,
definition_hash=def_hash,
defn=defn,
persist=True,
)
os.replace(tmp_path, write.output_path)
except FeatureLibraryError as exc:
if os.path.exists(tmp_path):
@ -2045,7 +2124,12 @@ def run_feature_batch(
os.remove(tmp_path)
except OSError:
pass
if exc.code in ("UNDECLARED_INPUT", "UNUSED_INPUT", "INVALID_SQL_PROJECTION"):
if not completed_writes and exc.code in (
"UNDECLARED_INPUT",
"UNUSED_INPUT",
"INVALID_SQL_PROJECTION",
"FEATURE_VERSION_IMMUTABLE",
):
raise
completed_years = [w.year for w in completed_writes]
raise FeatureLibraryError(