Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 65 additions & 58 deletions scripts/run_operational_replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import subprocess
import sys
import time
import tempfile
from pathlib import Path

import numpy as np
Expand All @@ -15,74 +16,77 @@
REPORTS = ROOT / "reports"


def run_pipeline_once(run_id: int, operating_day: str) -> dict:
start = time.perf_counter()
completed = subprocess.run(
[sys.executable, "scripts/run_pipeline.py"],
cwd=ROOT,
capture_output=True,
text=True,
)
runtime = time.perf_counter() - start

release_path = OUTPUTS / "release_decision.json"
health_path = OUTPUTS / "validation_health_scores.csv"
findings_path = OUTPUTS / "model_risk_findings.csv"
backtest_path = OUTPUTS / "backtesting_summary.csv"

release = json.loads(release_path.read_text(encoding="utf-8")) if release_path.exists() else {}
health = pd.read_csv(health_path) if health_path.exists() else pd.DataFrame()
findings = pd.read_csv(findings_path) if findings_path.exists() else pd.DataFrame()
backtest = pd.read_csv(backtest_path) if backtest_path.exists() else pd.DataFrame()

health_score = float(health["validation_health_score"].iloc[0]) if "validation_health_score" in health.columns and len(health) else np.nan
final_false_pass = float(health["false_pass_rate"].iloc[0]) if "false_pass_rate" in health.columns and len(health) else np.nan

high_or_critical = 0
if len(findings) and "severity" in findings.columns:
high_or_critical = int(findings["severity"].isin(["HIGH", "CRITICAL"]).sum())

recent_250_exceptions = np.nan
traffic_light_zone = "UNKNOWN"
if len(backtest):
if "recent_250_exceptions" in backtest.columns:
recent_250_exceptions = float(backtest["recent_250_exceptions"].iloc[0])
if "traffic_light_zone" in backtest.columns:
traffic_light_zone = str(backtest["traffic_light_zone"].iloc[0])

status = release.get("release_decision", release.get("decision", "UNKNOWN"))

recalibration_trigger = (
status in {"REVIEW", "BLOCK"}
or high_or_critical > 0
or (not np.isnan(health_score) and health_score < 85)
or (not np.isnan(final_false_pass) and final_false_pass > 0)
or traffic_light_zone in {"YELLOW", "RED"}
)

def read_run_metrics(output: Path) -> dict:
release = json.loads((output / "release_decision.json").read_text(encoding="utf-8"))
status = release.get("release_decision", release.get("decision"))
if status not in {"PASS", "REVIEW", "BLOCK"}:
raise ValueError("Missing or invalid release decision")
health = pd.read_csv(output / "validation_health_scores.csv")
findings = pd.read_csv(output / "model_risk_findings.csv")
backtest = pd.read_csv(output / "backtesting_summary.csv")
health_score = float(health["validation_health_score"].iloc[0])
# The release gate records the actual false-pass rate used in the decision.
false_pass = float(release["false_pass_rate"])
recent_exceptions = float(backtest["recent_250_exceptions"].iloc[0])
traffic_light_zone = backtest["traffic_light_zone"].iloc[0]
if not np.isfinite([health_score, false_pass, recent_exceptions]).all():
raise ValueError("Non-finite replay metrics")
if traffic_light_zone not in {"GREEN", "YELLOW", "RED"}:
raise ValueError("Missing or invalid backtest zone")
severities = findings["severity"]
if not severities.isin(["LOW", "MEDIUM", "HIGH", "CRITICAL"]).all():
raise ValueError("Missing or invalid finding severity")
high_or_critical = int(severities.isin(["HIGH", "CRITICAL"]).sum())
return {
"run_id": run_id,
"operating_day": operating_day,
"return_code": completed.returncode,
"runtime_seconds": round(runtime, 4),
"release_decision": status,
"validation_health_score": health_score,
"false_pass_rate": final_false_pass,
"false_pass_rate": false_pass,
"high_or_critical_findings": high_or_critical,
"recent_250_exceptions": recent_250_exceptions,
"recent_250_exceptions": recent_exceptions,
"traffic_light_zone": traffic_light_zone,
"recalibration_trigger": bool(recalibration_trigger),
"stdout_tail": completed.stdout[-300:],
"stderr_tail": completed.stderr[-300:],
"recalibration_trigger": bool(status in {"REVIEW", "BLOCK"} or high_or_critical
or health_score < 85 or false_pass > 0
or traffic_light_zone in {"YELLOW", "RED"}),
}


