Spaces:
Running

PolyHedra / src /polyhedra /core /baseline_selector.py
yf176
feat: select typed YOLO baselines
c690519
Raw History Blame Contribute Delete
5.98 kB
"""Select one immutable typed YOLO baseline from runtime run records."""
from collections.abc import Iterable, Mapping
from datetime import datetime
from enum import StrEnum
from typing import Any, Literal, Self
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
from polyhedra.core.artifacts import (
ArtifactRef, Identifier, JsonArtifactRef, RunMode, SchemaVersion, Ticker,
TickerScope, TypedModel,
)
class BaselineRejectionCode(StrEnum):
CURRENT_RUN = "CURRENT_RUN"
CROSS_SESSION = "CROSS_SESSION"
NOT_YOLO = "NOT_YOLO"
NOT_COMPLETED = "NOT_COMPLETED"
UNSUPPORTED_SCHEMA = "UNSUPPORTED_SCHEMA"
INVALID_RECORD = "INVALID_RECORD"
class BaselineCandidate(BaseModel):
"""Strict baseline-relevant projection of a larger runtime run record."""
model_config = ConfigDict(extra="ignore", frozen=True)
schema_version: SchemaVersion
run_id: Identifier
session_id: Identifier
execution_context: Literal["YOLO"]
status: Literal["completed"]
completed_at: AwareDatetime
ticker_scope: TickerScope
artifact_inventory: list[ArtifactRef] = Field(min_length=1)
@model_validator(mode="after")
def artifact_identity(self) -> Self:
for artifact in self.artifact_inventory:
if (artifact.run_id, artifact.session_id) != (self.run_id, self.session_id):
raise ValueError("baseline artifact belongs to another run or session")
if not any(isinstance(artifact, JsonArtifactRef) for artifact in self.artifact_inventory):
raise ValueError("baseline requires at least one typed JSON artifact")
return self
class BaselineRejection(TypedModel):
run_id: str
code: BaselineRejectionCode
reason: str
class BaselineSelection(TypedModel):
run_mode: RunMode
current_run_id: Identifier
session_id: Identifier
current_ticker_scope: TickerScope
baseline_run_id: Identifier | None
baseline_completed_at: AwareDatetime | None
baseline_ticker_scope: list[Ticker]
missing_tickers: list[Ticker]
baseline_artifacts: list[JsonArtifactRef]
rejections: list[BaselineRejection]
@model_validator(mode="after")
def coherent_mode(self) -> Self:
selected = self.baseline_run_id is not None
if selected != (self.run_mode == RunMode.DELTA):
raise ValueError("delta mode requires one selected baseline")
if not selected and (
self.baseline_completed_at is not None
or self.baseline_ticker_scope
or self.baseline_artifacts
):
raise ValueError("baseline mode cannot carry selected baseline data")
if not set(self.missing_tickers).issubset(self.current_ticker_scope):
raise ValueError("missing baseline tickers must belong to current scope")
return self
def select_typed_yolo_baseline(
records: Iterable[Mapping[str, Any]],
*,
session_id: str,
current_run_id: str,
ticker_scope: list[str],
) -> BaselineSelection:
"""Choose the latest valid completed V8 YOLO run and report every rejection."""
accepted: list[BaselineCandidate] = []
rejected: list[BaselineRejection] = []
for raw in records:
run_id = str(raw.get("run_id") or "unknown")
rejection = _precheck(raw, run_id, session_id, current_run_id)
if rejection is not None:
rejected.append(rejection)
continue
try:
accepted.append(BaselineCandidate.model_validate(raw))
except Exception as exc:
rejected.append(BaselineRejection(
run_id=run_id,
code=BaselineRejectionCode.INVALID_RECORD,
reason=f"Invalid typed baseline record: {exc}",
))
if not accepted:
return BaselineSelection(
run_mode=RunMode.BASELINE,
current_run_id=current_run_id,
session_id=session_id,
current_ticker_scope=ticker_scope,
baseline_run_id=None,
baseline_completed_at=None,
baseline_ticker_scope=[],
missing_tickers=list(ticker_scope),
baseline_artifacts=[],
rejections=rejected,
)
selected = max(accepted, key=lambda item: (item.completed_at, item.run_id))
baseline_tickers = list(selected.ticker_scope)
return BaselineSelection(
run_mode=RunMode.DELTA,
current_run_id=current_run_id,
session_id=session_id,
current_ticker_scope=ticker_scope,
baseline_run_id=selected.run_id,
baseline_completed_at=selected.completed_at,
baseline_ticker_scope=baseline_tickers,
missing_tickers=[ticker for ticker in ticker_scope if ticker not in baseline_tickers],
baseline_artifacts=[
artifact for artifact in selected.artifact_inventory
if isinstance(artifact, JsonArtifactRef)
],
rejections=rejected,
)
def _precheck(
raw: Mapping[str, Any],
run_id: str,
session_id: str,
current_run_id: str,
) -> BaselineRejection | None:
checks = (
(run_id == current_run_id, BaselineRejectionCode.CURRENT_RUN,
"The current run cannot be its own baseline."),
(raw.get("session_id") != session_id, BaselineRejectionCode.CROSS_SESSION,
"The run belongs to another session."),
(raw.get("schema_version") != "8.0", BaselineRejectionCode.UNSUPPORTED_SCHEMA,
"The run record schema is not supported by V8."),
(raw.get("execution_context") != "YOLO", BaselineRejectionCode.NOT_YOLO,
"Support-context runs are not YOLO baselines."),
(raw.get("status") != "completed", BaselineRejectionCode.NOT_COMPLETED,
"Only completed runs can replace the baseline."),
)
for failed, code, reason in checks:
if failed:
return BaselineRejection(run_id=run_id, code=code, reason=reason)
return None