def run_pipeline_once(run_id: int, operating_day: str, session: Path | None = None) -> dict:
start = time.perf_counter()
row = dict.fromkeys(("run_id", "operating_day", "return_code", "runtime_seconds", "release_decision", "validation_health_score", "false_pass_rate",
"high_or_critical_findings", "recent_250_exceptions",
"traffic_light_zone", "recalibration_trigger"))
row.update(run_id=run_id, operating_day=operating_day, run_status="FAILED",
return_code=None, stdout_tail="", stderr_tail="", error=None)
with tempfile.TemporaryDirectory(prefix=f"run-{run_id}-", dir=session) as temp:
try:
process = subprocess.run(
[sys.executable, str(ROOT / "scripts/run_pipeline.py"), "--run-root", temp],
cwd=ROOT, capture_output=True, text=True,
)
row.update(return_code=process.returncode, stdout_tail=process.stdout[-300:],
stderr_tail=process.stderr[-300:])
if process.returncode == 0:
row.update(read_run_metrics(Path(temp) / "outputs"))
row["run_status"] = "SUCCEEDED"
else:
row["error"] = f"Pipeline exited with status {process.returncode}"
except (OSError, ValueError, TypeError, AttributeError, KeyError, IndexError) as exc:
row["error"] = f"{type(exc).__name__}: {exc}"
row["runtime_seconds"] = round(time.perf_counter() - start, 4)
return row


def build_recalibration_summary(log: pd.DataFrame) -> pd.DataFrame:
valid = log["run_status"].eq("SUCCEEDED")
passed = valid & log["release_decision"].eq("PASS")
return pd.DataFrame(
[
{
"num_operating_runs": len(log),
"pass_rate": round((log["release_decision"] == "PASS").mean(), 4),
"num_decided_runs": int(valid.sum()),
"num_failed_runs": int((~valid).sum()),
"pass_rate": round(passed.mean(), 4),
"decided_pass_rate": round(passed[valid].mean(), 4),
"review_or_block_rate": round(log["release_decision"].isin(["REVIEW", "BLOCK"]).mean(), 4),
"recalibration_trigger_rate": round(log["recalibration_trigger"].mean(), 4),
"avg_runtime_seconds": round(log["runtime_seconds"].mean(), 4),
Expand Down Expand Up @@ -114,6 +118,8 @@ def write_reports(log: pd.DataFrame, summary: pd.DataFrame) -> None:
[
"run_id",
"operating_day",
"run_status",
"error",
"runtime_seconds",
"release_decision",
"validation_health_score",
Expand Down Expand Up @@ -171,8 +177,9 @@ def main() -> None:
operating_days = pd.date_range("2026-06-01", periods=5, freq="B")
rows = []

for i, day in enumerate(operating_days, start=1):
rows.append(run_pipeline_once(i, str(day.date())))
with tempfile.TemporaryDirectory(prefix="quant-replay-") as session:
for i, day in enumerate(operating_days, start=1):
rows.append(run_pipeline_once(i, str(day.date()), Path(session)))

log = pd.DataFrame(rows)
summary = build_recalibration_summary(log)
Expand All @@ -181,7 +188,7 @@ def main() -> None:
summary.to_csv(OUTPUTS / "recalibration_summary.csv", index=False)
write_reports(log, summary)

status = "PASS" if (log["return_code"].eq(0).all() and summary["pass_rate"].iloc[0] >= 0.8) else "REVIEW"
status = "PASS" if (log["run_status"].eq("SUCCEEDED").all() and summary["pass_rate"].iloc[0] >= 0.8) else "REVIEW"

print("Operational replay completed.")
print(f"Status: {status}")
Expand Down
Loading
Loading